Files
cobble/src/functions/backend/db/profile-images/set-profile-image.ts
T
tben f2802c1bf3 Let bots set a picture from a file they can see
A coordinator asked to set an uploaded logo as a workspace picture could
not: the picture tools take a media id, and nothing ever gave the bot one.
Attachments reached the model as "[Attached image \"logo.png\"]", every
file tool answers with a [file:ID] ref, and an SVG is deliberately stored
as a document rather than an image.

- copyMediaAsPicture copies an approved image into a new picture row
  (bot-image/workspace-image). The source keeps its row and bytes, so a
  message that attached it still loads and changing a picture can never
  take a file away from a conversation.
- grabPictureSource resolves a picture by [file:ID] (the same scope gate
  every file tool uses) or by the user's own upload; parseFileRef reads
  the [file:12] form.
- The new set_picture tool ships on every run: a bot sets its own face,
  the coordinator can also dress a worker. update_workspace gained
  picture_file_id, and setBotPicture/setProfileImage share the copy and
  the delete.
- removeReplacedPicture deletes a replaced picture only when it really is
  one, never a chat upload.
- uploadAndRecordMedia writes images in their own format: PNG stays PNG
  with its transparency, WebP stays WebP, GIF becomes PNG, everything
  else JPEG, and the row records the real mime type (it used to say jpeg
  for every image).
- Pictures change live: BotUpdatedData carries image_media_id and a new
  server:workspace-updated pushes workspace pictures, relayed between
  processes.
- Attachments are labelled with their media id, and BotFilesNote tells a
  bot that a [file:ID] can become a picture.
- grabRunScopes is now the single source of a run's reachable folders,
  shared by the file tools, imports and the picture tools.
2026-10-23 05:24:55 +01:00

99 lines
3.4 KiB
TypeScript

import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import grabUserBot from "@/src/functions/backend/db/bots/grab-user-bot";
import uploadAndRecordMedia from "@/src/functions/backend/db/users/media/upload-and-record-media";
import grabUserWorkspace from "@/src/functions/backend/db/workspaces/grab-user-workspace";
import type { ProfileImageTarget } from "@/src/schemas/profile-image-schema";
import AppError from "@/src/utils/app-error";
import bufferFromBase64 from "@/src/utils/buffer-from-base-64";
import assertCrewManager from "@/src/functions/backend/db/access/assert-crew-manager";
import { PictureParadigms } from "./copy-media-as-picture";
import removeReplacedPicture from "./remove-replaced-picture";
type Params = {
user_id: number | string;
target: ProfileImageTarget;
id: number | string;
/**
* The new picture as a base64 data URL; null removes it.
*/
data_url: string | null;
};
const Tables: Record<ProfileImageTarget, string> = {
bot: "bots",
workspace: "workspaces",
};
/**
* Sets (or removes) the picture of one of the user's bots or workspaces:
* a private image, the old picture deleted. Returns the new
* `image_media_id`.
*
* The picture picked here is copied into its own row
* (`PictureParadigms`), and only a picture is deleted when it is replaced
* (`removeReplacedPicture`), never a row a chat message still attaches.
*/
export default async function setProfileImage({ user_id, target, id, data_url }: Params) {
await assertCrewManager({ user_id });
const record =
target == "bot"
? await grabUserBot({ bot_id: id, user_id })
: await grabUserWorkspace({ workspace_id: id, user_id });
if (!record?.id) {
throw new AppError(target == "bot" ? `Bot not found.` : `Workspace not found.`);
}
const table = Tables[target];
let image_media_id: number | null = null;
if (data_url) {
if (!/^data:image\/(png|jpe?g|webp|gif)/i.test(data_url)) {
throw new AppError(`Pick a PNG, JPG, WebP or GIF image.`);
}
const { buffer, ext } = await bufferFromBase64(data_url);
if (buffer.length > AppData.ProfileImageMaxBytes) {
throw new AppError(
`That picture is too big. Pictures can be up to ${Math.round(AppData.ProfileImageMaxBytes / 1024 / 1024)} MB.`,
);
}
const res = await uploadAndRecordMedia({
data: buffer,
media_type: "image",
/**
* The image's own format: a transparent PNG stays a PNG
* (`imageOutputFormat`).
*/
media_mime_type: ext,
media_paradigms: [PictureParadigms[target]],
media: { title: `${record.name || target} picture` },
user: { id: Number(user_id) },
});
if (!res.singleRes?.id) {
throw new AppError(`Couldn't save the picture. Try another image.`);
}
image_media_id = Number(res.singleRes.id);
}
await BunSQLite.sql({
sql: `UPDATE ${table} SET image_media_id = ?, updated_at = ? WHERE id = ?`,
values: [image_media_id, Date.now(), record.id],
});
await removeReplacedPicture({
previous: record.image_media_id,
next: image_media_id,
user_id,
target,
});
return { image_media_id };
}