Multiplayer agent harness for work.
Allow uploaded custom logos for loop icons (#1496)
Regan Bellcb6e2d448e45
diff --git a/docs/qa/custom-loop-icons/inbox.png b/docs/qa/custom-loop-icons/inbox.pngnew file mode 100644index 000000000..7a237b6b5Binary files /dev/null and b/docs/qa/custom-loop-icons/inbox.png differdiff --git a/docs/qa/custom-loop-icons/picker.png b/docs/qa/custom-loop-icons/picker.pngnew file mode 100644index 000000000..450107d56Binary files /dev/null and b/docs/qa/custom-loop-icons/picker.png differdiff --git a/plugins/web-ui/src/loop-icon.ts b/plugins/web-ui/src/loop-icon.tsindex 07dc427ad..eb3010262 100644--- a/plugins/web-ui/src/loop-icon.ts+++ b/plugins/web-ui/src/loop-icon.ts@@ -38,6 +38,11 @@ export const LOOP_ICONS = [];export function loopIcon(loop: { icon?: string; source?: string; sources?: string[] }, size = 16): TemplateResult {+ if (loop.icon?.startsWith("data:image/png;base64,")) {+ return html`<span class="loop-icon" aria-hidden="true"+ ><img src=${loop.icon} width=${size} height=${size} alt=""+ /></span>`;+ }const source = loop.source ?? loop.sources?.[0];const fallback = ({ gmail: "mail", slack: "slack" } as Record<string, string>)[source ?? ""] ?? "repeat";const choice =@@ -47,3 +52,29 @@ export function loopIcon(loop: { icon?: string; source?: string; sources?: strin>${choice.id === "slack" ? slackMark(size) : icon(choice.glyph, size)}</span>`;}++export async function readLoopIcon(file: File): Promise<string> {+ if (file.size > 2 * 1024 * 1024) throw new Error("Choose an image smaller than 2 MB.");+ if (!["image/png", "image/jpeg", "image/webp", "image/gif", "image/svg+xml"].includes(file.type))+ throw new Error("Choose a PNG, JPEG, WebP, GIF, or SVG image.");+ const url = URL.createObjectURL(file);+ try {+ const image = new Image();+ image.src = url;+ await image.decode();+ if (!image.naturalWidth || !image.naturalHeight) throw new Error("This image has no visible size.");+ const canvas = document.createElement("canvas");+ canvas.width = canvas.height = 96;+ const context = canvas.getContext("2d");+ if (!context) throw new Error("Image uploads are unavailable in this browser.");+ const scale = Math.min(96 / image.naturalWidth, 96 / image.naturalHeight);+ const width = image.naturalWidth * scale;+ const height = image.naturalHeight * scale;+ context.drawImage(image, (96 - width) / 2, (96 - height) / 2, width, height);+ const value = canvas.toDataURL("image/png");+ if (value.length > 65_536) throw new Error("This image is too complex. Choose a simpler image.");+ return value;+ } finally {+ URL.revokeObjectURL(url);+ }+}diff --git a/plugins/web-ui/src/loops.ts b/plugins/web-ui/src/loops.tsindex 4ab73335d..5ea8c91b2 100644--- a/plugins/web-ui/src/loops.ts+++ b/plugins/web-ui/src/loops.ts@@ -1,4 +1,4 @@-import { LOOP_ICONS, loopIcon } from "./loop-icon";+import { LOOP_ICONS, loopIcon, readLoopIcon } from "./loop-icon";import { html, nothing, render, type TemplateResult } from "lit";import { CheckCircle2, CornerUpLeft, Pause, Play, Zap } from "lucide";import { api } from "./core-bridge";@@ -164,9 +164,10 @@ async function mutate(fn: () => Promise<unknown>): Promise<void> {}}-async function setLoopIcon(loop: LoopView, value: string | null): Promise<void> {+async function setLoopIcon(loop: LoopView, value: string | null | File): Promise<void> {await mutate(async () => {- await api(`/api/loops/${encodeURIComponent(loop.id)}`, { method: "PATCH", body: JSON.stringify({ icon: value }) });+ const icon = value instanceof File ? await readLoopIcon(value) : value;+ await api(`/api/loops/${encodeURIComponent(loop.id)}`, { method: "PATCH", body: JSON.stringify({ icon }) });iconPickerOpen = false;const { refreshInbox } = await import("./inbox");await refreshInbox({ silent: true });@@ -448,6 +449,22 @@ function detailTpl(detail: LoopDetail): TemplateResult {<div class="loop-icon-grid">${LOOP_ICONS.map((choice) => html`<button type="button" aria-label=${choice.label} title=${choice.label} aria-pressed=${loop.icon === choice.id ? "true" : "false"} ?disabled=${loopBusy} @click=${() => void setLoopIcon(loop, choice.id)}>${loopIcon({ icon: choice.id }, 20)}</button>`)}</div>+ <label class="loop-icon-upload">+ <span>${loopBusy ? "Saving…" : "Upload image"}</span>+ <input+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml"+ aria-label="Upload loop icon"+ ?disabled=${loopBusy}+ @change=${(event: Event) => {+ const input = event.currentTarget as HTMLInputElement;+ const file = input.files?.[0];+ input.value = "";+ if (file) void setLoopIcon(loop, file);+ }}+ />+ </label>+ <span class="loop-icon-hint">Images up to 2 MB, including SVG</span><buttonclass="loop-icon-default"type="button"diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 52dd9b656..1124778f2 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -12431,7 +12431,8 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {background: var(--accent);border-color: var(--border);}-.loop-icon-default {+.loop-icon-default,+.loop-icon-upload {display: flex;align-items: center;justify-content: center;@@ -12449,3 +12450,33 @@ body.app-edit-embed .custom-chat-shell.app-edit-chat > .chat-bottom-dock {opacity: 0.45;cursor: default;}++.loop-icon img {+ display: block;+ object-fit: contain;+}+.loop-icon-upload {+ position: relative;+}+.loop-icon-upload input {+ position: absolute;+ inset: 0;+ width: 100%;+ opacity: 0;+ cursor: pointer;+}+.loop-icon-upload:focus-within {+ outline: 2px solid var(--ring);+ outline-offset: 2px;+}+.loop-icon-upload:has(input:disabled) {+ opacity: 0.45;+ cursor: default;+}+.loop-icon-hint {+ display: block;+ margin-top: 8px;+ color: var(--muted-foreground);+ font-size: 11px;+ line-height: 1.5;+}diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex 04fb69a5b..72a1e5912 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -258,7 +258,7 @@ const FAMILIES: AgentApiFamily[] = [method: "GET|PATCH|DELETE",path: "/v1/loops/:id",summary:- "inspect a loop (items, held outputs, vitals), edit it (icon sets a named icon such as bug, rocket, mail, or slack; null restores the default; playbook edits are versioned; destinationKey sets escalation delivery and null clears it; state: enabled|paused clears or sets the pause; clearing quarantine or changing destination requires a live human), or delete it and its child cron",+ "inspect a loop (items, held outputs, vitals), edit it (icon sets a named icon such as bug or slack, or an uploaded PNG data URL up to 64 KiB and 128×128 pixels; null restores the default; playbook edits are versioned; destinationKey sets escalation delivery and null clears it; state: enabled|paused clears or sets the pause; clearing quarantine or changing destination requires a live human), or delete it and its child cron",},{ method: "POST", path: "/v1/loops/:id/fire", summary: "fire a loop now (intake → work → judge → hold/ship)" },{diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.tsindex c7e81d65f..505a8e55d 100644--- a/src/api/routes/loops.ts+++ b/src/api/routes/loops.ts@@ -1,4 +1,4 @@-import { validLoopIcon } from "../../loops/loop-store.ts";+import { LOOP_ICON_ERROR, validLoopIcon } from "../../loops/loop-store.ts";import { boundLoopCron } from "../../loops/authority.ts";import { unattendedGrantRefusal } from "../../cron/authority.ts";import type { AdvisoryLock } from "../../persistence/advisory-lock.ts";@@ -185,7 +185,7 @@ async function createLoop(ctx: ApiCtx): Promise<void> {if (b.icon !== undefined && !validLoopIcon(b.icon))return sendJson(ctx.res, 400, {error: "bad_request",- message: "icon must be a lowercase icon name of at most 48 characters, or null for the default",+ message: LOOP_ICON_ERROR,});if (typeof b.name !== "string" || !b.name.trim())return sendJson(ctx.res, 400, { error: "bad_request", message: "name required" });@@ -341,7 +341,7 @@ async function patchLoop(ctx: ApiCtx): Promise<void> {if (b.icon !== undefined && !validLoopIcon(b.icon))return sendJson(ctx.res, 400, {error: "bad_request",- message: "icon must be a lowercase icon name of at most 48 characters, or null for the default",+ message: LOOP_ICON_ERROR,});const patch: LoopPatch = {};if (typeof b.playbook === "string" && b.playbook.trim()) {diff --git a/src/loops/loop-store.ts b/src/loops/loop-store.tsindex 855d31970..13f2d0dc1 100644--- a/src/loops/loop-store.ts+++ b/src/loops/loop-store.ts@@ -80,15 +80,26 @@ export function isRunnable(loop: Loop): boolean {return RUNNABLE_STATES.has(loop.state);}+export const LOOP_ICON_ERROR =+ "icon must be a lowercase icon name, a PNG data URL up to 64 KiB and 128×128 pixels, or null for the default";+export function validLoopIcon(value: unknown): value is string | null {- return (- value === null || (typeof value === "string" && value.length <= 48 && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value))- );+ if (value === null) return true;+ if (typeof value !== "string") return false;+ if (value.length <= 48 && /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(value)) return true;+ if (value.length > 65_536 || !/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(value)) return false;+ const encoded = value.slice("data:image/png;base64,".length);+ const bytes = Buffer.from(encoded, "base64");+ if (bytes.toString("base64") !== encoded || bytes.length < 33) return false;+ if (!bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return false;+ if (bytes.readUInt32BE(8) !== 13 || bytes.toString("ascii", 12, 16) !== "IHDR") return false;+ const width = bytes.readUInt32BE(16);+ const height = bytes.readUInt32BE(20);+ return width > 0 && height > 0 && width <= 128 && height <= 128;}function normalizeIcon(value: string | null): string | undefined {- if (!validLoopIcon(value))- throw new Error("icon must be a lowercase icon name of at most 48 characters, or null for the default");+ if (!validLoopIcon(value)) throw new Error(LOOP_ICON_ERROR);return value ?? undefined;}diff --git a/test/loop-routes.test.ts b/test/loop-routes.test.tsindex 9f2efeaa2..6c6655726 100644--- a/test/loop-routes.test.ts+++ b/test/loop-routes.test.ts@@ -800,7 +800,11 @@ test("loop icons can be set and reset by their owner, reject invalid input and rassert.equal(created.status, 200);const loop = (created.body as { loop: Loop }).loop;assert.equal(loop.icon, "bug");- for (const icon of ["rocket", null]) {+ for (const icon of [+ "rocket",+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=",+ null,+ ]) {const result = await call(deps, "PATCH", `/v1/loops/${loop.id}`, { icon });assert.equal(result.status, 200);assert.equal((result.body as { loop: Loop }).loop.icon, icon ?? undefined);diff --git a/test/loop-store.test.ts b/test/loop-store.test.tsindex a13227809..96d4f3557 100644--- a/test/loop-store.test.ts+++ b/test/loop-store.test.ts@@ -1,6 +1,6 @@import { test } from "node:test";import assert from "node:assert/strict";-import { createLoopStore, isRunnable } from "../src/loops/loop-store.ts";+import { createLoopStore, isRunnable, validLoopIcon } from "../src/loops/loop-store.ts";import { createLoopItemLedger, loopItemId } from "../src/loops/item-ledger.ts";import { scopeId } from "../src/types.ts";@@ -180,3 +180,33 @@ test("loop icons persist and reset without changing identity or automation policassert.equal((await store.get(loop.id))!.icon, undefined);assert.equal((await store.create(base)).loop.id, loop.id);});++test("custom loop icons persist as bounded PNGs and reset to the source default", async () => {+ const icon =+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=";+ assert.equal(validLoopIcon(icon), true);+ const store = createLoopStore();+ const { loop } = await store.create({ ...base, icon });+ assert.equal((await store.get(loop.id))!.icon, icon);+ await store.update(loop.id, { icon: "bug" });+ await store.update(loop.id, { icon });+ assert.equal((await store.get(loop.id))!.icon, icon);+ assert.equal((await store.get(loop.id))!.playbookVersion, loop.playbookVersion);+ await store.update(loop.id, { icon: null });+ assert.equal((await store.get(loop.id))!.icon, undefined);+ for (const value of [+ "https://example.com/logo.png",+ "data:image/svg+xml;base64,PHN2Zz4=",+ "data:image/png;base64,YWJj",+ icon + "=",+ icon + "A".repeat(65_536),+ ]) {+ assert.equal(validLoopIcon(value), false);+ await assert.rejects(store.update(loop.id, { icon: value }), /icon must/);+ }+ for (const dimension of [0, 129, 0xffffffff]) {+ const bytes = Buffer.from(icon.slice("data:image/png;base64,".length), "base64");+ bytes.writeUInt32BE(dimension, 16);+ assert.equal(validLoopIcon(`data:image/png;base64,${bytes.toString("base64")}`), false);+ }+});