From b30d6118fee91a0e0741de83969bac4b5f497f67 Mon Sep 17 00:00:00 2001 From: Benjamin Toby Date: Sun, 22 Nov 2026 15:51:38 +0100 Subject: [PATCH] Transcribe on Alibaba's native route, and card the composer error The Token Plan host has no /audio/transcriptions: its ASR model is served at the DashScope host root, with the audio inline as a data URL and the model's own format and language hints. Async-only slugs (filetrans, paraformer) are refused with the synchronous model to pick instead. The image helpers that recognise those hosts move to one shared module. A failed send, or a failed dictation, now shows as a dismissible card under the composer in the error or warning tint rather than a line of grey text. --- AGENTS.md | 1 + src/harness/audio/transcribe-audio.ts | 3 +- .../openai-compatible/dashscope-hosts.ts | 59 ++++++++++ .../dashscope-native-image.ts | 24 +--- .../dashscope-native-transcribe.ts | 109 ++++++++++++++++++ .../openai-compatible/generate-image.ts | 35 +----- .../openai-compatible/transcribe.test.ts | 88 +++++++++++++- .../providers/openai-compatible/transcribe.ts | 29 ++++- .../[bot_id]/(partials)/composer-notice.tsx | 58 ++++++++++ .../bots/[bot_id]/(partials)/composer.tsx | 23 +++- 10 files changed, 366 insertions(+), 63 deletions(-) create mode 100644 src/harness/providers/openai-compatible/dashscope-hosts.ts create mode 100644 src/harness/providers/openai-compatible/dashscope-native-transcribe.ts create mode 100644 src/pages/admin/bots/[bot_id]/(partials)/composer-notice.tsx diff --git a/AGENTS.md b/AGENTS.md index 8479454c..d45cf5a6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -231,6 +231,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa - **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `video`, `video_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked. - **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; only while its `fallback` is on does `HarnessFallbacks` hand it to `image`, both while it is unpicked or off and after its pick fails), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`); DashScope/Model Studio hosts (`dashscope*.aliyuncs.com`, `*.maas.aliyuncs.com`) take them as the `image` extension field on `/images/generations` instead (they have no multipart edits endpoint) and always answer with URLs, ignoring `b64_json` (`isDashScopeHost` in the adapter). The Token Plan host (`token-plan.*.maas.aliyuncs.com`) has no compatible images route, so its call goes straight to Alibaba's native `multimodal-generation` on the host root (`dashscope-native-image.ts`, the documented body: `size` as `width*height`, no `prompt_extend`); a workspace host that answers 404/405 on the compatible route falls back to the same call. xAI takes no `size` (`imageRequestFields` maps one onto `aspect_ratio`). - **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`//content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos. +- **Transcription:** `transcribeAudio` -> `src/harness/providers/openai-compatible/transcribe.ts`. An OpenAI-compatible host gets multipart `/audio/transcriptions`; a DashScope host (`dashscope-hosts.ts`: `isDashScopeHost`, `isTokenPlanHost`, the Token Plan included) has no such route, so an ASR model there goes to `dashscope-native-transcribe.ts` (JSON `input_audio` as a `data:` URL of the bytes, `parameters.format`, at the host root's `/api/v1/services/aigc/multimodal-generation/generation`), and an async-only slug (filetrans, paraformer) is refused unretryably naming the synchronous model to pick instead. - **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop. - **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env. - **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown, and a run then works to `AppData.HarnessUnknownContextWindow` (1,000,000) less the answer reserve. That guess is not silent: the model picker marks a model with no declared window, and a provider that refuses the prompt for size stops the run with its own message and the fix (`fatal`, below). Never learn a smaller window into the constant: the provider has the last word. diff --git a/src/harness/audio/transcribe-audio.ts b/src/harness/audio/transcribe-audio.ts index 0a2ff33a..1d7b8386 100644 --- a/src/harness/audio/transcribe-audio.ts +++ b/src/harness/audio/transcribe-audio.ts @@ -27,7 +27,8 @@ type Params = { /** * Turns speech into text with the transcription harness: its - * speech-to-text model gets the file at `/audio/transcriptions`. + * speech-to-text model gets the file, at `/audio/transcriptions` or, on + * Alibaba's hosts, at their native multimodal route. */ export default async function transcribeAudio({ audio, diff --git a/src/harness/providers/openai-compatible/dashscope-hosts.ts b/src/harness/providers/openai-compatible/dashscope-hosts.ts new file mode 100644 index 00000000..d7af0ae5 --- /dev/null +++ b/src/harness/providers/openai-compatible/dashscope-hosts.ts @@ -0,0 +1,59 @@ +import HarnessError from "../../harness-error"; + +/** + * Alibaba's native routes (images, speech) live at the host root, beside + * `/compatible-mode/v1`, never under it. + */ +export const NativeGenerationPath = "/api/v1/services/aigc/multimodal-generation/generation"; + +/** + * The host root: the native routes live beside `/compatible-mode/v1`, + * never under it. + */ +export function dashScopeOrigin({ base_url }: { base_url: string }) { + try { + return new URL(base_url).origin; + } catch { + throw new HarnessError({ + message: `The provider's base URL can't be read as an address: ${base_url}`, + retryable: false, + }); + } +} + +/** + * Alibaba's Token Plan host. Its models are served only by the native + * calls; the compatible routes 404, and trying one first benches the model + * before the request that works. + */ +export function isTokenPlanHost({ base_url }: { base_url?: string | null }) { + if (!base_url) return false; + + try { + return new URL(base_url).hostname.startsWith("token-plan."); + } catch { + return false; + } +} + +/** + * A DashScope or Model Studio host, where the native calls take the + * provider's own extensions (`image` references, audio input). The shared + * `dashscope` hosts and the workspace `maas` hosts both count; a custom + * provider pointed elsewhere keeps the standard behaviour. + */ +export function isDashScopeHost({ base_url }: { base_url?: string | null }) { + if (!base_url) return false; + + try { + const host = new URL(base_url).hostname; + + return ( + host == "dashscope.aliyuncs.com" || + host == "dashscope-intl.aliyuncs.com" || + host.endsWith(".maas.aliyuncs.com") + ); + } catch { + return false; + } +} \ No newline at end of file diff --git a/src/harness/providers/openai-compatible/dashscope-native-image.ts b/src/harness/providers/openai-compatible/dashscope-native-image.ts index 894f44dc..4f5818bd 100644 --- a/src/harness/providers/openai-compatible/dashscope-native-image.ts +++ b/src/harness/providers/openai-compatible/dashscope-native-image.ts @@ -1,6 +1,7 @@ import { AppData } from "@/src/data/app-data"; import HarnessError from "../../harness-error"; import type { HarnessCandidate, HarnessImageOutput } from "../../types"; +import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts"; import downloadProviderFile from "./download-provider-file"; import providerRequest from "./provider-request"; @@ -24,8 +25,6 @@ type Params = { * how the native API takes image editing too. The answer carries image URLs, * downloaded here under the same guards as every other provider URL. */ -export const NativeImagePath = "/api/v1/services/aigc/multimodal-generation/generation"; - export default async function generateImageNative({ candidate, prompt, @@ -40,8 +39,8 @@ export default async function generateImageNative({ const res = await providerRequest({ provider, - base_url: nativeOrigin({ base_url: provider.base_url }), - path: NativeImagePath, + base_url: dashScopeOrigin({ base_url: provider.base_url }), + path: NativeGenerationPath, json: { model: model.slug, input: { @@ -90,7 +89,7 @@ export default async function generateImageNative({ if (!urls.length) { throw new HarnessError({ - message: `${name}: no image came back from ${NativeImagePath}.`, + message: `${name}: no image came back from ${NativeGenerationPath}.`, retryable: true, candidate_key: candidate.key, }); @@ -112,21 +111,6 @@ export default async function generateImageNative({ return { images }; } -/** - * The host root: the native routes live beside `/compatible-mode/v1`, - * never under it. - */ -function nativeOrigin({ base_url }: { base_url: string }) { - try { - return new URL(base_url).origin; - } catch { - throw new HarnessError({ - message: `The provider's base URL can't be read as an address: ${base_url}`, - retryable: false, - }); - } -} - /** * The tool's size is a plain `1024x1024`; the native API wants * `1024*1024` and ignores anything that isn't a pair of pixels. diff --git a/src/harness/providers/openai-compatible/dashscope-native-transcribe.ts b/src/harness/providers/openai-compatible/dashscope-native-transcribe.ts new file mode 100644 index 00000000..23e7f0e5 --- /dev/null +++ b/src/harness/providers/openai-compatible/dashscope-native-transcribe.ts @@ -0,0 +1,109 @@ +import HarnessError from "../../harness-error"; +import type { HarnessCandidate } from "../../types"; +import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts"; +import providerRequest from "./provider-request"; + +type Params = { + candidate: HarnessCandidate; + audio: { data: Uint8Array; format: string }; + language?: string; + signal: AbortSignal; +}; + +/** + * What the audio formats the browser records are called as MIME types. + * DashScope takes a data URL, and Safari's `audio/mp4` recording arrives + * here as `m4a`, which no browser spells as a MIME type. + */ +const AudioMimeTypes: Record = { + m4a: "audio/mp4", + mp4: "audio/mp4", + mp3: "audio/mpeg", + ogg: "audio/ogg", + opus: "audio/ogg", +}; + +/** + * Qwen-ASR on Alibaba's native multimodal route. The Token Plan host and the + * workspace Model Studio hosts have no `/audio/transcriptions` at all: the + * model is asked on the host root (beside `compatible-mode/v1`) with the + * audio inline as a data URL, and answers its transcript at `output.text`. + * + * The formats Alibaba documents are wav, mp3 and opus, but live calls take + * every format the recorders here produce (webm, m4a, ogg) when the label + * matches the bytes, so the browser's own recording is sent as it is rather + * than re-encoded first. + */ +export default async function transcribeNative({ + candidate, + audio, + language, + signal, +}: Params): Promise<{ text: string }> { + const { provider, model } = candidate; + const name = provider.name || "Alibaba Cloud"; + const format = audio.format.toLowerCase(); + const mime_type = AudioMimeTypes[format] || `audio/${format}`; + const data_url = `data:${mime_type};base64,${Buffer.from(audio.data).toString("base64")}`; + const hint = languageHint({ language }); + + const res = await providerRequest({ + provider, + base_url: dashScopeOrigin({ base_url: provider.base_url }), + path: NativeGenerationPath, + json: { + model: model.slug, + input: { + messages: [ + { + role: "user", + content: [{ type: "input_audio", input_audio: { data: data_url } }], + }, + ], + }, + parameters: { + format, + ...(hint ? { language_hints: [hint] } : {}), + }, + }, + signal, + candidate_key: candidate.key, + }); + + const json = await res.json().catch(() => null); + + /** + * A cut-off or malformed answer is a failed call, not silence: saying + * it failed lets the harness try the next model instead of handing the + * user an empty transcript. + */ + if (json === null) { + throw new HarnessError({ + message: `${name} returned an unreadable transcript.`, + retryable: true, + candidate_key: candidate.key, + }); + } + + const text = String(json?.output?.text ?? json?.text ?? "").trim(); + + if (!text) { + throw new HarnessError({ + message: `${name} returned an empty transcript.`, + retryable: true, + candidate_key: candidate.key, + }); + } + + return { text }; +} + +/** + * `language_hints` takes a language (`en`), not a locale (`en-US`), so the + * browser's BCP-47 tag is cut to its primary subtag. + */ +function languageHint({ language }: { language?: string }) { + const primary = language?.trim().split(/[-_]/)[0]?.toLowerCase() ?? ""; + + return /^[a-z]{2,3}$/.test(primary) ? primary : undefined; +} \ No newline at end of file diff --git a/src/harness/providers/openai-compatible/generate-image.ts b/src/harness/providers/openai-compatible/generate-image.ts index e7e1a1fd..4d28a744 100644 --- a/src/harness/providers/openai-compatible/generate-image.ts +++ b/src/harness/providers/openai-compatible/generate-image.ts @@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data"; import HarnessError from "../../harness-error"; import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../../types"; import grabProviderPreset from "../grab-provider-preset"; +import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts"; import downloadProviderFile from "./download-provider-file"; import generateImageNative from "./dashscope-native-image"; import imageRequestFields from "./image-request-fields"; @@ -217,37 +218,5 @@ async function editForm({ model, prompt, n, size, references, signal }: EditForm * Alibaba's DashScope and Model Studio (`maas`) hosts serve the OpenAI * images protocol with their own quirks: references go in the `image` * extension field on `/images/generations` (no multipart `/images/edits`), - * and the response is always URLs. The shared `dashscope` hosts and the - * workspace `maas` hosts both count; a custom provider pointed elsewhere - * keeps the standard behaviour. + * and the response is always URLs. */ -/** - * Alibaba's Token Plan host. Its image models are served only by the native - * call; the compatible `/images/generations` path 404s, and trying it first - * benches the model before the picture is made. - */ -export function isTokenPlanHost({ base_url }: { base_url?: string | null }) { - if (!base_url) return false; - - try { - return new URL(base_url).hostname.startsWith("token-plan."); - } catch { - return false; - } -} - -function isDashScopeHost({ base_url }: { base_url?: string | null }) { - if (!base_url) return false; - - try { - const host = new URL(base_url).hostname; - - return ( - host == "dashscope.aliyuncs.com" || - host == "dashscope-intl.aliyuncs.com" || - host.endsWith(".maas.aliyuncs.com") - ); - } catch { - return false; - } -} diff --git a/src/harness/providers/openai-compatible/transcribe.test.ts b/src/harness/providers/openai-compatible/transcribe.test.ts index e6acce91..8c11469e 100644 --- a/src/harness/providers/openai-compatible/transcribe.test.ts +++ b/src/harness/providers/openai-compatible/transcribe.test.ts @@ -3,9 +3,14 @@ import HarnessError from "../../harness-error"; import type { HarnessCandidate } from "../../types"; let payload: unknown = { text: "hello world" }; +let request: any = null; mock.module("./provider-request", () => ({ - default: async () => ({ json: async () => payload }), + default: async (args: any) => { + request = args; + + return { json: async () => payload }; + }, })); const { default: transcribe } = await import("./transcribe"); @@ -23,6 +28,7 @@ const signal = new AbortController().signal; afterAll(() => mock.restore()); beforeEach(() => { payload = { text: "hello world" }; + request = null; }); describe("transcribe", () => { @@ -64,4 +70,82 @@ describe("transcribe", () => { expect(result.usage).toEqual({ prompt_tokens: 10, completion_tokens: 2 }); }); -}); \ No newline at end of file + + test("Alibaba's hosts are asked on the native route, not /audio/transcriptions", async () => { + payload = { output: { text: " 你好 " } }; + + const result = await transcribe({ + candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }), + audio, + signal, + }); + + expect(result.text).toBe("你好"); + expect(request.path).toBe("/api/v1/services/aigc/multimodal-generation/generation"); + expect(request.base_url).toBe("https://token-plan.ap-southeast-1.maas.aliyuncs.com"); + expect(request.form).toBeUndefined(); + expect(request.json.model).toBe("qwen-audio-3.0-asr-flash"); + expect(request.json.input.messages[0].content[0]).toEqual({ + type: "input_audio", + input_audio: { data: "data:audio/wav;base64,AQID" }, + }); + expect(request.json.parameters).toEqual({ format: "wav" }); + }); + + test("the native call labels the recording's format and cuts the language to its primary subtag", async () => { + payload = { output: { text: "hello" } }; + + await transcribe({ + candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }), + audio: { data: new Uint8Array([1, 2, 3]), format: "webm" }, + language: "en-US", + signal, + }); + + expect(request.json.input.messages[0].content[0].input_audio.data).toStartWith( + "data:audio/webm;base64,", + ); + expect(request.json.parameters).toEqual({ format: "webm", language_hints: ["en"] }); + }); + + test("a model that only transcribes as a job is refused without a call", async () => { + const error = await transcribe({ + candidate: tokenPlanCandidate({ slug: "qwen3-asr-flash-filetrans" }), + audio, + signal, + }).catch((thrown: unknown) => thrown); + + expect(error).toBeInstanceOf(HarnessError); + expect(error).toMatchObject({ retryable: false }); + expect(request).toBeNull(); + }); + + test("an ASR model on another provider keeps the OpenAI-style upload", async () => { + payload = { text: "hello" }; + + await transcribe({ + candidate: { + ...candidate, + model: { slug: "qwen3-asr-flash" }, + } as unknown as HarnessCandidate, + audio, + signal, + }); + + expect(request.path).toBe("/audio/transcriptions"); + expect(request.form).toBeInstanceOf(FormData); + }); +}); + +function tokenPlanCandidate({ slug }: { slug: string }) { + return { + key: `transcription:${slug}`, + provider: { + kind: "custom", + base_url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", + name: "Alibaba Cloud Token Plan", + }, + model: { slug }, + source: "pinned", + } as unknown as HarnessCandidate; +} \ No newline at end of file diff --git a/src/harness/providers/openai-compatible/transcribe.ts b/src/harness/providers/openai-compatible/transcribe.ts index c85c09fb..a762c529 100644 --- a/src/harness/providers/openai-compatible/transcribe.ts +++ b/src/harness/providers/openai-compatible/transcribe.ts @@ -1,10 +1,25 @@ import HarnessError from "../../harness-error"; import type { HarnessAdapter } from "../../types"; +import { isDashScopeHost } from "./dashscope-hosts"; +import transcribeNative from "./dashscope-native-transcribe"; import providerRequest from "./provider-request"; +/** + * The native Qwen-ASR models: the only synchronous speech models Alibaba's + * DashScope/Model Studio hosts serve, at their own route rather than + * `/audio/transcriptions`. + */ +const NativeAsrModel = /asr|paraformer/i; +/** + * File transcription is a job at the provider (submit, then poll), which + * this adapter doesn't run: it would queue a task and wait for nothing. + */ +const AsyncOnlyAsrModel = /filetrans|paraformer/i; + /** * `POST /audio/transcriptions` as an OpenAI-style file upload, which - * OpenRouter, OpenAI, Groq and local servers all take. + * OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts have + * no such route, so their ASR models go to the native call instead. */ const transcribe: HarnessAdapter["transcribe"] = async ({ candidate, @@ -12,6 +27,18 @@ const transcribe: HarnessAdapter["transcribe"] = async ({ language, signal, }) => { + if (isDashScopeHost({ base_url: candidate.provider.base_url }) && NativeAsrModel.test(candidate.model.slug)) { + if (AsyncOnlyAsrModel.test(candidate.model.slug)) { + throw new HarnessError({ + message: `${candidate.provider.name || "Alibaba Cloud"}: ${candidate.model.slug} only transcribes as an asynchronous job, which this harness doesn't run. Pick a synchronous ASR model such as qwen-audio-3.0-asr-flash.`, + retryable: false, + candidate_key: candidate.key, + }); + } + + return await transcribeNative({ candidate, audio, language, signal }); + } + const form = new FormData(); form.append("model", candidate.model.slug); diff --git a/src/pages/admin/bots/[bot_id]/(partials)/composer-notice.tsx b/src/pages/admin/bots/[bot_id]/(partials)/composer-notice.tsx new file mode 100644 index 00000000..c5fcbb54 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/composer-notice.tsx @@ -0,0 +1,58 @@ +import Button from "@moduletrace/twui/layout/Button"; +import Card from "@moduletrace/twui/elements/Card"; +import Span from "@moduletrace/twui/layout/Span"; +import { TriangleAlert, X } from "lucide-react"; +import { twMerge } from "tailwind-merge"; + +type Props = { + message: string; + tone?: "error" | "warning"; + onClose: () => void; +}; + +/** + * Why the last send didn't go, or why dictation stopped, under the composer. + * A card rather than a line of grey text, so a failed send reads as a + * failure, and it can be put away once read. + */ +export default function ComposerNotice({ + message, + tone = "error", + onClose, +}: Props) { + return ( + + + + {message} + + + + ); +} diff --git a/src/pages/admin/bots/[bot_id]/(partials)/composer.tsx b/src/pages/admin/bots/[bot_id]/(partials)/composer.tsx index 430c0f70..33ff2aaa 100644 --- a/src/pages/admin/bots/[bot_id]/(partials)/composer.tsx +++ b/src/pages/admin/bots/[bot_id]/(partials)/composer.tsx @@ -8,7 +8,6 @@ import { } from "react"; import Row from "@moduletrace/twui/layout/Row"; import Stack from "@moduletrace/twui/layout/Stack"; -import P from "@moduletrace/twui/layout/P"; import type { BotExtensionsPayload, BotMessageAttachment, @@ -34,10 +33,12 @@ import ComposerAttachments from "./composer-attachments"; import ComposerClearButton from "./composer-clear-button"; import ComposerEditor from "./composer-editor"; import ComposerMentionList from "./composer-mention-list"; +import ComposerNotice from "./composer-notice"; import ComposerReplyPreview from "./composer-reply-preview"; import ComposerSendButton from "./composer-send-button"; import ComposerTools from "./composer-tools"; import ComposerVoiceButton from "./composer-voice-button"; +import { twMerge } from "tailwind-merge"; /** * What the conversation can do to the composer from outside it. @@ -477,13 +478,23 @@ export default function Composer({ /> {notice ? ( -

- {notice} -

+ { + setError(undefined); + recorder.setError(undefined); + }} + /> + ) : null} +