Compare commits

...
3 Commits
Author SHA1 Message Date
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
10 changed files with 380 additions and 116 deletions
+1 -1
View File
@@ -238,7 +238,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **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.24",
"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,72 @@
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();
});
});
@@ -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,72 @@
import guessModelModalities from "../../catalog/guess-model-modalities";
import type { HarnessCatalogModel } from "../../types";
/**
* 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", "image"], 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.
*/
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 input_modalities =
is_chat && guessModelModalities({ slug }).input_modalities.includes("image")
? ["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,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({