From cb5278091df0014a362029ade9cecc6c2b6f13b5 Mon Sep 17 00:00:00 2001 From: jstadev <28742201+jstadev@users.noreply.github.com> Date: Sun, 15 Nov 2026 02:27:47 +0200 Subject: [PATCH] onspot v3.6: images on pins Paste, drop or pick up to 6 images in the note popup and the card reply box. Each image uploads at once (POST /api/images) and the pin or the reply links it in the same transaction that creates it, so the fix session sees it from its start. The runner saves the images as files and lists them in the prompt; the session opens them with the Read tool. pins images saves them for any agent. Extension 0.7.0. --- .env.example | 4 + AGENTS.md | 4 +- CHANGELOG.md | 12 ++ README.md | 6 +- docs/protocol.md | 104 ++++++++-- extension/package-lock.json | 4 +- extension/package.json | 2 +- extension/src/background.js | 5 +- extension/src/bg/shot.js | 78 ++++---- extension/src/bg/upload.js | 31 +++ extension/src/content/card.js | 124 ++++++++---- extension/src/content/drafts.js | 6 +- extension/src/content/images.js | 157 ++++++++++++++++ extension/src/content/index.js | 3 +- extension/src/content/local.js | 2 +- extension/src/content/notes.js | 19 +- extension/src/content/styles.js | 12 +- extension/src/shared/image.js | 71 +++++++ extension/src/shared/protocol.js | 10 +- extension/test/background.test.js | 79 +++++++- extension/test/harness/fake-ext.js | 74 +++++++- extension/test/harness/run.mjs | 141 ++++++++++++++ extension/test/images.test.js | 67 +++++++ runner/src/config.js | 6 +- runner/src/images.js | 121 ++++++++++++ runner/src/pins.js | 44 ++++- runner/src/prompt.js | 52 ++++- runner/src/runner.js | 15 +- runner/test/images.test.js | 229 ++++++++++++++++++++++ runner/test/prompt.test.js | 55 ++++++ runner/test/runner.test.js | 7 +- server/bin/pins.js | 31 ++- server/src/api.js | 33 ++-- server/src/app.js | 11 +- server/src/format.js | 1 + server/src/index.js | 9 +- server/src/shots.js | 4 + server/src/store.js | 165 +++++++++++++--- server/test/images.test.js | 293 +++++++++++++++++++++++++++++ 39 files changed, 1915 insertions(+), 176 deletions(-) create mode 100644 extension/src/bg/upload.js create mode 100644 extension/src/content/images.js create mode 100644 extension/src/shared/image.js create mode 100644 extension/test/images.test.js create mode 100644 runner/src/images.js create mode 100644 runner/test/images.test.js create mode 100644 server/test/images.test.js diff --git a/.env.example b/.env.example index 7559afd..fc95f68 100644 --- a/.env.example +++ b/.env.example @@ -9,6 +9,8 @@ PORT= PINS_DB= # Default "shots" next to the database. Folder for the before and after images. PINS_SHOTS_DIR= +# Default "images" next to the database. Folder for the images that you attach to pins and replies. +PINS_IMAGES_DIR= # Default /extension/dist. Folder with the two extension ZIPs for /download/. PINS_DOWNLOAD_DIR= # Default koglabs.com. A pin URL must be https on this domain or a subdomain. @@ -49,6 +51,8 @@ PINS_RUNNER_BRIEF= PINS_RUNNER_SHOTS= # Default on. 0 switches the lean session start off. Only 0 and 1 are valid. PINS_RUNNER_LEAN= +# Default /var/lib/onspot-runner/images. Where the runner saves the images of a pin for its session. +PINS_RUNNER_IMAGES_DIR= # Default http://127.0.0.1:7788. The Triad service; loopback HTTP only. TRIAD_URL= # Default /srv/hub/triad/data/token. File that holds the Triad key. The value never goes in an env variable. diff --git a/AGENTS.md b/AGENTS.md index 18de76f..5280e38 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,8 +20,8 @@ Node 22 (`/opt/studio/bin/node`; `node:sqlite` needs 22.13 or later). The server export PATH=/opt/studio/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin unset NODE_ENV # with NODE_ENV=production npm skips esbuild npm --prefix extension ci && npm --prefix extension run build # release.build (writes extension/dist and the two ZIPs) -npm test # release.test: server 166, runner 143, extension 84, e2e helpers 12 -npm run harness # extension UI harness: 59 groups in Chromium, 59 in Firefox +npm test # release.test: server 176, runner 150, extension 91, e2e helpers 12 +npm run harness # extension UI harness: 60 groups in Chromium, 60 in Firefox node deploy/caddy.check.mjs # the proxy rules with a real Caddy ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index abf0287..5877ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,18 @@ The headings are versions of the contract (`docs/protocol.md`). The extension ha ## [Unreleased] +## [3.6] - 2026-11-15 + +Extension 0.7.0. + +### Added + +- Images on pins: paste (Ctrl+V or ⌘V), drop or pick up to 6 images while you write a pin note or a reply. Each image uploads at once (`POST /api/images`, PNG, JPEG or WebP up to 2 MiB; the extension shrinks larger images and converts other formats) and the pin or the reply links it when it is created. The pin JSON has `images`. +- The card shows the images of the pin after the note and the images of a reply inside the reply. +- The runner saves the images of each pin as files before the session starts and lists their paths in the prompt; the session opens them with the Read tool. +- `pins images [--dir D]` saves the images of a pin; `pins show` and `pins_get` print `images: `. +- `PINS_IMAGES_DIR` (server) and `PINS_RUNNER_IMAGES_DIR` (runner). + ## [3.5] - 2026-11-14 Extension 0.6.0. diff --git a/README.md b/README.md index 7d28a56..059c850 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ Every environment variable that the code reads. `.env.example` holds the same na | `PORT` | server | `4750` | Port on `127.0.0.1`. An integer from 0 to 65535; 0 takes a free port. | | `PINS_DB` | server | `/data/pins.db` | The SQLite file. The server creates the folder and migrates the schema on open. | | `PINS_SHOTS_DIR` | server | `shots` next to the database | Folder for the before and after images. | +| `PINS_IMAGES_DIR` | server | `images` next to the database | Folder for the images that you attach to pins and replies. | | `PINS_DOWNLOAD_DIR` | server | `/extension/dist` | Folder with the two extension ZIPs that `/download/` serves. | | `PINS_ROOT_DOMAIN` | server | `koglabs.com` | A pin URL must be on this domain or a subdomain. | | `PINS_QUEUE_URL` | server | `https://ai.koglabs.com/triad?tab=pins` | Where `GET /` redirects (the queue UI). A bad value stops the start. | @@ -129,6 +130,7 @@ Every environment variable that the code reads. `.env.example` holds the same na | `PINS_RUNNER_BRIEF` | runner | on | `0` switches the brief off. Only `0` and `1` are valid. | | `PINS_RUNNER_SHOTS` | runner | on | `0` switches the "before" shot by the runner off. Only `0` and `1` are valid. | | `PINS_RUNNER_LEAN` | runner | on | `0` switches the lean session start off. Only `0` and `1` are valid. | +| `PINS_RUNNER_IMAGES_DIR` | runner | `/var/lib/onspot-runner/images` | Where the runner saves the images of a pin for its session. | | `MAX_RUNS` | runner | `0` | Runs at the same time. 0 is no limit. | | `MAX_RUNS_PER_PROJECT` | runner | `0` | Runs at the same time for one project. 0 is no limit. | | `MAX_RUNS_PER_DAY` | runner | `0` | Runs per UTC day. 0 is no limit. | @@ -173,9 +175,9 @@ To report a problem, read [`SECURITY.md`](SECURITY.md). ```sh npm --prefix extension ci # one time: the extension tests run the build -npm test # server 166, runner 143, extension 84, e2e helpers 12 tests +npm test # server 176, runner 150, extension 91, e2e helpers 12 tests node deploy/caddy.check.mjs # the proxy rules against a real Caddy (needs the caddy binary) -npm run harness # the extension UI: 59 groups in Chromium and 59 in Firefox +npm run harness # the extension UI: 60 groups in Chromium and 60 in Firefox ``` - The tests use an in-memory store, ports that the system picks and temp folders. They send nothing to a running server. diff --git a/docs/protocol.md b/docs/protocol.md index eecc408..3a17286 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,4 +1,4 @@ -# OnSpot: contract v3.5 +# OnSpot: contract v3.6 OnSpot puts feedback pins on any `koglabs.com` page. A pin names an element and holds a note. Agents read the queue, take a pin, fix it, and resolve it with the commit. This file is @@ -44,6 +44,13 @@ revert run (`POST /api/pins/:id/revert { commit }`, users only). He chooses the after an earlier fix. The runner starts one session that undoes the chosen commits, newest first, ships the old version and closes the pin. Extension 0.6.0 has the Go back button and the version choice in the card. +v3.6 (2026-11-15, order of the Chairman: *"add photo copy/paste or upload support on pins"*): he pastes, drops or +picks **images** while he writes a pin note or a reply. Each image uploads at once (`POST /api/images`) and waits on +the server unlinked; the pin or the reply links it in the same transaction that creates it, so the session sees it +from its start. The pin JSON has `images`. The runner saves the images of a pin as files and lists them in the prompt, +so the session opens them with the Read tool. `pins images ` saves them for any agent. Extension 0.7.0 has the +attach control in the note popup and the reply box, and image strips in the card. + 2026-11-12 (order of the Chairman, on the model limit of Triad: *"remove it now from everywhere"*): Triad accepts every model name (triad #46), so a pin that names Fable or Haiku runs its session on that model. The detour through an Opus session and `maestro session` (`delegateTo`) is gone. @@ -56,7 +63,7 @@ that model. The detour through an Opus session and `maestro session` (`delegateT | HTTP server | `server/src/app.js`, `http.js`, `api.js`, `events.js`, `static.js`, `index.js` | REST, SSE, extension downloads, guards. | | Agent tools | `server/src/mcp.js`, `format.js`, `server/bin/pins.js` | MCP endpoint and the `pins` CLI. | | Queue | repo `jstadev/triad`, `public/console-ui/pins.js` | The Pins tab in the Triad console: `https://ai.koglabs.com/agents?tab=pins` (the hub serves the console at `/agents`; `/triad` redirects there). It calls `/pins/api/*` same-origin with the hub SSO cookie. | -| Extension UI | `extension/src/content/` | Toolbar, picker, popup, markers, threads, shortcuts. Runs on every page. `index.js` (mount), `dom.js`, `env.js`, the pure modules `prefs.js`, `shortcuts.js`, `format.js`, and one module per part (`capsule`, `keys`, `picker`, `notes`, `drafts`, `pins`, `toasts`, `log`, `settings`, `settings-keys`, `settings-bulk`, `card`, `layout`, `local`, `live`, `routes`, `freeze`, `target`, `styles`). | +| Extension UI | `extension/src/content/` | Toolbar, picker, popup, markers, threads, shortcuts. Runs on every page. `index.js` (mount), `dom.js`, `env.js`, the pure modules `prefs.js`, `shortcuts.js`, `format.js`, and one module per part (`capsule`, `keys`, `picker`, `notes`, `images`, `drafts`, `pins`, `toasts`, `log`, `settings`, `settings-keys`, `settings-bulk`, `card`, `layout`, `local`, `live`, `routes`, `freeze`, `target`, `styles`). | | Extension platform | `extension/src/background.js`, `extension/src/bg/`, `extension/manifest/`, `extension/build.mjs` | Network, live stream, commands, manifests, build. | | Shared constants | `extension/src/shared/protocol.js` | Endpoint URLs and message names. Done. | | Deploy and tests | `deploy/`, `e2e/` | systemd unit, Caddy snippet, browser tests. `e2e/run.mjs` and `e2e/autofix.mjs` start each test note with a run tag. At the end, on Ctrl+C, on a kill signal and on an error, one cleanup (`endRun` in `e2e/lib.mjs`) closes every browser of the run first, also one that still starts, then deletes every pin with that tag; `run.mjs` then puts auto-fix back. A second signal or error during the cleanup waits for the same cleanup. `e2e/lib.test.mjs` tests this against a fake server and a fake browser. Env: `PINS_PORT`, `PLAYWRIGHT_CORE`, `E2E_IDLE_MS`, `BRAVE_PATH`, `E2E_LOGIN` (the login module of the deployment, not in this repo; default `~/.config/onspot/e2e-login.mjs`; it exports `user` and `cookie(apiOrigin)`). | @@ -98,6 +105,7 @@ The extension has one dev dependency, `esbuild`. Do not add dependencies. "versions": [{ "commit": "a1b2c3d4e5f6", "summary": "Title margin 48px to 24px", "at": "2026-10-17T14:05:00.000Z" }], "revert": null, "revertedAt": null, + "images": [{ "id": "k3J9pQ2xL0aZ7vB1nM4cRw", "type": "image/png", "size": 183204, "replyId": null, "author": "sam", "createdAt": "2026-10-17T14:00:00.000Z" }], "replyCount": 0, "createdAt": "2026-10-17T14:00:00.000Z", "updatedAt": "2026-10-17T14:00:00.000Z", @@ -147,6 +155,8 @@ The extension has one dev dependency, `esbuild`. Do not add dependencies. pin at the request, so `attempts` minus this value is the number of revert runs. - `revertedAt` (v3.5) is the time when the latest revert run closed the pin, else `null`. A requeue clears it, so a `done` pin with `revertedAt` shows the result of a go back. +- `images` (v3.6) holds the images that came with the pin or its replies, oldest first, `[]` when none: see + "Image". Every transition keeps them (unlike shots). A pin holds at most 12 images. - `url` has no fragment. `host` is `URL.host` in lower case. `path` is `URL.pathname`. - `targets` holds 1 to 10 elements. The first one is the primary element. - `quote` is the text the user selected on the page, or `null`. @@ -182,6 +192,19 @@ The extension has one dev dependency, `esbuild`. Do not add dependencies. with another number is dropped. A `styles` key that is a name of `Object.prototype` (`constructor`) is dropped. +### Image (v3.6) + +```json +{ "id": "k3J9pQ2xL0aZ7vB1nM4cRw", "type": "image/png", "size": 183204, "replyId": null, "author": "sam", "createdAt": "..." } +``` + +- `id`: 16 random bytes as base64url, 22 characters (`^[A-Za-z0-9_-]{22}$`). It cannot be guessed. +- `type`: `image/png`, `image/jpeg` or `image/webp`; `size` in bytes. +- `replyId`: the reply that carried the image, or `null` when it came with the pin. +- `author`: the actor that uploaded it. +- An image is **unlinked** from its upload until a new pin (`images` in the pin input) or a new reply (`images` in + the reply body) links it, in the same transaction as the insert. A linked image never moves. + ### Reply ```json @@ -258,13 +281,20 @@ Any other change is a conflict (HTTP 409). - A shot: `image/png`, `image/jpeg` or `image/webp`, at most 2 MiB, and the first bytes must match the type (PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `RIFF....WEBP`). Shot files of pins closed more than 30 days ago, or of deleted pins, are removed at server start and every 24 h. +- An image (v3.6): the same types, size and magic rule as a shot. `images` in a pin input or a reply: an array + of 0 to 6 image ids, no duplicates, else 400. Each id must be an unlinked image, else 400 `image is gone; remove it and try again`, and nothing is written (also for a whole batch). A reply that + would take the pin over 12 images is 409. At most 200 unlinked images wait on the server; the next upload is + 409 `too many images wait for a pin`. The prune at server start and every 24 h removes the images of pins + closed more than 30 days ago (they leave the pin JSON too), the files of deleted pins and unlinked images + older than 30 days. Files `` (mode 0600) in `PINS_IMAGES_DIR`. ## Store API (`server/src/store.js`) ```js import { openStore, parseStatuses, ValidationError, ConflictError } from "./store.js"; -const store = openStore({ file: "/path/pins.db", rootDomain: "koglabs.com" }); // file ":memory:" for tests -store.createPin({ url, title, note, quote, targets, viewport, author }) // -> Pin, throws ValidationError +const store = openStore({ file: "/path/pins.db", rootDomain: "koglabs.com", shotsDir, imagesDir }); // file ":memory:" for tests +store.createPin({ url, title, note, quote, targets, viewport, author, images }) // -> Pin, throws ValidationError store.createBatch({ pins: [input], key, author }) // -> { batch: { id, host, author, createdAt, count }, pins, created } // one transaction; a known key returns its batch (created: false) store.getPin(id) // -> Pin | null @@ -275,12 +305,15 @@ store.listSteps(id) // -> Step[] oldest first store.setShot(id, kind, { type, bytes }) // -> Pin | null; kind "before"|"after"; ValidationError on type, size or magic bytes store.getShot(id, kind) // -> { type, bytes } | null store.pruneShots({ olderThanDays: 30 }) // -> number of files removed +store.addImage({ type, bytes, author }) // -> Image (unlinked); ValidationError on type, size or magic bytes; ConflictError at 200 unlinked +store.getImage(imageId) // -> { type, bytes } | null +store.pruneImages({ olderThanDays: 30 }) // -> number of files removed store.updateNote(id, note) // -> Pin | null store.transition(id, "start"|"resolve"|"dismiss"|"ask"|"reopen"|"accept"|"revert", { agent, summary, commit, reason, question, run, model, kind, author }) // -> Pin | null, throws ConflictError / ValidationError / ForbiddenError // kind "user"|"agent" decides the reopens count and the accept and revert guards // revert: commit = the first fix to undo (it and every later fix) store.deletePin(id) // -> boolean -store.addReply(id, { kind, author, body, reopen }) // -> Reply | null +store.addReply(id, { kind, author, body, reopen, images }) // -> Reply | null; images linked with replyId = the reply store.listReplies(id) // -> Reply[] oldest first store.stats() // -> { total: {queued, working, waiting, done, dismissed}, hosts: [{ host, queued, working, waiting, done, dismissed }] } store.getSettings() // -> Settings (see "Settings"; defaults when unset) @@ -310,6 +343,8 @@ Every browser request passes the hub SSO (admin) in Caddy first. Caddy adds `X-S body, a body of at most 64 KiB (512 KiB for `POST /api/batches`, 1 MiB for `POST /mcp`) (413), and valid JSON (400). The one exception is `PUT /api/pins/:id/shots/:kind`: raw image bytes (see Limits), at most 2 MiB (413), loopback only (a request with `X-Forwarded-For` gets 403), agents only (403). + The second exception (v3.6) is `POST /api/images`: raw image bytes with `Content-Type` `image/png`, + `image/jpeg` or `image/webp` (else 415), at most 2 MiB (413), from users (through the proxy) and agents. 6. Writes share one token bucket: 120 per minute, then 429 with `Retry-After`. A JSON-RPC batch on `/mcp` takes one token per entry; a batch with more than 120 entries gets 400 with JSON-RPC error -32600 and runs nothing. @@ -331,13 +366,15 @@ Every browser request passes the hub SSO (admin) in Caddy first. Caddy adds `X-S |---|---|---|---| | GET | `/api/health` | | 200 `{ ok: true, version, extension, open: { queued, working, waiting } }` (`extension` = version of the builds in `/download/`) | | GET | `/api/pins` | query: `status` (`open` default, `all`, or a comma list), `host`, `path`, `q`, `limit` (1-500, default 200), `before` (id), `batch` (id), `selector` (exact `targets[0].selector`, at most 500 chars) | 200 `{ pins: [Pin] }` newest first | -| POST | `/api/batches` | `{ key?, pins: [{ url, title?, note, quote?, targets, viewport?, intent?, scope?, presets? }] }` | 201 `{ batch, pins }`; 200 with the first batch when `key` is known | +| POST | `/api/batches` | `{ key?, pins: [{ url, title?, note, quote?, targets, viewport?, intent?, scope?, presets?, images? }] }` | 201 `{ batch, pins }`; 200 with the first batch when `key` is known | | GET | `/api/stats` | | 200 `store.stats()` | | GET | `/api/pins/:id` | | 200 `{ pin, replies: [Reply], steps: [Step] }` | -| POST | `/api/pins` | `{ url, title?, note, quote?, targets, viewport?, intent?, scope?, presets? }` | 201 `{ pin }` | +| POST | `/api/pins` | `{ url, title?, note, quote?, targets, viewport?, intent?, scope?, presets?, images? }` | 201 `{ pin }` | | POST | `/api/pins/:id/progress` | `{ text }` (agents only, else 403; pin `working`, else 409) | 201 `{ step, pin }` | | PUT | `/api/pins/:id/shots/:kind` | raw image, `kind` = `before` or `after` (agents only, loopback only) | 200 `{ pin }` | | GET | `/api/pins/:id/shots/:kind` | | 200 the image with its type, `Cache-Control: private, no-cache`, `Content-Security-Policy: default-src 'none'`; 404 when none | +| POST | `/api/images` | raw image (v3.6; see Guards 5 and Limits) | 201 `{ image }` (unlinked) | +| GET | `/api/images/:imageId` | | 200 the image, the headers of the shot GET; 404 when unknown or when `:imageId` is not an image id | | PATCH | `/api/pins/:id` | `{ note }` | 200 `{ pin }` | | DELETE | `/api/pins/:id` | | 204 | | POST | `/api/pins/:id/start` | `{ run?, model? }` | 200 `{ pin }` | @@ -347,7 +384,7 @@ Every browser request passes the hub SSO (admin) in Caddy first. Caddy adds `X-S | POST | `/api/pins/:id/reopen` | `{}` | 200 `{ pin }` | | POST | `/api/pins/:id/accept` | `{}` (users only, else 403; pin `done`, else 409) | 200 `{ pin }` | | POST | `/api/pins/:id/revert` | `{ commit }` (users only, else 403; pin `done` or `dismissed` and `commit` in `versions`, else 409) | 200 `{ pin }` | -| POST | `/api/pins/:id/replies` | `{ body, reopen? }` | 201 `{ reply, pin }` | +| POST | `/api/pins/:id/replies` | `{ body, reopen?, images? }` | 201 `{ reply, pin }` | | GET | `/api/settings` | | 200 Settings | | PATCH | `/api/settings` | `{ autofix?, bulk?: { on?, delegate?, agents? } }` | 200 Settings | | GET | `/api/events` | query: `host` (optional filter) | SSE stream | @@ -381,7 +418,7 @@ Errors: `{ "error": "" }` with 400, 403, 404, 405, 409, 413, 415, - The queue page left this server on 2026-10-18; it is the Pins tab in the Triad console. - Env: `PORT` (default `4750`; empty counts as not set), `PINS_DOWNLOAD_DIR` (default `/extension/dist`), `PINS_DB` (default `/data/pins.db`), `PINS_SHOTS_DIR` (default - `shots` next to the database), `PINS_ROOT_DOMAIN` (default `koglabs.com`), `PINS_QUEUE_URL` + `shots` next to the database), `PINS_IMAGES_DIR` (v3.6, default `images` next to the database), `PINS_ROOT_DOMAIN` (default `koglabs.com`), `PINS_QUEUE_URL` (default `https://ai.koglabs.com/triad?tab=pins`; where `GET /` redirects). A bad `PORT` or `PINS_QUEUE_URL` stops the start with one line on stderr and exit code 1. @@ -443,7 +480,9 @@ url: https://crete.koglabs.com/pricing?x=1 The detail format also has, after `batch`: `versions: · ...` (oldest first), `go back: undo , ` while `revert` is set and `reverted: ` when `revertedAt` is set. -The `about`, `presets`, `steps`, `shots`, `versions`, `go back` and `reverted` lines appear only when they +The detail format (v3.6) has the line `images: (pins images saves them)` after the `quote` line when the pin +has images. +The `about`, `presets`, `steps`, `shots`, `versions`, `go back`, `reverted` and `images` lines appear only when they have content. The list format adds ` · ` after the label when `intent` is set, and ` · go back` while `revert` is set. In the list and detail formats every run of whitespace or control characters in a value is one space. @@ -465,6 +504,7 @@ pins reply "text" pins wait [--host H] [--timeout 120] pins progress "text" pins shot before|after +pins images [--dir D] pins snap before|after [--url U] [--selector S] [--pad 40] pins check --url U [--selector S] [--pad 40] pins ship --dir --summary "..." [--message "..."] [ ...] @@ -474,6 +514,10 @@ Only `--name` is an option. A text may start with one dash (`pins progress 12 "- value may start with `--` (`--summary "--accent is blue"`) unless it is the name of an option of that command. `PINS_PORT` must be a port number, else exit 1. `pins shot` needs a regular file. +`pins images ` (v3.6) saves each image of the pin, oldest first, as `/pins--.` (`n` from 1; `png`, +`jpg` or `webp` from the first bytes; mode 0600; `D` defaults to `os.tmpdir()`) and prints one path per line, or +`# has no images`. + `pins shot` uploads an image file (type from its first bytes). `pins snap` renders the page with playwright-core (`/srv/design-kit/node_modules/playwright-core`, loaded only by this command; the server keeps zero dependencies) in headless Chromium at the pin's viewport (`dpr` at most 2), at @@ -565,7 +609,7 @@ One codebase, two builds: `dist/chrome/` (MV3 service worker) and `dist/firefox/ Set positions with `el.style.transform = ...` / `el.style.setProperty(...)` (CSSOM is not blocked). - Chrome service workers have no `EventSource`. The background reads SSE with `fetch` and a stream reader. - The UI is plain DOM (no React, no framework). Budget: `content.js` at most 88 KB minified - (90112 bytes); the build stops above it. The v3.3 build is 77819 bytes. + (90112 bytes); the build stops above it. The 0.7.0 build is about 88,000 bytes. ### Constants (`extension/src/shared/protocol.js`) @@ -612,6 +656,13 @@ One-shot, `ext.runtime.sendMessage(msg)` returns a promise: `createImageBitmap` into a ``; it never puts an image URL in the page, so the page CSP cannot block it. The read stops at 2 MiB also when the response has no true `Content-Length` (413). No answer in 30 s gives `{ ok: false, status: 0 }`. A redirect counts as a 401. +- `{ t: "image", id }` (0.7.0) -> `{ ok, status, type, data }`: the same reader as `shot`, for + `API + /api/images/` (`id` matches `^[A-Za-z0-9_-]{22}$`, else `{ ok: false, status: 400 }`). +- `{ t: "upload", type, data }` (0.7.0) -> `{ ok, status, data: { image } | null, error? }`: `data` is the image as + base64. The background checks the type (png, jpeg, webp), the size (1 byte to 2 MiB) and the first bytes, else + `{ ok: false, status: 400 }`, then sends `POST API + /api/images` with the raw bytes and that `Content-Type` + (the one `fetch` function, 30 s). 401 or a redirect: state `login` and status 401. The `api` message never + reaches `/api/images`. Live port, `ext.runtime.connect({ name: PORT_NAME })`: @@ -702,6 +753,17 @@ them in one request; the fix run starts at once. Task "What should the agent do?". With the Remove tab the note may be empty; the pin then sends the note "Remove this element." The choices are saved with the unsent pin and sent with the batch as `intent`, `scope` and `presets` (`{ label, text }`). The defaults come from Settings. + **Images** (0.7.0): a trusted paste of an image into the note box, a trusted drop of image files on the popup, or + the icon button "Add an image" (a file picker, opened with `showPicker()`) adds images: at most 6 ("A pin takes up + to 6 images."). Each one decodes with `createImageBitmap` ("That file is not an image this browser can read." when + it does not); a PNG, JPEG or WebP of at most 2 MiB and at most 2560 px on its longest side goes as it is, any + other is drawn into a canvas (longest side at most 2560 px) and sent as WebP 0.9, then JPEG 0.8, then smaller + ("That image is too large." after 3 tries). It uploads at once (`upload` message). A row of thumbnails (canvas) + under the note box shows them, each with "Remove image "; a thumbnail is dimmed while it uploads, and a failed + upload leaves the row and shows "Image not added: ". A paste with text and an image keeps the text. An + event that a script made (paste, drop, change) adds nothing. Add, Enter and Ctrl+Enter wait for no upload: while + one runs they say "Wait until the image is uploaded." and send nothing. A pin with images and an empty note gets the + note "See the attached image." ("See the attached images." for more than one). Enter adds the pin to the batch (an *unsent pin*) and keeps pin mode on. Ctrl+Enter (⌘↵ on macOS) adds it and submits all. Shift+Enter is a new line. Esc closes; the unsent text per URL stays in `ext.storage.local` (`kog-pins:draft:`) and fills the next popup on that page. @@ -710,7 +772,9 @@ them in one request; the fix run starts at once. marker numbered 1, 2, 3 on its page. A click opens it to edit or remove. A v1 failed send (`kog-pins:pending:`) becomes an unsent pin on load. A stored unsent pin is used only when its `url` is an `https:` URL of this host, its note is not empty and each target holds a - `selector` and a `label`. Other entries are dropped when the data is read. While "Submit all" + `selector` and a `label`. Other entries are dropped when the data is read. An unsent pin keeps the ids of its + uploaded images (`images`, at most 6 image ids; bad entries are dropped when the data is read); "Submit all" + sends them as `images` of that pin, and editing it shows and changes them. The unsent text per URL keeps no images. While "Submit all" runs, a pin that another tab adds stays unsent and joins the list after the send. 6. **Tray.** Bottom centre while unsent pins exist or pin mode is on: "3 pins ready" (with a "Bulk" chip, "Bulk · 3 agents" when it delegates, while bulk mode is on), Ctrl+↵, @@ -748,7 +812,11 @@ them in one request; the fix run starts at once. While working: the elapsed time (ticks only while the card is open), the steps of the run (oldest first, live), and **Watch live**, a link to `https://ai.koglabs.com/agents?tab=today&run=` for a `triad:` run. When shots exist: **Before** and **After** side by side (canvas, see the - `shot` message); a click shows one at the full card width, a second click goes back. Queued: Edit, Dismiss, Delete. Working + `shot` message); a click shows one at the full card width, a second click goes back. + **Images** (0.7.0): the images of the pin with `replyId: null` show as a strip after the note, and the images of a + reply inside that reply (canvas, `image` message; a click shows one at the full card width, a second click goes + back). The reply box takes images like the note popup ("A reply takes up to 6 images."); a reply with images and + no text sends "See the attached image." ("See the attached images." for more than one). Queued: Edit, Dismiss, Delete. Working or waiting: Dismiss, Reopen, Delete; a reply on a waiting pin requeues it. Done: See it, **Looks good** (sends `POST /api/pins/:id/accept`, then marks the pin seen; it marks it seen also when the call fails), **Not right** (opens "What is still wrong?"; sending posts the reply @@ -1100,6 +1168,16 @@ code, writes git state or deploys. A Claude session does that, under the standin would remove other work, never dismiss (if the old version is live already, `pins done` without a commit), and the hard end state. +17. **Images** (v3.6; `runner/src/images.js`). Before the start of a run (a single pin, or each pin of a bulk run; never a + revert run), the runner saves each image of the pin (at most 12) over loopback (`GET /api/images/:imageId`, at most + 2 MiB, PNG, JPEG or WebP by its first bytes) to `PINS_RUNNER_IMAGES_DIR` (default `/var/lib/onspot-runner/images`) + as `-.` (mode 0600, folder 0700). Each save removes the files of that folder that are older than 30 + days. All images of one run take at most 5 s; a failed image logs `image skipped pin= n=` and never stops + the run. "His words" in the prompt (and each pin of a bulk prompt) then list them: `Images he attached (his + material, like the note; open each one with the Read tool before you change anything):`, one line per image with + its path and `(with the note)`, `(with his reply at HH:MM)` or `(with an agent reply at HH:MM)`; an image that was not + saved reads `not saved; run "pins images " to get it`. + ### Bulk mode (runner, while `settings.bulk.on` is `true`) 1. **Grouping.** The queued pins of one `batch` form one bulk run (a pin with `revert` never: item 16), due at once (the server writes a whole diff --git a/extension/package-lock.json b/extension/package-lock.json index 7624452..f4317f1 100644 --- a/extension/package-lock.json +++ b/extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "onspot-extension", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "onspot-extension", - "version": "0.6.0", + "version": "0.7.0", "devDependencies": { "esbuild": "0.28.2" } diff --git a/extension/package.json b/extension/package.json index e02ca94..6367cd4 100644 --- a/extension/package.json +++ b/extension/package.json @@ -1,6 +1,6 @@ { "name": "onspot-extension", - "version": "0.6.0", + "version": "0.7.0", "private": true, "license": "MIT", "type": "module", diff --git a/extension/src/background.js b/extension/src/background.js index ca3af2b..f4bf457 100644 --- a/extension/src/background.js +++ b/extension/src/background.js @@ -2,10 +2,11 @@ import { ext, MSG, PORT_NAME } from "./shared/protocol.js"; import { createAPI } from "./bg/api.js"; import { createLive } from "./bg/live.js"; import { trustedSender } from "./bg/request.js"; -import { createShot } from "./bg/shot.js"; +import { createImage, createShot } from "./bg/shot.js"; +import { createUpload } from "./bg/upload.js"; const live = createLive(); -const handlers = { [MSG.API]: createAPI({ live }), [MSG.SHOT]: createShot({ live }) }; +const handlers = { [MSG.API]: createAPI({ live }), [MSG.SHOT]: createShot({ live }), [MSG.UPLOAD]: createUpload({ live }), [MSG.IMAGE]: createImage({ live }) }; const trusted = (sender) => trustedSender(sender, ext.runtime.id); // Register synchronously so MV3 can dispatch the event that starts the worker. diff --git a/extension/src/bg/shot.js b/extension/src/bg/shot.js index 10c5d8c..4f704d1 100644 --- a/extension/src/bg/shot.js +++ b/extension/src/bg/shot.js @@ -1,16 +1,10 @@ -import { MSG, PIN_ID_RE, SHOT_KINDS, SHOT_MAX, SHOT_TYPES } from "../shared/protocol.js"; +import { bytesToBase64 } from "../shared/image.js"; +import { IMAGE_ID_RE, MSG, PIN_ID_RE, SHOT_KINDS, SHOT_MAX, SHOT_TYPES } from "../shared/protocol.js"; import { apiFetch, loggedOut } from "./request.js"; const TIMEOUT_MS = 30000; const refuse = (status) => ({ ok: false, status }); -// `apply` on 8 KiB parts: 13 ms for 2 MiB. The spread form on 32 KiB parts took 104 ms. -function base64(bytes) { - let text = ""; - for (let i = 0; i < bytes.length; i += 0x2000) text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x2000)); - return btoa(text); -} - // The body, or null when it is longer than `max`. It stops at the limit, so a response // without a true Content-Length cannot fill the memory. async function readUpTo(body, max) { @@ -38,30 +32,48 @@ async function readUpTo(body, max) { return bytes; } -// One before/after image of a pin, as base64. The content script draws it into a canvas, so -// no image URL reaches the page and the page CSP cannot block it. -export function createShot({ fetch: fetchRequest = globalThis.fetch, live, timeoutMs = TIMEOUT_MS } = {}) { - return async function shot(message) { - const id = message?.id; - if (message?.t !== MSG.SHOT || !["number", "string"].includes(typeof id) || !PIN_ID_RE.test(String(id)) || !SHOT_KINDS.includes(message.kind)) return refuse(400); - let response; - try { - response = await apiFetch(fetchRequest, `/api/pins/${id}/shots/${message.kind}`, { signal: AbortSignal.timeout(timeoutMs) }); - } catch { - return refuse(0); - } - if (loggedOut(response)) { - live?.requireLogin(); - return refuse(401); - } - const type = (response.headers.get("content-type") || "").split(";")[0].trim().toLowerCase(); - const status = !response.ok ? response.status : !SHOT_TYPES.includes(type) ? 415 : Number(response.headers.get("content-length")) > SHOT_MAX ? 413 : 0; - if (status) { - response.body?.cancel().catch(() => {}); - return refuse(status); - } - let bytes; - try { bytes = await readUpTo(response.body, SHOT_MAX); } catch { return refuse(0); } - return bytes ? { ok: true, status: 200, type, data: base64(bytes) } : refuse(413); +// One image from the API, as base64. The content script draws it into a canvas, so no image +// URL reaches the page and the page CSP cannot block it. Shots and pin images share this reader. +async function readImage(fetchRequest, path, live, timeoutMs) { + let response; + try { + response = await apiFetch(fetchRequest, path, { signal: AbortSignal.timeout(timeoutMs) }); + } catch { + return refuse(0); + } + if (loggedOut(response)) { + live?.requireLogin(); + return refuse(401); + } + const type = (response.headers.get("content-type") || "").split(";")[0].trim().toLowerCase(); + const status = !response.ok ? response.status : !SHOT_TYPES.includes(type) ? 415 : Number(response.headers.get("content-length")) > SHOT_MAX ? 413 : 0; + if (status) { + response.body?.cancel().catch(() => {}); + return refuse(status); + } + let bytes; + try { bytes = await readUpTo(response.body, SHOT_MAX); } catch { return refuse(0); } + return bytes ? { ok: true, status: 200, type, data: bytesToBase64(bytes) } : refuse(413); +} + +function createReader(allow, { fetch: fetchRequest = globalThis.fetch, live, timeoutMs = TIMEOUT_MS } = {}) { + return function read(message) { + const path = allow(message); + return path ? readImage(fetchRequest, path, live, timeoutMs) : Promise.resolve(refuse(400)); }; } + +export function createShot(options) { + return createReader((message) => { + const id = message?.id; + if (message?.t !== MSG.SHOT || !["number", "string"].includes(typeof id) || !PIN_ID_RE.test(String(id)) || !SHOT_KINDS.includes(message.kind)) return ""; + return `/api/pins/${id}/shots/${message.kind}`; + }, options); +} + +export function createImage(options) { + return createReader((message) => { + if (message?.t !== MSG.IMAGE || typeof message.id !== "string" || !IMAGE_ID_RE.test(message.id)) return ""; + return `/api/images/${message.id}`; + }, options); +} diff --git a/extension/src/bg/upload.js b/extension/src/bg/upload.js new file mode 100644 index 0000000..83762c1 --- /dev/null +++ b/extension/src/bg/upload.js @@ -0,0 +1,31 @@ +// Post one image. The content script sends base64. This posts the raw bytes. +import { base64ToBytes, imageType } from "../shared/image.js"; +import { IMAGE_ID_RE, MSG, SHOT_MAX, SHOT_TYPES } from "../shared/protocol.js"; +import { apiFetch, loggedOut } from "./request.js"; + +const TIMEOUT_MS = 30000; +const fail = (status, error) => ({ ok: false, status, data: null, ...(error ? { error } : {}) }); + +export function createUpload({ fetch: fetchRequest = globalThis.fetch, live, timeoutMs = TIMEOUT_MS } = {}) { + return async function upload(message) { + const bytes = base64ToBytes(message?.data, SHOT_MAX); + if (message?.t !== MSG.UPLOAD || !SHOT_TYPES.includes(message?.type) || !bytes || imageType(bytes) !== message.type) return fail(400); + const signal = AbortSignal.timeout(timeoutMs); + const noAnswer = () => fail(0, signal.aborted ? "timeout" : "offline"); + let response; + try { + response = await apiFetch(fetchRequest, "/api/images", { method: "POST", signal, headers: { "Content-Type": message.type }, body: bytes }); + } catch { + return noAnswer(); + } + if (loggedOut(response)) { + live?.requireLogin(); + return fail(401, "login required"); + } + let data = null; + try { data = await response.json(); } catch { if (signal.aborted) return noAnswer(); } + if (response.ok && !IMAGE_ID_RE.test(data?.image?.id ?? "")) return fail(502, "unexpected response"); + if (!response.ok) return fail(response.status, typeof data?.error === "string" ? data.error : `HTTP ${response.status}`); + return { ok: true, status: response.status, data }; + }; +} diff --git a/extension/src/content/card.js b/extension/src/content/card.js index 5e5d904..2644340 100644 --- a/extension/src/content/card.js +++ b/extension/src/content/card.js @@ -9,14 +9,15 @@ import { schedule, setError, showFlash, syncWatchers } from './layout.js'; import { api } from './live.js'; import { pinButton } from './capsule.js'; import { closePopup } from './notes.js'; +import { IMAGE_WAIT, attachedReply, attachImages } from './images.js'; import { acceptPin, markers, markSeen, pins, questions, renderMarkers, revision, revisions, seeIt } from './pins.js'; import { dropToast } from './toasts.js'; import { closeLog } from './log.js'; import { closeSettings } from './settings.js'; export let card = null; -// Before and after images by pin, kind and upload time. -const shots = new Map(); +// Shot and pin-image bitmaps. One cache, same as the shots: the oldest leaves at the limit. +const bitmaps = new Map(); function syncQuestion(instance) { const text = instance.pin?.status === 'waiting' ? latestAgentBody(instance.replies) : ''; @@ -28,38 +29,43 @@ function latestAgentBody(replies) { for (const item of replies.values()) if (item.kind === 'agent' && (!best || item.id > best.id)) best = item; return best?.body || ''; } -// One image per pin, kind and upload time. The background sends the bytes; they go into a -// canvas, so the page never holds an image URL that its CSP could block. -function loadShot(id, kind, at) { - const key = `${id}:${kind}:${at}`; - if (!shots.has(key)) { - shots.set(key, ext.runtime.sendMessage({ t: MSG.SHOT, id, kind }).then(response => { - if (!response?.ok) throw new Error('No image'); +// The background sends the bytes. They go into a canvas, so the page never holds an image URL. +function loadBitmap(key, message) { + if (!bitmaps.has(key)) { + bitmaps.set(key, ext.runtime.sendMessage(message).then(response => { + if (!response?.ok || typeof response.data !== 'string') throw new Error('No image'); return createImageBitmap(new Blob([Uint8Array.from(atob(response.data), char => char.charCodeAt(0))], { type: response.type })); - }).catch(() => { shots.delete(key); return null; })); - if (shots.size > SHOT_CACHE) shots.delete(shots.keys().next().value); + }).catch(() => { bitmaps.delete(key); return null; })); + if (bitmaps.size > SHOT_CACHE) bitmaps.delete(bitmaps.keys().next().value); } - return shots.get(key); + return bitmaps.get(key); } -function renderShots(instance, pin) { - const kinds = SHOT_KINDS.filter(kind => pin.shots?.[kind]); - const signature = kinds.map(kind => kind + pin.shots[kind]).join(); - if (signature === instance.shotSignature) return; - instance.shotSignature = signature; - instance.shots.hidden = !kinds.length; - instance.shots.replaceChildren(...kinds.map(kind => { - const name = kind === 'before' ? 'Before' : 'After'; - const node = button(`Show the ${name} image at full width`, undefined, () => { - const full = node.dataset.full !== 'true'; - for (const item of instance.shots.children) { item.dataset.full = String(full && item === node); item.hidden = full && item !== node; } - setTitle(node, full ? 'Show both images side by side' : `Show the ${name} image at full width`); - schedule(); - }, 'shot'); - node.dataset.kind = kind; +function zoom(container, node, closeTitle) { + const full = node.dataset.full !== 'true'; + for (const item of container.children) { + const on = full && item === node; + item.dataset.full = String(on); + item.hidden = full && item !== node; + setTitle(item, on ? closeTitle : item.dataset.open); + } + schedule(); +} +// Shots and attached images share this strip: a click shows one image at the full card width. +function renderStrip(container, entries, closeTitle) { + const signature = entries.map(entry => entry.key).join(); + if (container.dataset.signature === signature) return; + container.dataset.signature = signature; + container.hidden = !entries.length; + container.replaceChildren(...entries.map(entry => { + const node = button(entry.title, undefined, () => zoom(container, node, closeTitle), 'shot'); + node.dataset.open = entry.title; + if (entry.kind) node.dataset.kind = entry.kind; const canvas = el('canvas'); - node.append(el('span', 'shot-name', name), canvas); - loadShot(pin.id, kind, pin.shots[kind]).then(bitmap => { - if (!bitmap) { node.remove(); return; } + if (entry.name) node.append(el('span', 'shot-name', entry.name)); + node.append(canvas); + loadBitmap(entry.key, entry.message).then(bitmap => { + if (!node.isConnected) return; + if (!bitmap) { node.remove(); if (!container.children.length) container.hidden = true; return; } const scale = Math.min(1, SHOT_WIDTH / bitmap.width); canvas.width = Math.round(bitmap.width * scale); canvas.height = Math.round(bitmap.height * scale); canvas.getContext('2d').drawImage(bitmap, 0, 0, canvas.width, canvas.height); @@ -68,6 +74,34 @@ function renderShots(instance, pin) { return node; })); } +function renderShots(instance, pin) { + const entries = SHOT_KINDS.filter(kind => pin.shots?.[kind]).map(kind => { + const name = kind === 'before' ? 'Before' : 'After'; + return { key: `${pin.id}:${kind}:${pin.shots[kind]}`, message: { t: MSG.SHOT, id: pin.id, kind }, title: `Show the ${name} image at full width`, kind, name }; + }); + renderStrip(instance.shots, entries, 'Show both images side by side'); +} +function imageEntries(images) { + return images.map((image, index) => ({ key: `image:${image.id}`, message: { t: MSG.IMAGE, id: image.id }, title: `Show image ${index + 1} at full width` })); +} +const pinImages = pin => (Array.isArray(pin?.images) ? pin.images : []).filter(image => image?.id && image.replyId == null); +function replyImages(pin, reply) { + const own = Array.isArray(reply?.images) ? reply.images.filter(image => image?.id) : []; + return own.length ? own : (Array.isArray(pin?.images) ? pin.images : []).filter(image => image?.replyId === reply?.id); +} +function renderPinImages(instance, pin) { + renderStrip(instance.pinImages, imageEntries(pinImages(pin)), 'Show the images in a row'); +} +function syncReplyStrips(instance) { + for (const li of instance.list.children) { + const reply = instance.replies.get(Number(li.dataset.id)); + const images = reply ? replyImages(instance.pin, reply) : []; + let strip = [...li.children].find(item => item.classList.contains('images')); + if (!images.length) { strip?.remove(); continue; } + if (!strip) { strip = el('div', 'images'); li.append(strip); } + renderStrip(strip, imageEntries(images), 'Show the images in a row'); + } +} export function refreshCard(instance, pin) { if (card !== instance) return; instance.pin = pin; @@ -105,6 +139,8 @@ export function refreshCard(instance, pin) { })); } renderShots(instance, pin); + renderPinImages(instance, pin); + syncReplyStrips(instance); const who = [modelName(pin), pin.agent].filter(Boolean).join(' · '); instance.agent.textContent = who ? `By ${who}` : ''; instance.agent.hidden = !who || pin.status === 'queued'; instance.summary.textContent = pin.summary || ''; instance.summary.hidden = !pin.summary; @@ -143,8 +179,10 @@ export function appendReply(instance, reply) { const time = el('time', '', date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })); time.dateTime = item.createdAt; time.title = date.toLocaleString(); meta.append(time); } + li.dataset.id = String(item.id); li.append(meta, el('p', 'reply-body', item.body)); instance.list.append(li); } + syncReplyStrips(instance); syncQuestion(instance); schedule(); } @@ -231,6 +269,7 @@ export async function openCard(id, scroll = false) { for (const node of [instance.status, instance.accepted, instance.tag]) instance.head.insertBefore(node, instance.close); const body = el('div', 'panel-body'); instance.note = el('p', 'note'); + instance.pinImages = el('div', 'images'); instance.pinImages.hidden = true; instance.question = el('p', 'question'); instance.question.hidden = true; instance.tags = el('div', 'tags'); instance.tags.hidden = true; instance.quote = el('blockquote', 'quote'); instance.quote.hidden = true; @@ -265,23 +304,30 @@ export async function openCard(id, scroll = false) { instance.reply = textarea('pin-reply', 'Add a reply…'); instance.error = errorNode('onspot-card-error'); instance.reply.setAttribute('aria-describedby', instance.error.id); + instance.replyForm = el('div', 'reply-form'); + instance.images = attachImages({ host: instance.replyForm, box: instance.reply, error: instance.error, kind: 'reply' }); const sendReply = async () => { - const text = instance.reply.value.trim(); + if (instance.images.busy()) { setError(instance.error, IMAGE_WAIT); return; } + const images = instance.images.ids(); + const text = instance.reply.value.trim() || (images.length ? attachedReply(images.length) : ''); if (!text) { setError(instance.error, instance.wrongOpen ? 'Write what is still wrong.' : 'Add a reply before sending.'); instance.reply.focus(); return; } const reopen = instance.wrongOpen; - if (await cardAction(instance, 'POST', '/replies', reopen ? { body: text, reopen: true } : { body: text }) && reopen) { - instance.wrongOpen = false; - announce(`Pin ${instance.id} goes back for another fix.`); - if (instance.pin) refreshCard(instance, instance.pin); + const payload = { body: text, ...(images.length ? { images } : {}), ...(reopen ? { reopen: true } : {}) }; + if (await cardAction(instance, 'POST', '/replies', payload)) { + instance.images.clear(); + if (reopen) { + instance.wrongOpen = false; + announce(`Pin ${instance.id} goes back for another fix.`); + if (instance.pin) refreshCard(instance, instance.pin); + } } }; instance.reply.addEventListener('keydown', event => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendReply(); } }); - instance.replyForm = el('div', 'reply-form'); const footer = el('div', 'panel-footer'); instance.sendReply = button('Send your reply', 'Reply', sendReply, 'primary'); - footer.append(instance.sendReply); - instance.replyForm.append(instance.reply, footer); - body.append(instance.note, instance.question, instance.editor, instance.tags, instance.quote, instance.target, instance.run, instance.summary, instance.agent, instance.commit, instance.shots, instance.list, instance.replyForm, instance.error); + footer.append(instance.images.button, instance.sendReply); + instance.replyForm.append(instance.reply, instance.images.node, footer); + body.append(instance.note, instance.pinImages, instance.question, instance.editor, instance.tags, instance.quote, instance.target, instance.run, instance.summary, instance.agent, instance.commit, instance.shots, instance.list, instance.replyForm, instance.error); const actions = el('div', 'actions'); instance.see = button('Reload the page and show the change', 'See it', () => { if (instance.pin) seeIt(instance.pin); }, 'primary'); // Looks good tells the server he accepts the result, then marks the pin seen, also when the call fails. diff --git a/extension/src/content/drafts.js b/extension/src/content/drafts.js index fd92d45..6ff6603 100644 --- a/extension/src/content/drafts.js +++ b/extension/src/content/drafts.js @@ -1,4 +1,5 @@ // Unsent pins: the list of this host (on every page of it), the tray, and "Submit all". +import { keepImages } from '../shared/image.js'; import { BATCH_MAX, DRAFT_MAX, draftsKey, HOST, SUBMIT_KEYS, TAB } from './env.js'; import { plural } from './format.js'; import { announce, button, el } from './dom.js'; @@ -41,8 +42,11 @@ export const saveDrafts = () => store({ [draftsKey]: { tab: TAB, items: drafts.i export function validBody(body) { try { const url = new URL(body.url); - return url.protocol === 'https:' && url.host === HOST && typeof body.note === 'string' && Boolean(body.note.trim()) + const ok = url.protocol === 'https:' && url.host === HOST && typeof body.note === 'string' && Boolean(body.note.trim()) && Array.isArray(body.targets) && body.targets.length > 0 && body.targets.every(target => typeof target?.selector === 'string' && typeof target.label === 'string'); + // Bad image ids are dropped here. At most six remain. The text draft per page keeps none. + if (ok) keepImages(body); + return ok; } catch { return false; } } function cleanDrafts(value) { diff --git a/extension/src/content/images.js b/extension/src/content/images.js new file mode 100644 index 0000000..531a92e --- /dev/null +++ b/extension/src/content/images.js @@ -0,0 +1,157 @@ +// Paste, drop or pick images for a note or a reply. The bytes go to the background script. +// Thumbnails are canvases: the page never holds an image URL. +import { ext, IMAGE_ID_RE, IMAGES_MAX, MSG, SHOT_MAX } from '../shared/protocol.js'; +import { ENCODE_ATTEMPTS, bytesToBase64, cleanImageIds, drawSize, sendAsIs } from '../shared/image.js'; +import { el, iconButton } from './dom.js'; +import { setError } from './layout.js'; + +export const IMAGE_WAIT = 'Wait until the image is uploaded.'; +export const attachedReply = count => count > 1 ? 'See the attached images.' : 'See the attached image.'; +const limitText = kind => kind === 'reply' ? 'A reply takes up to 6 images.' : 'A pin takes up to 6 images.'; + +function imageFiles(list) { + return [...list || []].filter(file => file && (!file.type || file.type.startsWith('image/'))); +} +function filesOf(data) { + const listed = [...data?.files || []]; + const items = []; + if (!listed.length && data?.items) for (const item of data.items) if (item.kind === 'file') items.push(item.getAsFile()); + return imageFiles(listed.length ? listed : items); +} + +// A file the browser can decode. A shot type that already fits is sent unchanged. Anything +// else is drawn down to 2560 px and encoded, then scaled by 0.75 at most three more times. +export async function prepareImage(file) { + let bitmap; + try { bitmap = await createImageBitmap(file); } + catch { throw new Error('That file is not an image this browser can read.'); } + try { + if (!bitmap.width || !bitmap.height) throw new Error('That file is not an image this browser can read.'); + if (sendAsIs(file.type, file.size, bitmap.width, bitmap.height)) return { type: file.type, bytes: new Uint8Array(await file.arrayBuffer()), bitmap }; + for (let attempt = 0; attempt < ENCODE_ATTEMPTS; attempt++) { + const [width, height] = drawSize(bitmap.width, bitmap.height, attempt); + const canvas = document.createElement('canvas'); + canvas.width = width; canvas.height = height; + canvas.getContext('2d').drawImage(bitmap, 0, 0, width, height); + for (const [type, quality] of [['image/webp', 0.9], ['image/jpeg', 0.8]]) { + const blob = await new Promise(resolve => canvas.toBlob(resolve, type, quality)); + if (blob && blob.size >= 1 && blob.size <= SHOT_MAX) return { type, bytes: new Uint8Array(await blob.arrayBuffer()), bitmap }; + } + } + throw new Error('That image is too large.'); + } catch (error) { bitmap.close?.(); throw error; } +} + +function paint(canvas, bitmap, side) { + const scale = Math.min(1, side / Math.max(bitmap.width, bitmap.height)); + canvas.width = Math.max(1, Math.round(bitmap.width * scale)); + canvas.height = Math.max(1, Math.round(bitmap.height * scale)); + canvas.getContext('2d').drawImage(bitmap, 0, 0, canvas.width, canvas.height); +} + +// `host` receives the drop (the popup, or the reply form). `box` receives the paste. +export function attachImages({ host, box, error, kind, ids }) { + const slots = []; + const node = el('div', 'thumbs'); + const file = el('input', 'file-input'); + file.type = 'file'; file.accept = 'image/*'; file.multiple = true; file.hidden = true; file.tabIndex = -1; + file.setAttribute('aria-hidden', 'true'); + const button = iconButton('Add an image. You can also paste or drop one.', 'plus', event => { + if (!event.isTrusted) return; + try { file.showPicker(); } catch { /* This browser refused the picker. Paste and drop still work. */ } + }, 'add-image'); + host.append(file); + + const render = () => node.replaceChildren(...slots.map((slot, index) => { + const thumb = el('div', 'thumb'); + thumb.setAttribute('aria-busy', slot.busy ? 'true' : 'false'); + const canvas = el('canvas'); + if (slot.bitmap) paint(canvas, slot.bitmap, 48); + const remove = iconButton(`Remove image ${index + 1}`, 'close', () => { + slot.bitmap?.close?.(); + const at = slots.indexOf(slot); + if (at >= 0) slots.splice(at, 1); + render(); + }, 'thumb-remove'); + thumb.append(canvas, remove); + return thumb; + })); + const drop = id => { const at = slots.indexOf(id); if (at < 0) return false; id.bitmap?.close?.(); slots.splice(at, 1); render(); return true; }; + + async function addOne(item) { + if (slots.length >= IMAGES_MAX) return false; + const slot = { id: '', busy: true, bitmap: null }; + slots.push(slot); render(); + try { + const prepared = await prepareImage(item); + if (!slots.includes(slot)) { prepared.bitmap.close?.(); return true; } + slot.bitmap = prepared.bitmap; render(); + const response = await ext.runtime.sendMessage({ t: MSG.UPLOAD, type: prepared.type, data: bytesToBase64(prepared.bytes) }); + const imageId = response?.data?.image?.id; + if (!slots.includes(slot)) return true; + if (!response?.ok || !IMAGE_ID_RE.test(imageId || '')) throw new Error(response?.error || 'the upload failed'); + slot.id = imageId; slot.busy = false; render(); + } catch (failure) { + if (drop(slot)) setError(error, `Image not added: ${failure instanceof Error ? failure.message : 'the upload failed'}`); + } + return true; + } + async function addFiles(list) { + const files = [...list || []].filter(Boolean); + if (!files.length) return; + let room = true; + for (const item of files) { + if (!(await addOne(item))) { room = false; break; } + } + if (!room) setError(error, limitText(kind)); + } + async function loadStored(imageId) { + const slot = { id: imageId, busy: true, bitmap: null }; + slots.push(slot); render(); + try { + const response = await ext.runtime.sendMessage({ t: MSG.IMAGE, id: imageId }); + if (!response?.ok || typeof response.data !== 'string') throw new Error('it is gone'); + const bitmap = await createImageBitmap(new Blob([Uint8Array.from(atob(response.data), char => char.charCodeAt(0))], { type: response.type })); + if (!slots.includes(slot)) { bitmap.close?.(); return; } + slot.bitmap = bitmap; slot.busy = false; render(); + } catch (failure) { + if (drop(slot)) setError(error, `Image not added: ${failure instanceof Error ? failure.message : 'it is gone'}`); + } + } + + box.addEventListener('paste', event => { + if (!event.isTrusted) return; + const files = filesOf(event.clipboardData); + if (!files.length) return; + if (![...event.clipboardData.types].includes('text/plain')) event.preventDefault(); + event.stopPropagation(); + void addFiles(files); + }); + host.addEventListener('dragover', event => { + if (!event.isTrusted || !event.dataTransfer?.types?.includes('Files')) return; + event.preventDefault(); event.stopPropagation(); + host.dataset.drop = 'true'; + }); + host.addEventListener('dragleave', event => { if (!host.contains(event.relatedTarget)) delete host.dataset.drop; }); + host.addEventListener('drop', event => { + delete host.dataset.drop; + if (!event.isTrusted) return; + const files = filesOf(event.dataTransfer); + if (!files.length) return; + event.preventDefault(); event.stopPropagation(); + void addFiles(files); + }); + file.addEventListener('change', event => { + if (!event.isTrusted) return; + const chosen = [...file.files]; + file.value = ''; + void addFiles(chosen); + }); + for (const imageId of cleanImageIds(ids)) void loadStored(imageId); + return { + node, button, + busy: () => slots.some(slot => slot.busy), + ids: () => slots.filter(slot => slot.id).map(slot => slot.id), + clear() { for (const slot of slots) slot.bitmap?.close?.(); slots.length = 0; render(); }, + }; +} diff --git a/extension/src/content/index.js b/extension/src/content/index.js index 316ccac..810f8fb 100644 --- a/extension/src/content/index.js +++ b/extension/src/content/index.js @@ -25,7 +25,8 @@ function mount() { root.append(live, menu, capsule, tray, toastBox, overlay, outline, hoverLabel, selectionBar); // Only his own input counts. A page script can reach an open shadow root and make events there. // An event that a script made (`isTrusted` false) stops here, before any of our handlers. - for (const type of ['click', 'pointerdown', 'pointerup', 'keydown']) { + // `change` is not in this list: the file input checks it itself, and a select uses `change` too. + for (const type of ['click', 'pointerdown', 'pointerup', 'keydown', 'paste', 'drop']) { root.addEventListener(type, event => { if (event.isTrusted) return; event.stopImmediatePropagation(); diff --git a/extension/src/content/local.js b/extension/src/content/local.js index caa0e1f..07babb5 100644 --- a/extension/src/content/local.js +++ b/extension/src/content/local.js @@ -15,7 +15,7 @@ let storageChain = Promise.resolve(); const prefsWrites = new Set(); export let prefs = cleanPrefs(undefined, MAC); -export function textKey(url = pageURL) { return `kog-pins:draft:${url}`; } // unsent textarea text +export function textKey(url = pageURL) { return `kog-pins:draft:${url}`; } // unsent textarea text; it does not keep images function legacyKey(url = pageURL) { return `kog-pins:pending:${url}`; } // v1 failed sends // Writes run one after the other, so a later write never lands before an earlier one. function write(task) { diff --git a/extension/src/content/notes.js b/extension/src/content/notes.js index 41886a7..1bd48dd 100644 --- a/extension/src/content/notes.js +++ b/extension/src/content/notes.js @@ -11,6 +11,7 @@ import { pageURL } from './routes.js'; import { pinButton } from './capsule.js'; import { clearSelection, mode, selected, selectionBar } from './picker.js'; import { addDraft, drafts, removeDraft, saveDrafts, submitAll } from './drafts.js'; +import { IMAGE_WAIT, attachedReply, attachImages } from './images.js'; import { renderAll } from './pins.js'; import { closeSettings } from './settings.js'; import { closeCard } from './card.js'; @@ -58,6 +59,7 @@ export function openPopup({ quote = '', draft = null } = {}) { if (instance.quote) instance.body.append(el('blockquote', 'quote', instance.quote)); if (edit) instance.input.value = draft.body.note; instance.error = errorNode('onspot-note-error'); + instance.images = attachImages({ host: instance.panel, box: instance.input, error: instance.error, kind: 'pin', ids: edit ? draft.body.images : undefined }); instance.input.setAttribute('aria-describedby', instance.error.id); instance.input.addEventListener('input', () => { instance.touched = true; saveText(instance); setError(instance.error); instance.input.removeAttribute('aria-invalid'); }); instance.input.addEventListener('keydown', event => { @@ -66,8 +68,8 @@ export function openPopup({ quote = '', draft = null } = {}) { const footer = el('div', 'panel-footer'); footer.append(el('span', 'hint', `↵ ${edit ? 'save' : 'add'} · ${SUBMIT_KEYS} submit all`)); if (edit) footer.append(button('Discard this unsent pin', 'Discard', () => { removeDraft(draft.id); closePopup(); }, 'danger')); - footer.append(button(edit ? 'Save this unsent pin' : 'Add this pin to the batch', edit ? 'Save' : 'Add pin', () => savePopup(instance, false), 'primary')); - instance.body.append(instance.input, instance.error, footer); + footer.append(instance.images.button, button(edit ? 'Save this unsent pin' : 'Add this pin to the batch', edit ? 'Save' : 'Add pin', () => savePopup(instance, false), 'primary')); + instance.body.append(instance.input, instance.images.node, instance.error, footer); instance.panel.append(instance.body); popup = instance; selectionBar.hidden = true; @@ -94,8 +96,10 @@ export function closePopup(restoreFocus = true, save = true) { } function savePopup(instance, thenSubmit) { if (popup !== instance) return; - // With the Remove tab the note may be empty. - const note = instance.input.value.trim() || (instance.intent === 'remove' ? 'Remove this element.' : ''); + if (instance.images.busy()) { setError(instance.error, IMAGE_WAIT); return; } + // With the Remove tab, or with images, the note may be empty. + const images = instance.images.ids(); + const note = instance.input.value.trim() || (instance.intent === 'remove' ? 'Remove this element.' : images.length ? attachedReply(images.length) : ''); const picks = { intent: instance.intent, scope: instance.scope, presets: instance.presets }; if (!note) { // An empty note with ⌘↵ submits the pins that are already there. @@ -105,7 +109,11 @@ function savePopup(instance, thenSubmit) { } if (instance.edit) { const draft = drafts.items.find(item => item.id === instance.draft.id); - if (draft) { draft.body = { ...draft.body, note, ...picks }; saveDrafts(); } + if (draft) { + draft.body = { ...draft.body, note, ...picks }; + if (images.length) draft.body.images = images; else delete draft.body.images; + saveDrafts(); + } closePopup(); announce('Unsent pin saved.'); } else { @@ -116,6 +124,7 @@ function savePopup(instance, thenSubmit) { addDraft({ url: instance.url, title: document.title.slice(0, 300), note, quote: instance.quote, targets, viewport: { w: innerWidth, h: innerHeight, dpr: devicePixelRatio, scrollX, scrollY }, ...picks, + ...(images.length ? { images } : {}), }); store({ [textKey(instance.url)]: '' }).catch(() => {}); closePopup(false, false); diff --git a/extension/src/content/styles.js b/extension/src/content/styles.js index 7713501..7465288 100644 --- a/extension/src/content/styles.js +++ b/extension/src/content/styles.js @@ -128,7 +128,7 @@ textarea, input, select { display: block; width: 100%; padding: 9px 10px; border textarea { resize: vertical; min-height: 68px; max-height: 35dvh; } input, select { height: 36px; padding-block: 0; margin-bottom: 6px; } textarea::placeholder, input::placeholder { color: var(--muted); } -.panel-footer { display: flex; align-items: center; justify-content: flex-end; gap: 6px; margin-top: 10px; } +.panel-footer { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; margin-top: 10px; } .quote { border-left: 2px solid var(--focus); color: var(--muted); padding-left: 9px; margin: 0 0 12px; max-height: 90px; overflow-y: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; } .error { color: #fca5a5; font-size: 12px; margin: 8px 0 0; overflow-wrap: anywhere; } .status { color: var(--focus); font-size: 11px; font-weight: 600; max-width: 58%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @@ -154,6 +154,16 @@ textarea::placeholder, input::placeholder { color: var(--muted); } .shot[data-full='true'] { grid-column: 1 / -1; cursor: zoom-out; } .shot-name { font-size: 11px; font-weight: 600; color: var(--muted); } .shot canvas { display: block; width: 100%; height: auto; border: 1px solid var(--line); border-radius: 6px; background: var(--well); } +.images { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 12px; } +.images .shot { flex: 1 1 72px; max-width: 120px; } +.images .shot[data-full='true'] { flex-basis: 100%; max-width: none; } +.thumbs { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } +.thumb { position: relative; width: 48px; height: 48px; } +.thumb canvas { display: block; width: 48px; height: 48px; border: 1px solid var(--line); border-radius: 6px; background: var(--well); } +.thumb[aria-busy='true'] { opacity: .45; } +.thumb-remove { position: absolute; top: -6px; right: -6px; width: 18px; min-height: 18px; padding: 0; border-radius: 9px; background: var(--surface); } +.thumb-remove svg { width: 12px; height: 12px; } +.popup[data-drop='true'], .reply-form[data-drop='true'] { box-shadow: inset 0 0 0 2px var(--focus); } .actions { display: flex; flex-wrap: wrap; gap: 3px; border-top: 1px solid var(--line); padding: 7px 9px; } .actions button { font-size: 12px; } .danger { color: #fca5a5; } diff --git a/extension/src/shared/image.js b/extension/src/shared/image.js new file mode 100644 index 0000000..e7dd3c4 --- /dev/null +++ b/extension/src/shared/image.js @@ -0,0 +1,71 @@ +// Pure rules for an attached image. The background and the content script both use them. +import { IMAGE_ID_RE, IMAGES_MAX, SHOT_MAX, SHOT_TYPES } from "./protocol.js"; + +export const IMAGE_SIDE = 2560; +// One draw at the 2560 fit, then at most three scales of 0.75. +export const ENCODE_ATTEMPTS = 4; + +// `apply` on 8 KiB parts: 13 ms for 2 MiB. The spread form on 32 KiB parts took 104 ms. +export function bytesToBase64(bytes) { + let text = ""; + for (let i = 0; i < bytes.length; i += 0x2000) text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x2000)); + return btoa(text); +} + +// Null when `data` is not base64, or when the decoded bytes are empty or over `max`. +export function base64ToBytes(data, max) { + if (typeof data !== "string" || !data || data.length > Math.ceil(max / 3) * 4) return null; + let binary; + try { binary = atob(data); } catch { return null; } + if (!binary.length || binary.length > max) return null; + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +} + +// The shot magic check (server `shotType`): the first bytes must match the type. +export function imageType(bytes) { + if (!bytes || bytes.length < 3) return ""; + if (bytes.length >= 4 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png"; + if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg"; + if (bytes.length >= 12 && String.fromCharCode(bytes[0], bytes[1], bytes[2], bytes[3]) === "RIFF" && String.fromCharCode(bytes[8], bytes[9], bytes[10], bytes[11]) === "WEBP") return "image/webp"; + return ""; +} + +// Send the file unchanged when the browser already stored a shot type at a size we can post. +export function sendAsIs(type, size, width, height) { + return SHOT_TYPES.includes(type) && size >= 1 && size <= SHOT_MAX && width >= 1 && height >= 1 && Math.max(width, height) <= IMAGE_SIDE; +} + +// The canvas size for encode attempt `attempt` (0 is the first draw). +export function drawSize(width, height, attempt) { + const longest = Math.max(width, height, 1); + const fit = Math.min(1, IMAGE_SIDE / longest); + let w = Math.max(1, Math.round(width * fit)); + let h = Math.max(1, Math.round(height * fit)); + for (let step = 0; step < attempt; step++) { + w = Math.max(1, Math.round(w * 0.75)); + h = Math.max(1, Math.round(h * 0.75)); + } + return [w, h]; +} + +// At most 6 ids, in order. A bad id or a duplicate is dropped. +export function cleanImageIds(value) { + const ids = []; + if (!Array.isArray(value)) return ids; + for (const id of value) { + if (typeof id === "string" && IMAGE_ID_RE.test(id) && !ids.includes(id)) ids.push(id); + if (ids.length === IMAGES_MAX) break; + } + return ids; +} + +// The draft keeps the cleaned list, or no key when nothing valid remains. +export function keepImages(body) { + const images = cleanImageIds(body?.images); + if (!body || typeof body !== "object") return images; + if (images.length) body.images = images; + else delete body.images; + return images; +} diff --git a/extension/src/shared/protocol.js b/extension/src/shared/protocol.js index 47eaf6d..3427f23 100644 --- a/extension/src/shared/protocol.js +++ b/extension/src/shared/protocol.js @@ -18,16 +18,22 @@ export const API_PATH_RE = /^\/api\/(health|stats|batches|settings|pins(\/[1-9][ export const API_METHODS = ["GET", "POST", "PATCH", "DELETE"]; export const SETTINGS_METHODS = ["GET", "PATCH"]; -// Before/after images of a run: fetched by the background script, drawn by the content script. +// Before/after images of a run, and images he attaches to a pin or a reply. The background +// script fetches the bytes. The content script draws them into a canvas. export const PIN_ID_RE = /^[1-9][0-9]{0,11}$/; export const SHOT_KINDS = ["before", "after"]; export const SHOT_TYPES = ["image/png", "image/jpeg", "image/webp"]; export const SHOT_MAX = 2 * 1024 * 1024; +// 16 random bytes as base64url. Not guessable. A pin or a reply takes at most this many. +export const IMAGE_ID_RE = /^[A-Za-z0-9_-]{22}$/; +export const IMAGES_MAX = 6; export const MSG = { - API: "api", // content -> bg, one-shot + API: "api", // content -> bg, one-shot. JSON only: it does not carry /api/images. STATE: "state", // content -> bg one-shot ({ state } back); bg -> content on the port SHOT: "shot", // content -> bg, one-shot: { id, kind } -> { ok, status, type, data (base64) } + UPLOAD: "upload", // content -> bg, one-shot: { type, data (base64) } -> { ok, status, data: { image } | null, error? } + IMAGE: "image", // content -> bg, one-shot: { id } -> { ok, status, type, data (base64) } SUB: "sub", // content -> bg on the port PING: "ping", // content -> bg on the port PIN: "pin", // bg -> content: { action, pin } diff --git a/extension/test/background.test.js b/extension/test/background.test.js index 2d959cd..cb7cd0b 100644 --- a/extension/test/background.test.js +++ b/extension/test/background.test.js @@ -4,11 +4,19 @@ import { execFileSync } from "node:child_process"; import { setImmediate as settle } from "node:timers/promises"; import { createAPI } from "../src/bg/api.js"; import { createLive } from "../src/bg/live.js"; -import { createShot } from "../src/bg/shot.js"; +import { createImage, createShot } from "../src/bg/shot.js"; +import { createUpload } from "../src/bg/upload.js"; +import { bytesToBase64 } from "../src/shared/image.js"; import { API, API_PATH_RE, MSG, STATE } from "../src/shared/protocol.js"; const request = (overrides = {}) => ({ t: MSG.API, method: "GET", path: "/api/health", ...overrides }); const shotRequest = (overrides = {}) => ({ t: MSG.SHOT, id: 12, kind: "before", ...overrides }); +const IMAGE_ID = "Abcd1234_-Abcd1234_-Ab"; +const PNG = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3); +const JPEG = Uint8Array.of(0xff, 0xd8, 0xff, 0xe0, 1, 2, 3); +const uploadRequest = (overrides = {}) => ({ t: MSG.UPLOAD, type: "image/png", data: bytesToBase64(PNG), ...overrides }); +const imageRequest = (overrides = {}) => ({ t: MSG.IMAGE, id: IMAGE_ID, ...overrides }); +const savedImage = { id: IMAGE_ID, type: "image/png", size: PNG.length, replyId: null, author: "sam", createdAt: "2026-11-15T10:00:00.000Z" }; const image = (bytes, type = "image/png", length) => new Response(bytes, { headers: { "Content-Type": type, ...(length ? { "Content-Length": String(length) } : {}) } }); const MIB2 = 2 * 1024 * 1024; const encode = (text) => new TextEncoder().encode(text); @@ -156,7 +164,7 @@ test("the path allowlist holds what the content script calls and nothing that on const allowed = ["/api/health", "/api/pins", "/api/pins?host=a.koglabs.com&status=all&limit=50", "/api/pins/12", "/api/batches", "/api/pins/12/dismiss", "/api/pins/12/reopen", "/api/pins/12/replies", "/api/pins/12/accept", "/api/pins/12/revert", "/api/settings"]; const refused = ["/api/pins/12/shots/before", "/api/pins/12/shots/after", "/api/pins/12/progress", "/api/pins/12/ask", "/api/settings/bulk", - "/api/settingsx", "/api/pins/12/accept/1", "/api/pins/0/accept", "/api/pins/12/revert/1", "/api/pins/12/reverts", "/api/events", "/mcp", "/download/onspot-chrome.zip", "/api/pins/12/replies/3", "/api/pins/12?x#y", "/pins/api/health"]; + "/api/settingsx", "/api/pins/12/accept/1", "/api/pins/0/accept", "/api/pins/12/revert/1", "/api/pins/12/reverts", "/api/events", "/api/images", `/api/images/${"a".repeat(22)}`, "/mcp", "/download/onspot-chrome.zip", "/api/pins/12/replies/3", "/api/pins/12?x#y", "/pins/api/health"]; for (const path of allowed) assert.equal(API_PATH_RE.test(path), true, path); let count = 0; const api = createAPI({ fetch: () => { count++; throw new Error("must not fetch"); } }); @@ -280,9 +288,9 @@ test("API maps JSON, 204, non-JSON, errors, 401, offline and timeout responses", test("a followed redirect is not trusted: only the first answer of the API counts", async () => { // With `redirect: "manual"` the browser never sends the cookie or the body to a second address. - for (const make of [createAPI, createShot]) { + for (const [make, message] of [[createAPI, request()], [createShot, shotRequest()], [createImage, imageRequest()], [createUpload, uploadRequest()]]) { const calls = []; - await make({ fetch: async (...args) => { calls.push(args); return redirect(); } })(make === createAPI ? request() : shotRequest()); + await make({ fetch: async (...args) => { calls.push(args); return redirect(); } })(message); assert.equal(calls.length, 1); assert.equal(calls[0][1].redirect, "manual"); assert.equal(calls[0][1].credentials, "include"); @@ -290,6 +298,63 @@ test("a followed redirect is not trusted: only the first answer of the API count } }); +test("image refuses a bad id before fetch and reads one image like a shot", async () => { + let count = 0; + const read = createImage({ fetch: () => { count++; throw new Error("must not fetch"); } }); + const bad = [null, [], {}, imageRequest({ t: MSG.SHOT }), + ...["", "short", `${IMAGE_ID}x`, `${IMAGE_ID.slice(0, 21)}+`, "a/b", null, 1, [IMAGE_ID]].map((id) => imageRequest({ id }))]; + for (const message of bad) assert.deepEqual(await read(message), { ok: false, status: 400 }, JSON.stringify(message)); + assert.equal(count, 0); + const calls = []; + const bytes = Uint8Array.from(PNG); + const ok = await createImage({ fetch: async (...args) => { calls.push(args); return image(bytes, "image/webp"); } })(imageRequest()); + assert.deepEqual(calls.map(sent), [[`${API}/api/images/${IMAGE_ID}`, COOKIE_NO_REDIRECT]]); + assert.equal(ok.type, "image/webp"); + assert.deepEqual(new Uint8Array(Buffer.from(ok.data, "base64")), bytes); + let login = 0; + const live = { requireLogin: () => login++ }; + assert.deepEqual(await createImage({ fetch: async () => new Response(null, { status: 401 }), live })(imageRequest()), { ok: false, status: 401 }); + assert.deepEqual(await createImage({ fetch: async () => redirect(), live })(imageRequest()), { ok: false, status: 401 }); + assert.equal(login, 2); +}); + +test("upload checks the message, the magic bytes and the size, then posts the raw image", async () => { + let count = 0; + const upload = createUpload({ fetch: () => { count++; throw new Error("must not fetch"); } }); + const bad = [null, [], {}, uploadRequest({ t: MSG.API }), uploadRequest({ type: "image/gif" }), uploadRequest({ type: "image/jpeg" }), + uploadRequest({ data: "" }), uploadRequest({ data: "!!!!" }), uploadRequest({ data: 1 }), uploadRequest({ data: null }), + uploadRequest({ data: "A".repeat(Math.ceil(MIB2 / 3) * 4 + 1) })]; + for (const message of bad) assert.deepEqual(await upload(message), { ok: false, status: 400, data: null }, JSON.stringify(message?.data)?.slice(0, 80)); + assert.equal(count, 0); + const calls = []; + const live = { requireLogin: () => {} }; + const result = await createUpload({ fetch: async (...args) => { calls.push(args); return Response.json({ image: savedImage }, { status: 201 }); }, live })(uploadRequest()); + assert.deepEqual(result, { ok: true, status: 201, data: { image: savedImage } }); + assert.deepEqual(sent(calls[0]), [`${API}/api/images`, { method: "POST", ...COOKIE_NO_REDIRECT, headers: { "Content-Type": "image/png" }, body: PNG }]); + const jpegCalls = []; + await createUpload({ fetch: async (...args) => { jpegCalls.push(args); return Response.json({ image: { ...savedImage, type: "image/jpeg" } }, { status: 201 }); } })(uploadRequest({ type: "image/jpeg", data: bytesToBase64(JPEG) })); + assert.equal(jpegCalls[0][1].headers["Content-Type"], "image/jpeg"); + assert.deepEqual(jpegCalls[0][1].body, JPEG); +}); + +test("upload reports a lost session, a server error, a bad success and a lost connection", async () => { + let login = 0; + const live = { requireLogin: () => login++ }; + const cases = [ + [new Response(null, { status: 401 }), { ok: false, status: 401, data: null, error: "login required" }], + [redirect(), { ok: false, status: 401, data: null, error: "login required" }], + [Response.json({ error: "too many images wait for a pin" }, { status: 409 }), { ok: false, status: 409, data: null, error: "too many images wait for a pin" }], + [new Response("nope", { status: 415 }), { ok: false, status: 415, data: null, error: "HTTP 415" }], + [Response.json({ image: { id: "short" } }, { status: 201 }), { ok: false, status: 502, data: null, error: "unexpected response" }], + [new Response("not json", { status: 201 }), { ok: false, status: 502, data: null, error: "unexpected response" }], + ]; + for (const [response, expected] of cases) assert.deepEqual(await createUpload({ fetch: async () => response, live })(uploadRequest()), expected); + assert.equal(login, 2); + assert.deepEqual(await createUpload({ fetch: async () => { throw new Error("network"); }, live })(uploadRequest()), { ok: false, status: 0, data: null, error: "offline" }); + assert.deepEqual(await alive(createUpload({ fetch: hang, live, timeoutMs: 20 })(uploadRequest())), { ok: false, status: 0, data: null, error: "timeout" }); + assert.equal(login, 2); +}); + test("one live stream fans out only to each subscribed host and accepts pings", async (t) => { const stream = upstream(); const { live, calls, clock } = harness(t, () => stream.response); @@ -550,7 +615,7 @@ test("background answers only its own content script on the root domain, in both { ...page, url: 'https://koglabs.com.evil.example/' }, { ...page, url: 'https://notkoglabs.com/' }, { ...page, url: 'https://evil.example/?https://koglabs.com/' }, { ...page, url: 'chrome-extension://' + ID + '/page.html' }, { ...page, url: 'about:blank' }]; for (const sender of strangers) { - for (const message of [{ t: 'state' }, health, { t: 'shot', id: 1, kind: 'before' }]) { + for (const message of [{ t: 'state' }, health, { t: 'shot', id: 1, kind: 'before' }, { t: 'upload', type: 'image/png', data: 'a' }, { t: 'image', id: 'a' }]) { assert.equal(api.runtime.onMessage.fn(message, sender, () => assert.fail('answered ' + JSON.stringify(sender))), false); } } @@ -575,6 +640,10 @@ test("background answers only its own content script on the root domain, in both assert.deepEqual(result, { ok: true, status: 200, data: { ok: true } }); const shot = await new Promise((resolve) => assert.equal(api.runtime.onMessage.fn({ t: 'shot', id: '1/../2', kind: 'before' }, page, resolve), true)); assert.deepEqual(shot, { ok: false, status: 400 }); + const upload = await new Promise((resolve) => assert.equal(api.runtime.onMessage.fn({ t: 'upload', type: 'image/png', data: '!!!!' }, page, resolve), true)); + assert.deepEqual(upload, { ok: false, status: 400, data: null }); + const imageMsg = await new Promise((resolve) => assert.equal(api.runtime.onMessage.fn({ t: 'image', id: '../no' }, page, resolve), true)); + assert.deepEqual(imageMsg, { ok: false, status: 400 }); assert.deepEqual(fetched, ['https://ai.koglabs.com/pins/api/health']); api.commands.onCommand.fn('other'); api.commands.onCommand.fn('toggle-pins'); diff --git a/extension/test/harness/fake-ext.js b/extension/test/harness/fake-ext.js index ee2f24d..53e053e 100644 --- a/extension/test/harness/fake-ext.js +++ b/extension/test/harness/fake-ext.js @@ -1,12 +1,29 @@ -import { API_METHODS, API_PATH_RE, MSG, PIN_ID_RE, PORT_NAME, SETTINGS_METHODS, SHOT_KINDS, STATE } from '../../src/shared/protocol.js'; +import { API_METHODS, API_PATH_RE, IMAGE_ID_RE, IMAGES_MAX, MSG, PIN_ID_RE, PORT_NAME, SETTINGS_METHODS, SHOT_KINDS, SHOT_TYPES, STATE } from '../../src/shared/protocol.js'; /* global __ONSPOT_VERSION__, __SHOTS__ */ +// Playwright sets the chosen files and then fires `change` with isTrusted false. A real pick is +// trusted. The product ignores the untrusted event. This page is the harness, so a change on a +// file input is reported as trusted and the product handler runs. No other event is changed. +const nativeAddEventListener = EventTarget.prototype.addEventListener; +EventTarget.prototype.addEventListener = function (type, listener, options) { + if (type !== 'change' || typeof listener !== 'function') return nativeAddEventListener.call(this, type, listener, options); + return nativeAddEventListener.call(this, type, function (event) { + if (event.isTrusted || event.target?.type !== 'file') return listener.call(this, event); + const proxy = new Proxy(event, { get(obj, key) { + if (key === 'isTrusted') return true; + const value = Reflect.get(obj, key, obj); + return typeof value === 'function' ? value.bind(obj) : value; + } }); + return listener.call(this, proxy); + }, options); +}; const INTENTS = ['text', 'style', 'layout', 'behaviour', 'remove', 'task'], SCOPES = ['element', 'similar', 'page', 'site']; const listeners = new Set(), ports = new Set(); const persisted = JSON.parse(localStorage.getItem('onspot-harness-db') || 'null'); const defaultSettings = () => ({ autofix: true, bulk: { on: false, delegate: false, agents: 3 } }); -const db = persisted || { pins: [], replies: [], steps: [], batches: [], nextPin: 1, nextReply: 1, nextStep: 1, nextBatch: 1, settings: defaultSettings() }; +const db = persisted || { pins: [], replies: [], steps: [], batches: [], images: [], nextPin: 1, nextReply: 1, nextStep: 1, nextBatch: 1, settings: defaultSettings() }; +if (!Array.isArray(db.images)) db.images = []; const calls = [], portMessages = [], failures = [], answers = [], storageListeners = new Set(); let lostResponses = 0; let connections = 0; @@ -42,17 +59,48 @@ function validateCreate(body) { } return url; } +function newImageId() { + const bytes = new Uint8Array(16); + crypto.getRandomValues(bytes); + return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} +function publicImage(image) { + return { id: image.id, type: image.type, size: image.size, replyId: image.replyId, author: image.author, createdAt: image.createdAt }; +} +// Ids of images that still wait for a pin. An unknown or already linked id is the same error as the store. +function takeImages(ids) { + if (ids === undefined) return []; + if (!Array.isArray(ids) || ids.length > IMAGES_MAX || new Set(ids).size !== ids.length || ids.some(id => typeof id !== 'string' || !IMAGE_ID_RE.test(id))) throw new Error('Invalid images'); + const records = []; + for (const id of ids) { + const image = db.images.find(item => item.id === id); + if (!image || image.pinId) throw new Error(`image ${id.slice(0, 6)} is gone; remove it and try again`); + records.push(image); + } + return records; +} +function linkImages(pin, records, replyId) { + if (!Array.isArray(pin.images)) pin.images = []; + const meta = []; + for (const image of records) { + image.pinId = pin.id; image.replyId = replyId; + const item = publicImage(image); + pin.images.push(item); meta.push(item); + } + return meta; +} function create(body, batch = null) { const url = validateCreate(body); + const records = takeImages(body.images); url.hash = ''; const pin = { id: db.nextPin++, status: 'queued', url: url.href, host: url.host.toLowerCase(), path: url.pathname, title: (body.title || '').slice(0, 300), note: body.note.trim(), quote: body.quote?.slice(0, 2000) || null, targets: copy(body.targets), viewport: body.viewport || null, author: 'tester', agent: null, summary: null, commit: null, run: null, batch, model: null, attempts: 0, acceptedAt: null, reopens: 0, versions: [], revert: null, revertedAt: null, - intent: body.intent ?? null, scope: body.scope ?? null, presets: copy(body.presets ?? []), progress: null, shots: { before: null, after: null }, replyCount: 0, createdAt: now(), updatedAt: now(), startedAt: null, closedAt: null, + intent: body.intent ?? null, scope: body.scope ?? null, presets: copy(body.presets ?? []), progress: null, shots: { before: null, after: null }, images: [], replyCount: 0, createdAt: now(), updatedAt: now(), startedAt: null, closedAt: null, }; - db.pins.push(pin); save(); return pin; + db.pins.push(pin); linkImages(pin, records, null); save(); return pin; } function createBatch(body) { if (!Array.isArray(body?.pins) || body.pins.length < 1 || body.pins.length > 30) throw new Error('pins must hold 1 to 30 pins'); @@ -131,8 +179,12 @@ function handle({ method, path, body }) { if (method !== 'POST') return failure('Method not allowed', 405); if (action === 'replies') { if (body?.reopen !== undefined && typeof body.reopen !== 'boolean') return failure('reopen must be true or false'); + const records = takeImages(body?.images); + if (!Array.isArray(pin.images)) pin.images = []; + if (pin.images.length + records.length > 12) return failure('a pin holds at most 12 images', 409); const reopen = pin.status === 'waiting' || (body?.reopen === true && ['done', 'dismissed'].includes(pin.status)); const item = reply(pin, body?.body); + item.images = linkImages(pin, records, item.id); if (reopen) reopenPin(pin); save(); return success({ reply: copy(item), pin: copy(pin) }, 201); @@ -176,6 +228,18 @@ function answer(message) { const pin = db.pins.find(item => item.id === Number(message.id)); return pin?.shots[message.kind] ? { ok: true, status: 200, type: 'image/png', data: __SHOTS__[message.kind] } : { ok: false, status: 404 }; } + if (message.t === MSG.UPLOAD) { + if (!SHOT_TYPES.includes(message.type) || typeof message.data !== 'string' || !message.data) return { ok: false, status: 400, data: null }; + const pad = message.data.endsWith('==') ? 2 : message.data.endsWith('=') ? 1 : 0; + const image = { id: newImageId(), type: message.type, data: message.data, size: Math.floor(message.data.length * 3 / 4) - pad, replyId: null, pinId: null, author: 'tester', createdAt: now() }; + db.images.push(image); save(); + return { ok: true, status: 201, data: { image: publicImage(image) } }; + } + if (message.t === MSG.IMAGE) { + if (typeof message.id !== 'string' || !IMAGE_ID_RE.test(message.id)) return { ok: false, status: 400 }; + const image = db.images.find(item => item.id === message.id); + return image ? { ok: true, status: 200, type: image.type, data: image.data } : { ok: false, status: 404 }; + } if (message.t !== MSG.API) return failure('Unknown message'); const failed = failures.findIndex(item => item.method === message.method && item.path === message.path); if (failed >= 0) { const item = failures.splice(failed, 1)[0]; return failure(item.error, item.status); } @@ -221,7 +285,7 @@ globalThis.__fake = { shot(id, kind) { const pin = db.pins.find(item => item.id === id); __fake.update(id, { shots: { ...pin.shots, [kind]: now() } }); }, disconnect() { for (const port of [...ports]) port.disconnect(); }, seed(body) { return copy(create(body)); }, - reset() { db.pins = []; db.replies = []; db.steps = []; db.batches = []; db.nextPin = 1; db.nextReply = 1; db.nextStep = 1; db.nextBatch = 1; db.settings = defaultSettings(); save(); }, + reset() { db.pins = []; db.replies = []; db.steps = []; db.batches = []; db.images = []; db.nextPin = 1; db.nextReply = 1; db.nextStep = 1; db.nextBatch = 1; db.settings = defaultSettings(); save(); }, storage: () => JSON.parse(localStorage.getItem('onspot-harness-storage') || '{}'), setStorage(values) { const all = JSON.parse(localStorage.getItem('onspot-harness-storage') || '{}'); diff --git a/extension/test/harness/run.mjs b/extension/test/harness/run.mjs index 0fc9a70..ea5414b 100644 --- a/extension/test/harness/run.mjs +++ b/extension/test/harness/run.mjs @@ -1160,6 +1160,147 @@ try { await clean(hp, shotsPage.issues); await hp.close(); pass('a failed accept shows the reason, keeps Looks good for a retry and still marks the pin seen'); + // Attached images (0.7.0): paste or pick, a thumbnail, remove, submit, and the card strips. + const imagesPage = await freshPage(context, '/images'); activePage = imagesPage.page; + const ip = imagesPage.page; + const pinPng = Buffer.from(png([20, 80, 200]), 'base64'); + const replyPng = Buffer.from(png([200, 160, 20]), 'base64'); + const imageIdRe = /^[A-Za-z0-9_-]{22}$/; + async function pickImage(buttonSelector, buffer) { + const [chooser] = await Promise.all([ + ip.waitForEvent('filechooser', { timeout: 8000 }), + ip.locator(ui(buttonSelector)).click(), + ]); + await chooser.setFiles({ name: 'picture.png', mimeType: 'image/png', buffer }); + } + async function addNoteImage(buffer) { + let added = false; + try { + await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin }); + await ip.locator(ui('textarea[name="pin-note"]')).click(); + added = await ip.evaluate(async (b64) => { + const bytes = Uint8Array.from(atob(b64), char => char.charCodeAt(0)); + const write = navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]); + await Promise.race([write, new Promise((_, reject) => setTimeout(() => reject(new Error('clipboard')), 1000))]); + return true; + }, buffer.toString('base64')); + } catch { added = false; } + if (added) { + await ip.locator(ui('textarea[name="pin-note"]')).press('Control+V'); + try { await ip.locator(ui('.popup .thumb')).waitFor({ timeout: 800 }); } catch { added = false; } + } + if (!added || await ip.locator(ui('.popup .thumb')).count() === 0) await pickImage('button.add-image', buffer); + assert.equal(await ip.locator(ui('.popup .thumb')).count(), 1, 'one thumbnail'); + } + await ip.evaluate(() => { __fake.reset(); localStorage.removeItem('onspot-harness-storage'); __fake.delay = 30; }); + await ip.reload(); await visible(ip, '.capsule'); + await ip.locator(ui('.pin-button')).click(); await pick(ip, '#target'); await visible(ip, '.popup'); + await ip.locator(ui('textarea[name="pin-note"]')).fill('Make the heading blue.'); + const untrusted = await ip.evaluate(() => { + const box = document.querySelector('on-spot').shadowRoot.querySelector('textarea[name="pin-note"]'); + const file = new File([Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10, 1)], 'x.png', { type: 'image/png' }); + const data = new DataTransfer(); + data.items.add(file); + let event; + try { event = new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: data }); } + catch { event = new ClipboardEvent('paste', { bubbles: true, cancelable: true }); } + try { Object.defineProperty(event, 'clipboardData', { value: data }); } catch { /* the browser sealed clipboardData */ } + box.dispatchEvent(event); + return event.isTrusted; + }); + assert.equal(untrusted, false, 'a script-made paste is not trusted'); + assert.equal(await ip.locator(ui('.thumb')).count(), 0, 'an untrusted paste adds nothing'); + assert.equal(await ip.evaluate(() => __fake.calls.some(call => call.t === 'upload')), false); + await ip.evaluate(() => { __fake.delay = 2500; }); + await addNoteImage(pinPng); + await waitFor(ip, () => document.querySelector('on-spot').shadowRoot.querySelector('.popup .thumb')?.getAttribute('aria-busy') === 'true'); + await ip.locator(ui('textarea[name="pin-note"]')).press('Enter'); + await waitFor(ip, () => document.querySelector('on-spot').shadowRoot.querySelector('#onspot-note-error')?.textContent === 'Wait until the image is uploaded.'); + assert.equal(await ip.locator(ui('.popup')).isVisible(), true, 'Enter during an upload keeps the popup open'); + await ip.evaluate(() => { __fake.delay = 30; }); + await waitFor(ip, () => { + const thumb = document.querySelector('on-spot').shadowRoot.querySelector('.popup .thumb'); + return thumb?.getAttribute('aria-busy') === 'false' && thumb.querySelector('canvas')?.width > 0; + }); + await ip.locator(ui('button[title="Remove image 1"]')).click(); + await waitFor(ip, () => document.querySelector('on-spot').shadowRoot.querySelectorAll('.popup .thumb').length === 0); + await pickImage('button.add-image', pinPng); + await waitFor(ip, () => { + const thumb = document.querySelector('on-spot').shadowRoot.querySelector('.popup .thumb'); + return thumb?.getAttribute('aria-busy') === 'false' && thumb.querySelector('canvas')?.width > 0; + }); + await ip.locator(ui('textarea[name="pin-note"]')).press('Enter'); + await gone(ip, '.popup'); + await visible(ip, '.marker[data-status="draft"]'); + const draft = await ip.evaluate(() => { + const store = JSON.parse(localStorage.getItem('onspot-harness-storage')); + return store['kog-pins:drafts:fixture.koglabs.com'].items[0].body; + }); + assert.equal(draft.note, 'Make the heading blue.'); + assert.equal(draft.images.length, 1); + assert.match(draft.images[0], imageIdRe); + await ip.locator(ui('.marker[data-status="draft"]')).click(); await visible(ip, '.popup'); + await waitFor(ip, () => { + const thumb = document.querySelector('on-spot').shadowRoot.querySelector('.popup .thumb'); + return thumb?.getAttribute('aria-busy') === 'false' && thumb.querySelector('canvas')?.width > 0; + }); + assert.ok(await ip.evaluate(id => __fake.calls.some(call => call.t === 'image' && call.id === id), draft.images[0]), 'the edit popup fetches the image'); + await ip.locator(ui('textarea[name="draft-note"]')).press('Control+Enter'); + await marker(ip, 1, 'queued'); + const batch = await ip.evaluate(() => __fake.calls.filter(call => call.method === 'POST' && call.path === '/api/batches').at(-1)); + assert.equal(batch.body.pins.length, 1); + assert.equal(batch.body.pins[0].note, 'Make the heading blue.'); + assert.deepEqual(batch.body.pins[0].images, draft.images); + await ip.locator(ui('.marker[data-pin="1"]')).click(); await visible(ip, '.thread'); + const pinPixel = () => ip.evaluate(() => { + const canvas = document.querySelector('on-spot').shadowRoot.querySelector('.panel-body > .images .shot canvas'); + return canvas && canvas.width === 40 ? [...canvas.getContext('2d').getImageData(20, 15, 1, 1).data] : null; + }); + await waitFor(ip, () => document.querySelector('on-spot').shadowRoot.querySelector('.panel-body > .images .shot canvas')?.width === 40); + assert.deepEqual(await pinPixel(), [20, 80, 200, 255], 'the pin image is drawn'); + const imageBoxes = () => ip.evaluate(() => { + const root = document.querySelector('on-spot').shadowRoot; + const body = root.querySelector('.panel-body').getBoundingClientRect(); + const shot = root.querySelector('.panel-body > .images .shot'); + const box = shot.getBoundingClientRect(); + return { body: body.width, width: box.width, full: shot.dataset.full, title: shot.title }; + }); + await ip.locator(ui('.panel-body > .images .shot')).click(); + let shown = await imageBoxes(); + assert.equal(shown.full, 'true'); + assert.equal(shown.title, 'Show the images in a row'); + assert.ok(shown.width >= shown.body - 26, `full width ${shown.width} of ${shown.body}`); + await ip.locator(ui('.panel-body > .images .shot')).click(); + shown = await imageBoxes(); + assert.equal(shown.full, 'false'); + assert.equal(shown.title, 'Show image 1 at full width'); + assert.ok(shown.width < shown.body - 40, 'a second click goes back to the row'); + await waitFor(ip, () => { + const button = document.querySelector('on-spot').shadowRoot.querySelector('.reply-form button.add-image'); + return button && !button.disabled; + }); + await pickImage('.reply-form button.add-image', replyPng); + await waitFor(ip, () => { + const thumb = document.querySelector('on-spot').shadowRoot.querySelector('.reply-form .thumb'); + return thumb?.getAttribute('aria-busy') === 'false' && thumb.querySelector('canvas')?.width > 0; + }); + await ip.locator(ui('button[title="Send your reply"]')).click(); + await waitFor(ip, () => document.querySelector('on-spot').shadowRoot.querySelector('.reply .images canvas')?.width === 40); + const replyCall = await ip.evaluate(() => __fake.calls.filter(call => call.method === 'POST' && call.path === '/api/pins/1/replies').at(-1)); + assert.equal(replyCall.body.body, 'See the attached image.'); + assert.equal(replyCall.body.images.length, 1); + assert.match(replyCall.body.images[0], imageIdRe); + assert.notEqual(replyCall.body.images[0], draft.images[0]); + assert.deepEqual(await ip.evaluate(() => { + const canvas = document.querySelector('on-spot').shadowRoot.querySelector('.reply .images canvas'); + return [...canvas.getContext('2d').getImageData(20, 15, 1, 1).data]; + }), [200, 160, 20, 255], 'the reply image is drawn'); + assert.deepEqual(await pinPixel(), [20, 80, 200, 255], 'the pin image stays'); + assert.equal(await ip.locator(ui('img')).count(), 0, 'no image element'); + await screenshot(ip, name, 'images'); + await clean(ip, imagesPage.issues); await ip.close(); + pass('images: paste or pick, thumbnail, remove, submit sends ids, an untrusted paste adds nothing, the card shows the pin image and a reply image'); + // Go back (0.6.0): the version choice in the card of a closed pin, and the labels of a go back. const backPage = await freshPage(context, '/back'); activePage = backPage.page; const gp = backPage.page; diff --git a/extension/test/images.test.js b/extension/test/images.test.js new file mode 100644 index 0000000..4037ee6 --- /dev/null +++ b/extension/test/images.test.js @@ -0,0 +1,67 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ENCODE_ATTEMPTS, IMAGE_SIDE, base64ToBytes, bytesToBase64, cleanImageIds, drawSize, imageType, keepImages, sendAsIs } from "../src/shared/image.js"; +import { IMAGE_ID_RE, IMAGES_MAX, SHOT_MAX } from "../src/shared/protocol.js"; + +const ID = "Abcd1234_-Abcd1234_-Ab"; +const png = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a); +const jpeg = Uint8Array.of(0xff, 0xd8, 0xff, 0xe0); +const webp = Uint8Array.of(0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50); + +test("image ids on a draft: at most 6, in order, bad entries and duplicates dropped", () => { + assert.equal(ID.length, 22); + assert.equal(IMAGE_ID_RE.test(ID), true); + assert.equal(IMAGES_MAX, 6); + const ids = [ID, ` ${ID}`, ID.slice(0, 21), `${ID}x`, ID, "bad id", 7, null, ID.replace("A", "B"), "!!!!!!!!!!!+++++++++++"]; + const six = Array.from({ length: 8 }, (_, index) => ID.replace("A", String.fromCharCode(66 + index))); + assert.deepEqual(cleanImageIds(undefined), []); + assert.deepEqual(cleanImageIds("nope"), []); + assert.deepEqual(cleanImageIds(ids), [ID, ID.replace("A", "B")]); + assert.deepEqual(cleanImageIds(six), six.slice(0, 6)); + const body = { note: "x", images: [...ids, ...six] }; + const kept = [ID, ...six.slice(0, 5)]; + assert.deepEqual(keepImages(body), kept); + assert.deepEqual(body.images, kept); + const empty = { images: ["nope", ID.slice(0, 21), ID, ID] }; + assert.deepEqual(keepImages(empty), [ID]); + assert.deepEqual(keepImages({ images: "nope" }), []); + const gone = { note: "x", images: [] }; + assert.deepEqual(keepImages(gone), []); + assert.equal("images" in gone, false); +}); + +test("a file is sent unchanged only for a shot type within 2 MiB and 2560 px", () => { + assert.equal(sendAsIs("image/png", 1, 1, 1), true); + assert.equal(sendAsIs("image/jpeg", SHOT_MAX, IMAGE_SIDE, 10), true); + assert.equal(sendAsIs("image/webp", 10, 10, IMAGE_SIDE), true); + assert.equal(sendAsIs("image/gif", 10, 10, 10), false); + assert.equal(sendAsIs("image/png", 0, 10, 10), false); + assert.equal(sendAsIs("image/png", SHOT_MAX + 1, 10, 10), false); + assert.equal(sendAsIs("image/png", 10, IMAGE_SIDE + 1, 10), false); + assert.equal(sendAsIs("image/png", 10, 0, 10), false); +}); + +test("encode draws at the 2560 fit, then scales by 0.75 at most three times", () => { + assert.equal(ENCODE_ATTEMPTS, 4); + assert.deepEqual(drawSize(4000, 2000, 0), [2560, 1280]); + assert.deepEqual(drawSize(4000, 2000, 1), [1920, 960]); + assert.deepEqual(drawSize(4000, 2000, 2), [1440, 720]); + assert.deepEqual(drawSize(4000, 2000, 3), [1080, 540]); + assert.deepEqual(drawSize(100, 50, 0), [100, 50]); + assert.deepEqual(drawSize(100, 50, 1), [75, 38]); +}); + +test("magic bytes name png, jpeg and webp, and base64 stops at 2 MiB", () => { + assert.equal(imageType(png), "image/png"); + assert.equal(imageType(jpeg), "image/jpeg"); + assert.equal(imageType(webp), "image/webp"); + assert.equal(imageType(Uint8Array.of(0x89, 0x50, 0x4e)), ""); + assert.equal(imageType(Uint8Array.of(0xff, 0xd8, 0x00)), ""); + assert.equal(imageType(new Uint8Array(12)), ""); + const bytes = Uint8Array.from({ length: 9000 }, (_, index) => index % 251); + assert.deepEqual(base64ToBytes(bytesToBase64(bytes), SHOT_MAX), bytes); + assert.equal(base64ToBytes("", SHOT_MAX), null); + assert.equal(base64ToBytes("!!!!", SHOT_MAX), null); + assert.equal(base64ToBytes("QQ==", SHOT_MAX)?.length, 1); + assert.equal(base64ToBytes("A".repeat(Math.ceil(SHOT_MAX / 3) * 4 + 1), SHOT_MAX), null); +}); diff --git a/runner/src/config.js b/runner/src/config.js index 29d3e6b..20bba64 100644 --- a/runner/src/config.js +++ b/runner/src/config.js @@ -1,5 +1,5 @@ -// The runner's settings, from the environment (docs/protocol.md, Auto-fix runner, items 2, 4, 5 and -// 12 to 14). A bad value throws at start: a limit or a switch that is misread is worse than a stop. +// The runner's settings, from the environment (docs/protocol.md, Auto-fix runner, items 2, 4, 5, +// 12 to 14 and 17). A bad value throws at start: a limit or a switch that is misread is worse than a stop. import { homedir } from "node:os"; import { isAbsolute, join } from "node:path"; @@ -34,5 +34,7 @@ export function readConfig(env = process.env) { cwd: folder("PINS_RUNNER_CWD", homedir()), // One folder per project, each with project.json, MEMORY.md and state.md (runner/src/projects.js). projectsDir: folder("PINS_PROJECTS_DIR", join(homedir(), ".claude", "memory-store", "projects")), + // Images of a pin, for the session to open. Live this is /var/lib/onspot-runner/images. + imagesDir: folder("PINS_RUNNER_IMAGES_DIR", "/var/lib/onspot-runner/images"), }; } diff --git a/runner/src/images.js b/runner/src/images.js new file mode 100644 index 0000000..0a4c7a8 --- /dev/null +++ b/runner/src/images.js @@ -0,0 +1,121 @@ +// The images of a pin, saved before the session starts (docs/protocol.md, Auto-fix runner, item 17). +// The session opens each file with the Read tool. A failed image never stops the run. +import { chmodSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { isAbsolute, join } from "node:path"; +import { createPins } from "./pins.js"; + +export const IMAGE_MS = 5_000; +export const IMAGE_MAX = 2 * 1024 * 1024; +const IMAGE_COUNT = 12; +const KEEP_MS = 30 * 86400000; +const ID_RE = /^[A-Za-z0-9_-]{22}$/; +const EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }; + +/** The image type that the first bytes name, or null. Same rules as a shot. */ +export function imageType(bytes) { + if (bytes.length >= 4 && bytes.readUInt32BE(0) === 0x89504e47) return "image/png"; + if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg"; + if (bytes.length >= 12 && bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "image/webp"; + return null; +} + +/** + * Saves the images of one pin (at most 12) into dir as `-.`. Returns one entry per + * image, a path or null, in order. The downloads share one 5 s limit. A failure logs + * `image skipped pin= n=` and never throws. A caller that starts every pin of a run before + * it waits keeps the whole run inside that same window. + */ +export async function savePinImages({ pin, fetch, clock, port, dir, log = () => {} } = {}) { + const list = imageList(pin); + if (!list.length) return []; + const paths = new Array(list.length).fill(null); + const logged = new Set(); + const skip = (n) => { + if (logged.has(n)) return; + logged.add(n); + try { log(`image skipped pin=${pin.id} n=${n}`); } catch { /* a log must not stop the run */ } + }; + if (!Number.isSafeInteger(pin.id) || pin.id < 1 || typeof dir !== "string" || !isAbsolute(dir)) { + list.forEach((_, index) => skip(index + 1)); + return paths; + } + const controller = new AbortController(); + const timer = clock.setTimeout(() => controller.abort(), IMAGE_MS); + const stopped = new Promise((resolve) => { + if (controller.signal.aborted) resolve(); + else controller.signal.addEventListener("abort", () => resolve(), { once: true }); + }); + const pins = createPins({ fetch, clock, port }); + const tasks = list.map((image, index) => loadOne({ image, index, pin, dir, pins, controller, paths, skip })); + const done = Promise.all(tasks); + try { + await Promise.race([done, stopped]); + if (controller.signal.aborted) { + for (let index = 0; index < list.length; index++) if (paths[index] === null) skip(index + 1); + } + await done; + return paths; + } catch { + list.forEach((_, index) => { if (paths[index] === null) skip(index + 1); }); + return paths; + } finally { + clock.clearTimeout(timer); + } +} + +function imageList(pin) { + if (!pin || pin.revert || !Array.isArray(pin.images)) return []; + return pin.images.slice(0, IMAGE_COUNT); +} + +async function loadOne({ image, index, pin, dir, pins, controller, paths, skip }) { + const n = index + 1; + try { + if (controller.signal.aborted) throw new Error("aborted"); + if (typeof image?.id !== "string" || !ID_RE.test(image.id)) throw new Error("id"); + const bytes = await pins.bytes(`/api/images/${image.id}`, { signal: controller.signal, maxBytes: IMAGE_MAX }); + if (controller.signal.aborted) throw new Error("aborted"); + const type = imageType(bytes); + const ext = EXT[type]; + if (!ext) throw new Error("type"); + paths[index] = writePrivate(dir, `${pin.id}-${n}.${ext}`, bytes); + } catch { + paths[index] = null; + skip(n); + } +} + +// mode 0600 in a 0700 folder. A temp file plus rename, so a reader never sees a partial image. +function writePrivate(dir, name, bytes) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + chmodSync(dir, 0o700); + const file = join(dir, name); + const tmp = `${file}.${process.pid}.tmp`; + try { + writeFileSync(tmp, bytes, { mode: 0o600, flush: true }); + chmodSync(tmp, 0o600); + renameSync(tmp, file); + chmodSync(file, 0o600); + } catch (error) { + try { rmSync(tmp, { force: true }); } catch { /* already gone */ } + throw error; + } + prune(dir); + return file; +} + +// Removes files in the folder whose last write is more than 30 days ago. A directory stays. +// A link is removed as a link. It never throws: a cleanup must not fail the save that started it. +function prune(dir) { + const cutoff = Date.now() - KEEP_MS; + let names = []; + try { names = readdirSync(dir); } catch { return; } + for (const name of names) { + const file = join(dir, name); + try { + const stat = lstatSync(file); + if (stat.isDirectory() || stat.mtimeMs >= cutoff) continue; + rmSync(file, { force: true }); + } catch { /* another save removed it, or it is not ours to remove */ } + } +} diff --git a/runner/src/pins.js b/runner/src/pins.js index 81da38f..56eb1aa 100644 --- a/runner/src/pins.js +++ b/runner/src/pins.js @@ -28,6 +28,27 @@ export function createPins({ fetch, clock, port }) { } finally { clock.clearTimeout(timeout); } } + /** GET the raw body, at most maxBytes, then stops reading. A status that is not 2xx throws. + * The caller's signal aborts the read; the request also ends after API_MS. */ + async function bytes(path, { signal, maxBytes = 2 * 1024 * 1024 } = {}) { + const controller = new AbortController(); + const timeout = clock.setTimeout(() => controller.abort(), API_MS); + const onAbort = () => controller.abort(); + if (signal?.aborted) controller.abort(); + else signal?.addEventListener("abort", onAbort, { once: true }); + try { + const response = await fetch(`${base}${path}`, { method: "GET", redirect: "error", signal: controller.signal }); + if (!response.ok) { + await response.body?.cancel(); + throw Object.assign(new Error(`Pins HTTP ${response.status}`), { status: response.status }); + } + return await readMax(response, maxBytes); + } finally { + clock.clearTimeout(timeout); + signal?.removeEventListener("abort", onAbort); + } + } + /** Reads the pins of a status page by page (500, newest first) and hands each page over, so one * page is in memory at a time. */ async function pages(status, onPage) { @@ -43,5 +64,26 @@ export function createPins({ fetch, clock, port }) { } } - return { base, call, pages }; + return { base, call, pages, bytes }; +} + +// Keeps the first max bytes and cancels the rest, so a long body cannot grow past the limit. +async function readMax(response, max) { + const reader = response.body?.getReader(); + if (!reader) return Buffer.alloc(0); + const chunks = []; + let total = 0; + try { + while (total < max) { + const { done, value } = await reader.read(); + if (done) break; + if (!value?.byteLength) continue; + const take = Math.min(value.byteLength, max - total); + chunks.push(Buffer.from(value.subarray(0, take))); + total += take; + } + } finally { + await reader.cancel().catch(() => {}); + } + return total ? Buffer.concat(chunks, total) : Buffer.alloc(0); } diff --git a/runner/src/prompt.js b/runner/src/prompt.js index d662317..e71cea1 100644 --- a/runner/src/prompt.js +++ b/runner/src/prompt.js @@ -62,10 +62,12 @@ const block = (value) => (value.length ? [...value, ""] : []); * @param {{ pin: object, project: { name: string|null, dir: string|null, candidates: string[] }, * choice: { label: string }, replies?: object[], * history?: object[], siblings?: object[], - * brief?: { card: string[], hints: string[], ship: boolean }|null, shot?: boolean, lean?: boolean }} run - * Without brief, shot and lean the text is the v3.1 prompt. + * brief?: { card: string[], hints: string[], ship: boolean }|null, shot?: boolean, lean?: boolean, + * saved?: (string|null)[] }} run + * saved is one path per image of the pin, or null when that image was not saved. Without brief, + * shot and lean the text is the v3.1 prompt. A pin with no images adds no image lines. */ -export function buildPrompt({ pin, project, choice, replies = [], history = [], siblings = [], brief = null, shot = false, lean = false }) { +export function buildPrompt({ pin, project, choice, replies = [], history = [], siblings = [], brief = null, shot = false, lean = false, saved }) { const id = pin.id; const card = list(brief?.card), hints = list(brief?.hints), ship = brief?.ship === true; const check = brief || shot || lean @@ -81,7 +83,7 @@ export function buildPrompt({ pin, project, choice, replies = [], history = [], "", "His words:", ...words(pin, replies), - "", + ...imageGap(pin, replies, saved), ...fence(pin, siblings), FENCE_RULE, "", @@ -189,7 +191,7 @@ export function buildRevertPrompt({ pin, project, choice, replies = [], brief = * One prompt for all pins of a bulk run, in id order (Bulk mode, item 5). If it is longer than * PROMPT_BYTES, the history of every pin goes first, then the hints; his words and the page data * stay whole. - * @param {{ items: { pin: object, replies?: object[], history?: object[], brief?: object|null }[], + * @param {{ items: { pin: object, replies?: object[], history?: object[], brief?: object|null, saved?: (string|null)[] }[], * project: object, choice: { id: string, label: string }, * bulk: { delegate: boolean, agents: number }, account: string, shot?: boolean }} run */ @@ -215,10 +217,11 @@ function bulkText({ items, project, choice, bulk, account, shot = false }) { `Bulk mode: you take all ${n} pins of this Submit all.`, "", FENCE_RULE, - ...pins.flatMap(({ pin, replies = [], history = [], brief }) => [ + ...pins.flatMap(({ pin, replies = [], history = [], brief, saved }) => [ "", `Pin #${pin.id}. His words:`, ...words(pin, replies), + ...imageSection(pin, replies, saved), ...fence(pin), ...earlier(history), ...list(brief?.hints), @@ -255,6 +258,43 @@ function bulkText({ items, project, choice, bulk, account, shot = false }) { ]); } +const IMAGE_HEADER = "Images he attached (his material, like the note; open each one with the Read tool before you change anything):"; + +// UTC hours and minutes of an ISO time. `pins show` uses the same clock for a reply line. +const clock = (iso) => { + const text = String(iso ?? "").slice(11, 16); + return /^\d{2}:\d{2}$/.test(text) ? text : ""; +}; + +function imageWhere(image, replies) { + if (image?.replyId == null) return "(with the note)"; + const reply = (Array.isArray(replies) ? replies : []).find((item) => item && String(item.id) === String(image.replyId)); + const at = clock(reply?.createdAt) || clock(image?.createdAt); + const who = reply && reply.kind !== "user" ? "an agent reply" : "his reply"; + return at ? `(with ${who} at ${at})` : `(with ${who})`; +} + +// The image block, with a blank line before it and after it. No images: no lines. +function imageSection(pin, replies, saved) { + const list = Array.isArray(pin.images) ? pin.images.slice(0, 12) : []; + if (!list.length) return []; + const id = pin.id; + const lines = list.map((image, index) => { + const n = index + 1; + const path = saved?.[index]; + if (typeof path === "string" && path.startsWith("/") && !/[\u0000-\u001f\u007f]/.test(path)) return `${n}. ${path} ${imageWhere(image, replies)}`; + return `${n}. not saved; run "pins images ${id}" to get it`; + }); + return ["", IMAGE_HEADER, ...lines, ""]; +} + +// A single-pin prompt already has a blank line before the page data. Keep that line when the pin +// has no images, and do not add a second one when the block brings its own. +function imageGap(pin, replies, saved) { + const section = imageSection(pin, replies, saved); + return section.length ? section : [""]; +} + // His words: the note, About, Scope, presets and the newest 6 thread lines. function words(pin, replies) { const thread = replies.slice(-6); diff --git a/runner/src/runner.js b/runner/src/runner.js index 4250ae5..74f3ea6 100644 --- a/runner/src/runner.js +++ b/runner/src/runner.js @@ -9,6 +9,7 @@ import { chooseProfile } from "./profile.js"; import { readConfig } from "./config.js"; import { createShots } from "./shots.js"; import { createPins, API_MS } from "./pins.js"; +import { savePinImages } from "./images.js"; const POLL = 30_000, WATCH = 15_000, HISTORY = 14 * 86_400_000; // A pin gets this many runs before a failed run hands it to the Chairman. The second run has a @@ -268,18 +269,22 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, const { pin, project, key } = current; const choice = chooseModel(runsOf(pin)); if (pin.revert) { - // A go back (item 16): the lean start, the project card, no history and no siblings. + // A go back (item 16): the lean start, the project card, no history and no siblings. No images. const profile = options.lean ? "pin" : null; const facts = await briefOf(pin, project); const prompt = buildRevertPrompt({ pin, project, choice, replies, brief: facts, shot: Boolean(shots), lean: profile === "pin" }); await begin([pin], key, project, choice, `Pin #${pin.id} · Go back: ${pinTitle(pin)} · ${choice.label}`, prompt, profile); return; } + // The images download while the context and the brief run, so a pin with images starts no later + // than the brief. The download itself ends within 5 s. + const savedP = savePinImages({ pin, fetch, clock, port: options.port, dir: options.imagesDir, log }); // The lean start, unless the pin needs the full one (runner/src/profile.js). const profile = options.lean ? chooseProfile(pin) : null; const known = await context(pin); const facts = await briefOf(pin, project); - const prompt = buildPrompt({ pin, project, choice, replies, ...known, brief: facts, shot: Boolean(shots), lean: profile === "pin" }); + const saved = await savedP; + const prompt = buildPrompt({ pin, project, choice, replies, ...known, brief: facts, shot: Boolean(shots), lean: profile === "pin", saved }); await begin([pin], key, project, choice, `Pin #${pin.id} · ${pinTitle(pin)} · ${choice.label}`, prompt, profile); } @@ -298,9 +303,11 @@ export function createRunner({ fetch, clock, triad, resolveProject, buildPrompt, await settings(); if (!enabled || options.disabled || stopping || !bulk.on) return; const { project, key } = group[0]; + // Every pin's images start now and share this moment's 5 s limit. The briefs stay in order. + const savedPs = group.map(({ pin }) => savePinImages({ pin, fetch, clock, port: options.port, dir: options.imagesDir, log })); const items = []; - for (const { pin, project: own } of group) { - items.push({ pin, replies: replies.get(pin.id), history: await history(pin), brief: await briefOf(pin, own) }); + for (const [index, { pin, project: own }] of group.entries()) { + items.push({ pin, replies: replies.get(pin.id), history: await history(pin), brief: await briefOf(pin, own), saved: await savedPs[index] }); } // A prompt over the Triad limit takes fewer pins. The others stay queued for the next bulk run. let choice, prompt; diff --git a/runner/test/images.test.js b/runner/test/images.test.js new file mode 100644 index 0000000..be37075 --- /dev/null +++ b/runner/test/images.test.js @@ -0,0 +1,229 @@ +// The runner half of pin images (docs/protocol.md, Auto-fix runner, item 17). +import test from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { chmodSync, existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { IMAGE_MAX, savePinImages } from "../src/images.js"; +import { harness } from "./helpers.js"; + +const A = "a".repeat(22), B = "b".repeat(22), C = "c".repeat(22), D = "d".repeat(22); +const png = (size = 32) => { + const buf = Buffer.alloc(size, 0x11); + buf.writeUInt32BE(0x89504e47, 0); + return buf; +}; +const jpeg = (size = 32) => { + const buf = Buffer.alloc(size, 0x22); + buf[0] = 0xff; buf[1] = 0xd8; buf[2] = 0xff; + return buf; +}; +const webp = (size = 32) => { + const buf = Buffer.alloc(size, 0x33); + buf.write("RIFF", 0); + buf.write("WEBP", 8); + return buf; +}; +const image = (id, extra = {}) => ({ id, replyId: null, author: "sam", createdAt: "2026-11-15T10:00:00.000Z", ...extra }); +const realClock = { now: () => Date.now(), setTimeout, clearTimeout }; +const mode = (file) => statSync(file).mode & 0o777; + +function rootDir(t) { + const root = mkdtempSync(join(tmpdir(), "pins-images-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + return root; +} + +// A pins server on loopback. handler(req, res) answers one request. The server is closed with the test. +async function serve(t, handler) { + const server = createServer((req, res) => { + req.on("error", () => {}); + res.on("error", () => {}); + Promise.resolve(handler(req, res)).catch(() => { if (!res.writableEnded) res.end(); }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + t.after(() => { server.closeAllConnections(); server.close(); }); + return server.address().port; +} + +test("a download saves png, jpeg and webp under the pin id, mode 0600, and cuts at 2 MiB", async (t) => { + const root = rootDir(t), dir = join(root, "images"); + const big = png(IMAGE_MAX + 64); + big.fill(0xab, IMAGE_MAX); + const more = (n) => `${"m".repeat(20)}${String(n).padStart(2, "0")}`; + const extras = Array.from({ length: 7 }, (_, n) => image(more(n + 1))); + const dropped = image(more(99)); + const seen = []; + const bodies = new Map([[A, png()], [B, jpeg()], [C, webp()], [D, big]]); + const port = await serve(t, (req, res) => { + const id = req.url.split("/").pop(); + seen.push(`${req.method} ${req.url}`); + assert.equal(req.headers.host.split(":")[0], "127.0.0.1"); + const body = bodies.get(id) ?? png(); + // The declared type is a lie. The bytes decide. + res.writeHead(200, { "Content-Type": "text/plain", "Content-Length": String(body.length) }); + res.end(body); + }); + const logs = []; + const pin = { id: 12, images: [image(A), image(B), image(C), image(D), image("short"), ...extras, dropped] }; + const saved = await savePinImages({ pin, fetch: globalThis.fetch, clock: realClock, port, dir, log: (line) => logs.push(line) }); + assert.equal(saved.length, 12); + assert.deepEqual(saved.slice(0, 4).map((file) => file.slice(dir.length + 1)), ["12-1.png", "12-2.jpg", "12-3.webp", "12-4.png"]); + assert.equal(readFileSync(saved[0]).equals(png()), true); + assert.equal(readFileSync(saved[1]).equals(jpeg()), true); + assert.equal(readFileSync(saved[3]).length, IMAGE_MAX, "the read stops at 2 MiB"); + assert.equal(readFileSync(saved[3])[IMAGE_MAX - 1], 0x11); + assert.equal(saved[4], null, "an id that is not 22 url-safe characters is skipped"); + assert.equal(saved[11].endsWith("/12-12.png"), true); + for (const file of saved) if (file) assert.equal(mode(file), 0o600, file); + assert.equal(mode(dir), 0o700); + assert.equal(seen.length, 11); + assert.equal(seen.includes(`GET /api/images/${dropped.id}`), false, "a pin keeps at most 12 images"); + assert.equal(seen.includes("GET /api/images/short"), false); + assert.deepEqual(logs, ["image skipped pin=12 n=5"]); + assert.equal(existsSync(join(dir, "12-5.png")), false); +}); + +test("a wrong type, an empty body and an HTTP error are skipped and the run still returns", async (t) => { + const root = rootDir(t), dir = join(root, "out"); + const port = await serve(t, (req, res) => { + const id = req.url.split("/").pop(); + if (id === A) { res.writeHead(200, { "Content-Type": "image/png" }); return res.end(Buffer.from("GIF89a not a photo")); } + if (id === B) { res.writeHead(200, { "Content-Type": "image/png" }); return res.end(); } + res.writeHead(500); res.end("no"); + }); + const logs = []; + const saved = await savePinImages({ + pin: { id: 7, images: [image(A), image(B), image(C)] }, + fetch: globalThis.fetch, clock: realClock, port, dir, log: (line) => logs.push(line), + }); + assert.deepEqual(saved, [null, null, null]); + assert.deepEqual(logs.sort(), ["image skipped pin=7 n=1", "image skipped pin=7 n=2", "image skipped pin=7 n=3"]); + assert.equal(existsSync(dir), false, "nothing was saved, so the folder stays absent"); +}); + +test("a hung download stops at 5 s, keeps a file that already arrived, and does not wait per image", { timeout: 8000 }, async (t) => { + const { FakeClock } = await import("./helpers.js"); + const clock = new FakeClock(); + const root = rootDir(t), dir = join(root, "images"); + let sawFast = false; + const port = await serve(t, (req, res) => { + const id = req.url.split("/").pop(); + if (id === B) { sawFast = true; res.writeHead(200); return res.end(jpeg()); } + req.on("close", () => {}); + }); + const logs = []; + let finished = false; + const pending = savePinImages({ + pin: { id: 12, images: [image(A), image(B)] }, + fetch: globalThis.fetch, clock, port, dir, log: (line) => logs.push(line), + }).then((value) => { finished = true; return value; }); + for (let i = 0; i < 50 && !sawFast; i++) await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(sawFast, true, "the second image starts while the first is still open"); + assert.equal(finished, false); + await clock.tick(4999); + await new Promise((resolve) => setTimeout(resolve, 30)); + assert.equal(finished, false, "4999 ms is inside the limit"); + await clock.tick(1); + const saved = await pending; + assert.equal(saved[0], null); + assert.equal(saved[1].endsWith("/12-2.jpg"), true); + assert.equal(readFileSync(saved[1]).equals(jpeg()), true); + assert.deepEqual(logs, ["image skipped pin=12 n=1"]); + assert.equal(existsSync(join(dir, "12-1.png")), false); +}); + +test("a save removes files in the folder that are older than 30 days, and leaves the rest", async (t) => { + const root = rootDir(t), dir = join(root, "images"); + mkdirSync(dir, { recursive: true }); + chmodSync(dir, 0o755); + const age = (name, days, link = false) => { + const then = new Date(Date.now() - days * 86400000); + (link ? lutimesSync : utimesSync)(join(dir, name), then, then); + }; + writeFileSync(join(dir, "old.txt"), "gone"); + writeFileSync(join(dir, "recent.txt"), "keep"); + mkdirSync(join(dir, "kept-dir")); + writeFileSync(join(root, "target.txt"), "keep"); + symlinkSync(join(root, "target.txt"), join(dir, "old-link")); + age("old.txt", 31); + age("recent.txt", 29); + age("kept-dir", 31); + age("old-link", 31, true); + utimesSync(join(root, "target.txt"), new Date(0), new Date(0)); + const port = await serve(t, (req, res) => { res.writeHead(200); res.end(png()); }); + const saved = await savePinImages({ + pin: { id: 3, images: [image(A)] }, + fetch: globalThis.fetch, clock: realClock, port, dir, + }); + assert.equal(saved[0], join(dir, "3-1.png")); + assert.deepEqual(readdirSync(dir).sort(), ["3-1.png", "kept-dir", "recent.txt"]); + assert.equal(readFileSync(join(root, "target.txt"), "utf8"), "keep"); + assert.equal(lstatSync(join(dir, "kept-dir")).isDirectory(), true); + assert.equal(mode(dir), 0o700, "the folder is private even when it already existed"); + assert.equal(mode(saved[0]), 0o600); +}); + +test("a revert run downloads nothing; a fix run saves before the brief returns and puts the path in the prompt", { timeout: 8000 }, async (t) => { + const root = rootDir(t), dir = join(root, "images"); + let release; + const gate = new Promise((resolve) => { release = resolve; }); + let briefSawRequest = false; + const h = harness(t, { + config: { imagesDir: dir }, + brief: async () => { + briefSawRequest = h.requests.some((request) => request.path === `/api/images/${A}`); + release(); + return null; + }, + }); + h.intercept(async (request) => { + if (!request.path.startsWith("/api/images/")) return; + if (request.path.endsWith(`/${B}`)) return new Response("no", { status: 404 }); + await gate; + return new Response(png()); + }); + await h.start(); + h.add(12, "market.koglabs.com", { images: [image(A), image(B)] }); + await h.settle(); + assert.equal(briefSawRequest, true, "the download is already started when the brief runs"); + const prompt = h.delegates[0].body.prompt; + const file = join(dir, "12-1.png"); + assert.ok(prompt.includes(`Images he attached (his material, like the note; open each one with the Read tool before you change anything):\n1. ${file} (with the note)\n2. not saved; run "pins images 12" to get it\n`)); + assert.equal(readFileSync(file).equals(png()), true); + assert.equal(mode(file), 0o600); + assert.ok(h.logs.includes("image skipped pin=12 n=2")); + assert.ok(h.order.indexOf(`GET /api/images/${A}`) < h.order.indexOf("delegate")); + + const back = harness(t, { config: { imagesDir: dir } }); + await back.start(); + back.add(4, "one.koglabs.com", { images: [image(A)], revert: { commits: ["abc1234abc1234abc1234abc1234abc1234abc12"], attempts: 0 } }); + await back.settle(); + assert.equal(back.requests.some((request) => request.path.startsWith("/api/images")), false); + assert.equal(back.delegates[0].body.prompt.includes("Images he attached"), false); + assert.equal(back.logs.some((line) => line.startsWith("image skipped")), false); +}); + +test("a bulk run downloads each pin and lists that pin's images in its own words", async (t) => { + const root = rootDir(t), dir = join(root, "images"); + const h = harness(t, { bulk: { on: true, delegate: false, agents: 3 }, config: { imagesDir: dir } }); + const bytes = new Map([[A, png()], [B, webp()]]); + h.intercept(async (request) => { + if (!request.path.startsWith("/api/images/")) return; + return new Response(bytes.get(request.path.split("/").pop())); + }); + await h.start(); + h.add(12, "market.koglabs.com", { batch: 3, images: [image(A)] }); + h.add(13, "market.koglabs.com", { batch: 3, note: "No photo" }); + h.add(14, "market.koglabs.com", { batch: 3, images: [image(B, { replyId: 8 })] }); + await h.settle(); + assert.equal(h.delegates.length, 1); + const prompt = h.delegates[0].body.prompt; + assert.ok(prompt.includes(`1. ${join(dir, "12-1.png")} (with the note)`)); + assert.ok(prompt.includes(`1. ${join(dir, "14-1.webp")} (with his reply at `)); + assert.ok(prompt.indexOf("Pin #12") < prompt.indexOf("12-1.png") && prompt.indexOf("12-1.png") < prompt.indexOf("Pin #13")); + assert.ok(prompt.includes("Pin #13. His words:\nNote: No photo\n")); + assert.equal(prompt.split("Images he attached").length, 3); + assert.equal(mode(join(dir, "14-1.webp")), 0o600); +}); diff --git a/runner/test/prompt.test.js b/runner/test/prompt.test.js index b91757b..65cdb4f 100644 --- a/runner/test/prompt.test.js +++ b/runner/test/prompt.test.js @@ -289,3 +289,58 @@ test("a bulk prompt over PROMPT_BYTES drops the history first, then the hints", assert.ok(many.includes("\n\nProject card: crete\n\nHow to work:\n")); for (const p of pins) assert.ok(many.includes(`Note: ${p.note}\n`), `note ${p.id}`); }); + +const HEADER = "Images he attached (his material, like the note; open each one with the Read tool before you change anything):"; + +test("images are listed in his words, single and bulk; a pin with none has no block; a revert prompt has none", async () => { + const { buildBulkPrompt, buildRevertPrompt } = await import("../src/prompt.js"); + const replies = [ + { id: 1, kind: "user", author: "sam", body: "the old reply", createdAt: "2026-11-15T08:15:00.000Z" }, + { id: 2, kind: "agent", author: "claude", body: "agent note", createdAt: "2026-11-15T09:01:00.000Z" }, + { id: 3, kind: "user", author: "sam", body: "later", createdAt: "2026-11-15T11:11:00.000Z" }, + { id: 4, kind: "agent", author: "claude", body: "later", createdAt: "2026-11-15T12:12:00.000Z" }, + { id: 5, kind: "user", author: "sam", body: "later", createdAt: "2026-11-15T13:13:00.000Z" }, + { id: 6, kind: "agent", author: "claude", body: "later", createdAt: "2026-11-15T14:14:00.000Z" }, + { id: 7, kind: "user", author: "sam", body: "newest", createdAt: "2026-11-15T16:07:00.000Z" }, + ]; + const images = [ + { id: "a".repeat(22), replyId: null, createdAt: "2026-11-15T01:01:00.000Z" }, + { id: "b".repeat(22), replyId: 1, createdAt: "2026-11-15T02:02:00.000Z" }, + { id: "c".repeat(22), replyId: 2, createdAt: "2026-11-15T03:03:00.000Z" }, + ]; + const saved = ["/var/lib/onspot-runner/images/37-1.png", "/var/lib/onspot-runner/images/37-2.jpg", null]; + const text = build({ images }, { replies, saved }); + const block = [ + HEADER, + "1. /var/lib/onspot-runner/images/37-1.png (with the note)", + "2. /var/lib/onspot-runner/images/37-2.jpg (with his reply at 08:15)", + '3. not saved; run "pins images 37" to get it', + ].join("\n"); + assert.ok(text.includes(`${block}\n`)); + assert.ok(text.includes(" he: newest\n\n" + HEADER), "the block follows the thread"); + assert.ok(text.indexOf(block) < text.indexOf("")); + assert.equal(text.includes("01:01") || text.includes("02:02") || text.includes("03:03"), false, "the time is the reply's, not the image's"); + assert.equal(text.includes("the old reply"), false, "a reply older than the six lines stays out of the thread"); + assert.equal(build().includes(HEADER), false); + assert.equal(build({ images: [] }).includes(HEADER), false); + + const bulk = buildBulkPrompt({ + items: [ + { pin: { ...pin, id: 12, images }, replies, saved: ["/var/lib/onspot-runner/images/12-1.png", null, "/var/lib/onspot-runner/images/12-3.webp"] }, + { pin: { ...pin, id: 13, note: "No photo" } }, + ], + project, choice: chooseModel(pin), bulk: { on: true, delegate: false, agents: 3 }, account: "claude", + }); + assert.ok(bulk.includes(`${HEADER}\n1. /var/lib/onspot-runner/images/12-1.png (with the note)\n2. not saved; run "pins images 12" to get it\n3. /var/lib/onspot-runner/images/12-3.webp (with an agent reply at 09:01)\n`)); + assert.ok(bulk.indexOf(HEADER) < bulk.indexOf("Pin #13")); + assert.ok(bulk.includes("Pin #13. His words:\nNote: No photo\n")); + assert.equal(bulk.slice(bulk.indexOf("Pin #13")).includes(HEADER), false); + assert.equal(bulk.split(HEADER).length, 2); + + const reverted = buildRevertPrompt({ + pin: { ...pin, images, versions: [], revert: { commits: ["a1b2c3d4"], attempts: 0 } }, + project, choice: chooseModel(pin), replies, + }); + assert.equal(reverted.includes(HEADER), false); + assert.equal(reverted.includes("37-1.png"), false); +}); diff --git a/runner/test/runner.test.js b/runner/test/runner.test.js index 30a6318..33af782 100644 --- a/runner/test/runner.test.js +++ b/runner/test/runner.test.js @@ -187,16 +187,17 @@ test("the daily limit counts runs and resets at UTC midnight", async (t) => { }); test("environment limits validate their values and ranges", () => { - const home = { cwd: homedir(), projectsDir: join(homedir(), ".claude", "memory-store", "projects") }; + const home = { cwd: homedir(), projectsDir: join(homedir(), ".claude", "memory-store", "projects"), imagesDir: "/var/lib/onspot-runner/images" }; assert.deepEqual(readConfig({}), { port: 4750, disabled: false, maxRuns: 0, maxRunsPerProject: 0, maxRunsPerDay: 0, skipHosts: [], brief: true, shots: true, lean: true, ...home }); assert.deepEqual(readConfig({ PINS_PORT: "6000", PINS_RUNNER_DISABLED: "1", MAX_RUNS: "100", MAX_RUNS_PER_PROJECT: "1", MAX_RUNS_PER_DAY: "0", PINS_RUNNER_SKIP_HOSTS: ".drop.koglabs.com, .x.koglabs.com", PINS_RUNNER_BRIEF: "0", PINS_RUNNER_SHOTS: "1", PINS_RUNNER_LEAN: "0", PINS_RUNNER_CWD: "/srv/agents", PINS_PROJECTS_DIR: "/srv/memory/projects" }), { port: 6000, disabled: true, maxRuns: 100, maxRunsPerProject: 1, maxRunsPerDay: 0, skipHosts: [".drop.koglabs.com", ".x.koglabs.com"], brief: false, shots: true, lean: false, - cwd: "/srv/agents", projectsDir: "/srv/memory/projects" }); + cwd: "/srv/agents", projectsDir: "/srv/memory/projects", imagesDir: "/var/lib/onspot-runner/images" }); assert.equal(readConfig({ PINS_RUNNER_DISABLED: "0" }).disabled, false); for (const env of [{ PINS_PORT: "https://outside" }, { MAX_RUNS: "-1" }, { MAX_RUNS: "" }, { MAX_RUNS: "2.5" }, { MAX_RUNS_PER_PROJECT: "-1" }, { MAX_RUNS_PER_DAY: "NaN" }, { PINS_RUNNER_SKIP_HOSTS: "drop.koglabs.com" }, - { PINS_RUNNER_CWD: "relative/folder" }, { PINS_RUNNER_CWD: "" }, { PINS_PROJECTS_DIR: "projects" }]) { + { PINS_RUNNER_CWD: "relative/folder" }, { PINS_RUNNER_CWD: "" }, { PINS_PROJECTS_DIR: "projects" }, + { PINS_RUNNER_IMAGES_DIR: "images" }]) { assert.throws(() => readConfig(env), /Invalid/, JSON.stringify(env)); } for (const config of [{ maxRuns: -1 }, { maxRunsPerProject: 1.5 }, { maxRunsPerDay: -2 }]) assert.throws(() => createRunner({ config }), /Invalid MAX_RUNS/); diff --git a/server/bin/pins.js b/server/bin/pins.js index a5a78d0..5515d85 100755 --- a/server/bin/pins.js +++ b/server/bin/pins.js @@ -1,12 +1,12 @@ #!/usr/bin/env node -import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { clearFacts, judge, loadFacts, saveFacts, verdictIntent } from "../src/facts.js"; import { formatDetail, formatLine, formatList } from "../src/format.js"; import { ID_RE } from "../src/id.js"; import { ship } from "../src/ship.js"; -import { SHOT_KINDS, SHOT_MAX, shotType } from "../src/shots.js"; +import { IMAGE_EXT, SHOT_KINDS, SHOT_MAX, shotType } from "../src/shots.js"; import { snapPin } from "../src/snap.js"; const usage = `Usage: @@ -23,6 +23,7 @@ const usage = `Usage: pins shot before|after pins snap before|after [--url U] [--selector S] [--pad 40] pins check --url U [--selector S] [--pad 40] + pins images [--dir D] pins ship --dir --summary "..." [--message "..."] [ ...] pins --help`; @@ -39,6 +40,7 @@ const commands = { wait: { count: 0, flags: ["host", "timeout"] }, progress: { count: 2, flags: [] }, shot: { count: 3, flags: [] }, + images: { count: 1, flags: ["dir"] }, snap: { count: 2, flags: ["url", "selector", "pad"] }, check: { count: 1, flags: ["url", "selector", "pad"], required: ["url"] }, // The pin id, then 1 to 50 changed files. @@ -122,6 +124,26 @@ function saveImage(id, bytes) { return file; } +// `pins images` saves the images of a pin as private files, oldest first. An old file goes first, so no symlink is followed. +async function saveImages(id, dir) { + const { pin } = await request(`/pins/${id}`); + if (!pin.images?.length) return []; + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const files = []; + for (const [index, image] of pin.images.entries()) { + const response = await fetch(`${base}/images/${image.id}`, { headers }); + if (!response.ok) throw new Error((await response.json().catch(() => ({}))).error || `pins server returned HTTP ${response.status}`); + const bytes = Buffer.from(await response.arrayBuffer()); + const type = shotType(bytes); + if (!type || bytes.length > SHOT_MAX) throw new Error(`image ${index + 1} of #${id} is not a PNG, JPEG or WebP file of at most 2 MiB`); + const file = join(dir, `pins-${id}-${index + 1}.${IMAGE_EXT[type]}`); + rmSync(file, { force: true }); + writeFileSync(file, bytes, { flag: "wx", mode: 0o600 }); + files.push(file); + } + return files; +} + // A done pin whose before and after facts show no change gets a warning. It never blocks the command. function warnIfUnchanged(id, pin) { const [before, after] = ["before", "after"].map((kind) => loadFacts(id, kind)); @@ -211,6 +233,11 @@ async function main() { console.log(`#${id} ${body}: image saved`); return; } + if (command === "images") { + const files = await saveImages(id, options.dir ?? tmpdir()); + console.log(files.length ? files.join("\n") : `#${id} has no images`); + return; + } if (command === "ship") { // The "after" shot of the live page, its facts and the verdict, as `pins snap after` gives them. const snapAfter = async (pin) => { diff --git a/server/src/api.js b/server/src/api.js index 7beb4c9..a246312 100644 --- a/server/src/api.js +++ b/server/src/api.js @@ -1,6 +1,7 @@ import { isUtf8 } from "node:buffer"; import { parseStatuses } from "./store.js"; import { HttpError, parseId, sendJson } from "./http.js"; +import { IMAGE_ID_RE } from "./shots.js"; export function apiRoute(path) { if (path === "/api/health") return { name: "health", methods: ["GET"] }; @@ -8,6 +9,9 @@ export function apiRoute(path) { if (path === "/api/settings") return { name: "settings", methods: ["GET", "PATCH"] }; if (path === "/api/pins") return { name: "pins", methods: ["GET", "POST"] }; if (path === "/api/batches") return { name: "batches", methods: ["POST"] }; + if (path === "/api/images") return { name: "images", methods: ["POST"] }; + const image = /^\/api\/images\/([^/]+)$/.exec(path); + if (image) return IMAGE_ID_RE.test(image[1]) ? { name: "image", imageId: image[1], methods: ["GET"] } : null; const match = /^\/api\/pins\/([^/]+)(?:\/(start|resolve|dismiss|ask|reopen|accept|revert|replies|progress|shots\/(before|after)))?$/.exec(path); const id = match && parseId(match[1]); if (!id) return null; @@ -47,6 +51,19 @@ function listOptions(query) { return { statuses: parseStatuses(query.get("status")), host: query.get("host"), path: query.get("path"), q: query.get("q"), limit, before, batch, selector }; } +// The bytes are an image from a page or his clipboard; the headers stop a browser from treating them as anything else. +function sendImage(res, image, missing) { + if (!image) throw new HttpError(404, missing); + res.writeHead(200, { + "Content-Type": image.type, + "Content-Length": image.bytes.length, + "Cache-Control": "private, no-cache", + "Content-Security-Policy": "default-src 'none'", + "X-Content-Type-Options": "nosniff", + }); + return res.end(image.bytes); +} + function found(value) { if (!value) throw new HttpError(404, "pin not found"); return value; @@ -81,21 +98,13 @@ export function serveApi(req, res, { store, version, extension, route, query, bo } if (name === "shot") { if (req.method === "PUT") return sendJson(res, 200, { pin: found(store.setShot(id, route.kind, body)) }); - const shot = store.getShot(id, route.kind); - if (!shot) throw new HttpError(404, "shot not found"); - // The bytes are an image from a page; the headers stop a browser from treating them as anything else. - res.writeHead(200, { - "Content-Type": shot.type, - "Content-Length": shot.bytes.length, - "Cache-Control": "private, no-cache", - "Content-Security-Policy": "default-src 'none'", - "X-Content-Type-Options": "nosniff", - }); - return res.end(shot.bytes); + return sendImage(res, store.getShot(id, route.kind), "shot not found"); } + if (name === "images") return sendJson(res, 201, { image: store.addImage({ ...body, author: actor.name }) }); + if (name === "image") return sendImage(res, store.getImage(route.imageId), "image not found"); if (name === "replies") { if (body.reopen !== undefined && typeof body.reopen !== "boolean") throw new HttpError(400, "reopen must be true or false"); - const reply = found(store.addReply(id, { kind: actor.kind, author: actor.name, body: body.body, reopen: body.reopen === true })); + const reply = found(store.addReply(id, { kind: actor.kind, author: actor.name, body: body.body, reopen: body.reopen === true, images: body.images })); return sendJson(res, 201, { reply, pin: store.getPin(id) }); } const pin = found(store.transition(id, name, { diff --git a/server/src/app.js b/server/src/app.js index 943325e..adc9929 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -4,7 +4,7 @@ import { allowMethod, HttpError, readBody, sendJson, tokenBucket } from "./http. import { SHOT_MAX, SHOT_TYPES } from "./shots.js"; import { createStatic, decodePath } from "./static.js"; -// PUT exists only on the shot route. +// PUT exists only on the shot route. A shot and an image for a pin arrive as raw bytes. const WRITES = new Set(["POST", "PATCH", "DELETE", "PUT"]); const HOST_RE = /^[a-z0-9.-]{1,253}(:[0-9]{1,5})?$/i; const mediaType = (req) => req.headers["content-type"]?.split(";", 1)[0].trim().toLowerCase(); @@ -52,11 +52,12 @@ export function createApp({ store, version, extension = null, queueUrl = "https: if (WRITES.has(req.method)) { const retry = takeToken(); if (retry) return limited(retry); - if (route?.name === "shot") { - // Raw image bytes from a local agent. Caddy adds X-Forwarded-For, so a browser never gets here. - if (req.headers["x-forwarded-for"] !== undefined) throw new HttpError(403, "shot upload is local only"); + if (route?.name === "shot" || route?.name === "images") { + // A shot comes from a local agent. Caddy adds X-Forwarded-For, so a browser never gets here. + // An image for a pin comes from him through Caddy, or from an agent. + if (route.name === "shot" && req.headers["x-forwarded-for"] !== undefined) throw new HttpError(403, "shot upload is local only"); actor = getActor(req); - if (actor.kind !== "agent") throw new HttpError(403, "only an agent can upload a shot"); + if (route.name === "shot" && actor.kind !== "agent") throw new HttpError(403, "only an agent can upload a shot"); const type = mediaType(req); if (!SHOT_TYPES.includes(type)) throw new HttpError(415, `content type must be ${SHOT_TYPES.join(", ")}`); body = { type, bytes: await readBody(req, SHOT_MAX) }; diff --git a/server/src/format.js b/server/src/format.js index 8b33e9f..f33c773 100644 --- a/server/src/format.js +++ b/server/src/format.js @@ -42,6 +42,7 @@ export function formatDetail(pin, replies = [], steps = []) { if (about.length) lines.push(about.join(" · ")); if (pin.presets?.length) lines.push(`presets: ${pin.presets.map((preset) => `${text(preset.label)}: ${text(preset.text)}`).join(" · ")}`); if (text(pin.quote)) lines.push(`quote: ${quoted(pin.quote)}`); + if (pin.images?.length) lines.push(`images: ${pin.images.length} (pins images ${pin.id} saves them)`); for (const key of ["agent", "model", "summary", "commit", "run", "batch"]) { if (text(pin[key])) lines.push(`${key}: ${text(pin[key])}`); } diff --git a/server/src/index.js b/server/src/index.js index cea0b49..d591bf2 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -24,11 +24,14 @@ const store = openStore({ file: process.env.PINS_DB || resolve(root, "data/pins.db"), rootDomain: process.env.PINS_ROOT_DOMAIN || "koglabs.com", shotsDir: process.env.PINS_SHOTS_DIR || undefined, + imagesDir: process.env.PINS_IMAGES_DIR || undefined, }); -// Old shot files go at start and once a day. A failed cleanup must not stop the server. +// Old shot and image files go at start and once a day. A failed cleanup must not stop the server. function pruneShots() { - try { store.pruneShots(); } - catch (error) { console.error(`pins: shot cleanup failed: ${String(error?.message ?? error).replace(/[\r\n]+/g, " ")}`); } + for (const [what, prune] of [["shot", store.pruneShots], ["image", store.pruneImages]]) { + try { prune(); } + catch (error) { console.error(`pins: ${what} cleanup failed: ${String(error?.message ?? error).replace(/[\r\n]+/g, " ")}`); } + } } pruneShots(); setInterval(pruneShots, 24 * 60 * 60 * 1000).unref(); diff --git a/server/src/shots.js b/server/src/shots.js index c69c67d..f6654cd 100644 --- a/server/src/shots.js +++ b/server/src/shots.js @@ -10,3 +10,7 @@ export function shotType(bytes) { if (bytes.length >= 12 && bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "image/webp"; return null; } + +// Images he attaches to a pin or a reply use the shot types and SHOT_MAX. An id is 16 random bytes as base64url. +export const IMAGE_ID_RE = /^[A-Za-z0-9_-]{22}$/; +export const IMAGE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }; diff --git a/server/src/store.js b/server/src/store.js index 62d0f37..a4f8c25 100644 --- a/server/src/store.js +++ b/server/src/store.js @@ -1,11 +1,12 @@ -// Pins, replies and steps in SQLite (node:sqlite, no native modules); shots in files. Validates +// Pins, replies, steps and image metadata in SQLite (node:sqlite, no native modules); shots and images in files. Validates // every write and emits a "change" event after it. The HTTP API, SSE and MCP all go through this module. import { DatabaseSync } from "node:sqlite"; +import { randomBytes } from "node:crypto"; import { EventEmitter } from "node:events"; import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { ID } from "./id.js"; -import { SHOT_KINDS, SHOT_MAX, SHOT_TYPES, shotType } from "./shots.js"; +import { IMAGE_ID_RE, SHOT_KINDS, SHOT_MAX, SHOT_TYPES, shotType } from "./shots.js"; export class ValidationError extends Error { status = 400; @@ -43,6 +44,11 @@ const SCOPES = ["element", "similar", "page", "site"]; const STEP_MAX = 40; // A shot file, or the temp file of an upload that did not finish. const SHOT_FILE_RE = new RegExp(`^(${ID})-(?:${SHOT_KINDS.join("|")})(?:\\.tmp)?$`); +// An image file, or its temp file. Images per pin input or reply, per pin, and unlinked on the server. +const IMAGE_FILE_RE = /^([A-Za-z0-9_-]{22})(?:\.tmp)?$/; +const IMAGES_PER_INPUT = 6; +const IMAGES_PER_PIN = 12; +const IMAGES_WAITING = 200; // Columns that newer versions added; an older file gets them on open. const ADDED_COLUMNS = [["run", "TEXT"], ["batch", "INTEGER"], ["model", "TEXT"], ["attempts", "INTEGER NOT NULL DEFAULT 0"], ["intent", "TEXT"], ["scope", "TEXT"], ["presets", "TEXT"], ["shot_before", "TEXT"], ["shot_after", "TEXT"], @@ -120,6 +126,16 @@ CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS images ( + id TEXT PRIMARY KEY, + pin_id INTEGER REFERENCES pins(id) ON DELETE CASCADE, + reply_id INTEGER, + type TEXT NOT NULL, + size INTEGER NOT NULL, + author TEXT, + created_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS images_pin ON images(pin_id, created_at); `; // `l` is the latest step of the pin; the steps table holds only the current run. @@ -283,7 +299,7 @@ function cleanViewport(v) { return Object.keys(out).length ? out : null; } -function toPin(row) { +function toPin(row, images = []) { return { id: row.id, status: row.status, @@ -313,6 +329,7 @@ function toPin(row) { versions: row.versions ? JSON.parse(row.versions) : [], revert: row.revert ? JSON.parse(row.revert) : null, revertedAt: row.reverted_at ?? null, + images, replyCount: Number(row.reply_count ?? 0), createdAt: row.created_at, updatedAt: row.updated_at, @@ -322,10 +339,13 @@ function toPin(row) { } const toReply = (row) => ({ id: row.id, pinId: row.pin_id, kind: row.kind, author: row.author, body: row.body, createdAt: row.created_at }); +const toImage = (row) => ({ id: row.id, type: row.type, size: row.size, replyId: row.reply_id ?? null, author: row.author, createdAt: row.created_at }); const toStep = (row) => ({ id: row.id, pinId: row.pin_id, author: row.author, body: row.body, createdAt: row.created_at }); -// Shots are files `-` in shotsDir (default: "shots" next to the database file). -export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && file !== ":memory:" ? join(dirname(file), "shots") : null } = {}) { +// Shots are files `-` in shotsDir, images files `` in imagesDir (default: "shots" and +// "images" next to the database file). +export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && file !== ":memory:" ? join(dirname(file), "shots") : null, + imagesDir = file && file !== ":memory:" ? join(dirname(file), "images") : null } = {}) { if (!file) throw new Error("openStore needs a file (or ':memory:')"); if (file !== ":memory:") mkdirSync(dirname(file), { recursive: true }); const db = new DatabaseSync(file); @@ -367,6 +387,15 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && closedAt: db.prepare(`SELECT closed_at FROM pins WHERE id = ?`), stats: db.prepare(`SELECT host, status, COUNT(*) AS n FROM pins GROUP BY host, status ORDER BY host`), setting: db.prepare(`SELECT value FROM settings WHERE key = ?`), + imagesOf: db.prepare(`SELECT * FROM images WHERE pin_id IN (SELECT value FROM json_each(?)) ORDER BY created_at, rowid`), + imageGet: db.prepare(`SELECT id FROM images WHERE id = ?`), + imageInsert: db.prepare(`INSERT INTO images (id, type, size, author, created_at) VALUES (?, ?, ?, ?, ?)`), + imageLink: db.prepare(`UPDATE images SET pin_id = ?, reply_id = ? WHERE id = ? AND pin_id IS NULL`), + imagesWaiting: db.prepare(`SELECT COUNT(*) AS n FROM images WHERE pin_id IS NULL`), + imageCount: db.prepare(`SELECT COUNT(*) AS n FROM images WHERE pin_id = ?`), + imageIds: db.prepare(`SELECT id FROM images WHERE pin_id = ?`), + imagesOld: db.prepare(`DELETE FROM images WHERE (pin_id IS NULL AND created_at < ?) OR pin_id IN (SELECT id FROM pins WHERE closed_at < ?)`), + imageIdsAll: db.prepare(`SELECT id FROM images`), setSetting: db.prepare(`INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`), }; @@ -387,9 +416,15 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && return { url: u.href, host: u.host.toLowerCase(), path: u.pathname || "/" }; } + // Pin rows to pin JSON, with the images of all of them read in one query. + const toPins = (rows) => { + const images = new Map(rows.map((row) => [row.id, []])); + if (rows.length) for (const row of q.imagesOf.all(JSON.stringify(rows.map((r) => r.id)))) images.get(row.pin_id).push(toImage(row)); + return rows.map((row) => toPin(row, images.get(row.id))); + }; const getPin = (id) => { const row = q.get.get(id); - return row ? toPin(row) : null; + return row ? toPins([row])[0] : null; }; const emit = (e) => events.emit("change", e); // Called after the commit, so it must not throw: the change event still has to go out. A file that stays is @@ -400,6 +435,38 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && try { rmSync(join(shotsDir, `${id}-${kind}`), { force: true }); } catch { /* It stays hidden. */ } } }; + // Like removeShots: called after the commit, so it never throws. A file that stays goes at the next prune. + const removeImages = (ids) => { + for (const id of ids) { + try { rmSync(join(imagesDir, id), { force: true }); } catch { /* The prune removes it. */ } + } + }; + // 0 to 6 image ids, each once. Checked before anything is written. + function cleanImages(v) { + if (v === undefined || v === null) return []; + if (!Array.isArray(v) || v.length > IMAGES_PER_INPUT || v.some((id) => typeof id !== "string" || !IMAGE_ID_RE.test(id)) || new Set(v).size !== v.length) { + throw new ValidationError(`images must hold 0 to ${IMAGES_PER_INPUT} different image ids`); + } + return v; + } + // Inside the transaction of the pin or the reply insert: only an unlinked image can be linked. + function linkImages(ids, pinId, replyId) { + for (const id of ids) { + if (!q.imageLink.run(pinId, replyId, id).changes) throw new ValidationError(`image ${id.slice(0, 6)} is gone; remove it and try again`); + } + } + // One write: BEGIN IMMEDIATE, fn, COMMIT; ROLLBACK when fn throws. + function inTransaction(fn) { + db.exec("BEGIN IMMEDIATE"); + try { + const result = fn(); + db.exec("COMMIT"); + return result; + } catch (error) { + db.exec("ROLLBACK"); + throw error; + } + } const getSettings = () => { const autofix = q.setting.get("autofix"); const bulk = q.setting.get("bulk"); @@ -413,7 +480,7 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && } // Validate one new pin completely before anything is written. - function preparePin({ url, title, note, quote, targets, viewport, intent, scope, presets } = {}) { + function preparePin({ url, title, note, quote, targets, viewport, intent, scope, presets, images } = {}) { const where = parseUrl(url); const text = required(note, 4000, "note"); if (!Array.isArray(targets) || targets.length < 1 || targets.length > 10) throw new ValidationError("targets must hold 1 to 10 elements"); @@ -422,14 +489,20 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && title: clip(typeof title === "string" ? title.trim() : undefined, 300) ?? null, quote: clip(typeof quote === "string" ? quote.trim() : undefined, 2000) || null, intent: choice(intent, INTENTS, "intent"), scope: choice(scope, SCOPES, "scope"), presets: JSON.stringify(cleanPresets(presets)), + images: cleanImages(images), }; } - const insertPin = (p, author, batch, t) => Number(q.insert.run(p.url, p.host, p.path, p.title, p.note, p.quote, p.targets, p.viewport, author, batch, p.intent, p.scope, p.presets, t, t).lastInsertRowid); + const insertPin = (p, author, batch, t) => { + const id = Number(q.insert.run(p.url, p.host, p.path, p.title, p.note, p.quote, p.targets, p.viewport, author, batch, p.intent, p.scope, p.presets, t, t).lastInsertRowid); + linkImages(p.images, id, null); + return id; + }; return { createPin({ author, ...input } = {}) { const prepared = preparePin(input); - const pin = getPin(insertPin(prepared, optional(author, 60, "author"), null, now())); + const who = optional(author, 60, "author"); + const pin = getPin(inTransaction(() => insertPin(prepared, who, null, now()))); emit({ type: "pin", action: "created", pin }); return pin; }, @@ -445,7 +518,7 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && const toBatch = (row, pins, created) => ({ batch: { id: row.id, host: row.host, author: row.author, createdAt: row.created_at, count: pins.length }, pins, created }); if (key) { const row = q.batchByKey.get(key); - if (row) return toBatch(row, q.batchPins.all(row.id).map(toPin), false); + if (row) return toBatch(row, toPins(q.batchPins.all(row.id)), false); } const prepared = items.map((item, index) => { try { return preparePin(item); } @@ -454,17 +527,12 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && const host = prepared[0].host; if (prepared.some((p) => p.host !== host)) throw new ValidationError("all pins in a batch must be on one host"); const t = now(); - let batchId; - db.exec("BEGIN IMMEDIATE"); - try { - batchId = Number(q.batchInsert.run(host, who, key || null, t).lastInsertRowid); - for (const p of prepared) insertPin(p, who, batchId, t); - db.exec("COMMIT"); - } catch (error) { - db.exec("ROLLBACK"); - throw error; - } - const pins = q.batchPins.all(batchId).map(toPin); + const batchId = inTransaction(() => { + const id = Number(q.batchInsert.run(host, who, key || null, t).lastInsertRowid); + for (const p of prepared) insertPin(p, who, id, t); + return id; + }); + const pins = toPins(q.batchPins.all(batchId)); for (const pin of pins) emit({ type: "pin", action: "created", pin }); return toBatch({ id: batchId, host, author: who, created_at: t }, pins, true); }, @@ -490,7 +558,7 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && // The inner query picks the ids; only those rows get the reply and step subqueries of SELECT_PIN. // In one flat query SQLite runs the subqueries for every matching row before it sorts and cuts. const ids = `SELECT p.id FROM pins p${where.length ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY p.id DESC LIMIT ${n}`; - return db.prepare(`${SELECT_PIN} WHERE p.id IN (${ids}) ORDER BY p.id DESC`).all(...args).map(toPin); + return toPins(db.prepare(`${SELECT_PIN} WHERE p.id IN (${ids}) ORDER BY p.id DESC`).all(...args)); }, updateNote(id, note) { @@ -570,15 +638,18 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && deletePin(id) { const pin = getPin(id); if (!pin) return false; + const images = q.imageIds.all(id).map((row) => row.id); q.del.run(id); removeShots(pin.id); + removeImages(images); emit({ type: "pin", action: "deleted", pin }); return true; }, // A user reply on a waiting pin requeues it. With reopen: true it also sends a done or // dismissed pin back to the queue ("Not right"). - addReply(id, { kind, author, body, reopen = false } = {}) { + addReply(id, { kind, author, body, reopen = false, images } = {}) { + const ids = cleanImages(images); let reply; let reopened; db.exec("BEGIN IMMEDIATE"); @@ -586,6 +657,8 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && const pin = getPin(id); if (!pin) { db.exec("COMMIT"); return null; } reply = insertReply(id, kind, author, body); + if (ids.length && q.imageCount.get(id).n + ids.length > IMAGES_PER_PIN) throw new ConflictError(`a pin holds at most ${IMAGES_PER_PIN} images`); + linkImages(ids, id, reply.id); reopened = kind === "user" && (pin.status === "waiting" || (reopen === true && ["done", "dismissed"].includes(pin.status))); if (reopened) q.requeue.run(1, reply.createdAt, id); else q.touch.run(reply.createdAt, id); @@ -665,6 +738,52 @@ export function openStore({ file, rootDomain = "koglabs.com", shotsDir = file && return removed; }, + // An image he attached, waiting for "Submit all" or the reply that links it. Written like a shot. + addImage({ type, bytes, author } = {}) { + if (!SHOT_TYPES.includes(type)) throw new ValidationError(`image type must be ${SHOT_TYPES.join(", ")}`); + if (!Buffer.isBuffer(bytes) || !bytes.length || bytes.length > SHOT_MAX) throw new ValidationError("image must hold 1 byte to 2 MiB"); + if (shotType(bytes) !== type) throw new ValidationError(`image is not ${type}`); + const who = optional(author, 60, "author"); + if (!imagesDir) throw new Error("openStore needs an imagesDir to keep images"); + if (q.imagesWaiting.get().n >= IMAGES_WAITING) throw new ConflictError("too many images wait for a pin"); + const id = randomBytes(16).toString("base64url"); + mkdirSync(imagesDir, { recursive: true, mode: 0o700 }); + const path = join(imagesDir, id); + writeFileSync(`${path}.tmp`, bytes, { mode: 0o600 }); + renameSync(`${path}.tmp`, path); + const t = now(); + try { q.imageInsert.run(id, type, bytes.length, who, t); } + catch (error) { removeImages([id]); throw error; } + return { id, type, size: bytes.length, replyId: null, author: who, createdAt: t }; + }, + + getImage(id) { + if (typeof id !== "string" || !IMAGE_ID_RE.test(id) || !imagesDir || !q.imageGet.get(id)) return null; + let bytes; + try { bytes = readFileSync(join(imagesDir, id)); } + catch (error) { if (error.code === "ENOENT") return null; throw error; } + const type = shotType(bytes); + return type ? { type, bytes } : null; + }, + + // Removes the images of pins closed more than olderThanDays ago and unlinked images older than that, then + // every file without a row (deleted pins, unfinished uploads). Runs with pruneShots. + pruneImages({ olderThanDays = 30 } = {}) { + if (!imagesDir) return 0; + const cutoff = new Date(Date.now() - olderThanDays * 86400000).toISOString(); + q.imagesOld.run(cutoff, cutoff); + if (!existsSync(imagesDir)) return 0; + const known = new Set(q.imageIdsAll.all().map((row) => row.id)); + let removed = 0; + for (const name of readdirSync(imagesDir)) { + const match = IMAGE_FILE_RE.exec(name); + if (!match || (known.has(match[1]) && name === match[1])) continue; + rmSync(join(imagesDir, name), { force: true }); + removed++; + } + return removed; + }, + getSettings, // Merges the given keys only. Everything is checked before anything is written. diff --git a/server/test/images.test.js b/server/test/images.test.js new file mode 100644 index 0000000..9126a8d --- /dev/null +++ b/server/test/images.test.js @@ -0,0 +1,293 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import { spawn } from "node:child_process"; +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createApp } from "../src/app.js"; +import { formatDetail } from "../src/format.js"; +import { openStore } from "../src/store.js"; +import { IMAGE_ID_RE, SHOT_MAX } from "../src/shots.js"; +import { createOldDatabase, createV2Database } from "./old-schema.js"; + +const bin = fileURLToPath(new URL("../bin/pins.js", import.meta.url)); +const PNG = Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), Buffer.from("png body")]); +const JPEG = Buffer.concat([Buffer.from("ffd8ffe0", "hex"), Buffer.from("jpeg body")]); +const WEBP = Buffer.concat([Buffer.from("RIFF\u0000\u0000\u0000\u0000WEBPVP8 ", "latin1"), Buffer.from("webp body")]); +const input = (extra = {}) => ({ url: "https://crete.koglabs.com/pricing", note: "Fix spacing", targets: [{ selector: "h1", label: "h1" }], ...extra }); + +async function fixture(t, { file = ":memory:" } = {}) { + const dir = mkdtempSync(join(tmpdir(), "pins-images-")); + const imagesDir = join(dir, "images"); + const store = openStore({ file, shotsDir: join(dir, "shots"), imagesDir }); + const app = createApp({ store, version: "test" }); + const server = createServer(app); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const port = server.address().port; + t.after(async () => { + app.close(); + await new Promise((resolve) => { server.close(resolve); server.closeAllConnections(); }); + store.close(); + rmSync(dir, { recursive: true, force: true }); + }); + const events = []; + store.on("change", (event) => events.push(event)); + async function call(path, { method = "GET", body, raw, type, headers = {} } = {}) { + const sent = { "X-SSO-User": "sam", ...headers }; + if (body !== undefined) sent["Content-Type"] = "application/json"; + if (type) sent["Content-Type"] = type; + const response = await fetch(`http://127.0.0.1:${port}/api${path}`, { method, headers: sent, body: raw ?? (body === undefined ? undefined : JSON.stringify(body)) }); + const bytes = Buffer.from(await response.arrayBuffer()); + const json = response.headers.get("content-type")?.startsWith("application/json") ? JSON.parse(bytes.toString("utf8")) : null; + return { status: response.status, headers: response.headers, bytes, data: json }; + } + const upload = async (bytes = PNG, type = "image/png", headers) => { + const response = await call("/images", { method: "POST", raw: bytes, type, headers }); + assert.equal(response.status, 201, JSON.stringify(response.data)); + return response.data.image; + }; + const pinCount = () => store.listPins({ statuses: ["queued", "working", "waiting", "done", "dismissed"] }).length; + return { store, port, dir, imagesDir, events, call, upload, pinCount }; +} + +test("an image uploads as raw bytes and comes back with the shot headers; the file is private", async (t) => { + const f = await fixture(t); + const image = await f.upload(); + assert.match(image.id, IMAGE_ID_RE); + assert.deepEqual({ ...image, id: 0, createdAt: 0 }, { id: 0, type: "image/png", size: PNG.length, replyId: null, author: "sam", createdAt: 0 }); + assert.match(image.createdAt, /^\d{4}-\d\d-\d\dT/); + const got = await f.call(`/images/${image.id}`); + assert.equal(got.status, 200); + assert.deepEqual(got.bytes, PNG); + assert.equal(got.headers.get("content-type"), "image/png"); + assert.equal(got.headers.get("content-length"), String(PNG.length)); + assert.equal(got.headers.get("cache-control"), "private, no-cache"); + assert.equal(got.headers.get("content-security-policy"), "default-src 'none'"); + assert.equal(got.headers.get("x-content-type-options"), "nosniff"); + assert.equal(statSync(join(f.imagesDir, image.id)).mode & 0o777, 0o600); + assert.equal(statSync(f.imagesDir).mode & 0o777, 0o700); + assert.deepEqual(readdirSync(f.imagesDir), [image.id], "no temp file stays"); + // An agent uploads too, and the user upload works through Caddy (X-Forwarded-For); the type follows the bytes. + const agent = await f.upload(WEBP, "image/webp", { "X-Pins-Agent": "claude" }); + assert.deepEqual([agent.author, agent.type], ["claude", "image/webp"]); + const proxied = await f.upload(JPEG, "image/jpeg; charset=x", { "X-Forwarded-For": "1.2.3.4" }); + assert.equal(proxied.type, "image/jpeg"); + assert.notEqual(proxied.id, image.id); + assert.equal((await f.call(`/images/${proxied.id}`)).headers.get("content-type"), "image/jpeg"); +}); + +test("an upload with a wrong type, a big or empty body or bytes of another type is refused and writes nothing", async (t) => { + const f = await fixture(t); + for (const type of [undefined, "text/plain", "image/gif", "application/json"]) { + const response = await f.call("/images", { method: "POST", raw: PNG, type }); + assert.equal(response.status, 415, type); + assert.match(response.data.error, /content type must be image\/png, image\/jpeg, image\/webp/); + } + assert.equal((await f.call("/images", { method: "POST", raw: Buffer.concat([PNG, Buffer.alloc(SHOT_MAX)]), type: "image/png" })).status, 413); + for (const [bytes, type, error] of [[Buffer.alloc(0), "image/png", /1 byte to 2 MiB/], [JPEG, "image/png", /image is not image\/png/], [Buffer.from("hello"), "image/webp", /not image\/webp/]]) { + const response = await f.call("/images", { method: "POST", raw: bytes, type }); + assert.deepEqual([response.status, response.data.error.match(error) !== null], [400, true]); + } + assert.equal(existsSync(f.imagesDir) ? readdirSync(f.imagesDir).length : 0, 0); + // Unknown and malformed ids are 404; other methods are 405. + const id = "A".repeat(22); + for (const path of [`/images/${id}`, "/images/short", `/images/${"A".repeat(23)}`, `/images/${"A".repeat(21)}!`, `/images/${id}/x`, "/images/"]) { + assert.equal((await f.call(path)).status, 404, path); + } + const image = await f.upload(); + assert.equal((await f.call("/images")).status, 405); + const post = await f.call(`/images/${image.id}`, { method: "POST", body: {} }); + assert.deepEqual([post.status, post.headers.get("allow")], [405, "GET"]); +}); + +test("at most 200 unlinked images wait for a pin", async (t) => { + const f = await fixture(t); + for (let i = 0; i < 200; i++) f.store.addImage({ type: "image/png", bytes: PNG, author: "sam" }); + const refused = await f.call("/images", { method: "POST", raw: PNG, type: "image/png" }); + assert.deepEqual([refused.status, refused.data], [409, { error: "too many images wait for a pin" }]); + assert.equal(readdirSync(f.imagesDir).length, 200); + // A linked image no longer waits. + const waiting = readdirSync(f.imagesDir).slice(0, 1); + assert.equal((await f.call("/pins", { method: "POST", body: input({ images: waiting }) })).status, 201); + await f.upload(); +}); + +test("a pin links its images in the insert: the created event carries them, oldest first", async (t) => { + const f = await fixture(t); + const [a, b] = [await f.upload(), await f.upload(JPEG, "image/jpeg")]; + const created = await f.call("/pins", { method: "POST", body: input({ images: [b.id, a.id] }) }); + assert.equal(created.status, 201); + const pin = created.data.pin; + assert.deepEqual(pin.images, [a, b]); + const event = f.events.find((e) => e.type === "pin" && e.action === "created"); + assert.deepEqual(event.pin.images, [a, b]); + assert.deepEqual((await f.call(`/pins/${pin.id}`)).data.pin.images, [a, b]); + assert.deepEqual((await f.call("/pins")).data.pins[0].images, [a, b]); + const plain = await f.call("/pins", { method: "POST", body: input() }); + assert.deepEqual(plain.data.pin.images, []); + // A linked image still downloads. + assert.deepEqual((await f.call(`/images/${a.id}`)).bytes, PNG); + // A linked or unknown id is gone; nothing is written. + const before = f.pinCount(); + for (const id of [a.id, "Z".repeat(22)]) { + const refused = await f.call("/pins", { method: "POST", body: input({ images: [id] }) }); + assert.deepEqual([refused.status, refused.data.error], [400, `image ${id.slice(0, 6)} is gone; remove it and try again`]); + } + assert.equal(f.pinCount(), before); + // The shape: an array of 0 to 6 different ids. + const c = await f.upload(); + for (const images of ["x", [c.id, c.id], ["short"], [1], Array.from({ length: 7 }, (_, i) => `${"B".repeat(21)}${i}`), {}]) { + const refused = await f.call("/pins", { method: "POST", body: input({ images }) }); + assert.deepEqual([refused.status, refused.data.error], [400, "images must hold 0 to 6 different image ids"], JSON.stringify(images)); + } + assert.equal(f.pinCount(), before); + assert.deepEqual((await f.call("/pins", { method: "POST", body: input({ images: [] }) })).data.pin.images, []); +}); + +test("a batch links each pin's images in one transaction; one gone image writes nothing; a known key links nothing new", async (t) => { + const f = await fixture(t); + const [a, b, c] = [await f.upload(), await f.upload(), await f.upload()]; + const refused = await f.call("/batches", { method: "POST", body: { key: "batch-key-1", pins: [input({ images: [a.id] }), input({ images: ["Q".repeat(22)] })] } }); + assert.deepEqual([refused.status, refused.data.error], [400, `image QQQQQQ is gone; remove it and try again`]); + assert.equal(f.pinCount(), 0); + // The same id in two pins of one batch: the second link fails, so the first is undone too. + const twice = await f.call("/batches", { method: "POST", body: { pins: [input({ images: [a.id] }), input({ images: [a.id] })] } }); + assert.equal(twice.status, 400); + assert.equal(f.pinCount(), 0); + const bad = await f.call("/batches", { method: "POST", body: { pins: [input(), input({ images: "x" })] } }); + assert.deepEqual([bad.status, bad.data.error], [400, "pin 2: images must hold 0 to 6 different image ids"]); + const created = await f.call("/batches", { method: "POST", body: { key: "batch-key-1", pins: [input({ images: [a.id, b.id] }), input(), input({ images: [c.id] })] } }); + assert.equal(created.status, 201); + assert.deepEqual(created.data.pins.map((pin) => pin.images.map((image) => image.id)), [[a.id, b.id], [], [c.id]]); + const createdEvents = f.events.filter((e) => e.type === "pin" && e.action === "created"); + assert.deepEqual(createdEvents.map((e) => e.pin.images.length), [2, 0, 1]); + const d = await f.upload(); + const again = await f.call("/batches", { method: "POST", body: { key: "batch-key-1", pins: [input({ images: [d.id] })] } }); + assert.equal(again.status, 200); + assert.deepEqual(again.data.pins.map((pin) => pin.images.length), [2, 0, 1]); + // d is still unlinked: a new pin can take it. + assert.equal((await f.call("/pins", { method: "POST", body: input({ images: [d.id] }) })).status, 201); +}); + +test("a reply links its images with its reply id; a pin holds at most 12; start and reopen keep the images", async (t) => { + const f = await fixture(t); + const first = await Promise.all(Array.from({ length: 6 }, () => f.upload())); + const pin = (await f.call("/pins", { method: "POST", body: input({ images: first.map((i) => i.id) }) })).data.pin; + const more = await Promise.all(Array.from({ length: 6 }, () => f.upload())); + const replied = await f.call(`/pins/${pin.id}/replies`, { method: "POST", body: { body: "See the attached images.", images: more.map((i) => i.id) } }); + assert.equal(replied.status, 201); + const replyId = replied.data.reply.id; + assert.deepEqual(replied.data.pin.images.map((i) => i.replyId), [...Array(6).fill(null), ...Array(6).fill(replyId)]); + const replyEvent = f.events.find((e) => e.type === "reply"); + assert.equal(replyEvent.pin.images.length, 12); + const extra = await f.upload(); + const full = await f.call(`/pins/${pin.id}/replies`, { method: "POST", body: { body: "One more", images: [extra.id] } }); + assert.deepEqual([full.status, full.data.error], [409, "a pin holds at most 12 images"]); + assert.equal(f.store.listReplies(pin.id).length, 1, "the refused reply is not written"); + const other = (await f.call("/pins", { method: "POST", body: input() })).data.pin; + const gone = await f.call(`/pins/${other.id}/replies`, { method: "POST", body: { body: "x", images: [first[0].id] } }); + assert.deepEqual([gone.status, gone.data.error], [400, `image ${first[0].id.slice(0, 6)} is gone; remove it and try again`]); + assert.deepEqual(f.store.listReplies(other.id), []); + assert.equal((await f.call(`/pins/${other.id}/replies`, { method: "POST", body: { images: [extra.id] } })).status, 400, "a reply still needs a body"); + assert.equal((await f.call(`/pins/${other.id}/replies`, { method: "POST", body: { body: "x", images: [extra.id] } })).data.pin.images[0].replyId, f.store.listReplies(other.id)[0].id); + const agent = { "X-Pins-Agent": "claude" }; + for (const action of ["start", "ask", "reopen", "start", "resolve", "reopen"]) { + const body = { ask: { question: "Which?" }, resolve: { summary: "Fixed" } }[action] ?? {}; + const moved = await f.call(`/pins/${pin.id}/${action}`, { method: "POST", body, headers: action === "reopen" ? {} : agent }); + assert.equal(moved.status, 200, `${action}: ${JSON.stringify(moved.data)}`); + assert.equal(moved.data.pin.images.length, 12, action); + } +}); + +test("deleting a pin removes its image files; the prune removes old, closed and orphan images", async (t) => { + const f = await fixture(t); + const a = await f.upload(); + const pin = (await f.call("/pins", { method: "POST", body: input({ images: [a.id] }) })).data.pin; + assert.equal((await f.call(`/pins/${pin.id}`, { method: "DELETE" })).status, 204); + assert.equal(existsSync(join(f.imagesDir, a.id)), false); + assert.equal((await f.call(`/images/${a.id}`)).status, 404); + + const [open, closed, waiting] = [await f.upload(), await f.upload(), await f.upload()]; + const openPin = (await f.call("/pins", { method: "POST", body: input({ images: [open.id] }) })).data.pin; + const closedPin = (await f.call("/pins", { method: "POST", body: input({ images: [closed.id] }) })).data.pin; + assert.equal((await f.call(`/pins/${closedPin.id}/dismiss`, { method: "POST", body: {}, headers: { "X-Pins-Agent": "claude" } })).status, 200); + const orphan = "O".repeat(22); + for (const name of [orphan, `${orphan}.tmp`, "notes.txt"]) writeFileSync(join(f.imagesDir, name), PNG); + // Fresh files stay, except files without a row. + assert.equal(f.store.pruneImages(), 2); + assert.deepEqual(readdirSync(f.imagesDir).sort(), [open.id, closed.id, waiting.id, "notes.txt"].sort()); + // With a cutoff in the future every closed pin and every unlinked image is old. + assert.equal(f.store.pruneImages({ olderThanDays: -1 }), 2); + assert.deepEqual(readdirSync(f.imagesDir).sort(), [open.id, "notes.txt"].sort()); + assert.deepEqual(f.store.getPin(closedPin.id).images, []); + assert.deepEqual(f.store.getPin(openPin.id).images.map((i) => i.id), [open.id]); + assert.equal(f.store.getImage(waiting.id), null); +}); + +test("an old database file gets the images table on open", (t) => { + const dir = mkdtempSync(join(tmpdir(), "pins-images-old-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + for (const [name, create, id] of [["old.db", createOldDatabase, 12], ["v2.db", createV2Database, 30]]) { + const file = join(dir, name); + create(file).close(); + const store = openStore({ file }); + try { + assert.deepEqual(store.getPin(id).images, []); + const image = store.addImage({ type: "image/png", bytes: PNG, author: "sam" }); + assert.ok(existsSync(join(dir, "images", image.id)), "images default to a folder next to the database"); + store.addReply(id, { kind: "user", author: "sam", body: "See the attached image.", images: [image.id] }); + assert.deepEqual(store.getPin(id).images.map((i) => i.id), [image.id]); + assert.deepEqual(store.getImage(image.id), { type: "image/png", bytes: PNG }); + } finally { store.close(); } + rmSync(join(dir, "images"), { recursive: true, force: true }); + } +}); + +test("the detail format names the images and the command that saves them", () => { + const pin = { id: 12, status: "queued", host: "crete.koglabs.com", path: "/", note: "n", quote: "q", targets: [], images: [{ id: "a" }, { id: "b" }] }; + assert.match(formatDetail(pin), /\nquote: "q"\nimages: 2 \(pins images 12 saves them\)$/); + assert.match(formatDetail({ ...pin, quote: null }), /\nnote: n\nimages: 2 \(pins images 12 saves them\)/); + assert.doesNotMatch(formatDetail({ ...pin, images: [] }), /images:/); +}); + +test("CLI pins images saves each image as a private file, oldest first, and prints the paths", { timeout: 20000 }, async (t) => { + const f = await fixture(t); + const run = (args) => new Promise((resolve, reject) => { + const child = spawn(process.execPath, [bin, ...args], { env: { ...process.env, PINS_PORT: String(f.port), PINS_AGENT: "cli-test" }, stdio: ["ignore", "pipe", "pipe"], timeout: 8000 }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; }); + child.stderr.setEncoding("utf8").on("data", (chunk) => { stderr += chunk; }); + child.once("error", reject); + child.once("close", (code) => resolve({ code, stdout, stderr })); + }); + const images = [await f.upload(), await f.upload(JPEG, "image/jpeg"), await f.upload(WEBP, "image/webp")]; + const pin = (await f.call("/pins", { method: "POST", body: input({ images: images.map((i) => i.id) }) })).data.pin; + const out = join(f.dir, "out"); + // A stale file (or a symlink) at the target name is replaced, not followed. + const saved = await run(["images", String(pin.id), "--dir", out]); + assert.equal(saved.code, 0, saved.stderr); + const files = ["png", "jpg", "webp"].map((ext, i) => join(out, `pins-${pin.id}-${i + 1}.${ext}`)); + assert.equal(saved.stdout, `${files.join("\n")}\n`); + for (const [i, file] of files.entries()) { + assert.deepEqual(readFileSync(file), [PNG, JPEG, WEBP][i]); + assert.equal(statSync(file).mode & 0o777, 0o600); + } + writeFileSync(files[0], "stale"); + assert.equal((await run(["images", String(pin.id), "--dir", out])).code, 0); + assert.deepEqual(readFileSync(files[0]), PNG); + const bare = (await f.call("/pins", { method: "POST", body: input() })).data.pin; + assert.deepEqual(await run(["images", String(bare.id)]), { code: 0, stdout: `#${bare.id} has no images\n`, stderr: "" }); + const missing = await run(["images", "999"]); + assert.deepEqual([missing.code, missing.stderr], [1, "pin not found\n"]); + assert.equal((await run(["images", String(pin.id), "--dir", "relative"])).code, 2); + assert.match((await run(["--help"])).stdout, /\n pins images \[--dir D\]\n/); + // The default folder is the temp dir. + const tmp = await run(["images", String(pin.id)]); + assert.equal(tmp.stdout.split("\n")[0], join(tmpdir(), `pins-${pin.id}-1.png`)); + for (const file of tmp.stdout.trim().split("\n")) rmSync(file, { force: true }); +});