Compare commits

...
5 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 23187f160c Bump version to 0.28.25
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 12:00:24 +01:00
tbenandClaude Opus 5.5 942fba5bf1 Generate images on Cloudflare Workers AI through its native run route
Cloudflare's /ai/v1 has no images route, so every image call there failed
with 7000 No route for that URI. Image models now go to
<account>/ai/run/<model>: FLUX.2 as a multipart form with references as
input_image_<n>, the rest as JSON, retrying without width/height when a
model refuses them, and reading either the base64 envelope or raw bytes.
Only FLUX.2 models are catalogued as taking reference images.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 11:51:33 +01:00
tbenandClaude Opus 5.5 d807f1f328 Bump version to 0.28.24
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 11:13:30 +01:00
tbenandClaude Opus 5.5 a94cccfd28 List Cloudflare AI models from ai/models/search
Cloudflare's OpenAI-compatible /ai/v1 has no /models route (7001 GET not
supported), so a provider on it never synced. Read the list from the
account's ai/models/search instead, paged, with the task deciding the
modalities and function_calling deciding tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 11:13:30 +01:00
tbenandClaude Opus 5.5 422d1a78fe Open a routine's edit modal over the list when its name is clicked
The bot's routines modal now opens the shared RoutineEditModal on top
of the list (from the row's name or its Edit item) instead of swapping
the list for the form; /admin/routines opens it from the name too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-06 07:34:56 +01:00
14 changed files with 835 additions and 117 deletions
+2 -2
View File
@@ -233,12 +233,12 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
### Harness (the model layer, `src/harness/`)
- **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: the Models page's Image group says so when its pick can't take one, naming the edit model a reference call goes to, and a failure carries that note (`referenceModelNote`). One provider timeout (`HarnessError.timed_out`, the 3-minute header timeout) makes `generate_image` refuse the run's later calls instead of waiting the same span again (four attempts once took 29 minutes). 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`).
- **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: the Models page's Image group says so when its pick can't take one, naming the edit model a reference call goes to, and a failure carries that note (`referenceModelNote`). One provider timeout (`HarnessError.timed_out`, the 3-minute header timeout) makes `generate_image` refuse the run's later calls instead of waiting the same span again (four attempts once took 29 minutes). 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`). Cloudflare's AI API (`api.cloudflare.com/.../ai/v1`) has no images route either (`7000 No route for that URI`): its image models go to the native `<account>/ai/run/<model>` (`cloudflare-native-image.ts`), FLUX.2 as a multipart form with references as `input_image_<n>` (the only ones that take any, so the catalog gives only them image input), the rest as JSON, a model that refuses `width`/`height` asked again without them, the answer read from `result.image` base64 or raw image bytes.
- **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 (`<video_path>/<id>/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. Vercel AI Gateway (`ai-gateway.vercel.sh`, `vercel-gateway-hosts.ts`) has no `/v1/audio/*` either: transcription and speech go to its own `/v4/ai/transcription-model` and `/v4/ai/speech-model` on the host root, the model in the `ai-model-id` header and the audio as base64 JSON (`vercel-gateway-transcribe.ts`, `vercel-gateway-speak.ts`). Every transcript is cleaned before it is used (`cleanTranscript` in `transcribeAudio`): speaker tokens (`<|speaker:0|>`) and bracketed sound events (`[laughs]`) that Fish Audio and ElevenLabs write are dropped, so only the words reach the composer or the bot.
- **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). So does a provider's content filter refusing the transcript (a 4xx, `isContentFilterError`; the same transcript is refused on every retry), with a line saying it was the provider's filter; a filter that is down (5xx) stays retryable. Never learn a smaller window into the constant: the provider has the last word.
- **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). So does a provider's content filter refusing the transcript (a 4xx, `isContentFilterError`; the same transcript is refused on every retry), with a line saying it was the provider's filter; a filter that is down (5xx) stays retryable. Never learn a smaller window into the constant: the provider has the last word. Cloudflare's AI API (`api.cloudflare.com/client/v4/accounts/<id>/ai/v1`) has no `/models` (`7001 GET not supported`), so its list is read from `<id>/ai/models/search`, paged, with the task deciding the modalities and `function_calling` the tools (`cloudflareAiRoot`, `listCloudflareModels`).
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A failed job's retry is held to it too (`providerRetryAt`), and its face goes to waiting meanwhile: a quota resetting in nine days held a routine's retry a full day with the face still on working. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars` (a namespace of `HarnessDeferredNamespaceMin` tools or more is listed by name alone on one line: one GitHub connection's 905 tools were 148,000 characters of descriptions on every turn), and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.23",
"version": "0.28.25",
"module": "index.ts",
"type": "module",
"private": true,
+15 -1
View File
@@ -15,6 +15,10 @@ type Props = {
busy?: boolean;
onToggle: () => void;
onEdit: () => void;
/**
* What clicking its name does: opens it for editing, over the list.
*/
onOpen?: () => void;
onDelete: () => void;
/**
* Hand it to another bot where it runs.
@@ -33,7 +37,16 @@ type Props = {
* latest run left its messages in), Chat, Pause or Resume, Edit, Hand
* over and Delete.
*/
export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete, onHandOver, compact }: Props) {
export default function RoutineRow({
cron_job,
busy,
onToggle,
onEdit,
onOpen,
onDelete,
onHandOver,
compact,
}: Props) {
const title = cron_job.title || `Routine ${cron_job.id}`;
const done = Boolean(cron_job.max_runs && Number(cron_job.run_count || 0) >= cron_job.max_runs);
const chat_url = conversationHref({
@@ -58,6 +71,7 @@ export default function RoutineRow({ cron_job, busy, onToggle, onEdit, onDelete,
/>
}
title={title}
onOpen={onOpen}
badge={cron_job.enabled ? undefined : done ? "Done" : "Paused"}
subtitle={routineSubtitle({
cron_job,
@@ -0,0 +1,90 @@
import { describe, expect, test } from "bun:test";
import cloudflareAiRoot from "./cloudflare-ai-hosts";
import cloudflareModelToCatalog from "./cloudflare-model-to-catalog";
describe("cloudflareAiRoot", () => {
test("the OpenAI-compatible base maps to the account's ai root", () => {
expect(
cloudflareAiRoot({ base_url: "https://api.cloudflare.com/client/v4/accounts/abc123/ai/v1" }),
).toBe("https://api.cloudflare.com/client/v4/accounts/abc123/ai");
expect(
cloudflareAiRoot({ base_url: "https://api.cloudflare.com/client/v4/accounts/abc123/ai/v1/" }),
).toBe("https://api.cloudflare.com/client/v4/accounts/abc123/ai");
});
test("other hosts and paths are not Cloudflare's AI API", () => {
expect(cloudflareAiRoot({ base_url: "https://openrouter.ai/api/v1" })).toBeNull();
expect(cloudflareAiRoot({ base_url: "https://api.cloudflare.com/client/v4/zones" })).toBeNull();
expect(cloudflareAiRoot({ base_url: "not a url" })).toBeNull();
expect(cloudflareAiRoot({ base_url: null })).toBeNull();
});
});
describe("cloudflareModelToCatalog", () => {
test("a chat model takes its context window and function calling from its properties", () => {
const model = cloudflareModelToCatalog({
model: {
name: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
task: { name: "Text Generation" },
properties: [
{ property_id: "context_window", value: "24000" },
{ property_id: "function_calling", value: "true" },
],
},
});
expect(model).toMatchObject({
slug: "@cf/meta/llama-3.3-70b-instruct-fp8-fast",
output_modalities: ["text"],
supports_tools: true,
context_length: 24000,
});
});
test("a chat model without function calling gets no tools", () => {
const model = cloudflareModelToCatalog({
model: { name: "@cf/qwen/qwq-32b", task: { name: "Text Generation" } },
});
expect(model?.supports_tools).toBe(false);
});
test("the task decides the modality, not the id", () => {
expect(
cloudflareModelToCatalog({
model: { name: "@cf/deepgram/nova-3", task: { name: "Automatic Speech Recognition" } },
})?.output_modalities,
).toEqual(["transcription"]);
expect(
cloudflareModelToCatalog({
model: { name: "@cf/baai/bge-m3", task: { name: "Text Embeddings" } },
})?.output_modalities,
).toEqual(["embeddings"]);
});
test("tasks no harness calls are left out", () => {
expect(
cloudflareModelToCatalog({
model: { name: "@cf/meta/m2m100-1.2b", task: { name: "Translation" } },
}),
).toBeNull();
});
test("only the multipart FLUX.2 image models take reference images", () => {
expect(
cloudflareModelToCatalog({
model: { name: "@cf/black-forest-labs/flux-2-klein-9b", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text", "image"]);
expect(
cloudflareModelToCatalog({
model: { name: "@cf/leonardo/lucid-origin", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text"]);
expect(
cloudflareModelToCatalog({
model: { name: "@cf/black-forest-labs/flux-1-schnell", task: { name: "Text-to-Image" } },
})?.input_modalities,
).toEqual(["text"]);
});
});
@@ -0,0 +1,23 @@
/**
* Cloudflare's AI REST API (Workers AI and AI Gateway's unified API) at
* `https://api.cloudflare.com/client/v4/accounts/<account>/ai/v1`. Chat,
* embeddings and responses are OpenAI-compatible there, but `/v1/models`
* answers `7001 GET not supported`: the model list lives beside it, at
* `<account>/ai/models/search`. Returns that `.../ai` root, or null for any
* other host.
*/
export default function cloudflareAiRoot({ base_url }: { base_url?: string | null }) {
if (!base_url) return null;
try {
const url = new URL(base_url);
if (url.hostname != "api.cloudflare.com") return null;
const match = url.pathname.match(/^(\/client\/v4\/accounts\/[^/]+\/ai)(?:\/|$)/);
return match ? `${url.origin}${match[1]}` : null;
} catch {
return null;
}
}
@@ -0,0 +1,76 @@
import guessModelModalities from "../../catalog/guess-model-modalities";
import type { HarnessCatalogModel } from "../../types";
import isCloudflareMultipartImageModel from "./cloudflare-multipart-image-model";
/**
* One row of Cloudflare's `ai/models/search`.
*/
export type CloudflareModel = {
name?: string;
description?: string;
task?: { name?: string } | null;
properties?: { property_id?: string; value?: unknown }[] | null;
};
type Modalities = Pick<HarnessCatalogModel, "input_modalities" | "output_modalities">;
/**
* What each Cloudflare task takes and makes. Tasks the harnesses have no
* use for (classification, translation, detection) are left out.
*/
const TaskModalities: Record<string, Modalities> = {
"text generation": { input_modalities: ["text"], output_modalities: ["text"] },
"image-to-text": { input_modalities: ["text", "image"], output_modalities: ["text"] },
"text embeddings": { input_modalities: ["text"], output_modalities: ["embeddings"] },
"text-to-image": { input_modalities: ["text"], output_modalities: ["image"] },
"automatic speech recognition": { input_modalities: ["audio"], output_modalities: ["transcription"] },
"text-to-speech": { input_modalities: ["text"], output_modalities: ["speech"] },
};
function property({ model, id }: { model: CloudflareModel; id: string }) {
return model.properties?.find((entry) => entry?.property_id == id)?.value;
}
function truthy(value: unknown) {
return value === true || value === "true";
}
/**
* A Cloudflare model as the catalog keeps it, or null for a task no harness
* calls. The task decides the modalities (the id alone misreads many
* `@cf/...` names); a chat model calls tools only when Cloudflare says it
* does function calling, and reads images when the id says so. An image
* model takes reference images only when it is one of the multipart FLUX.2
* models, so a reference call never goes to one that would drop them.
*/
export default function cloudflareModelToCatalog({
model,
}: {
model: CloudflareModel;
}): HarnessCatalogModel | null {
const slug = typeof model.name == "string" ? model.name.trim() : "";
if (!slug) return null;
const modalities = TaskModalities[(model.task?.name || "").toLowerCase()];
if (!modalities) return null;
const is_chat = modalities.output_modalities.includes("text");
const context = Number(property({ model, id: "context_window" }));
const reads_images = is_chat
? guessModelModalities({ slug }).input_modalities.includes("image")
: modalities.output_modalities.includes("image") &&
isCloudflareMultipartImageModel({ slug });
const input_modalities = reads_images ? ["text", "image"] : modalities.input_modalities;
return {
slug,
name: slug,
free: false,
input_modalities,
output_modalities: modalities.output_modalities,
supports_tools: is_chat && truthy(property({ model, id: "function_calling" })),
...(Number.isFinite(context) && context > 0 ? { context_length: context } : {}),
};
}
@@ -0,0 +1,11 @@
/**
* Whether a Workers AI image model takes its input as a multipart form
* rather than JSON. The FLUX.2 models (`@cf/black-forest-labs/flux-2-dev`,
* `flux-2-klein-4b`, `flux-2-klein-9b`) declare only a `multipart` input and
* refuse a JSON body ("required properties at '/' are 'multipart'"); they are
* also the only ones that take reference images (`input_image_0`...). Every
* other text-to-image model there reads a JSON body and no reference.
*/
export default function isCloudflareMultipartImageModel({ slug }: { slug: string }) {
return /^@cf\/black-forest-labs\/flux-2-/i.test(slug.trim());
}
@@ -0,0 +1,148 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import HarnessError from "../../harness-error";
import type { HarnessCandidate } from "../../types";
/**
* Workers AI makes images only at `<account>/ai/run/<model>` (its `/ai/v1`
* has no images route), and its models differ: FLUX.2 takes a multipart form
* with references as `input_image_<n>`, the rest JSON; most answer a base64
* envelope, some the bytes themselves; flux-1-schnell refuses a size.
*/
let calls: any[] = [];
let respond: (params: any) => Promise<any>;
mock.module("./provider-request", () => ({
default: async (params: any) => {
calls.push(params);
return await respond(params);
},
}));
const { default: generateImage } = await import("./generate-image");
afterAll(() => mock.restore());
const jpeg = Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
const envelope = () =>
new Response(JSON.stringify({ result: { image: Buffer.from(jpeg).toString("base64") }, success: true }), {
headers: { "content-type": "application/json" },
});
const signal = new AbortController().signal;
const candidate = (slug: string): HarnessCandidate => ({
key: `18:${slug}`,
provider: {
kind: "custom",
name: "Cloudflare",
base_url: "https://api.cloudflare.com/client/v4/accounts/abc123/ai/v1",
},
model: { slug, input_modalities: ["text"], output_modalities: ["image"], supports_tools: false },
source: "pinned",
});
const reference = `data:image/png;base64,${Buffer.from("ref-bytes").toString("base64")}`;
beforeEach(() => {
calls = [];
respond = async () => envelope();
});
describe("generateImage on Cloudflare Workers AI", () => {
test("FLUX.2 posts a multipart form to the native run route", async () => {
const out = await generateImage({
candidate: candidate("@cf/black-forest-labs/flux-2-klein-9b"),
prompt: "a cube",
size: "512x768",
references: [reference],
signal,
});
expect(calls[0].base_url).toBe("https://api.cloudflare.com/client/v4/accounts/abc123/ai");
expect(calls[0].path).toBe("/run/@cf/black-forest-labs/flux-2-klein-9b");
expect(calls[0].json).toBeUndefined();
const form: FormData = calls[0].form;
expect(form.get("prompt")).toBe("a cube");
expect(form.get("width")).toBe("512");
expect(form.get("height")).toBe("768");
expect(form.get("input_image_0")).toBeInstanceOf(Blob);
expect(out.images[0]).toEqual({ data: jpeg, media_type: "image/jpeg" });
});
test("other models get JSON, and raw image bytes are read as they are", async () => {
respond = async () => new Response(jpeg, { headers: { "content-type": "image/jpeg" } });
const out = await generateImage({
candidate: candidate("@cf/leonardo/phoenix-1.0"),
prompt: "a cube",
size: "1024x1024",
signal,
});
expect(calls[0].json).toEqual({ prompt: "a cube", width: 1024, height: 1024 });
expect(out.images[0]).toEqual({ data: jpeg, media_type: "image/jpeg" });
});
test("a model that refuses the size is asked again without it, and remembered", async () => {
respond = async (params) => {
if (params.json.width) {
throw new HarnessError({
message:
"Cloudflare: AiError: Bad input: Error: Additional or unevaluated properties '/width, /height' at '/' not allowed",
status: 400,
retryable: false,
});
}
return envelope();
};
const model = candidate("@cf/black-forest-labs/flux-1-schnell");
await generateImage({ candidate: model, prompt: "a cube", size: "512x512", signal });
expect(calls.map((call) => call.json)).toEqual([
{ prompt: "a cube", width: 512, height: 512 },
{ prompt: "a cube" },
]);
calls = [];
await generateImage({ candidate: model, prompt: "a cube", size: "512x512", signal });
expect(calls.map((call) => call.json)).toEqual([{ prompt: "a cube" }]);
});
test("n images are n calls", async () => {
const out = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
n: 2,
signal,
});
expect(calls).toHaveLength(2);
expect(out.images).toHaveLength(2);
});
test("references to a model that takes none are refused, not dropped", async () => {
const failure = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
references: [reference],
signal,
}).catch((error) => error);
expect(failure).toBeInstanceOf(HarnessError);
expect(failure.retryable).toBe(false);
expect(calls).toHaveLength(0);
});
test("an answer with no image is a retryable failure", async () => {
respond = async () => new Response(JSON.stringify({ result: {} }), { headers: { "content-type": "application/json" } });
const failure = await generateImage({
candidate: candidate("@cf/leonardo/lucid-origin"),
prompt: "a cube",
signal,
}).catch((error) => error);
expect(failure).toBeInstanceOf(HarnessError);
expect(failure.retryable).toBe(true);
});
});
@@ -0,0 +1,254 @@
import { AppData } from "@/src/data/app-data";
import HarnessError from "../../harness-error";
import type { HarnessCandidate, HarnessImageOutput } from "../../types";
import isCloudflareMultipartImageModel from "./cloudflare-multipart-image-model";
import providerRequest from "./provider-request";
import referenceBlob from "./reference-blob";
type Params = {
candidate: HarnessCandidate;
/**
* `https://api.cloudflare.com/client/v4/accounts/<account>/ai`.
*/
root: string;
prompt: string;
n?: number;
size?: string;
references?: string[];
signal: AbortSignal;
};
const PixelSize = /^(\d+)\s*[x*]\s*(\d+)$/i;
const MaxImagesPerCall = 4;
/**
* Models that refused `width`/`height` in this process
* (`@cf/black-forest-labs/flux-1-schnell` answers "Additional or unevaluated
* properties '/width, /height' at '/' not allowed"), so their next call
* leaves the size out instead of spending a refusal on it again.
*/
const NoSizeModels = new Set<string>();
/**
* Image generation on Cloudflare's Workers AI. Its OpenAI-compatible
* `/ai/v1` has no images route (`7000 No route for that URI`), so the call
* goes to the native `POST <account>/ai/run/<model>`, which differs by model:
* the FLUX.2 models take a multipart form (references as `input_image_0`...),
* the rest a JSON body; most answer `{ result: { image: <base64> } }`, some
* (`@cf/leonardo/phoenix-1.0`) the image bytes themselves. Each call makes
* one image, so `n` is that many calls.
*/
export default async function generateImageCloudflare({
candidate,
root,
prompt,
n,
size,
references = [],
signal,
}: Params): Promise<{ images: HarnessImageOutput[] }> {
const { provider, model } = candidate;
const name = provider.name || "Cloudflare";
const multipart = isCloudflareMultipartImageModel({ slug: model.slug });
if (references.length && !multipart) {
throw new HarnessError({
message: `${name}: ${model.slug} takes no reference images on Workers AI. Pick a FLUX.2 model (@cf/black-forest-labs/flux-2-...) for image editing in Settings > Models.`,
retryable: false,
candidate_key: candidate.key,
});
}
const count = Math.min(Math.max(Math.floor(n || 1), 1), MaxImagesPerCall);
const images: HarnessImageOutput[] = [];
for (let index = 0; index < count; index++) {
images.push(
await runImageModel({ candidate, root, prompt, size, references, multipart, signal }),
);
}
return { images };
}
type RunParams = {
candidate: HarnessCandidate;
root: string;
prompt: string;
size?: string;
references: string[];
multipart: boolean;
signal: AbortSignal;
};
/**
* One `ai/run` call, retried once without the size when the model's schema
* refuses `width`/`height`.
*/
async function runImageModel(params: RunParams): Promise<HarnessImageOutput> {
const { candidate } = params;
const pixels = NoSizeModels.has(candidate.model.slug) ? undefined : pixelSize(params);
try {
return await requestImage({ ...params, pixels });
} catch (error: unknown) {
if (!pixels || !refusedSize({ error })) throw error;
NoSizeModels.add(candidate.model.slug);
return await requestImage({ ...params, pixels: undefined });
}
}
async function requestImage({
candidate,
root,
prompt,
references,
multipart,
signal,
pixels,
}: RunParams & { pixels?: { width: number; height: number } }): Promise<HarnessImageOutput> {
const { provider, model } = candidate;
const path = `/run/${model.slug}`;
const res = multipart
? await providerRequest({
provider,
base_url: root,
path,
form: await imageForm({ prompt, pixels, references, signal }),
signal,
candidate_key: candidate.key,
})
: await providerRequest({
provider,
base_url: root,
path,
json: { prompt, ...(pixels || {}) },
signal,
candidate_key: candidate.key,
});
return await readImage({ res, candidate });
}
/**
* The FLUX.2 form: the prompt, the size and each reference as
* `input_image_<n>` (a plain `image` field is ignored, not refused).
*/
async function imageForm({
prompt,
pixels,
references,
signal,
}: {
prompt: string;
pixels?: { width: number; height: number };
references: string[];
signal: AbortSignal;
}) {
const form = new FormData();
form.append("prompt", prompt);
if (pixels) {
form.append("width", String(pixels.width));
form.append("height", String(pixels.height));
}
const kept = references.slice(0, AppData.ImageReferenceMaxCount);
for (let index = 0; index < kept.length; index++) {
const { blob, ext } = await referenceBlob({ url: kept[index]!, signal });
form.append(`input_image_${index}`, blob, `reference-${index + 1}.${ext}`);
}
return form;
}
/**
* The picture from either answer: the bytes themselves under an `image/*`
* content type, or the JSON envelope's base64 `result.image`.
*/
async function readImage({
res,
candidate,
}: {
res: Response;
candidate: HarnessCandidate;
}): Promise<HarnessImageOutput> {
const name = candidate.provider.name || "Cloudflare";
const type = (res.headers.get("content-type") || "").split(";")[0]!.trim().toLowerCase();
if (type.startsWith("image/")) {
const data = new Uint8Array(await res.arrayBuffer());
if (data.length > AppData.HarnessImageDownloadMaxBytes) {
throw new HarnessError({
message: `${name}: the image ${candidate.model.slug} sent is larger than the app keeps.`,
retryable: false,
candidate_key: candidate.key,
});
}
if (data.length) return { data, media_type: type };
} else {
const json: any = await res.json().catch(() => null);
const encoded =
typeof json?.result?.image == "string"
? json.result.image
: typeof json?.result == "string"
? json.result
: "";
if (encoded) {
const data = Uint8Array.from(Buffer.from(encoded, "base64"));
return { data, media_type: sniffImageType({ data }) };
}
}
throw new HarnessError({
message: `${name}: no image came back from ${candidate.model.slug}.`,
retryable: true,
candidate_key: candidate.key,
});
}
function pixelSize({ size }: { size?: string }) {
const pair = size?.trim().match(PixelSize);
if (!pair) return undefined;
const width = Number(pair[1]);
const height = Number(pair[2]);
return width > 0 && height > 0 ? { width, height } : undefined;
}
/**
* Workers AI's schema refusal of the size fields, e.g. `5006 Bad input:
* Additional or unevaluated properties '/width, /height' at '/' not allowed`.
*/
function refusedSize({ error }: { error: unknown }) {
if (!(error instanceof HarnessError) || error.status != 400) return false;
const refused = error.message.match(/unevaluated properties '([^']*)'/i)?.[1] || "";
return /\/(width|height)\b/.test(refused);
}
/**
* The image type from its first bytes: the base64 answer names none, and the
* FLUX models send JPEG.
*/
function sniffImageType({ data }: { data: Uint8Array }) {
if (data[0] == 0xff && data[1] == 0xd8) return "image/jpeg";
if (data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47) return "image/png";
if (data[0] == 0x52 && data[1] == 0x49 && data[2] == 0x46 && data[3] == 0x46 && data[8] == 0x57)
return "image/webp";
return "image/png";
}
@@ -2,6 +2,8 @@ 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 cloudflareAiRoot from "./cloudflare-ai-hosts";
import generateImageCloudflare from "./cloudflare-native-image";
import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts";
import downloadProviderFile from "./download-provider-file";
import generateImageNative from "./dashscope-native-image";
@@ -23,6 +25,9 @@ import referenceBlob from "./reference-blob";
* `multimodal-generation` call at the host root, so that call goes there
* directly. A workspace Model Studio host that answers 404 or 405 on the
* compatible route falls back to the same native call.
*
* Cloudflare's AI API has no images route under `/ai/v1` either: its image
* models answer only at the native `<account>/ai/run/<model>`.
*/
const generateImage: HarnessAdapter["generateImage"] = async ({
candidate,
@@ -35,6 +40,20 @@ const generateImage: HarnessAdapter["generateImage"] = async ({
const { provider } = candidate;
const preset = grabProviderPreset({ kind: provider.kind });
const cloudflare_root = cloudflareAiRoot({ base_url: provider.base_url });
if (cloudflare_root) {
return await generateImageCloudflare({
candidate,
root: cloudflare_root,
prompt,
n,
size,
references,
signal,
});
}
if (isTokenPlanHost({ base_url: provider.base_url })) {
return await generateImageNative({ candidate, prompt, n, size, references, signal });
}
@@ -0,0 +1,65 @@
import HarnessError from "../../harness-error";
import type { HarnessCatalogModel, HarnessProviderConfig } from "../../types";
import cloudflareModelToCatalog, { type CloudflareModel } from "./cloudflare-model-to-catalog";
import providerRequest from "./provider-request";
const PerPage = 100;
/**
* A bound on the paging, far past the catalog's size, so a listing that
* never says it is done can't loop.
*/
const MaxPages = 30;
type Params = {
provider: HarnessProviderConfig;
/**
* `https://api.cloudflare.com/client/v4/accounts/<account>/ai`.
*/
root: string;
signal?: AbortSignal;
};
/**
* Every model Cloudflare's `ai/models/search` lists, page by page, kept to
* the tasks a harness calls. Its `/ai/v1/models` doesn't exist.
*/
export default async function listCloudflareModels({
provider,
root,
signal,
}: Params): Promise<HarnessCatalogModel[]> {
const rows: CloudflareModel[] = [];
for (let page = 1; page <= MaxPages; page++) {
const res = await providerRequest({
provider,
base_url: root,
path: `/models/search?per_page=${PerPage}&page=${page}`,
method: "GET",
signal,
});
const json = await res.json().catch(() => null);
if (!json || !Array.isArray(json.result)) {
throw new HarnessError({
message: `${provider.name || "Cloudflare"} returned an unreadable model list.`,
retryable: true,
});
}
rows.push(...json.result);
if (json.result.length < PerPage) break;
}
const seen = new Set<string>();
return rows
.map((model) => cloudflareModelToCatalog({ model }))
.filter((model): model is HarnessCatalogModel => {
if (!model || seen.has(model.slug)) return false;
seen.add(model.slug);
return true;
});
}
@@ -5,6 +5,8 @@ import grabProviderPreset from "../grab-provider-preset";
import openRouterModelToCatalog, {
type OpenRouterModel,
} from "../openrouter/openrouter-model-to-catalog";
import cloudflareAiRoot from "./cloudflare-ai-hosts";
import listCloudflareModels from "./list-cloudflare-models";
import providerRequest from "./provider-request";
/**
@@ -19,6 +21,23 @@ const listModels: HarnessAdapter["listModels"] = async ({
}) => {
const preset = grabProviderPreset({ kind: provider.kind });
const is_openrouter = preset.catalog == "openrouter";
const cloudflare_root = cloudflareAiRoot({ base_url: provider.base_url });
/**
* Cloudflare's `/ai/v1` has no `/models`; its list is `ai/models/search`.
*/
if (cloudflare_root) {
const models = await listCloudflareModels({ provider, root: cloudflare_root, signal });
if (models.length === 0) {
throw new HarnessError({
message: `${provider.name || preset.title} returned an empty model list.`,
retryable: true,
});
}
return models;
}
const res = await providerRequest({
provider,
@@ -10,7 +10,7 @@ import { Clock } from "lucide-react";
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import type { BotWithLastMessage, CronJobWithNames } from "@/src/types";
import HandOverForm from "@/src/components/general/hand-over-form";
import RoutineForm from "@/src/components/general/routine-form";
import RoutineEditModal from "@/src/components/general/routine-edit-modal";
import RoutineRow from "@/src/components/general/routine-row";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import SettingsList from "@/src/pages/admin/settings/(partials)/settings-list";
@@ -108,124 +108,122 @@ export default function BotRoutinesModal({ bot, workspace, menu, on_open, comman
};
return (
<Modal
target={
menu ? (
<HeaderMenuItem icon={Clock} title="Schedules" description={title} loading={loading} />
) : (
<Button
title={title}
type="button"
variant="ghost"
color="text"
className="shrink-0 p-2! text-ink-secondary hover:text-ink hover:bg-sunken rounded-default"
>
<Clock size={18} aria-hidden />
</Button>
)
}
targetWrapperProps={{ className: menu ? "w-full" : "shrink-0" }}
open={open}
setOpen={(next) => {
set_open(next);
if (!next) {
set_editing(undefined);
set_handing(undefined);
set_status(undefined);
}
}}
className="max-w-xl bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">
{editing ? editing.title || "Routine" : handing ? `Hand over ${handing.title || "the routine"}` : title}
</H2>
{editing || handing ? (
<>
<Modal
target={
menu ? (
<HeaderMenuItem icon={Clock} title="Schedules" description={title} loading={loading} />
) : (
<Button
title="Back to the list"
title={title}
type="button"
variant="ghost"
color="gray"
size="small"
onClick={() => {
set_editing(undefined);
set_handing(undefined);
set_status(undefined);
}}
className="px-2! text-[12px]"
color="text"
className="shrink-0 p-2! text-ink-secondary hover:text-ink hover:bg-sunken rounded-default"
>
Back
<Clock size={18} aria-hidden />
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{editing
? `${name} gets this brief as a task at every run, and the result lands here.`
: handing
? `It keeps its schedule and where it runs; from then on its results land in the new bot's conversation.`
: workspace?.id
? `Work ${name} does on a schedule in ${place}. Each run is a task, and its result lands here.`
: `Work ${name} does on its own, on a schedule. Each run is a task, and its result lands here.`}
</Span>
</Stack>
)
}
targetWrapperProps={{ className: menu ? "w-full" : "shrink-0" }}
open={open}
setOpen={(next) => {
set_open(next);
<Stack className="mt-4 max-h-[55vh] w-full gap-0! items-stretch overflow-y-auto">
{editing ? (
<RoutineForm
key={editing.id}
cron_job={editing}
onCancel={() => set_editing(undefined)}
onSaved={({ cron_job }) => {
replace({ cron_job });
set_editing(undefined);
set_status({ success: true, msg: "Saved." });
}}
/>
) : handing ? (
<HandOverForm<CronJobWithNames>
key={handing.id}
what={`"${handing.title}"`}
targets_path="routines/hand-over-targets"
submit_path="routines/hand-over-routine"
body={{ cron_job_id: handing.id }}
onCancel={() => set_handing(undefined)}
onHandedOver={({ saved, msg }) => {
setRoutines((prev) => dropRoutine({ routines: prev, cron_job_id: saved.id }));
set_handing(undefined);
set_status({ success: true, msg });
}}
/>
) : (
<SettingsList
is_empty={!routines.length}
empty={loading ? "Loading routines..." : error || "No routines here yet."}
>
{routines.map((cron_job) => (
<RoutineRow
key={cron_job.id}
cron_job={cron_job}
compact
busy={busy}
onToggle={() => toggle({ cron_job }).catch(() => {})}
onEdit={() => set_editing(cron_job)}
onHandOver={() => set_handing(cron_job)}
onDelete={() => remove({ cron_job }).catch(() => {})}
/>
))}
</SettingsList>
)}
</Stack>
<Stack className="mt-3 gap-1! items-stretch">
<SettingsStatus status={status} />
{editing || handing ? null : (
<Span className="text-[12px] leading-4 text-ink-secondary">
{`Ask ${name} in chat to set one up, or change one here.`}
if (!next) {
set_editing(undefined);
set_handing(undefined);
set_status(undefined);
}
}}
className="max-w-xl bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">
{handing ? `Hand over ${handing.title || "the routine"}` : title}
</H2>
{handing ? (
<Button
title="Back to the list"
type="button"
variant="ghost"
color="gray"
size="small"
onClick={() => {
set_handing(undefined);
set_status(undefined);
}}
className="px-2! text-[12px]"
>
Back
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{handing
? `It keeps its schedule and where it runs; from then on its results land in the new bot's conversation.`
: workspace?.id
? `Work ${name} does on a schedule in ${place}. Each run is a task, and its result lands here.`
: `Work ${name} does on its own, on a schedule. Each run is a task, and its result lands here.`}
</Span>
)}
</Stack>
</Modal>
</Stack>
<Stack className="mt-4 max-h-[55vh] w-full gap-0! items-stretch overflow-y-auto">
{handing ? (
<HandOverForm<CronJobWithNames>
key={handing.id}
what={`"${handing.title}"`}
targets_path="routines/hand-over-targets"
submit_path="routines/hand-over-routine"
body={{ cron_job_id: handing.id }}
onCancel={() => set_handing(undefined)}
onHandedOver={({ saved, msg }) => {
setRoutines((prev) => dropRoutine({ routines: prev, cron_job_id: saved.id }));
set_handing(undefined);
set_status({ success: true, msg });
}}
/>
) : (
<SettingsList
is_empty={!routines.length}
empty={loading ? "Loading routines..." : error || "No routines here yet."}
>
{routines.map((cron_job) => (
<RoutineRow
key={cron_job.id}
cron_job={cron_job}
compact
busy={busy}
onToggle={() => toggle({ cron_job }).catch(() => {})}
onEdit={() => set_editing(cron_job)}
onOpen={() => set_editing(cron_job)}
onHandOver={() => set_handing(cron_job)}
onDelete={() => remove({ cron_job }).catch(() => {})}
/>
))}
</SettingsList>
)}
</Stack>
<Stack className="mt-3 gap-1! items-stretch">
<SettingsStatus status={status} />
{handing ? null : (
<Span className="text-[12px] leading-4 text-ink-secondary">
{`Ask ${name} in chat to set one up, or change one here.`}
</Span>
)}
</Stack>
</Modal>
<RoutineEditModal
cron_job={editing}
onClose={() => set_editing(undefined)}
onSaved={({ cron_job }) => {
replace({ cron_job });
set_editing(undefined);
set_status({ success: true, msg: "Saved." });
}}
/>
</>
);
}
@@ -56,6 +56,7 @@ export default function RoutinesSection() {
busy={busy}
onToggle={() => toggle({ cron_job })}
onEdit={() => setEditing(cron_job)}
onOpen={() => setEditing(cron_job)}
onHandOver={() => setHanding(cron_job)}
onDelete={() =>
remove({