Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ace6a61a1a | ||
|
|
d7ce96339b | ||
|
|
c60402831f | ||
|
|
b0bad82b78 |
@@ -90,7 +90,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
|
||||
@@ -205,6 +205,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`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech and embedding have no automatic picks: unavailable until a model is picked.
|
||||
- **Images:** `generate_image` 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; `HarnessFallbacks` hands it to `image` while unpicked or off, and after its pick fails when `fallback` is on), 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`).
|
||||
- **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`.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`), trims old tool output to fit context. 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; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.12.1",
|
||||
"version": "0.12.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -367,6 +367,16 @@ export const AppData = {
|
||||
*/
|
||||
ImageReferenceMaxCount: 4,
|
||||
ImageReferenceMaxBytes: 10 * 1024 * 1024,
|
||||
/**
|
||||
* `transform_image`: the largest source file and source (in pixels) it
|
||||
* opens, the longest side a result may have, the steps one call takes,
|
||||
* and the longest side of the preview the bot looks at afterwards.
|
||||
*/
|
||||
ImageTransformMaxBytes: 25 * 1024 * 1024,
|
||||
ImageTransformMaxInputPixels: 100_000_000,
|
||||
ImageTransformMaxDimension: 8192,
|
||||
ImageTransformMaxOperations: 12,
|
||||
ImageTransformPreviewMaxSide: 1024,
|
||||
/**
|
||||
* Connecting to an MCP server (a computer) gives up after this long.
|
||||
*/
|
||||
|
||||
@@ -72,7 +72,7 @@ export const botFilesNote = ({ bot_id }: { bot_id: number | string }) => `# Your
|
||||
|
||||
You have a folder of your own, kept with the app (not on a computer), and it stays between runs and conversations.
|
||||
|
||||
- list_files shows what's in it; read_file opens one (by its [file:ID] ref or path); write_file saves a text file, make_pdf a PDF, generate_image an image. Move and delete with move_file and delete_file when something is out of date, so the folder stays useful.
|
||||
- list_files shows what's in it; read_file opens one (by its [file:ID] ref or path); write_file saves a text file, make_pdf a PDF, generate_image an image; transform_image crops, resizes, rotates or adjusts an image you have (no model needed, so use it rather than generate_image when the user wants the same picture cut or changed). Move and delete with move_file and delete_file when something is out of date, so the folder stays useful.
|
||||
- Files are found by name or path, never by what's in them: list_files with "search" matches names and paths, then read_file reads the one you want. Look for a file and read it before saying you don't know something it may hold, and when the user asks about a document they gave you. Searching by content is what knowledgebases are for; your files aren't indexed.
|
||||
- Uploaded files land in the same folder, under uploads/ (uploads/2026-10/logo.png), so what the user sent you earlier is there to list and read later too.
|
||||
- A picture can be set from a file: set_picture makes a file your own avatar, and update_workspace sets a workspace's. Both take the [file:ID] ref, so a logo the user sent you is usually ready to go: list_files for it, then set it. An SVG or another kind of file is turned into a PNG first. Its picture is free to change and never removes your file.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
const Side = z.number().int().positive().max(AppData.ImageTransformMaxDimension);
|
||||
|
||||
/**
|
||||
* One step of an `transform_image` call. Strict, so a misnamed field is refused
|
||||
* instead of silently dropped (a crop with `w` for `width` would otherwise
|
||||
* fail as "no width").
|
||||
*/
|
||||
export const ImageTransformOperationSchema = z.discriminatedUnion("op", [
|
||||
z
|
||||
.object({
|
||||
op: z.literal("crop"),
|
||||
x: z.number().min(0).describe(`Left edge of the box`),
|
||||
y: z.number().min(0).describe(`Top edge of the box`),
|
||||
width: z.number().positive(),
|
||||
height: z.number().positive(),
|
||||
unit: z
|
||||
.enum(["px", "percent"])
|
||||
.optional()
|
||||
.describe(`"px" (default) or "percent" of the image's width and height`),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
op: z.literal("resize"),
|
||||
width: Side.optional(),
|
||||
height: Side.optional(),
|
||||
fit: z
|
||||
.enum(["inside", "cover", "contain", "fill"])
|
||||
.optional()
|
||||
.describe(
|
||||
`With both sides: "inside" (default) keeps the aspect ratio within the box, "cover" fills it and crops the overflow, "contain" fits it and pads with transparency, "fill" stretches`,
|
||||
),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
op: z.literal("rotate"),
|
||||
degrees: z.number().min(-360).max(360).describe(`Clockwise; other than 90s leave transparent corners`),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ op: z.literal("flip"), direction: z.enum(["horizontal", "vertical"]) }).strict(),
|
||||
z.object({ op: z.literal("grayscale") }).strict(),
|
||||
z.object({ op: z.literal("blur"), sigma: z.number().min(0.3).max(100).optional() }).strict(),
|
||||
z.object({ op: z.literal("sharpen"), sigma: z.number().min(0.01).max(10).optional() }).strict(),
|
||||
z
|
||||
.object({
|
||||
op: z.literal("adjust"),
|
||||
brightness: z.number().min(0).max(10).optional().describe(`1 is unchanged`),
|
||||
saturation: z.number().min(0).max(10).optional().describe(`1 is unchanged, 0 grey`),
|
||||
hue: z.number().min(-360).max(360).optional().describe(`Degrees to turn the hues`),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
op: z.literal("trim"),
|
||||
threshold: z
|
||||
.number()
|
||||
.min(0)
|
||||
.max(255)
|
||||
.optional()
|
||||
.describe(`How different from the corner colour a pixel must be to stay (default 10)`),
|
||||
})
|
||||
.strict(),
|
||||
]);
|
||||
|
||||
export type ImageTransformOperation = z.infer<typeof ImageTransformOperationSchema>;
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import sharp from "sharp";
|
||||
import transformImage from "./transform-image";
|
||||
import { ImageTransformOperationSchema } from "./image-transform-operations";
|
||||
|
||||
/**
|
||||
* A 200x100 PNG: left half red, right half blue.
|
||||
*/
|
||||
async function halves() {
|
||||
const red = await sharp({
|
||||
create: { width: 100, height: 100, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } },
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
|
||||
return new Uint8Array(
|
||||
await sharp({
|
||||
create: { width: 200, height: 100, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } },
|
||||
})
|
||||
.composite([{ input: red, left: 0, top: 0 }])
|
||||
.png()
|
||||
.toBuffer(),
|
||||
);
|
||||
}
|
||||
|
||||
async function pixel({ data, x, y }: { data: Uint8Array; x: number; y: number }) {
|
||||
const { data: raw, info } = await sharp(data).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
const at = (y * info.width + x) * 4;
|
||||
|
||||
return [raw[at], raw[at + 1], raw[at + 2]];
|
||||
}
|
||||
|
||||
describe("transformImage", () => {
|
||||
test("crops in pixels", async () => {
|
||||
const result = await transformImage({
|
||||
data: await halves(),
|
||||
operations: [{ op: "crop", x: 120, y: 10, width: 50, height: 40 }],
|
||||
format: "png",
|
||||
});
|
||||
|
||||
expect([result.width, result.height]).toEqual([50, 40]);
|
||||
expect([result.source_width, result.source_height]).toEqual([200, 100]);
|
||||
expect(await pixel({ data: result.data, x: 0, y: 0 })).toEqual([0, 0, 255]);
|
||||
});
|
||||
|
||||
test("crops in percent and clamps a box running off the edge", async () => {
|
||||
const result = await transformImage({
|
||||
data: await halves(),
|
||||
operations: [{ op: "crop", x: 0, y: 0, width: 50, height: 500, unit: "percent" }],
|
||||
format: "png",
|
||||
});
|
||||
|
||||
expect([result.width, result.height]).toEqual([100, 100]);
|
||||
expect(await pixel({ data: result.data, x: 99, y: 99 })).toEqual([255, 0, 0]);
|
||||
});
|
||||
|
||||
test("refuses a box outside the image, naming the step", async () => {
|
||||
await expect(
|
||||
transformImage({
|
||||
data: await halves(),
|
||||
operations: [{ op: "crop", x: 300, y: 0, width: 10, height: 10 }],
|
||||
format: "png",
|
||||
}),
|
||||
).rejects.toThrow("Step 1 (crop)");
|
||||
});
|
||||
|
||||
test("runs steps in the order given", async () => {
|
||||
const result = await transformImage({
|
||||
data: await halves(),
|
||||
operations: [
|
||||
{ op: "flip", direction: "horizontal" },
|
||||
{ op: "crop", x: 0, y: 0, width: 100, height: 100 },
|
||||
{ op: "resize", width: 10 },
|
||||
],
|
||||
format: "png",
|
||||
});
|
||||
|
||||
expect([result.width, result.height]).toEqual([10, 10]);
|
||||
expect(await pixel({ data: result.data, x: 5, y: 5 })).toEqual([0, 0, 255]);
|
||||
});
|
||||
|
||||
test("rotates by quarter turns", async () => {
|
||||
const result = await transformImage({
|
||||
data: await halves(),
|
||||
operations: [{ op: "rotate", degrees: 90 }],
|
||||
format: "jpeg",
|
||||
});
|
||||
|
||||
expect([result.width, result.height]).toEqual([100, 200]);
|
||||
});
|
||||
|
||||
test("refuses SVG", async () => {
|
||||
const svg = new TextEncoder().encode(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>`,
|
||||
);
|
||||
|
||||
await expect(transformImage({ data: svg, operations: [], format: "png" })).rejects.toThrow("isn't an image");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ImageTransformOperationSchema", () => {
|
||||
test("refuses a misnamed field rather than dropping it", () => {
|
||||
expect(ImageTransformOperationSchema.safeParse({ op: "crop", x: 0, y: 0, w: 10, height: 10 }).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import sharp, { type OutputInfo } from "sharp";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import type { ImageTransformOperation } from "./image-transform-operations";
|
||||
|
||||
/**
|
||||
* Formats a transform reads. Never SVG: it's a document, not pixels, and what
|
||||
* it references would be fetched while rendering.
|
||||
*/
|
||||
const TransformableFormats = ["jpeg", "png", "webp", "gif", "avif", "tiff"];
|
||||
|
||||
export type ImageTransformFormat = "png" | "jpeg" | "webp";
|
||||
|
||||
type Params = {
|
||||
data: Uint8Array;
|
||||
/**
|
||||
* Applied in order, each on the result of the one before.
|
||||
*/
|
||||
operations: ImageTransformOperation[];
|
||||
format: ImageTransformFormat;
|
||||
/**
|
||||
* 1 to 100, for JPEG and WebP.
|
||||
*/
|
||||
quality?: number;
|
||||
};
|
||||
|
||||
type Raw = { data: Buffer; info: OutputInfo };
|
||||
|
||||
/**
|
||||
* Transforms an image with sharp (no model: the `image_edit` harness is
|
||||
* `generate_image` with references), one operation at a time on raw pixels, so the
|
||||
* order is the bot's (sharp's own pipeline runs its steps in a fixed order)
|
||||
* and nothing is re-compressed between steps. The source is turned upright
|
||||
* by its EXIF orientation first, so coordinates match what the bot saw.
|
||||
* Only the first frame of an animation is kept. Throws `AppError` with a
|
||||
* message for the bot when an operation can't apply.
|
||||
*/
|
||||
export default async function transformImage({
|
||||
data,
|
||||
operations,
|
||||
format,
|
||||
quality,
|
||||
}: Params): Promise<{
|
||||
data: Uint8Array;
|
||||
width: number;
|
||||
height: number;
|
||||
source_width: number;
|
||||
source_height: number;
|
||||
}> {
|
||||
const meta = await sharp(data, { limitInputPixels: AppData.ImageTransformMaxInputPixels })
|
||||
.metadata()
|
||||
.catch(() => null);
|
||||
|
||||
if (!meta?.format || !TransformableFormats.includes(meta.format)) {
|
||||
throw new AppError(`That file isn't an image this tool can transform (PNG, JPEG, WebP, GIF, AVIF or TIFF).`);
|
||||
}
|
||||
|
||||
let current: Raw = await sharp(data, { limitInputPixels: AppData.ImageTransformMaxInputPixels })
|
||||
.rotate()
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
|
||||
const source_width = current.info.width;
|
||||
const source_height = current.info.height;
|
||||
|
||||
for (let index = 0; index < operations.length; index++) {
|
||||
const operation = operations[index]!;
|
||||
|
||||
try {
|
||||
current = await applyOperation({ current, operation });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
|
||||
throw new AppError(
|
||||
`Step ${index + 1} (${operation.op}) failed on a ${current.info.width}x${current.info.height} image: ${message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let output = sharp(current.data, { raw: rawInput({ info: current.info }) });
|
||||
|
||||
if (format == "jpeg") {
|
||||
output = output.flatten({ background: "#ffffff" }).jpeg({ quality: quality || 85, mozjpeg: true });
|
||||
} else if (format == "webp") {
|
||||
output = output.webp({ quality: quality || 85 });
|
||||
} else {
|
||||
output = output.png({ compressionLevel: 9 });
|
||||
}
|
||||
|
||||
return {
|
||||
data: new Uint8Array(await output.toBuffer()),
|
||||
width: current.info.width,
|
||||
height: current.info.height,
|
||||
source_width,
|
||||
source_height,
|
||||
};
|
||||
}
|
||||
|
||||
function rawInput({ info }: { info: OutputInfo }) {
|
||||
return { width: info.width, height: info.height, channels: info.channels as 1 | 2 | 3 | 4 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one operation on raw pixels and returns raw pixels.
|
||||
*/
|
||||
async function applyOperation({
|
||||
current,
|
||||
operation,
|
||||
}: {
|
||||
current: Raw;
|
||||
operation: ImageTransformOperation;
|
||||
}): Promise<Raw> {
|
||||
const { width, height } = current.info;
|
||||
let image = sharp(current.data, { raw: rawInput({ info: current.info }) });
|
||||
|
||||
switch (operation.op) {
|
||||
case "crop": {
|
||||
const percent = operation.unit == "percent";
|
||||
const left = Math.round(percent ? (operation.x / 100) * width : operation.x);
|
||||
const top = Math.round(percent ? (operation.y / 100) * height : operation.y);
|
||||
const right = Math.min(
|
||||
width,
|
||||
left + Math.round(percent ? (operation.width / 100) * width : operation.width),
|
||||
);
|
||||
const bottom = Math.min(
|
||||
height,
|
||||
top + Math.round(percent ? (operation.height / 100) * height : operation.height),
|
||||
);
|
||||
|
||||
if (left < 0 || top < 0 || left >= width || top >= height || right <= left || bottom <= top) {
|
||||
throw new Error(`the crop box falls outside the image`);
|
||||
}
|
||||
|
||||
image = image.extract({ left, top, width: right - left, height: bottom - top });
|
||||
break;
|
||||
}
|
||||
case "resize": {
|
||||
if (!operation.width && !operation.height) {
|
||||
throw new Error(`give a width, a height or both`);
|
||||
}
|
||||
|
||||
image = image.resize({
|
||||
width: operation.width,
|
||||
height: operation.height,
|
||||
fit: operation.fit || "inside",
|
||||
background: { r: 0, g: 0, b: 0, alpha: 0 },
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "rotate":
|
||||
image = image.rotate(operation.degrees, { background: { r: 0, g: 0, b: 0, alpha: 0 } });
|
||||
break;
|
||||
case "flip":
|
||||
image = operation.direction == "vertical" ? image.flip() : image.flop();
|
||||
break;
|
||||
case "grayscale":
|
||||
image = image.grayscale();
|
||||
break;
|
||||
case "blur":
|
||||
image = image.blur(operation.sigma || 3);
|
||||
break;
|
||||
case "sharpen":
|
||||
image = image.sharpen(operation.sigma ? { sigma: operation.sigma } : undefined);
|
||||
break;
|
||||
case "adjust":
|
||||
image = image.modulate({
|
||||
brightness: operation.brightness,
|
||||
saturation: operation.saturation,
|
||||
hue: operation.hue,
|
||||
});
|
||||
break;
|
||||
case "trim":
|
||||
image = image.trim({ threshold: operation.threshold ?? 10 });
|
||||
break;
|
||||
}
|
||||
|
||||
const result = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
|
||||
if (
|
||||
result.info.width > AppData.ImageTransformMaxDimension ||
|
||||
result.info.height > AppData.ImageTransformMaxDimension
|
||||
) {
|
||||
throw new Error(`the result would be larger than ${AppData.ImageTransformMaxDimension}px on a side`);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -59,7 +59,9 @@ export default function createBotTool({
|
||||
|
||||
if (args.workspace_id && !target?.id) {
|
||||
throw new Error(
|
||||
`No workspace has id ${args.workspace_id}. Workspaces: ${list || "none"}.`,
|
||||
`No workspace has id ${args.workspace_id}. Workspaces: ${
|
||||
workspaces.map((w) => `${w.id}: ${w.name}`).join("; ") || "none"
|
||||
}.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -163,11 +163,15 @@ export default async function grabBotChatTools({
|
||||
|
||||
const workspaces = (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived);
|
||||
|
||||
tools.push(createWorkspaceTool({ user_id, workspaces }));
|
||||
|
||||
if (workspaces.length) {
|
||||
tools.push(updateWorkspaceTool({ user_id, workspaces, workspace_id, scopes }));
|
||||
}
|
||||
/**
|
||||
* Offered even with no workspace yet: create_workspace adds the one it
|
||||
* makes to `workspaces`, and the same reply then sets its picture or
|
||||
* puts bots in it.
|
||||
*/
|
||||
tools.push(
|
||||
createWorkspaceTool({ user_id, workspaces }),
|
||||
updateWorkspaceTool({ user_id, workspaces, workspace_id, scopes }),
|
||||
);
|
||||
|
||||
tools.push(createBotTool({ user_id, workspaces, workspace_id }));
|
||||
|
||||
@@ -211,9 +215,7 @@ export default async function grabBotChatTools({
|
||||
...(await grabCoordinatorExtensionTools({ user_id, bot_id, session_id, workspace_id, onPropose })),
|
||||
);
|
||||
|
||||
if (workspaces.length) {
|
||||
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
|
||||
}
|
||||
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
|
||||
|
||||
if (!workers.length) return tools;
|
||||
|
||||
@@ -256,15 +258,13 @@ export default async function grabBotChatTools({
|
||||
tools.push(assignComputerTool({ user_id, workers, computers, access }));
|
||||
}
|
||||
|
||||
if (workspaces.length) {
|
||||
tools.push(
|
||||
addBotToWorkspaceTool({ user_id, workers, workspaces }),
|
||||
removeBotFromWorkspaceTool({ user_id, workers, workspaces }),
|
||||
);
|
||||
tools.push(
|
||||
addBotToWorkspaceTool({ user_id, workers, workspaces }),
|
||||
removeBotFromWorkspaceTool({ user_id, workers, workspaces }),
|
||||
);
|
||||
|
||||
if (powers.can("set_bot_types")) {
|
||||
tools.push(setBotTypeTool({ user_id, bot_id, workers, workspaces }));
|
||||
}
|
||||
if (powers.can("set_bot_types")) {
|
||||
tools.push(setBotTypeTool({ user_id, bot_id, workers, workspaces }));
|
||||
}
|
||||
|
||||
return tools;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
|
||||
import updateWorkspaceTool from "./update-workspace-tool";
|
||||
|
||||
describe("updateWorkspaceTool", () => {
|
||||
test("lists a workspace created after the tool was built", async () => {
|
||||
const workspaces: BUN_SQLITE_COBBLE_WORKSPACES[] = [];
|
||||
const tool = updateWorkspaceTool({ user_id: 1, workspaces });
|
||||
|
||||
/**
|
||||
* What create_workspace does with the row it makes, later in the
|
||||
* same reply.
|
||||
*/
|
||||
workspaces.push({ id: 12, name: "Beetrelle" } as BUN_SQLITE_COBBLE_WORKSPACES);
|
||||
|
||||
await expect(
|
||||
tool.run({ args: { workspace_id: 99, description: "Home fragrance" } } as never),
|
||||
).rejects.toThrow("Workspaces: 12: Beetrelle.");
|
||||
});
|
||||
});
|
||||
@@ -54,7 +54,12 @@ export default function updateWorkspaceTool({
|
||||
workspace_id,
|
||||
scopes = [],
|
||||
}: Params): HarnessTool<Args> {
|
||||
const list = workspaces.map((w) => `${w.id}: ${w.name}`).join("; ");
|
||||
/**
|
||||
* Read at call time: create_workspace adds the row it makes to the
|
||||
* same array, so a workspace made earlier in this reply is listed too.
|
||||
*/
|
||||
const listed = () => workspaces.map((w) => `${w.id}: ${w.name}`).join("; ") || "none";
|
||||
const list = listed();
|
||||
|
||||
return {
|
||||
name: "update_workspace",
|
||||
@@ -94,7 +99,7 @@ export default function updateWorkspaceTool({
|
||||
|
||||
if (!target?.id) {
|
||||
throw new Error(
|
||||
`No workspace has id ${args.workspace_id ?? "(none given)"}. Workspaces: ${list}.`,
|
||||
`No workspace has id ${args.workspace_id ?? "(none given)"}. Workspaces: ${listed()}.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import TaskTimeoutError from "@/src/utils/task-timeout-error";
|
||||
import withTimeout from "@/src/utils/with-timeout";
|
||||
import HarnessError from "../harness-error";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
|
||||
|
||||
type Params = {
|
||||
@@ -60,6 +61,12 @@ async function runTool({ call, tools, signal }: Params) {
|
||||
return `Error: The arguments for ${call.name} must be a JSON object.`;
|
||||
}
|
||||
|
||||
const { unknown, known } = unknownToolArgs({ schema: tool.schema, args: raw as Record<string, unknown> });
|
||||
|
||||
if (unknown.length) {
|
||||
return `Error: ${call.name} doesn't take ${unknown.join(", ")}. Its arguments are: ${known.join(", ") || "none"}. Nothing was done; call it again with those names.`;
|
||||
}
|
||||
|
||||
const parsed = tool.schema?.safeParse(raw);
|
||||
|
||||
if (parsed && !parsed.success) {
|
||||
|
||||
@@ -35,7 +35,7 @@ export default function generateImageTool(context: StorageToolContext): HarnessT
|
||||
|
||||
return {
|
||||
name: "generate_image",
|
||||
description: `Make an image from a description and save it in your files. Describe what should be in it, in one clear prompt. To work from existing images (a logo to rework, a style or palette to follow, a photo to change), pass them as "references" ([file:ID] refs from list_files) or "reference_media_ids" (images the user uploaded), up to ${AppData.ImageReferenceMaxCount}, and say in the prompt what to take from each. The image is saved (so you can send it now and show it later) and can ride on this reply with "attach".`,
|
||||
description: `Make an image from a description and save it in your files. Describe what should be in it, in one clear prompt. To work from existing images (a logo to rework, a style or palette to follow, a photo to change), pass them as "references" ([file:ID] refs from list_files) or "reference_media_ids" (images the user uploaded), up to ${AppData.ImageReferenceMaxCount}, and say in the prompt what to take from each. The image is saved (so you can send it now and show it later) and can ride on this reply with "attach". To only crop, resize, rotate or adjust an image you have, use transform_image instead: it needs no model and keeps the picture exactly as it is.`,
|
||||
schema: z.object({
|
||||
prompt: z.string().min(3).max(4000),
|
||||
references: z
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
|
||||
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
|
||||
import type { StorageScope } from "@/src/utils/storage-access";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import transformImageTool from "./transform-image-tool";
|
||||
import generateImageTool from "./generate-image-tool";
|
||||
import grabStorageTools from "./grab-storage-tools";
|
||||
import makePdfTool from "./make-pdf-tool";
|
||||
@@ -28,7 +29,7 @@ type Params = {
|
||||
* The tools a bot uses to keep and search files (`src/harness/tools/
|
||||
* storage/`): listing, reading, writing, moving, deleting and searching
|
||||
* its own directory and, in a workspace or as the coordinator, the shared
|
||||
* ones, plus making images and PDFs into them. Every run gets them, so a
|
||||
* ones, plus making images and PDFs into them and editing images. Every run gets them, so a
|
||||
* chat reply, a task and a scheduled run all work with the same files.
|
||||
*/
|
||||
export default async function grabBotFileTools({
|
||||
@@ -48,5 +49,10 @@ export default async function grabBotFileTools({
|
||||
onAttach,
|
||||
});
|
||||
|
||||
return [...grabStorageTools(context), generateImageTool(context), makePdfTool(context)];
|
||||
return [
|
||||
...grabStorageTools(context),
|
||||
generateImageTool(context),
|
||||
transformImageTool(context),
|
||||
makePdfTool(context),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import sharp from "sharp";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import grabBotFile from "@/src/functions/backend/db/bot-files/grab-bot-file";
|
||||
import recordBotFile from "@/src/functions/backend/db/bot-files/record-bot-file";
|
||||
import grabPictureSource from "@/src/functions/backend/db/profile-images/grab-picture-source";
|
||||
import transformImage, { type ImageTransformFormat } from "@/src/harness/image/transform-image";
|
||||
import {
|
||||
ImageTransformOperationSchema,
|
||||
type ImageTransformOperation,
|
||||
} from "@/src/harness/image/image-transform-operations";
|
||||
import imageOutputFormat from "@/src/utils/image-output-format";
|
||||
import mediaFilePath from "@/src/utils/media-file-path";
|
||||
import parseFileRef from "@/src/utils/parse-file-ref";
|
||||
import type { HarnessTool } from "../../types";
|
||||
import {
|
||||
describeScope,
|
||||
fileRef,
|
||||
findNamedScope,
|
||||
formatBytes,
|
||||
type StorageToolContext,
|
||||
} from "./storage-tool-context";
|
||||
|
||||
type Args = {
|
||||
file?: string | number;
|
||||
media_id?: number;
|
||||
operations: ImageTransformOperation[];
|
||||
path?: string;
|
||||
format?: ImageTransformFormat;
|
||||
quality?: number;
|
||||
attach?: boolean;
|
||||
scope?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Transforms an image in the app with sharp (crop, resize, rotate, flip,
|
||||
* grayscale, blur, sharpen, brightness/saturation/hue, trim), no model and
|
||||
* no computer needed, and saves the result in the bot's files. The source
|
||||
* is a file the run reaches or the user's own upload, checked the way a
|
||||
* picture source is. The bot gets a small preview of the result back, so it
|
||||
* can check a crop landed where it meant before sending it.
|
||||
*/
|
||||
export default function transformImageTool(context: StorageToolContext): HarnessTool<Args> {
|
||||
const own = context.scopes[0];
|
||||
|
||||
return {
|
||||
name: "transform_image",
|
||||
description: `Change an image's pixels without a model: crop, resize, rotate, flip, grayscale, blur, sharpen, adjust (brightness, saturation, hue) and trim (cut away a plain border). Steps run in the order given, each on the result of the one before. The source is a [file:ID] ref ("file") or an image the user uploaded ("media_id"). Crop boxes are in pixels of the upright image, or "percent" of its size when you don't know its pixels; the result says the source's size. The result is saved as a new file (unless "path" names the source's own) and shown back to you, so look at it and fix the box if it's off. Send it with "attach". This only cuts, turns and adjusts what is already there: to change what the image shows (a new background, a restyle, removing an object), use generate_image with the image as a reference.`,
|
||||
schema: z.object({
|
||||
file: z
|
||||
.union([z.string().max(60), z.number().int().positive()])
|
||||
.optional()
|
||||
.describe(`The image in your files, e.g. "[file:12]"`),
|
||||
media_id: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe(`An image the user uploaded, by media id`),
|
||||
operations: z.array(ImageTransformOperationSchema).max(AppData.ImageTransformMaxOperations),
|
||||
path: z
|
||||
.string()
|
||||
.max(AppData.BotFilePathMaxChars)
|
||||
.optional()
|
||||
.describe(`Where to save it, e.g. "images/logo-cropped.png"; named after the source otherwise`),
|
||||
format: z
|
||||
.enum(["png", "jpeg", "webp"])
|
||||
.optional()
|
||||
.describe(`Defaults to the source's (PNG for a GIF, JPEG for other kinds)`),
|
||||
quality: z.number().int().min(1).max(100).optional().describe(`JPEG/WebP, default 85`),
|
||||
attach: z.boolean().optional().describe(`Send it to the user with this reply`),
|
||||
scope: z.string().optional().describe(`"bot:<id>" or "workspace:<id>"`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const named = args.scope
|
||||
? findNamedScope({ scopes: context.scopes, name: args.scope })
|
||||
: own;
|
||||
|
||||
if (!named) {
|
||||
return `You can't save there. Your directories: ${context.scopes
|
||||
.map((s) => `${s.scope}:${s.owner_id}`)
|
||||
.join(", ")}.`;
|
||||
}
|
||||
|
||||
const file_id = args.file != undefined ? parseFileRef({ ref: args.file }) : null;
|
||||
|
||||
if (args.file != undefined && !file_id) {
|
||||
return `Give the image as its [file:ID] ref, e.g. "[file:12]". list_files lists them.`;
|
||||
}
|
||||
|
||||
if (!file_id == !args.media_id) {
|
||||
return `Give exactly one of "file" (a [file:ID] ref) and "media_id" (an upload).`;
|
||||
}
|
||||
|
||||
const source_file = file_id
|
||||
? await grabBotFile({ scopes: context.scopes, file_id })
|
||||
: null;
|
||||
const media = await grabPictureSource({
|
||||
user_id: context.user_id,
|
||||
scopes: context.scopes,
|
||||
file_id,
|
||||
media_id: args.media_id,
|
||||
});
|
||||
|
||||
const absolute = mediaFilePath({ write_path: media?.media_write_path });
|
||||
const disk = absolute ? Bun.file(absolute) : null;
|
||||
|
||||
if (!media || media.media_type != "image" || !disk || !(await disk.exists())) {
|
||||
return `That isn't an image you can transform. Use list_files to find one.`;
|
||||
}
|
||||
|
||||
if (disk.size > AppData.ImageTransformMaxBytes) {
|
||||
return `That image is too large to transform (at most ${Math.round(AppData.ImageTransformMaxBytes / (1024 * 1024))} MB).`;
|
||||
}
|
||||
|
||||
const source_name =
|
||||
source_file?.path || media.title || `image.${(media.mime_type || "").split("/").pop()}`;
|
||||
const format = args.format || imageOutputFormat({ ext: source_name }).format;
|
||||
const ext = format == "jpeg" ? "jpg" : format;
|
||||
|
||||
const transformed = await transformImage({
|
||||
data: new Uint8Array(await disk.arrayBuffer()),
|
||||
operations: args.operations,
|
||||
format,
|
||||
quality: args.quality,
|
||||
});
|
||||
|
||||
const path = args.path
|
||||
? withExtension({ path: args.path, ext })
|
||||
: `${stripExtension({ path: source_name.replace(/^uploads\/[^/]+\//, "images/") })}-transformed.${ext}`;
|
||||
|
||||
const file = await recordBotFile({
|
||||
bot_id: context.bot_id,
|
||||
scope: named.scope,
|
||||
owner_id: named.owner_id,
|
||||
path,
|
||||
data: transformed.data,
|
||||
purpose: "image",
|
||||
source: "tool",
|
||||
media_type: "image",
|
||||
mime_type: `image/${format}`,
|
||||
user_id: context.user_id,
|
||||
});
|
||||
|
||||
if (args.attach && file.media_id) {
|
||||
context.onAttach?.({ media_id: Number(file.media_id), name: file.name || "" });
|
||||
}
|
||||
|
||||
const preview = await sharp(transformed.data)
|
||||
.resize({
|
||||
width: AppData.ImageTransformPreviewMaxSide,
|
||||
height: AppData.ImageTransformPreviewMaxSide,
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
})
|
||||
.png()
|
||||
.toBuffer();
|
||||
|
||||
return {
|
||||
text: [
|
||||
`Saved ${file.path} (${transformed.width}x${transformed.height}, ${formatBytes({ bytes: transformed.data.byteLength })}) in ${describeScope(named)}. ${fileRef({ file_id: file.id! })}`,
|
||||
`The source was ${transformed.source_width}x${transformed.source_height} (upright).`,
|
||||
args.attach ? "" : `It isn't attached to this reply; the user sees it in your files.`,
|
||||
`[Result: shown after the tool results]`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
images: [{ url: `data:image/png;base64,${preview.toString("base64")}` }],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function stripExtension({ path }: { path: string }) {
|
||||
return path.replace(/\.[a-zA-Z0-9]{1,5}$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The path with the extension the bytes are, so a "logo.png" saved as JPEG
|
||||
* isn't served as a PNG.
|
||||
*/
|
||||
function withExtension({ path, ext }: { path: string; ext: string }) {
|
||||
const current = path.match(/\.([a-zA-Z0-9]{1,5})$/)?.[1]?.toLowerCase();
|
||||
|
||||
if (current == ext || (ext == "jpg" && current == "jpeg")) return path;
|
||||
|
||||
return `${stripExtension({ path })}.${ext}`;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import unknownToolArgs from "./unknown-tool-args";
|
||||
|
||||
describe("unknownToolArgs", () => {
|
||||
const schema = z
|
||||
.object({ workspace_id: z.number().int().optional(), name: z.string().optional() })
|
||||
.refine((args) => args.name !== undefined, "Give a name.");
|
||||
|
||||
test("names keys the schema doesn't take, through a refine", () => {
|
||||
expect(unknownToolArgs({ schema, args: { id: 9, name: "x" } })).toEqual({
|
||||
unknown: ["id"],
|
||||
known: ["workspace_id", "name"],
|
||||
});
|
||||
});
|
||||
|
||||
test("passes a call that only uses known keys", () => {
|
||||
expect(unknownToolArgs({ schema, args: { workspace_id: 9 } }).unknown).toEqual([]);
|
||||
});
|
||||
|
||||
test("ignores tools without an object schema", () => {
|
||||
expect(unknownToolArgs({ schema: undefined, args: { id: 9 } }).unknown).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod";
|
||||
|
||||
type Params = {
|
||||
schema?: z.ZodType;
|
||||
args: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The argument names a call gave that its tool doesn't take. Zod drops
|
||||
* unknown keys without a word, so a model that wrote `id` for
|
||||
* `workspace_id` would only hear that no id was given and retry the same
|
||||
* call. Only object schemas are checked (refined ones too); anything else
|
||||
* returns none.
|
||||
*/
|
||||
export default function unknownToolArgs({ schema, args }: Params): { unknown: string[]; known: string[] } {
|
||||
if (!(schema instanceof z.ZodObject)) return { unknown: [], known: [] };
|
||||
|
||||
const known = Object.keys(schema.shape);
|
||||
|
||||
return { unknown: Object.keys(args).filter((key) => !known.includes(key)), known };
|
||||
}
|
||||
@@ -23,7 +23,7 @@ type Props = {
|
||||
*/
|
||||
export default function RailWorkspacesSection({ workspaces: listed, selected_id }: Props) {
|
||||
const { openForm } = useContext(AddFlowContext);
|
||||
const workspaces = orderByLastVisit({ items: listed });
|
||||
const workspaces = orderByLastVisit({ items: listed, unvisited_by_created: true });
|
||||
const [open, setOpen] = useState(false);
|
||||
const shown = workspaces.slice(0, AppData.RailRecentWorkspaces);
|
||||
const hidden = workspaces.slice(AppData.RailRecentWorkspaces);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import orderByLastVisit from "./order-by-last-visit";
|
||||
|
||||
type Item = { id: number; last_visited_at?: number | null };
|
||||
type Item = { id: number; last_visited_at?: number | null; created_at?: number | null };
|
||||
|
||||
function ids(items: Item[]) {
|
||||
return orderByLastVisit({ items }).map((item) => item.id);
|
||||
@@ -34,4 +34,16 @@ describe("orderByLastVisit", () => {
|
||||
|
||||
expect(items.map((item) => item.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("a new unvisited item leads when ranked by creation", () => {
|
||||
const items = [
|
||||
{ id: 1, created_at: 10, last_visited_at: 500 },
|
||||
{ id: 2, created_at: 20 },
|
||||
{ id: 3, created_at: 900 },
|
||||
{ id: 4, created_at: 30, last_visited_at: 400 },
|
||||
];
|
||||
|
||||
expect(orderByLastVisit({ items, unvisited_by_created: true }).map((item) => item.id)).toEqual([3, 1, 4, 2]);
|
||||
expect(orderByLastVisit({ items }).map((item) => item.id)).toEqual([1, 4, 2, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
type Item = { last_visited_at?: number | null; created_at?: number | string | null };
|
||||
|
||||
type Params<T> = {
|
||||
items: T[];
|
||||
/**
|
||||
* Rank an item nobody visited yet by when it was made, so a new one
|
||||
* (a workspace just created) leads instead of falling below every
|
||||
* visited one, out of the rail's shown slice.
|
||||
*/
|
||||
unvisited_by_created?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A rail list (workspaces, bots): what the user has visited first, latest
|
||||
* first, then the rest in their order.
|
||||
* first, then the rest in their order. With `unvisited_by_created`, an
|
||||
* unvisited item ranks by its `created_at` among the visited ones.
|
||||
*/
|
||||
export default function orderByLastVisit<T extends { last_visited_at?: number | null }>({ items }: Params<T>): T[] {
|
||||
const visited = items
|
||||
.filter((item) => item.last_visited_at)
|
||||
.sort((a, b) => Number(b.last_visited_at) - Number(a.last_visited_at));
|
||||
export default function orderByLastVisit<T extends Item>({ items, unvisited_by_created }: Params<T>): T[] {
|
||||
const rank = (item: T) =>
|
||||
Number(item.last_visited_at || (unvisited_by_created ? item.created_at : 0) || 0);
|
||||
|
||||
return [...visited, ...items.filter((item) => !item.last_visited_at)];
|
||||
const ranked = items.filter((item) => rank(item)).sort((a, b) => rank(b) - rank(a));
|
||||
|
||||
return [...ranked, ...items.filter((item) => !rank(item))];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user