Compare commits

...
Author SHA1 Message Date
spark a4647a4390 feat(autopilot): treat the gallery size as a target
ci / typescript (pull_request) Successful in 13m30s
ci / rust (pull_request) Successful in 10m16s
A rich match may pass the asked size by about 15 percent, and never by more than 25 frames. A thin match stays under.
2026-11-07 15:01:28 +00:00
spark 145f693d8d feat(autopilot): give each destination its own gallery size (#244)
ci / rust (push) Successful in 8m9s
ci / typescript (push) Successful in 13m1s
feat(autopilot): give each destination its own gallery size
2026-11-07 14:56:35 +00:00
spark e4a61d3127 fix(delivery): send ZeroZero the full author line (#242)
ci / rust (push) Successful in 7m1s
ci / typescript (push) Successful in 10m19s
fix(delivery): send ZeroZero the full author line
2026-11-07 14:46:31 +00:00
spark efc3aafd8a fix(library): open a photo large on double-click (#240)
ci / rust (push) Successful in 8m19s
ci / typescript (push) Successful in 11m45s
fix(library): open a photo large on double-click
2026-11-07 03:22:08 +00:00
spark 5728c1782a feat(mcp): open the PhotoReport window from the assistant (#238)
ci / rust (push) Successful in 7m21s
ci / typescript (push) Successful in 13m30s
feat(mcp): open the PhotoReport window from the assistant
2026-11-07 03:12:45 +00:00
spark 0bff3c9794 feat(mcp): add an assistant server for the photographer (#236)
ci / rust (push) Successful in 7m13s
ci / typescript (push) Successful in 11m53s
feat(mcp): add an assistant server for the photographer
2026-11-07 02:56:08 +00:00
spark dddfa19ca3 feat(ui): use the quiet controls across the working modules (#234)
ci / rust (push) Successful in 9m13s
ci / typescript (push) Successful in 14m42s
feat(ui): use the quiet controls across the working modules
2026-11-07 02:51:23 +00:00
65 changed files with 1767 additions and 110 deletions

No files matched your search

+1 -1
View File
@@ -136,7 +136,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
});
await registerAuthRoutes(app, { db, config, sessions });
await registerMeRoutes(app, { db, sessions });
await registerMeRoutes(app, { db, sessions, broadcaster });
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
await registerOrgRoutes(app, { db, sessions });
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
+34 -7
View File
@@ -1,7 +1,8 @@
/**
* "Only the best" (docs/photo-editing-rules.md §5): for clients that want a short gallery of the match, not every
* usable frame. The match is cut into short windows, and each window may add its share of the gallery size, with
* the share it did not use carried forward (half-time adds nothing, a busy spell may take a little more). Within a
* the share it did not use carried forward (half-time adds nothing, a busy spell may take a little more).
* The asked size is a target: a rich match may pass it by about 15% (never more than 25 frames); a thin one stays under. Within a
* window the frames with the most action win: the ball in play, a duel or a celebration, a subject big in the
* frame and sharp; one frame per burst, and not two from the same few seconds. Anything well below the match's
* typical frame is left out even when the window has room.
@@ -65,6 +66,15 @@ const median = (xs: number[]) => {
return s[Math.floor(s.length / 2)]!;
};
/**
* How many frames a gallery may reach. The asked size is the target: about 15% more when the match is rich,
* at least 2 and never more than 25 past it, so a short gallery stays close and a long one can breathe.
*/
export function galleryCeiling(count: number): number {
const extra = Math.min(25, Math.max(2, Math.round(count * 0.15)));
return count + extra;
}
/**
* Decides the windows that have closed and are not decided yet. `decided` holds the candidates already decided
* (chosen or not), so earlier choices count against the gallery size.
@@ -75,11 +85,14 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
const settleMs = opts.settleMs ?? 60_000;
const done = new Map(decided.map((d) => [d.id, d.chosen]));
let chosenSoFar = [...done.values()].filter(Boolean).length;
const cap = Math.round(opts.count * 1.1);
const cap = galleryCeiling(opts.count);
const perWindow = (opts.count * windowMs) / opts.durationMs;
// The match's typical frame, for the floor: half of the median of the frames with a subject.
const windows = Math.max(1, opts.durationMs / windowMs);
// The match's typical frame. The floor drops weak frames; only a frame at or above the typical one may use the slack.
const scored = candidates.map((c) => ({ c, s: actionScore(c) }));
const floor = scored.filter((x) => x.s > 0).length >= 10 ? 0.5 * median(scored.filter((x) => x.s > 0).map((x) => x.s)) : 0;
const positives = scored.filter((x) => x.s > 0).map((x) => x.s);
const typical = positives.length >= 10 ? median(positives) : Number.POSITIVE_INFINITY;
const floor = positives.length >= 10 ? 0.5 * typical : 0;
const byWindow = new Map<number, typeof scored>();
for (const x of scored) {
@@ -98,15 +111,29 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
const end = opts.start + (w + 1) * windowMs;
if (end + settleMs > opts.now) break;
// The share up to the end of this window, minus what was already chosen; at most three windows' worth at once.
const target = Math.min(cap, Math.round(perWindow * (w + 1)));
const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), cap - chosenSoFar));
const target = Math.min(opts.count, Math.round(perWindow * (w + 1)));
const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), opts.count - chosenSoFar));
const ranked = list.filter((x) => x.s > 0 && x.s >= floor).sort((a, b) => b.s - a.s);
const chosen: Candidate[] = [];
const fits = (c: Candidate) => !chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs);
for (const { c } of ranked) {
if (chosen.length >= room) break;
if (chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs)) continue;
if (!fits(c)) continue;
chosen.push(c);
}
// Slack follows the match, about 15% by the end. A quiet spell leaves it; a rich window may spend up to two frames of it.
const slackByNow = Math.round(((cap - opts.count) * (w + 1)) / windows);
const alreadyOver = Math.max(0, chosenSoFar - opts.count);
let extraLeft = Math.min(2, Math.max(0, slackByNow - alreadyOver), cap - chosenSoFar - chosen.length);
if (extraLeft > 0 && typical !== Number.POSITIVE_INFINITY) {
for (const { c, s } of ranked) {
if (extraLeft <= 0) break;
if (chosen.includes(c)) continue;
if (s < typical || !fits(c)) continue;
chosen.push(c);
extraLeft -= 1;
}
}
chosenSoFar += chosen.length;
out.push({ window: w, ids: list.map((x) => x.c.id), chosen: chosen.sort((a, b) => a.at - b.at).map((c) => c.id) });
}
+80 -5
View File
@@ -20,7 +20,7 @@ import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.j
import { curate, matchMinutes } from "./curate.js";
import { type LearntStyle, learntStyle } from "./learning.js";
import { detailForCrop, lookValues } from "./look.js";
import { exportTargets, MELHORES_GAP_MS, picksNeeded } from "./targets.js";
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
@@ -63,6 +63,8 @@ export interface AutopilotRecord {
chosen?: boolean;
/** "ball": the picture cuts the ball, so it is not delivered. */
hold?: "ball";
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
gallery?: Record<string, boolean>;
/**
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
* near-duplicates left unflagged.
@@ -374,15 +376,42 @@ export class AutopilotService {
.filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.curated)
.map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen }));
const targets = exportTargets(settings);
const galleries = settings.galleries ?? [];
// With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target.
// Separate gallery sizes curate to the largest, and each smaller one keeps its own spread.
const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best");
const decisions = curate(candidates, decided, {
count: settings.bestCount,
const curateOpts = {
start: event.startsAt.getTime(),
durationMs: matchMinutes(event.sport) * 60_000,
now: now.getTime(),
minGapMs: MELHORES_GAP_MS,
};
const decisions = curate(candidates, decided, {
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
...curateOpts,
});
const chosenBy = new Map<string, Set<string>>();
const seenBy = new Map<string, Set<string>>();
if (galleries.length) {
const max = Math.max(...galleries.map((g) => g.count));
const bigChosen = new Set(decisions.flatMap((d) => d.chosen));
const bigSeen = new Set(decisions.flatMap((d) => d.ids));
for (const g of galleries) {
if (g.count !== max) continue;
chosenBy.set(g.targetId, bigChosen);
seenBy.set(g.targetId, bigSeen);
}
for (const g of galleries) {
if (g.count === max) continue;
const earlier = photos.flatMap((p) => {
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
return flag === undefined ? [] : [{ id: p.id, chosen: flag }];
});
const parts = curate(candidates, earlier, { count: g.count, ...curateOpts });
chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen)));
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
}
}
const records = new Map(photos.map((p) => [p.id, p.autopilot as unknown as AutopilotRecord | null]));
// Frames that were not their burst's candidate are decided with it.
const burstOf = new Map<string, string[]>();
@@ -400,12 +429,13 @@ export class AutopilotService {
for (const id of ids) {
const rec = records.get(id);
if (!rec || rec.curated) continue;
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id) } as object } });
const gallery = galleryMarks(id, galleries, chosenBy, seenBy, rec.gallery);
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id), ...(gallery ? { gallery } : {}) } as object } });
nowCurated.push(id);
}
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
chosenCount += chosen.size;
if (targets.length && this.deps.deliveries && event.createdById) {
if (!galleries.length && targets.length && this.deps.deliveries && event.createdById) {
// Per chosen moment (burst): rank i → export i. Same photo never to two destinations.
for (const momentId of chosen) {
const burstIds = burstOf.get(momentId) ?? [momentId];
@@ -427,6 +457,33 @@ export class AutopilotService {
}
if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window");
}
if (galleries.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const moments = new Set<string>();
for (const [targetId, picked] of chosenBy) {
const seen = seenBy.get(targetId);
for (const id of picked) if (seen?.has(id)) moments.add(id);
}
for (const momentId of moments) {
if (!takenHere([momentId], when, event).length) continue;
for (const targetId of galleryReceivers(momentId, galleries, chosenBy)) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId, photoIds: [momentId], again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
}
}
// Windows already closed before these galleries existed still need their decision recorded.
for (const [targetId, seen] of seenBy) {
for (const id of seen) {
const rec = records.get(id);
if (!rec?.curated || rec.gallery?.[targetId] !== undefined) continue;
const gallery = galleryMarks(id, galleries, chosenBy, seenBy, rec.gallery);
if (!gallery) continue;
rec.gallery = gallery;
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, gallery } as object } });
}
}
}
return chosenCount;
}
}
@@ -435,6 +492,24 @@ export class AutopilotService {
* The photos of a decided window that go to the second client: the picked ones (by the autopilot or a person) the
* gallery did not take. Never a chosen one, so no photo reaches both clients.
*/
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
function galleryMarks(
id: string,
galleries: readonly GalleryExport[],
chosenBy: ReadonlyMap<string, ReadonlySet<string>>,
seenBy: ReadonlyMap<string, ReadonlySet<string>>,
previous: Record<string, boolean> | undefined,
): Record<string, boolean> | undefined {
const flags: Record<string, boolean> = { ...previous };
let touched = false;
for (const g of galleries) {
if (!seenBy.get(g.targetId)?.has(id)) continue;
flags[g.targetId] = chosenBy.get(g.targetId)?.has(id) ?? false;
touched = true;
}
return touched ? flags : undefined;
}
export function restOf(ids: readonly string[], chosen: ReadonlySet<string>, flags: ReadonlyMap<string, string>): string[] {
return ids.filter((id) => !chosen.has(id) && flags.get(id) === "PICK");
}
+20
View File
@@ -31,3 +31,23 @@ export function picksNeeded(settings: AutopilotSettings): number {
/** Melhores spacing between two sends to the same destination (ms). */
export const MELHORES_GAP_MS = 5_000;
export interface GalleryExport {
targetId: string;
count: number;
}
/**
* Destinations that receive this frame. A frame picked for a smaller gallery also goes to every larger one,
* so the short gallery is part of the long one. A frame only the long gallery picked stays out of the short one.
*/
export function galleryReceivers(momentId: string, galleries: readonly GalleryExport[], chosen: ReadonlyMap<string, ReadonlySet<string>>): string[] {
if (!galleries.length) return [];
const max = Math.max(...galleries.map((g) => g.count));
const hit = galleries.filter((g) => chosen.get(g.targetId)?.has(momentId));
const ids = new Set(hit.map((g) => g.targetId));
if (hit.some((g) => g.count < max)) {
for (const g of galleries) if (g.count === max) ids.add(g.targetId);
}
return [...ids];
}
+2 -2
View File
@@ -591,8 +591,8 @@ export class DeliveryService {
}
const client = this.client(item.target);
await client.ensureFolder(folder);
// The author as the service shows it: the photographer's name from the IPTC creator ("Peter Spark / PhotoReport.pt").
const creator = typeof iptc?.values.creator === "string" ? iptc.values.creator.split(" / ")[0]!.trim() : "";
// ZeroZero's Autor / Fotógrafo is this whole line ("Peter Spark / Kapta+"), not only the name before the slash.
const creator = typeof iptc?.values.creator === "string" ? iptc.values.creator.trim() : "";
const remote = await client.upload(folder + fileName, data, { author: creator || item.photo.uploader?.name || undefined });
const remotePath = typeof remote === "string" ? remote : folder + fileName;
// "synced-…" means the desk already had this file, so this attempt did not put a new image up.
+11 -1
View File
@@ -15,6 +15,16 @@ import { splitStoredPlace } from "../sports/providers.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
/** An older app does not send `galleries`. Keep the sizes already stored instead of clearing them. */
function keptGalleries(next: AutopilotSettings | null, current: Prisma.JsonValue): AutopilotSettings | typeof Prisma.DbNull {
if (!next) return Prisma.DbNull;
if (next.galleries !== undefined) return next;
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
const kept = (current as { galleries?: AutopilotSettings["galleries"] }).galleries;
if (!Array.isArray(kept) || kept.length === 0) return next;
return { ...next, galleries: kept };
}
const OrgParams = z.object({ orgId: z.uuid() });
const EventParams = z.object({ eventId: z.uuid() });
@@ -242,7 +252,7 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
...(startsAt && { startsAt }),
...window,
...(iptcTemplate && { iptcTemplate }),
...(autopilot !== undefined && { autopilot: autopilot ?? Prisma.DbNull }),
...(autopilot !== undefined && { autopilot: keptGalleries(autopilot, current.autopilot) }),
...(archived !== undefined && { archivedAt: archived ? (current.archivedAt ?? new Date()) : null }),
},
include,
+11 -2
View File
@@ -1,10 +1,11 @@
import { MODULES } from "@photoreport/contracts";
import { DeskCommand, MODULES } from "@photoreport/contracts";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { currentUserId, requireAuth } from "../auth/guard.js";
import type { SessionService } from "../auth/sessions.js";
import type { Db } from "../db.js";
import { notFound } from "../lib/errors.js";
import { silentBroadcaster, type Broadcaster } from "../realtime.js";
const PreferencesBody = z.object({
editorModules: z
@@ -13,8 +14,9 @@ const PreferencesBody = z.object({
.transform((mods) => [...new Set(mods)]),
});
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService }) {
export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; broadcaster?: Broadcaster }) {
const { db } = deps;
const broadcaster = deps.broadcaster ?? silentBroadcaster;
const authenticate = requireAuth(deps.sessions);
app.get("/v1/me", { preHandler: authenticate }, async (req) => {
@@ -52,4 +54,11 @@ export async function registerMeRoutes(app: FastifyInstance, deps: { db: Db; ses
});
return { editorModules: prefs.editorModules };
});
/** The assistant asks the open PhotoReport of this person to change module, photo or tool. */
app.post("/v1/me/desk", { preHandler: authenticate }, async (req) => {
const command = DeskCommand.parse(req.body);
broadcaster.desk(currentUserId(req), command);
return { ok: true as const };
});
}
+37 -3
View File
@@ -1,4 +1,4 @@
import { LIBRARY_CHANNEL, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage, roomForOrg, roomForUser } from "@photoreport/contracts";
import type { Server as HttpServer } from "node:http";
import pg from "pg";
import { Server } from "socket.io";
@@ -8,17 +8,23 @@ import type { Db } from "./db.js";
/** Anything that can push library messages to the people of an organization. */
export interface Broadcaster {
library(organizationId: string, message: LibraryMessage): void;
/** The open PhotoReport of this user: change module, photo or tool. */
desk(userId: string, command: DeskCommand): void;
close(): Promise<void>;
}
export const silentBroadcaster: Broadcaster = { library: () => {}, close: async () => {} };
export const silentBroadcaster: Broadcaster = { library: () => {}, desk: () => {}, close: async () => {} };
/** Records messages; used by tests. */
export class MemoryBroadcaster implements Broadcaster {
readonly sent: { organizationId: string; message: LibraryMessage }[] = [];
readonly deskSent: { userId: string; command: DeskCommand }[] = [];
library(organizationId: string, message: LibraryMessage): void {
this.sent.push({ organizationId, message });
}
desk(userId: string, command: DeskCommand): void {
this.deskSent.push({ userId, command });
}
async close(): Promise<void> {}
}
@@ -27,6 +33,8 @@ export class MemoryBroadcaster implements Broadcaster {
* delivers to its own sockets, the ingest worker only publishes. No Redis, no sticky sessions.
*/
const PG_CHANNEL = "photoreport_realtime";
/** Window instructions, delivered to one person's sockets (not the whole organization). */
const DESK_CHANNEL = "photoreport_desk";
/** NOTIFY payloads are limited to 8000 bytes; batch updates are split so each message fits. */
const IDS_PER_MESSAGE = 100;
@@ -113,8 +121,14 @@ export function attachRealtime(
if (closed) return;
const client = new pg.Client({ connectionString: deps.databaseUrl });
client.on("notification", (n) => {
if (n.channel !== PG_CHANNEL || !n.payload) return;
if (!n.payload) return;
try {
if (n.channel === DESK_CHANNEL) {
const { userId, command } = JSON.parse(n.payload) as { userId: string; command: DeskCommand };
io.to(roomForUser(userId)).emit("desk", command);
return;
}
if (n.channel !== PG_CHANNEL) return;
const { organizationId, message } = JSON.parse(n.payload) as Envelope;
io.to(roomForOrg(organizationId)).emit(LIBRARY_CHANNEL, message);
} catch (err) {
@@ -132,6 +146,7 @@ export function attachRealtime(
return;
}
await client.query(`LISTEN ${PG_CHANNEL}`);
await client.query(`LISTEN ${DESK_CHANNEL}`);
listener = client;
};
const ready = listen().catch((err) => {
@@ -139,8 +154,18 @@ export function attachRealtime(
if (!closed) retry = setTimeout(() => void listen().catch(onError), 1000);
});
const desk = (userId: string, command: DeskCommand) => {
if (closed) return;
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
if (closed && isPoolEndedError(err)) return;
onError(err);
});
trackPending(pending)(q);
};
return {
library: publisher(pool, onError, () => closed, trackPending(pending)),
desk,
close: async () => {
if (closed) return;
closed = true;
@@ -159,8 +184,17 @@ export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unkn
const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 });
let closed = false;
const pending = new Set<Promise<unknown>>();
const desk = (userId: string, command: DeskCommand) => {
if (closed) return;
const q = pool.query("SELECT pg_notify($1, $2)", [DESK_CHANNEL, JSON.stringify({ userId, command })]).catch((err) => {
if (closed && isPoolEndedError(err)) return;
onError(err);
});
trackPending(pending)(q);
};
return {
library: publisher(pool, onError, () => closed, trackPending(pending)),
desk,
close: async () => {
if (closed) return;
closed = true;
+5 -2
View File
@@ -5,7 +5,7 @@ import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { AutopilotService } from "../src/autopilot/service.js";
import { bestOf, groupBursts, reportagePickCount } from "../src/autopilot/bursts.js";
import { type Candidate, actionScore, curate } from "../src/autopilot/curate.js";
import { type Candidate, actionScore, curate, galleryCeiling } from "../src/autopilot/curate.js";
import { correctionOf, fold, learntStyle, recordCorrection, styleOf } from "../src/autopilot/learning.js";
import type { Detections } from "../src/composition/compose.js";
import type { SubjectDetector } from "../src/composition/detect.js";
@@ -103,7 +103,10 @@ describe("only the best", () => {
const opts = { count: 30, start, durationMs: 105 * min, now: start + 200 * min };
const all = curate(frames, [], opts).flatMap((d) => d.chosen);
expect(all.length).toBeGreaterThanOrEqual(28);
expect(all.length).toBeLessThanOrEqual(33);
expect(all.length).toBeLessThanOrEqual(galleryCeiling(30));
expect(galleryCeiling(30)).toBe(35);
expect(galleryCeiling(100)).toBe(115);
expect(galleryCeiling(300)).toBe(325);
expect(all).toContain(great.id);
expect(all).not.toContain(twin.id);
expect(all).not.toContain(rejected.id);
+2 -2
View File
@@ -585,7 +585,7 @@ describe("delivery", () => {
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "PS_{home} x {away}_{n}.jpg", longEdge: 3000, jpegQuality: 92 },
payload: { name: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "PS_{home} x {away}_{n}.jpg", longEdge: 3000, jpegQuality: 92, iptcOverrides: { creator: "Peter Spark / Kapta+", credit: "Peter Spark / Kapta+", copyright: "Peter Spark / Kapta+", source: "Peter Spark / Kapta+" } },
});
expect(created.statusCode).toBe(201);
const targetId = (created.json() as { id: string }).id;
@@ -619,7 +619,7 @@ describe("delivery", () => {
expect(items.map((i) => i.remotePath).sort()).toEqual(["12627747/img-1", "12627747/img-2"]);
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: event.id } })).zerozeroGameId).toBe("12627747");
const first = [...zz.uploads.values()].find((u) => u.meta.filename?.endsWith("_1.jpg"))!;
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.data.length).toBe(first.length);
expect((await sharp(first.data).metadata()).width).toBe(3000);
// Signed in once for the whole batch.
+27 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { AutopilotSettings } from "@photoreport/contracts";
import { exportTargets, picksNeeded } from "../src/autopilot/targets.js";
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
const a = "11111111-1111-4111-8111-111111111111";
const b = "22222222-2222-4222-8222-222222222222";
@@ -27,3 +27,29 @@ describe("picksNeeded", () => {
expect(picksNeeded(AutopilotSettings.parse({ enabled: true, picksPerBurst: 2 }))).toBe(2);
});
});
describe("galleryReceivers", () => {
const zz = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const liga = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
const galleries = [
{ targetId: zz, count: 30 },
{ targetId: liga, count: 100 },
];
it("sends a short-gallery frame to the short client and to the larger one", () => {
const chosen = new Map<string, Set<string>>([
[zz, new Set(["p1"])],
[liga, new Set(["p1", "p2"])],
]);
expect(galleryReceivers("p1", galleries, chosen).sort()).toEqual([liga, zz].sort());
expect(galleryReceivers("p2", galleries, chosen)).toEqual([liga]);
});
it("puts a frame only the short gallery picked into the larger gallery too", () => {
const chosen = new Map<string, Set<string>>([
[zz, new Set(["p1"])],
[liga, new Set()],
]);
expect(galleryReceivers("p1", galleries, chosen).sort()).toEqual([liga, zz].sort());
});
});
+25
View File
@@ -0,0 +1,25 @@
import { deskPath, type DeskCommand } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { deskState } from "./desk.js";
const show = (patch: Partial<DeskCommand>): DeskCommand => ({ module: "library", ...patch });
describe("deskPath", () => {
it("opens the library at the front page", () => {
expect(deskPath(show({ module: "library" }))).toBe("/");
});
it("opens one photo in develop", () => {
expect(deskPath(show({ module: "develop", photoId: "11111111-1111-4111-8111-111111111111" }))).toBe("/develop/11111111-1111-4111-8111-111111111111");
});
it("opens a shop tab", () => {
expect(deskPath(show({ module: "shop", section: "orders" }))).toBe("/shop?tab=orders");
});
});
describe("deskState", () => {
it("asks develop to start on the crop", () => {
expect(deskState(show({ module: "develop", tool: "crop" }))).toEqual({ crop: true });
});
});
+12
View File
@@ -0,0 +1,12 @@
import { deskPath, type DeskCommand } from "@photoreport/contracts";
export { deskPath };
export type { DeskCommand };
/** Where a develop tool is asked for. Crop and white balance already open from this state. */
export function deskState(command: DeskCommand): { crop?: boolean; picking?: boolean; spotting?: boolean } | null {
if (command.tool === "crop") return { crop: true };
if (command.tool === "wb") return { picking: true };
if (command.tool === "spot") return { spotting: true };
return null;
}
+1 -1
View File
@@ -15,7 +15,7 @@ export interface ScanStatus {
failed: number;
}
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
/**
* Local catalogue (desktop): folders on this computer whose photos the editor opens straight from disk, at full
+1 -1
View File
@@ -562,7 +562,7 @@ export const t = {
selectionBursts: "As escolhidas de cada sequência",
selectionBest: "Só as melhores do jogo",
bestCount: "Fotos na galeria (aprox.)",
bestHelp: "Uma galeria curta de momentos de jogo: bola em jogo, duelos e festejos, jogadores grandes e nítidos no enquadramento, espalhados pelo jogo (a cada 5 minutos entram as melhores desse período). Numa sequência fica a de frente e com os olhos abertos, quando dá para distinguir. Aquecimento e intervalo ficam de fora; as fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
bestHelp: "Uma galeria curta de momentos de jogo: bola em jogo, duelos e festejos, jogadores grandes e nítidos no enquadramento, espalhados pelo jogo (a cada 5 minutos entram as melhores desse período). O número é a meta: num jogo rico pode ir um pouco acima (cerca de 15%, nunca mais de 25 fotos), num jogo fraco fica aquém. Numa sequência fica a de frente e com os olhos abertos, quando dá para distinguir. Aquecimento e intervalo ficam de fora; as fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
restTarget: "As outras escolhidas para",
restHelp:
"Cada foto vai só para um cliente. A galeria acima leva a segunda melhor de cada sequência escolhida; todas as outras escolhidas seguem para aqui quando fecha cada período de 5 minutos.",
+1 -1
View File
@@ -111,7 +111,7 @@ function CardDialog({ onClose }: { onClose: () => void }) {
<h2 className="font-semibold uppercase tracking-wide text-ink">{t.card.title}</h2>
<div className="flex items-center gap-2">
<SnapshotMenu kind="card" current={s} onApply={setS} />
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
<button onClick={onClose} className="pr-quiet">
{t.card.close}
</button>
</div>
+5 -5
View File
@@ -438,11 +438,11 @@ export function CardScan({
{t.cardScan.reopen}
</button>
{running ? (
<button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={cancelScan} className="pr-quiet">
{t.cardScan.cancel}
</button>
) : (
<button type="button" onClick={onDismiss} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={onDismiss} className="pr-quiet">
{t.cardScan.close}
</button>
)}
@@ -477,7 +477,7 @@ export function CardScan({
aria-label={t.cardScan.search}
className="h-7 min-w-[220px] flex-1 border border-black bg-cell px-2 text-[13px] text-ink"
/>
<button type="button" onClick={() => void pick()} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={() => void pick()} className="pr-quiet">
{t.cardScan.pick}
</button>
<input
@@ -496,11 +496,11 @@ export function CardScan({
}}
/>
{running && (
<button type="button" onClick={cancelScan} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={cancelScan} className="pr-quiet">
{t.cardScan.cancel}
</button>
)}
<button type="button" onClick={hide} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={hide} className="pr-quiet">
{t.cardScan.close}
</button>
</div>
+2 -2
View File
@@ -294,7 +294,7 @@ export function EventSettingsButton(props: {
setOpen(false);
})
}
className="h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
title={event.archivedAt ? L.unarchiveHelp : L.archiveHelp}
>
{event.archivedAt ? L.unarchive : L.archive}
@@ -332,7 +332,7 @@ export function EventSettingsButton(props: {
type="button"
disabled={busy}
onClick={() => setConfirm(true)}
className="h-7 border border-black bg-cell px-3 text-[12px] text-[#e8857a] hover:bg-cell-on disabled:opacity-40"
className="pr-quiet text-danger disabled:opacity-40"
>
{L.delete}
</button>
+2 -2
View File
@@ -261,7 +261,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
</Link>
{selected.length === 2 && (
<button
className="h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on"
className="pr-quiet"
onClick={() => {
const [a, b] = selected as [string, string];
const sizeOf = (id: string) => groups?.find((g) => g.id === id)?.size ?? 0;
@@ -280,7 +280,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
)}
{canAnalyse && (
<button
className="ml-auto h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on"
className="pr-quiet ml-auto"
onClick={() =>
void api.analyseEventFaces(eventId).then(
(r) => {
+1 -1
View File
@@ -80,7 +80,7 @@ export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryF
<select
value={f.delivery}
onChange={(e) => set({ delivery: e.target.value as LibraryFilter["delivery"] })}
className={`h-6 border border-black bg-cell px-1 text-[12px] ${f.delivery === "any" ? "text-muted" : "text-ink"}`}
className={`pr-field ${f.delivery === "any" ? "" : "text-ink"}`}
>
{DELIVERY.map((d) => (
<option key={d} value={d}>
+3 -3
View File
@@ -202,7 +202,7 @@ export function FolderDevelop(props: {
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-wrap items-center gap-2 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<button type="button" onClick={onClose} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={onClose} className="pr-quiet">
{t.folderDevelop.back}
</button>
<span className="min-w-0 flex-1 truncate text-ink" title={file.path}>
@@ -213,7 +213,7 @@ export function FolderDevelop(props: {
title={t.folderDevelop.presetHelp}
disabled={!opened || !engine || saving}
onClick={() => void applyInterior(path, false)}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
>
{t.folderDevelop.preset}
</button>
@@ -221,7 +221,7 @@ export function FolderDevelop(props: {
type="button"
disabled={!opened || !settings || saving}
onClick={() => void save()}
className="h-6 border border-black bg-accent px-2.5 text-[12px] text-white disabled:opacity-40"
className="pr-go disabled:opacity-40"
>
{t.folderDevelop.save}
</button>
+3 -3
View File
@@ -277,7 +277,7 @@ export function FolderSheet(props: {
type="button"
title={t.folderSheet.developTitle}
onClick={() => onDevelop(focus)}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
className="pr-quiet"
>
{t.folderSheet.develop}
</button>
@@ -289,7 +289,7 @@ export function FolderSheet(props: {
title={t.folderSheet.mergeTitle}
disabled={merging}
onClick={runMerge}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
>
{t.merge.button}
</button>
@@ -312,7 +312,7 @@ export function FolderSheet(props: {
)}
</span>
)}
<button type="button" onClick={onClose} className="ml-auto h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={onClose} className="pr-quiet ml-auto">
{t.folderSheet.close}
</button>
</div>
+51
View File
@@ -0,0 +1,51 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { Grid } from "./Grid.js";
function photo(id: string): PhotoSummary {
return {
id,
eventId: "e1",
originalName: `${id}.jpg`,
name: `${id}.jpg`,
sha256: `sha-${id}`,
originalStored: true,
status: "READY",
width: 600,
height: 400,
capturedAt: "2026-09-23T20:00:00Z",
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
};
}
describe("grid", () => {
it("opens the photo on a double-click", () => {
const onOpen = vi.fn();
render(
<Grid
photos={[photo("a")]}
selected={new Set()}
focus={null}
srcFor={() => ""}
onPick={() => {}}
onSelectMany={() => {}}
onOpen={onOpen}
/>,
);
fireEvent.doubleClick(screen.getByRole("button", { name: /a\.jpg/ }));
expect(onOpen).toHaveBeenCalledWith("a");
});
});
+9 -4
View File
@@ -171,6 +171,8 @@ export function Grid(props: {
const dy = e.clientY - current.y;
if (!current.moved && Math.hypot(dx, dy) < DRAG_PX) return;
current.moved = true;
// Capture only once the drag is real. Capturing on the first press steals the second click, so a double-click never opens the photo.
if (!section.hasPointerCapture(e.pointerId)) section.setPointerCapture(e.pointerId);
const left = Math.min(current.x, e.clientX);
const top = Math.min(current.y, e.clientY);
const width = Math.abs(e.clientX - current.x);
@@ -197,7 +199,6 @@ export function Grid(props: {
base: [...props.selected],
moved: false,
};
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={moveBand}
onPointerUp={(e) => {
@@ -256,6 +257,7 @@ export function Loupe({
total,
faces = [],
onMenu,
onClose,
}: {
photo: PhotoSummary;
src: string;
@@ -264,6 +266,8 @@ export function Loupe({
total: number;
faces?: LoupeFace[];
onMenu?: (id: string, e: React.MouseEvent) => void;
/** Double-click returns to the grid. */
onClose?: () => void;
}) {
// Desktop app: previews seen once show again without a network; never seen, the thumbnail stands in.
const preview = useCachedImage(src, isDesktop());
@@ -288,7 +292,8 @@ export function Loupe({
return (
<section
aria-label="Lupa"
className="relative flex h-full min-h-[420px] items-center justify-center bg-[#121213] p-6"
className="relative flex h-full min-h-0 flex-1 items-center justify-center bg-[#121213]"
onDoubleClick={() => onClose?.()}
onContextMenu={(e) => {
if (!onMenu) {
e.preventDefault();
@@ -298,13 +303,13 @@ export function Loupe({
onMenu(photo.id, e);
}}
>
<span className="relative inline-block max-h-full max-w-full">
<span className="relative flex h-full max-h-full w-full items-center justify-center">
<img
src={shown}
onError={() => setFailed(true)}
alt={photo.name}
draggable={false}
className="pointer-events-none block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]"
className="pointer-events-none block max-h-full max-w-full object-contain"
/>
{softCrop && <SoftCropGuide crop={softCrop} />}
{faces.map((f) => (
+1 -1
View File
@@ -583,7 +583,7 @@ export function LocalFtpButton({ ftp, events, openEventId }: { ftp: LocalFtpStat
<div className="flex items-center gap-2">
{running ? (
<button onClick={() => void ftp.stop()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
<button onClick={() => void ftp.stop()} className="pr-quiet">
{L.stop}
</button>
) : (
+1 -1
View File
@@ -313,7 +313,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
)}
{note && <span className="text-[11px] text-ok">{note}</span>}
{already.length > 0 && (
<button onClick={() => void send(already, true)} disabled={busy} title={t.sendAgainHelp} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
<button onClick={() => void send(already, true)} disabled={busy} title={t.sendAgainHelp} className="pr-quiet disabled:opacity-40">
{t.sendAgain(already.length)}
</button>
)}
+2 -2
View File
@@ -24,7 +24,7 @@ export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; curr
refresh();
setOpen((value) => !value);
}}
className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
className="pr-quiet"
>
{t.snapshots.button}
</button>
@@ -50,7 +50,7 @@ export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; curr
setItems(saveSnapshot(kind, name, current));
setName("");
}}
className="h-7 shrink-0 border border-black bg-cell px-2 text-ink hover:bg-cell-on"
className="pr-quiet shrink-0"
>
{t.snapshots.save}
</button>
+2 -2
View File
@@ -99,7 +99,7 @@ export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, sele
setShowFaces(next);
prefs.set(FACES_PREF, next ? "1" : "0");
}}
className={`h-6 border border-black px-2 ${showFaces ? "bg-accent text-white" : "bg-cell text-ink hover:bg-cell-on"}`}
className={`pr-quiet ${showFaces ? "is-on" : ""}`}
>
{t.sports.showFaces}
</button>
@@ -148,7 +148,7 @@ export function SquadsButton({ api, event, canEdit, onSaved, facesTick = 0, sele
<div className="flex items-center gap-2 border-t border-line px-3 py-2">
{status && <span className="mr-auto text-muted">{status}</span>}
{linked && canEdit && (
<button disabled={busy} onClick={() => void sync()} className="ml-auto h-7 border border-black bg-cell px-3 hover:bg-cell-on disabled:opacity-50">
<button disabled={busy} onClick={() => void sync()} className="pr-quiet ml-auto disabled:opacity-50">
{t.sports.squadsSync}
</button>
)}
+2 -2
View File
@@ -458,11 +458,11 @@ export function UsbCameraButton({
<p className="mb-3 text-[11px] text-faint">{L.rawKept}</p>
{status && (
<div className="flex gap-2">
<button onClick={() => void usb.setTether(!status.tether)} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
<button onClick={() => void usb.setTether(!status.tether)} className="pr-quiet">
{status.tether ? L.turnOff : L.turnOn}
</button>
{on && (
<button onClick={() => void usb.syncClock()} className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on">
<button onClick={() => void usb.syncClock()} className="pr-quiet">
{L.clockSync}
</button>
)}
+4 -1
View File
@@ -1,4 +1,4 @@
import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts";
import { LIBRARY_CHANNEL, type DeskCommand, type LibraryMessage } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { io } from "socket.io-client";
@@ -40,6 +40,9 @@ export function useLibraryLive(api: ApiClient, onMessage: (message: LibraryMessa
socket.on("disconnect", () => setState("offline"));
socket.on("connect_error", () => setState("offline"));
socket.on(LIBRARY_CHANNEL, (message: LibraryMessage) => handler.current(message));
socket.on("desk", (command: DeskCommand) => {
window.dispatchEvent(new CustomEvent("photoreport-desk", { detail: command }));
});
return () => {
socket.close();
};
+8 -8
View File
@@ -200,7 +200,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
<button
type="button"
onClick={() => void navigator.clipboard?.writeText(viewerUrl).then(() => (setCopied(true), setTimeout(() => setCopied(false), 1500)))}
className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on"
className="pr-quiet"
>
{copied ? A.copied : A.copy}
</button>
@@ -252,7 +252,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
className="h-6 min-w-[220px] border border-black bg-cell px-2 text-[11px] text-ink"
/>
{name.trim() && name.trim() !== source.name && (
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
<button type="submit" disabled={busy} className="pr-quiet disabled:opacity-40">
{A.hostnameSave}
</button>
)}
@@ -276,7 +276,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
className="h-6 min-w-[220px] border border-black bg-cell px-2 font-mono text-[11px] text-ink"
/>
{hostname.trim() !== (source.hostname ?? "") && (
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
<button type="submit" disabled={busy} className="pr-quiet disabled:opacity-40">
{A.hostnameSave}
</button>
)}
@@ -288,12 +288,12 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
<div className="flex flex-wrap gap-2 border-t border-line pt-3">
{source.status !== "LOGIN" && (
<button type="button" disabled={busy} onClick={() => run(() => api.scanCloudSource(source.id))} className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40">
<button type="button" disabled={busy} onClick={() => run(() => api.scanCloudSource(source.id))} className="pr-quiet disabled:opacity-40">
{A.scanNow}
</button>
)}
{isAdmin && source.account && (
<button type="button" disabled={busy} onClick={() => run(() => api.updateCloudSource(source.id, { paused: source.status !== "PAUSED" }))} className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40">
<button type="button" disabled={busy} onClick={() => run(() => api.updateCloudSource(source.id, { paused: source.status !== "PAUSED" }))} className="pr-quiet disabled:opacity-40">
{source.status === "PAUSED" ? A.resume : A.pause}
</button>
)}
@@ -308,7 +308,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
return s;
})
}
className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
>
{A.reauthorise}
</button>
@@ -441,10 +441,10 @@ function Galleries({ api, source }: { api: ApiClient; source: CloudSource }) {
{A.galleries} · {source.name}
</span>
<span className="flex gap-2 normal-case tracking-normal">
<button type="button" disabled={check?.busy} onClick={() => runCheck(false)} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40" title="Volta a ligar já cada galeria de jogo oficial ao seu jogo, com as regras de hoje">
<button type="button" disabled={check?.busy} onClick={() => runCheck(false)} className="pr-quiet disabled:opacity-40" title="Volta a ligar já cada galeria de jogo oficial ao seu jogo, com as regras de hoje">
{check?.busy ? "A rever…" : "Rever jogos"}
</button>
<button type="button" disabled={check?.busy} onClick={() => runCheck(true)} className="h-6 border border-black bg-cell px-2 text-[12px] text-muted hover:bg-cell-on disabled:opacity-40" title="Revê todas as galerias (pode demorar)">
<button type="button" disabled={check?.busy} onClick={() => runCheck(true)} className="pr-quiet disabled:opacity-40" title="Revê todas as galerias (pode demorar)">
Rever tudo
</button>
</span>
+1 -1
View File
@@ -6,7 +6,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
const td = "border-b border-line px-3 py-1.5";
const ERRORS: Record<string, string> = {
digital_product_not_found: "Escolhe um produto digital.",
+5 -5
View File
@@ -136,7 +136,7 @@ export function DeliveryPage() {
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
{i.status === "FAILED" && (
<button className="h-6 border border-black bg-cell px-2 text-[11px] hover:bg-cell-on" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
{t.retry}
</button>
)}
@@ -184,7 +184,7 @@ export function DeliveryPage() {
</dl>
<div className="flex gap-2 px-3 pb-3">
<button
className="h-7 flex-1 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
className="pr-quiet"
onClick={() => {
setNote("A ligar…");
api.testDeliveryTarget(orgId, target.id).then(
@@ -200,10 +200,10 @@ export function DeliveryPage() {
</button>
{isAdmin && (
<>
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" onClick={() => setEditing(target)}>
<button className="pr-quiet" onClick={() => setEditing(target)}>
Editar
</button>
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" title="Mesmo servidor e credenciais, outro nome e pasta" onClick={() => setCopyName(`${target.name} (cópia)`)}>
<button className="pr-quiet" title="Mesmo servidor e credenciais, outro nome e pasta" onClick={() => setCopyName(`${target.name} (cópia)`)}>
Duplicar
</button>
</>
@@ -226,7 +226,7 @@ export function DeliveryPage() {
}}
>
<input autoFocus aria-label="Nome da cópia" className="h-7 flex-1 border border-black bg-[#161617] px-2 text-[12px]" value={copyName} onChange={(e) => setCopyName(e.target.value)} />
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on">OK</button>
<button className="pr-go">OK</button>
</form>
)}
{target.shareLinks === false ? (
+21 -20
View File
@@ -684,16 +684,18 @@ export function DevelopPage() {
// R in the library: the photo opens here with the crop tool on, once it is loaded (opening a photo turns it off).
const location = useLocation();
// W: with the white balance eyedropper.
const asked = location.state as { crop?: boolean; picking?: boolean } | null;
const asked = location.state as { crop?: boolean; picking?: boolean; spotting?: boolean } | null;
const cropAsked = asked?.crop === true;
const pickAsked = asked?.picking === true;
const spotAsked = asked?.spotting === true;
const loadedId = session?.loaded ? session.photoId : null;
useEffect(() => {
if ((!cropAsked && !pickAsked) || !loadedId || loadedId !== current?.id) return;
if ((!cropAsked && !pickAsked && !spotAsked) || !loadedId || loadedId !== current?.id) return;
if (canEdit && cropAsked) setCropping(true);
if (canEdit && pickAsked) setPicking(true);
if (canEdit && spotAsked) setSpotting(true);
navigate(".", { replace: true, state: null });
}, [cropAsked, pickAsked, loadedId, current?.id, canEdit, navigate]);
}, [cropAsked, pickAsked, spotAsked, loadedId, current?.id, canEdit, navigate]);
// Entering crop on a photo that was never cropped: it starts with the default aspect (the last one chosen).
const defaulted = useRef(new Set<string>());
@@ -728,16 +730,16 @@ export function DevelopPage() {
{canCull && orgId && scope && !scope.startsWith("search:") && !scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={scope === "inbox" ? null : scope} photos={photos} selectedIds={[...selected]} />
)}
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
<button className="pr-quiet disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
{t.dev.undo}
</button>
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canRedo} onClick={() => session?.redo()}>
<button className="pr-quiet disabled:opacity-40" disabled={!session?.canRedo} onClick={() => session?.redo()}>
{t.dev.redo}
</button>
<button className={`h-6 border border-black px-2.5 ${oneToOne ? "bg-accent text-white" : "bg-cell"}`} aria-pressed={oneToOne} title={t.dev.oneToOneHelp} onClick={() => setOneToOne(!oneToOne)}>
<button className={`pr-quiet ${oneToOne ? "is-on" : ""}`} aria-pressed={oneToOne} title={t.dev.oneToOneHelp} onClick={() => setOneToOne(!oneToOne)}>
1:1
</button>
<button className={`h-6 border border-black px-2.5 ${before ? "bg-accent text-white" : "bg-cell"}`} aria-pressed={before} onClick={() => setBefore(!before)}>
<button className={`pr-quiet ${before ? "is-on" : ""}`} aria-pressed={before} onClick={() => setBefore(!before)}>
{before ? t.dev.before : t.dev.after}
</button>
<span className={`min-w-20 text-right font-mono text-[11px] ${session?.offline ? "text-[#f0a35a]" : "text-faint"}`} role="status">
@@ -844,14 +846,13 @@ export function DevelopPage() {
</div>
{spotting && (
<Section title={t.dev.spot}>
<div className="mb-2 flex flex-wrap gap-1">
<div className="pr-chips mb-2">
{SPOT_MODES.map((m) => (
<button
key={m.id}
disabled={!canEdit}
onClick={() => setSpotMode(m.id)}
aria-pressed={spotMode === m.id}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${spotMode === m.id ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
>
{t.dev[m.labelKey]}
</button>
@@ -925,13 +926,13 @@ export function DevelopPage() {
disabled={!canEdit || !session?.loaded || !sourceSize}
onClick={() => void autoCrop()}
title={t.dev.autoCropHelp}
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
>
{t.dev.auto}
</button>
<span className="text-[11px] text-faint">{t.dev.aspect}</span>
</div>
<div className="mb-2 flex flex-wrap gap-1">
<div className="pr-chips mb-2">
{ASPECTS.map((a) => {
// "Original" stays lit after X turns it (W:H or H:W of the photo).
const on =
@@ -945,7 +946,7 @@ export function DevelopPage() {
key={a.label}
disabled={!canEdit || !sourceSize}
onClick={() => setAspect(a.value)}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${on ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
aria-pressed={on}
>
{a.label}
</button>
@@ -958,19 +959,19 @@ export function DevelopPage() {
onClick={toggleLock}
aria-pressed={!!crop.aspect}
title={t.dev.cropLockHelp}
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${crop.aspect ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
className={`pr-quiet disabled:opacity-40 ${crop.aspect ? "is-on" : ""}`}
>
{t.dev.cropLock}
</button>
<button disabled={!canEdit || !sourceSize} onClick={swapCrop} title={t.dev.cropSwapHelp} className="h-6 border border-black bg-cell px-2 text-[11px] text-muted disabled:opacity-40">
<button disabled={!canEdit || !sourceSize} onClick={swapCrop} title={t.dev.cropSwapHelp} className="pr-quiet disabled:opacity-40">
{t.dev.cropSwap}
</button>
<button disabled={!canEdit || !sourceSize} onClick={resetCrop} title={t.dev.cropResetHelp} className="h-6 border border-black bg-cell px-2 text-[11px] text-muted disabled:opacity-40">
<button disabled={!canEdit || !sourceSize} onClick={resetCrop} title={t.dev.cropResetHelp} className="pr-quiet disabled:opacity-40">
{t.dev.cropReset}
</button>
<label className="ml-auto flex items-center gap-1 text-[11px] text-faint" title={t.dev.guidesHelp}>
{t.dev.guides}
<select value={guide} onChange={(e) => chooseGuide(e.target.value as Guide)} className="h-6 border border-black bg-cell px-1 text-[11px] text-ink">
<select value={guide} onChange={(e) => chooseGuide(e.target.value as Guide)} className="pr-field">
{GUIDES.map((g) => (
<option key={g} value={g}>
{t.dev.guideNames[g]}
@@ -995,7 +996,7 @@ export function DevelopPage() {
disabled={!canEdit || !session?.loaded}
onClick={() => void autoLevel()}
title={t.dev.levelHelp}
className="mb-1 h-6 shrink-0 border border-black bg-cell px-2 text-[11px] disabled:opacity-40"
className="pr-quiet mb-1 shrink-0 disabled:opacity-40"
>
{t.dev.level}
</button>
@@ -1018,7 +1019,7 @@ export function DevelopPage() {
/>
<div className="flex flex-wrap gap-2 p-3">
<button
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
disabled={!session?.loaded}
onClick={() => {
if (!session) return;
@@ -1044,7 +1045,7 @@ export function DevelopPage() {
/>
)}
<button
className="h-7 border border-black bg-cell px-3 text-[12px] disabled:opacity-40"
className="pr-quiet disabled:opacity-40"
disabled={!canEdit || !clip}
onClick={() => {
if (!session || !clip) return;
@@ -1055,7 +1056,7 @@ export function DevelopPage() {
{t.dev.paste}
</button>
<button
className="ml-auto h-7 border border-black bg-cell px-3 text-[12px] text-muted disabled:opacity-40"
className="pr-quiet ml-auto disabled:opacity-40"
disabled={!canEdit || !session?.loaded}
onClick={() => {
session?.edit({ command: "develop.reset" });
+1 -1
View File
@@ -8,7 +8,7 @@ import { openExternal } from "../platform.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const day = (iso: string) => new Date(iso).toLocaleDateString("pt-PT");
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
const th = "border-b border-line px-3 py-2 font-semibold";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
+1 -1
View File
@@ -5,7 +5,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? t.invoicing.errors[err.code] ?? err.code) : t.unexpectedError);
+12 -2
View File
@@ -191,6 +191,15 @@ export function LibraryPage() {
[api, orgId, state.scope],
);
useEffect(() => {
const onOpen = (ev: Event) => {
const id = (ev as CustomEvent<string>).detail;
if (typeof id === "string" && id) void open(id).catch(() => setError(t.unexpectedError));
};
window.addEventListener("photoreport-open-event", onOpen);
return () => window.removeEventListener("photoreport-open-event", onOpen);
}, [open]);
useEffect(() => {
if (!orgId) return;
let alive = true;
@@ -768,7 +777,7 @@ export function LibraryPage() {
)}
<div
className={`min-h-0 flex-1 ${sheet ? "flex flex-col overflow-hidden" : "overflow-y-auto"} ${dragging ? "outline outline-2 -outline-offset-4 outline-accent" : ""}`}
className={`min-h-0 flex-1 ${sheet || loupe ? "flex flex-col overflow-hidden" : "overflow-y-auto"} ${dragging ? "outline outline-2 -outline-offset-4 outline-accent" : ""}`}
onDragOver={(e) => {
if (!e.dataTransfer.types.includes("Files")) return;
e.preventDefault();
@@ -796,7 +805,7 @@ export function LibraryPage() {
<span>{t.dropPartial}</span>
<button
type="button"
className="h-7 border border-black bg-cell px-2.5 text-ink hover:bg-cell-on"
className="pr-quiet"
onClick={() => {
setDropPartial(false);
fileInput.current?.click();
@@ -875,6 +884,7 @@ export function LibraryPage() {
index={visibleIds.indexOf(focus.id)}
total={visibleIds.length}
faces={loupeFaces}
onClose={() => setLoupe(false)}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
/>
) : visible.length || suggested.length ? (
+1 -1
View File
@@ -70,7 +70,7 @@ export function MetadataPage() {
}`}
>
<span className="flex items-center justify-between gap-2">
<span className="font-display text-[15px] font-semibold uppercase tracking-wide">{it.title}</span>
<span className="text-[14px] font-semibold">{it.title}</span>
{it.badge && <span className={`font-mono text-[10.5px] max-md:hidden ${it.id === "faces" ? (it.on ? "text-ok" : "text-faint") : "text-faint"}`}>{it.badge}</span>}
</span>
<span className="mt-0.5 block text-[12px] leading-snug text-faint max-md:hidden">{it.hint}</span>
+1 -1
View File
@@ -6,7 +6,7 @@ import { t } from "../i18n.js";
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
const th = "border-b border-line px-3 py-2 font-semibold";
const td = "border-b border-line px-3 py-1.5";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.press.errors[err.code] ?? t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
+4 -4
View File
@@ -9,8 +9,8 @@ import { PageHeader } from "./Shell.js";
import { API_URL, eventsUrlFor } from "../api.js";
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const primary = "h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50";
const btn = "pr-quiet disabled:opacity-40";
const primary = "pr-go";
const STATUS_COLOR: Record<PrintJobSummary["status"], string> = {
PAYMENT: "text-faint",
@@ -239,12 +239,12 @@ export function KioskPanel({ event, onChange }: { event: PrintEventSummary; onCh
</div>
)}
<div className="flex gap-2">
<button className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on" onClick={make}>
<button className="pr-quiet" onClick={make}>
{event.kiosk ? "Novo link" : "Ligar quiosque"}
</button>
{event.kiosk && (
<button
className="h-7 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on"
className="pr-quiet"
onClick={() =>
void api.disablePrintKiosk(event.id).then(() => {
setLink(null);
+1 -1
View File
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
const btn = "h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const btn = "pr-quiet disabled:opacity-40";
const LABELS = ["PURPLE", "GREEN", "BLUE", "YELLOW", "RED"] as const;
const SWATCH: Record<(typeof LABELS)[number], string> = { RED: "#d64545", YELLOW: "#d8b33a", GREEN: "#4c9a52", BLUE: "#4a78c9", PURPLE: "#8d5bc4" };
+21 -2
View File
@@ -1,5 +1,7 @@
import { hasRole } from "@photoreport/sdk";
import { NavLink, Outlet } from "react-router";
import { useEffect } from "react";
import { NavLink, Outlet, useNavigate } from "react-router";
import { deskPath, deskState, type DeskCommand } from "../desk.js";
import { useAuth } from "../auth.js";
import { Bell } from "../components/Bell.js";
import { Logo } from "../components/ui.js";
@@ -140,6 +142,7 @@ export function Shell() {
</div>
</details>
</header>
<DeskHost />
<UpdateNotice />
<UiReadyNotice />
<LocalDeliveries />
@@ -156,6 +159,22 @@ export function Shell() {
);
}
/** Follows the assistant: the open window changes module, photo or tool. */
function DeskHost() {
const navigate = useNavigate();
useEffect(() => {
const onDesk = (ev: Event) => {
const command = (ev as CustomEvent<DeskCommand>).detail;
if (!command || typeof command.module !== "string") return;
navigate(deskPath(command), { state: deskState(command) });
if (command.eventId) window.dispatchEvent(new CustomEvent("photoreport-open-event", { detail: command.eventId }));
};
window.addEventListener("photoreport-desk", onDesk);
return () => window.removeEventListener("photoreport-desk", onDesk);
}, [navigate]);
return null;
}
function initials(name: string): string {
return name
.split(/\s+/)
@@ -168,7 +187,7 @@ function initials(name: string): string {
export function PageHeader({ title, children }: { title: string; children?: React.ReactNode }) {
return (
<header className="flex h-12 items-center justify-between border-b border-line bg-panel px-6">
<h1 className="font-display text-lg font-semibold uppercase tracking-wide">{title}</h1>
<h1 className="text-[15px] font-semibold">{title}</h1>
{children}
</header>
);
+3 -3
View File
@@ -16,8 +16,8 @@ const TABS: Tab[] = ["galleries", "orders", "products", "sites", "earnings", "af
const eur = (cents: number) => new Intl.NumberFormat("pt-PT", { style: "currency", currency: "EUR" }).format(cents / 100);
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink placeholder:text-faint focus:border-accent focus:outline-none";
const btn = "h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40";
const primary = "h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50";
const btn = "pr-quiet disabled:opacity-40";
const primary = "pr-go";
const errorText = (err: unknown) => (err instanceof ApiError ? (t.shop.errors[err.code] ?? err.code) : t.unexpectedError);
@@ -43,7 +43,7 @@ export function ShopPage() {
<PageHeader title={t.shop.title}>
<nav className="flex gap-1" aria-label={t.shop.title}>
{tabs.map((x) => (
<button key={x} onClick={() => setTab(x)} aria-pressed={tab === x} className={`h-7 px-3 text-[12px] ${tab === x ? "bg-cell-on text-ink" : "text-faint hover:text-muted"}`}>
<button key={x} onClick={() => setTab(x)} aria-pressed={tab === x} className={`pr-quiet ${tab === x ? "is-on" : ""}`}>
{t.shop.tabs[x]}
</button>
))}
+56
View File
@@ -111,6 +111,62 @@ body {
color: var(--color-accent);
}
/* A set of choices inside a panel: the active one is underlined, the rest stay text. */
.pr-chips {
display: flex;
flex-wrap: wrap;
gap: 2px;
}
.pr-chips button {
height: 28px;
padding: 0 8px;
border: none;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--color-faint);
font-size: 12px;
}
.pr-chips button:hover {
color: var(--color-ink);
}
.pr-chips button[aria-pressed="true"] {
color: var(--color-ink);
border-bottom-color: var(--color-accent);
}
.pr-chips button:disabled {
opacity: 0.4;
}
/* A choice sitting in a toolbar, not a form field. */
.pr-field {
height: 28px;
border: none;
background: transparent;
color: var(--color-muted);
font-size: 12px;
}
.pr-field:focus {
outline: none;
color: var(--color-ink);
}
/* The one action on a screen. */
.pr-go {
height: 32px;
padding: 0 14px;
border: none;
background: var(--color-accent);
color: #fff;
font-size: 13px;
font-weight: 600;
}
.pr-go:hover {
background: var(--color-accent-strong);
}
.pr-go:disabled {
opacity: 0.5;
}
/* Develop sliders: thin track drawn by the panel, small round thumb (Lightroom-like). */
.pr-range {
-webkit-appearance: none;
+21
View File
@@ -0,0 +1,21 @@
{
"name": "@photoreport/mcp",
"version": "0.1.0",
"private": true,
"type": "module",
"bin": {
"photoreport-mcp": "dist/index.js"
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"start": "node dist/index.js"
},
"dependencies": {
"@modelcontextprotocol/server": "^2.3.1",
"@photoreport/contracts": "workspace:*",
"@photoreport/sdk": "workspace:*",
"zod": "^4.2.0"
}
}
+16
View File
@@ -0,0 +1,16 @@
import { getControl } from "@photoreport/contracts";
/** Checks each develop value against the engine's control list before it is sent. */
export function developValues(input: Record<string, number>): Record<string, number> {
const out: Record<string, number> = {};
for (const [id, value] of Object.entries(input)) {
const control = getControl(id);
if (!control) throw new Error(`Unknown control "${id}". Call photoreport_develop_controls for the ids and ranges.`);
if (!Number.isFinite(value) || value < control.min || value > control.max) {
throw new Error(`${id} is ${value}. It must be between ${control.min} and ${control.max} (default ${control.default}).`);
}
out[id] = value;
}
if (Object.keys(out).length === 0) throw new Error("No controls to change.");
return out;
}
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env node
/**
* PhotoReport assistant. Speaks MCP over stdio and calls the PhotoReport API
* as the signed-in photographer. Stdout is the protocol; logs go to stderr.
*/
import { pathToFileURL } from "node:url";
import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { registerAccount } from "./tools/account.js";
import { registerDelivery } from "./tools/delivery.js";
import { registerDevelop } from "./tools/develop.js";
import { registerLibrary } from "./tools/library.js";
import { registerScreen } from "./tools/screen.js";
import { registerTeach } from "./tools/teach.js";
export function createServer(): McpServer {
const server = new McpServer({ name: "photoreport", version: "0.1.0" });
registerAccount(server);
registerScreen(server);
registerLibrary(server);
registerDevelop(server);
registerDelivery(server);
registerTeach(server);
return server;
}
const isMain = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
serveStdio(createServer);
console.error("photoreport-mcp on stdio");
}
+29
View File
@@ -0,0 +1,29 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { failText } from "./session.js";
type ToolContent = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string };
type ToolResult = { content: ToolContent[]; isError?: boolean };
/** Tool results the model reads. Lists are already capped by the caller. */
export function text(body: string): ToolResult {
return { content: [{ type: "text", text: body }] };
}
export function textAndImages(body: string, images: { data: string; mimeType: string }[]): ToolResult {
return {
content: [
{ type: "text", text: body },
...images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mimeType })),
],
};
}
export async function guard(work: () => Promise<ToolResult>): Promise<ToolResult> {
try {
return await work();
} catch (err) {
return { isError: true, content: [{ type: "text", text: failText(err) }] };
}
}
export type Server = McpServer;
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import type { PhotoSummary } from "@photoreport/contracts";
import { developValues } from "./edits.js";
import { reviewPhotos } from "./review.js";
function photo(patch: Partial<PhotoSummary>): PhotoSummary {
return {
id: "p",
eventId: "e",
originalName: "a.jpg",
name: "a.jpg",
sha256: "abc",
originalStored: true,
status: "READY",
width: 1000,
height: 800,
capturedAt: null,
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
...patch,
};
}
describe("reviewPhotos", () => {
it("counts the frames a photographer still has to look at", () => {
const report = reviewPhotos([
photo({ id: "1", name: "pick.jpg", flag: "PICK" }),
photo({ id: "2", name: "bad.jpg", status: "FAILED", error: "truncated" }),
photo({ id: "3", name: "sent.jpg", flag: "PICK", developSeq: 4, delivery: "DONE", players: ["Ana"] }),
]);
expect(report.picks).toBe(2);
expect(report.uneditedPicks).toBe(1);
expect(report.failed).toBe(1);
expect(report.unsentPicks).toBe(1);
expect(report.lookAt.map((note) => note.name)).toEqual(["pick.jpg", "bad.jpg"]);
});
});
describe("developValues", () => {
it("refuses a control the engine does not have", () => {
expect(() => developValues({ "light.nope": 1 })).toThrow(/Unknown control/);
});
it("refuses a value outside the range", () => {
expect(() => developValues({ "light.exposure": 99 })).toThrow(/between/);
});
it("keeps a value inside the range", () => {
expect(developValues({ "light.exposure": 0.2 })).toEqual({ "light.exposure": 0.2 });
});
});
+75
View File
@@ -0,0 +1,75 @@
import type { PhotoSummary } from "@photoreport/contracts";
export interface ReviewNote {
id: string;
name: string;
reasons: string[];
}
export interface ReviewReport {
total: number;
ready: number;
failed: number;
processing: number;
picks: number;
rejects: number;
unrated: number;
uneditedPicks: number;
withoutPlayers: number;
deliveryFailed: number;
unsentPicks: number;
lookAt: ReviewNote[];
}
/**
* What a photographer (or the assistant) should look at. Sharpness is not on the photo row: a face tool
* answers that. This uses the catalogue: flags, ratings, edits, players and delivery.
*/
export function reviewPhotos(photos: PhotoSummary[], limit = 20): ReviewReport {
const lookAt: ReviewNote[] = [];
let ready = 0;
let failed = 0;
let processing = 0;
let picks = 0;
let rejects = 0;
let unrated = 0;
let uneditedPicks = 0;
let withoutPlayers = 0;
let deliveryFailed = 0;
let unsentPicks = 0;
for (const photo of photos) {
if (photo.status === "READY") ready += 1;
else if (photo.status === "FAILED") failed += 1;
else processing += 1;
if (photo.flag === "PICK") picks += 1;
if (photo.flag === "REJECT") rejects += 1;
if (photo.rating === 0 && photo.flag === "NONE") unrated += 1;
if (photo.flag === "PICK" && photo.developSeq === 0) uneditedPicks += 1;
if (photo.players.length === 0 && photo.flag !== "REJECT") withoutPlayers += 1;
if (photo.delivery === "FAILED") deliveryFailed += 1;
if (photo.flag === "PICK" && photo.delivery !== "DONE" && photo.delivery !== "QUEUED") unsentPicks += 1;
const reasons: string[] = [];
if (photo.status === "FAILED") reasons.push(photo.error ? `failed to read (${photo.error})` : "failed to read");
if (photo.delivery === "FAILED") reasons.push("delivery failed");
if (photo.flag === "PICK" && photo.developSeq === 0) reasons.push("pick with no edit yet");
if (photo.flag === "NONE" && photo.rating === 0 && photo.status === "READY") reasons.push("not culled");
if (reasons.length && lookAt.length < limit) lookAt.push({ id: photo.id, name: photo.name, reasons });
}
return {
total: photos.length,
ready,
failed,
processing,
picks,
rejects,
unrated,
uneditedPicks,
withoutPlayers,
deliveryFailed,
unsentPicks,
lookAt,
};
}
+118
View File
@@ -0,0 +1,118 @@
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { ApiClient, ApiError, type RefreshTokenStore } from "@photoreport/sdk";
/** Where the assistant's refresh token lives. Never printed. */
export const sessionFile = process.env.PHOTOREPORT_SESSION_FILE ?? join(homedir(), ".config", "photoreport", "mcp-session.json");
interface Saved {
refreshToken?: string;
deviceCode?: string;
userCode?: string;
}
async function readSaved(): Promise<Saved> {
try {
const parsed = JSON.parse(await readFile(sessionFile, "utf8")) as unknown;
if (!parsed || typeof parsed !== "object") return {};
return parsed as Saved;
} catch {
return {};
}
}
async function writeSaved(next: Saved): Promise<void> {
await mkdir(dirname(sessionFile), { recursive: true });
await writeFile(sessionFile, JSON.stringify(next), { mode: 0o600 });
await chmod(sessionFile, 0o600);
}
const store: RefreshTokenStore = {
async get() {
const saved = await readSaved();
return saved.refreshToken ?? process.env.PHOTOREPORT_REFRESH_TOKEN ?? null;
},
async set(token: string) {
const saved = await readSaved();
saved.refreshToken = token;
delete saved.deviceCode;
delete saved.userCode;
await writeSaved(saved);
},
async clear() {
const saved = await readSaved();
delete saved.refreshToken;
await writeSaved(saved);
},
};
export const api = new ApiClient({
baseUrl: (process.env.PHOTOREPORT_API_URL ?? "https://api.next.photoreport.pt").replace(/\/$/, ""),
refreshStore: store,
});
const SIGN_IN = "Not signed in. Call photoreport_connect, approve the code in PhotoReport (the bell, or the link), then photoreport_connect_finish.";
/** Restores the saved session, or signs in with PHOTOREPORT_EMAIL and PHOTOREPORT_PASSWORD when both are set. */
export async function ensureSession(): Promise<void> {
if (api.isAuthenticated) return;
const email = process.env.PHOTOREPORT_EMAIL;
const password = process.env.PHOTOREPORT_PASSWORD;
if (email && password) {
await api.login(email, password, "PhotoReport assistant");
return;
}
if (!(await api.resume())) throw new Error(SIGN_IN);
}
let cachedOrg: string | null = process.env.PHOTOREPORT_ORG_ID ?? null;
/** The organization to work in: the argument, PHOTOREPORT_ORG_ID, or the account's first one. */
export async function orgId(given?: string): Promise<string> {
if (given) return given;
if (cachedOrg) return cachedOrg;
await ensureSession();
const me = await api.me();
const id = me.memberships[0]?.organization.id;
if (!id) throw new Error("This account belongs to no organization.");
cachedOrg = id;
return id;
}
export async function beginConnect(): Promise<{ userCode: string; url: string; expiresIn: number }> {
const grant = await api.startDeviceLogin("PhotoReport assistant");
const saved = await readSaved();
saved.deviceCode = grant.deviceCode;
saved.userCode = grant.userCode;
await writeSaved(saved);
return { userCode: grant.userCode, url: grant.verificationUriComplete, expiresIn: grant.expiresIn };
}
export async function finishConnect(): Promise<"approved" | "pending" | "expired" | "denied"> {
const saved = await readSaved();
if (!saved.deviceCode) throw new Error("No sign-in in progress. Call photoreport_connect first.");
const result = await api.pollDeviceLogin(saved.deviceCode);
if (result.status === "approved") return "approved";
if (result.status === "pending" || result.status === "slow_down") return "pending";
if (result.status === "denied") return "denied";
return "expired";
}
export async function disconnect(): Promise<void> {
await ensureSession();
await api.logout();
cachedOrg = process.env.PHOTOREPORT_ORG_ID ?? null;
}
/** What the model should read when a call fails. */
export function failText(err: unknown): string {
if (err instanceof ApiError) {
if (err.status === 401) return `${SIGN_IN} (${err.code})`;
if (err.status === 403) return `Not allowed (${err.code}). This account's role cannot do that.`;
if (err.status === 404) return `Not found (${err.code}). Check the id from a list tool.`;
return `The API refused the call (${err.status} ${err.code}).`;
}
if (err instanceof Error) return err.message;
return "The call failed.";
}
+96
View File
@@ -0,0 +1,96 @@
import * as z from "zod/v4";
import { api, beginConnect, disconnect, ensureSession, finishConnect, orgId } from "../session.js";
import { guard, text, type Server } from "../result.js";
export function registerAccount(server: Server): void {
server.registerTool(
"photoreport_connect",
{
title: "Sign in to PhotoReport",
description: "Starts a sign-in. Returns a short code and a link. The photographer approves it in the PhotoReport app, then call photoreport_connect_finish. The refresh token stays on this computer and is never returned.",
annotations: { readOnlyHint: false, openWorldHint: true, idempotentHint: true },
},
async () =>
guard(async () => {
const grant = await beginConnect();
return text(`Approve this code in PhotoReport: ${grant.userCode}\n${grant.url}\nIt expires in ${grant.expiresIn} seconds. Then call photoreport_connect_finish.`);
}),
);
server.registerTool(
"photoreport_connect_finish",
{
title: "Finish PhotoReport sign-in",
description: "Checks whether the photographer approved photoreport_connect. Call again in a few seconds while the status is pending.",
annotations: { readOnlyHint: false, openWorldHint: true },
},
async () =>
guard(async () => {
const status = await finishConnect();
if (status === "approved") return text("Signed in. Call photoreport_whoami to see the account and organization.");
if (status === "pending") return text("Still waiting. Ask the photographer to approve the code, then call this again.");
if (status === "denied") return text("The photographer refused. Call photoreport_connect to start again.");
return text("The code expired. Call photoreport_connect to start again.");
}),
);
server.registerTool(
"photoreport_disconnect",
{
title: "Sign out of PhotoReport",
description: "Forgets the assistant's PhotoReport session on this computer.",
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
},
async () =>
guard(async () => {
await disconnect();
return text("Signed out.");
}),
);
server.registerTool(
"photoreport_whoami",
{
title: "Who is signed in",
description: "The signed-in photographer and their organizations. Use the organization id in later calls when they belong to more than one. Example: who am I working as?",
annotations: { readOnlyHint: true, openWorldHint: true },
},
async () =>
guard(async () => {
await ensureSession();
const me = await api.me();
const lines = [`${me.user.name} <${me.user.email}>`];
for (const membership of me.memberships) {
lines.push(`- ${membership.organization.name} (${membership.organization.id}) role ${membership.role}`);
}
if (me.memberships.length === 0) lines.push("No organization.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_list_events",
{
title: "List events",
description: "Events in the organization, newest ingest window first as the API returns them. Use this to find the match the photographer is shooting before listing photos or sending. Pass archived to include closed events.",
inputSchema: z.object({
organizationId: z.string().optional().describe("Organization id. Defaults to PHOTOREPORT_ORG_ID or the account's first organization."),
archived: z.boolean().default(false).describe("Include archived events."),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId, archived }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { events } = await api.listEvents(id, archived ? { includeArchived: true } : {});
if (events.length === 0) return text("No events.");
const lines = events.slice(0, 40).map((event) => {
const match = event.away ? `${event.home} x ${event.away}` : event.home;
return `- ${match} (${event.id}) ${event.startsAt} · ${event.photoCount} photos${event.archivedAt ? " · archived" : ""}`;
});
if (events.length > 40) lines.push(`… ${events.length - 40} more. Narrow by asking for one event id.`);
return text(lines.join("\n"));
}),
);
}
+136
View File
@@ -0,0 +1,136 @@
import type { PhotoQuery } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { guard, text, type Server } from "../result.js";
export function registerDelivery(server: Server): void {
server.registerTool(
"photoreport_list_destinations",
{
title: "List send destinations",
description: "Where photos can be sent (FTP, SFTP, Nextcloud, a local folder, and the rest). Use the name or id with photoreport_send_photos. Example: where can I send this match?",
inputSchema: z.object({ organizationId: z.string().optional() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { targets } = await api.listDeliveryTargets(id);
if (targets.length === 0) return text("No destinations. Create one in Entregar.");
return text(targets.map((target) => `- ${target.name} (${target.id}) · ${target.kind}`).join("\n"));
}),
);
server.registerTool(
"photoreport_send_photos",
{
title: "Send photos",
description: "Sends photos to one destination. Pass photoIds, or an eventId plus picksOnly to send that event's picks (up to limit, ready photos, rejects are left out by the server). originals sends the camera file instead of the destination's resize. again sends photos that destination already has. Example: send the picks of this event to Cofina, at most 40.",
inputSchema: z.object({
organizationId: z.string().optional(),
destination: z.string().describe("Destination id or name."),
photoIds: z.array(z.string()).max(500).optional(),
eventId: z.string().optional().describe("Used when photoIds is omitted."),
picksOnly: z.boolean().default(true),
limit: z.number().int().min(1).max(300).default(40),
originals: z.boolean().default(false),
again: z.boolean().default(false),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const { targets } = await api.listDeliveryTargets(id);
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
let ids = input.photoIds ?? [];
if (ids.length === 0) {
if (!input.eventId) throw new Error("Pass photoIds or an eventId.");
const query: PhotoQuery = { event: input.eventId, limit: input.limit };
if (input.picksOnly) query.flag = "PICK";
const page = await api.listPhotos(id, query);
ids = page.photos.filter((photo) => photo.status === "READY" && photo.flag !== "REJECT").map((photo) => photo.id);
}
if (ids.length === 0) return text("Nothing to send. No ready photos matched.");
const result = await api.deliver(id, target.id, ids, input.again, input.originals);
const skipped = result.skipped.map((item) => `${item.photoId} ${item.reason}`).join(", ");
return text(`Queued ${result.queued.length} to ${target.name}.${result.skipped.length ? ` Skipped ${result.skipped.length}: ${skipped}.` : ""} Call photoreport_delivery_status to watch them.`);
}),
);
server.registerTool(
"photoreport_send_best",
{
title: "Send the best of a match",
description: "Sends the best N moments of an event, spread over the match, to one destination. dryRun only lists the choice and sends nothing. Example: send the best 30 of this match to Cofina.",
inputSchema: z.object({
organizationId: z.string().optional(),
destination: z.string(),
eventId: z.string(),
count: z.number().int().min(1).max(300).default(30),
dryRun: z.boolean().default(false),
again: z.boolean().default(false),
originals: z.boolean().default(false),
}),
annotations: { readOnlyHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const { targets } = await api.listDeliveryTargets(id);
const target = targets.find((item) => item.id === input.destination || item.name.toLowerCase() === input.destination.toLowerCase());
if (!target) throw new Error(`No destination named "${input.destination}". Call photoreport_list_destinations.`);
const result = await api.deliverBest(id, { targetId: target.id, eventId: input.eventId, count: input.count, dryRun: input.dryRun, again: input.again, originals: input.originals });
if (input.dryRun) return text(`Would send ${result.chosen.length} photos. Nothing was queued.`);
return text(`Queued ${result.queued.length} of ${result.chosen.length} chosen for ${target.name}. Skipped ${result.skipped.length}.`);
}),
);
server.registerTool(
"photoreport_delivery_status",
{
title: "Delivery status",
description: "Recent deliveries and how many are queued, running, done or failed. Pass a destination id to narrow it.",
inputSchema: z.object({
organizationId: z.string().optional(),
destinationId: z.string().optional(),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: { targetId?: string } = {};
if (input.destinationId) query.targetId = input.destinationId;
const page = await api.listDeliveries(id, query);
const counts = Object.entries(page.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
const lines = [counts || "No deliveries.", ...page.items.slice(0, 20).map((item) => `- ${item.status} ${item.remotePath ?? item.photoId} (${item.id})${item.lastError ? ` · ${item.lastError}` : ""}`)];
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_retry_delivery",
{
title: "Retry a delivery",
description: "Retries one failed delivery. The id comes from photoreport_delivery_status.",
inputSchema: z.object({
organizationId: z.string().optional(),
deliveryId: z.string(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ organizationId, deliveryId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const item = await api.retryDelivery(id, deliveryId);
return text(`Delivery ${item.id} is ${item.status}.`);
}),
);
}
+128
View File
@@ -0,0 +1,128 @@
import { CONTROLS, type Module } from "@photoreport/contracts";
import { randomUUID } from "node:crypto";
import * as z from "zod/v4";
import { api, ensureSession } from "../session.js";
import { developValues } from "../edits.js";
import { guard, text, type Server } from "../result.js";
const CLIENT = "photoreport-mcp";
export function registerDevelop(server: Server): void {
server.registerTool(
"photoreport_develop_controls",
{
title: "Develop controls",
description: "The edit controls the engine accepts, with min, max and default. Call this before photoreport_edit_photo when the control id is not already known. Common ones: light.exposure, light.contrast, light.highlights, light.shadows, light.whites, light.blacks, color.temperature, color.tint, detail.sharpenAmount.",
inputSchema: z.object({
module: z.string().optional().describe("One module: basic controls live under light and color ids. Pass crop, detail, optics, vignette, or leave empty for the basic light and colour ids."),
}),
annotations: { readOnlyHint: true, openWorldHint: false },
},
async ({ module }) =>
guard(async () => {
const wanted = module ? CONTROLS.filter((control) => control.module === (module as Module) || control.id.startsWith(`${module}.`)) : CONTROLS.filter((control) => control.id.startsWith("light.") || control.id.startsWith("color.") || control.id.startsWith("detail."));
const lines = wanted.slice(0, 80).map((control) => `- ${control.id} (${control.label}) ${control.min}…${control.max}, default ${control.default}`);
if (wanted.length > 80) lines.push(`… ${wanted.length - 80} more. Pass a module name.`);
if (lines.length === 0) return text("No controls for that module. Modules include crop, basic, detail, optics, vignette, colorGrading.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_develop_state",
{
title: "Develop state",
description: "The current edit of one photo: snapshot sequence and the commands applied after it. Use photoreport_edit_photo to change it.",
inputSchema: z.object({ photoId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ photoId }) =>
guard(async () => {
await ensureSession();
const state = await api.developState(photoId);
const lines = [`Sequence ${state.developSeq}, snapshot ${state.snapshotSeq}, ${state.ops.length} later edits.`];
for (const op of state.ops.slice(-12)) lines.push(`- ${op.seq} ${op.command.command}`);
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_edit_photo",
{
title: "Edit a photo",
description: "Applies develop commands to one photo. Values must be inside the control ranges (photoreport_develop_controls). Crop rect is 0..1 of the frame. reset clears the edit first. The same command is safe to retry: each call has its own id and the server stores it once. Example: raise exposure by setting light.exposure to 0.4 on photo <id>.",
inputSchema: z.object({
photoId: z.string(),
values: z.record(z.string(), z.number()).optional().describe("Control id to value, for example { \"light.exposure\": 0.3, \"light.contrast\": 10 }."),
reset: z.boolean().default(false).describe("Clear the edit before applying values."),
crop: z
.object({
x0: z.number().min(0).max(1),
y0: z.number().min(0).max(1),
x1: z.number().min(0).max(1),
y1: z.number().min(0).max(1),
angle: z.number().min(-45).max(45).default(0),
aspectW: z.number().int().positive().nullable().default(null),
aspectH: z.number().int().positive().nullable().default(null),
})
.optional(),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const ops: { opId: string; command: { command: "develop.reset" } | { command: "develop.set"; params: { values: Record<string, number> } } | { command: "crop.set"; params: { rect: { x0: number; y0: number; x1: number; y1: number }; angle: number; aspect: [number, number] | null } } }[] = [];
if (input.reset) ops.push({ opId: randomUUID(), command: { command: "develop.reset" } });
if (input.values) ops.push({ opId: randomUUID(), command: { command: "develop.set", params: { values: developValues(input.values) } } });
if (input.crop) {
if (input.crop.x0 >= input.crop.x1 || input.crop.y0 >= input.crop.y1) throw new Error("The crop must have a positive size (x0 < x1 and y0 < y1).");
const aspect = input.crop.aspectW && input.crop.aspectH ? ([input.crop.aspectW, input.crop.aspectH] as [number, number]) : null;
ops.push({
opId: randomUUID(),
command: { command: "crop.set", params: { rect: { x0: input.crop.x0, y0: input.crop.y0, x1: input.crop.x1, y1: input.crop.y1 }, angle: input.crop.angle, aspect } },
});
}
if (ops.length === 0) throw new Error("Nothing to change. Pass values, crop, or reset.");
const result = await api.postEdits(input.photoId, { clientId: CLIENT, ops });
return text(`Edited. Sequence is now ${result.developSeq}. The preview updates when the render worker finishes.`);
}),
);
server.registerTool(
"photoreport_set_autopilot",
{
title: "Set autopilot",
description: "Turns the event autopilot on or off and sets how it edits arriving photos (crop, level, tone, white balance, look). New camera photos are edited on the desktop and the server with these rules. It does not re-edit photos already in the event.",
inputSchema: z.object({
eventId: z.string(),
enabled: z.boolean(),
crop: z.boolean().default(true),
level: z.boolean().default(true),
tone: z.boolean().default(true),
whiteBalance: z.boolean().default(true),
toneStrength: z.number().min(0).max(1).default(0.75),
look: z.enum(["agency", "natural", "none"]).default("none"),
framing: z.enum(["tight", "full"]).default("tight"),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const event = await api.updateEvent(input.eventId, {
autopilot: {
enabled: input.enabled,
crop: input.crop,
level: input.level,
tone: input.tone,
whiteBalance: input.whiteBalance,
toneStrength: input.toneStrength,
look: input.look,
framing: input.framing,
},
});
return text(`Autopilot on ${event.title}: ${input.enabled ? "on" : "off"}.`);
}),
);
}
+273
View File
@@ -0,0 +1,273 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { PhotoQuery } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { reviewPhotos } from "../review.js";
import { guard, text, type Server } from "../result.js";
const Flag = z.enum(["PICK", "REJECT", "NONE"]);
const Color = z.enum(["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"]);
function line(photo: PhotoSummary): string {
const exposure = [photo.focalLength ? `${photo.focalLength}mm` : "", photo.aperture ? `f/${photo.aperture}` : "", photo.iso ? `ISO ${photo.iso}` : ""].filter(Boolean).join(" ");
const mark = photo.flag === "NONE" ? "" : ` ${photo.flag}`;
const stars = photo.rating > 0 ? ` ${photo.rating}★` : "";
const players = photo.players.length ? ` · ${photo.players.join(", ")}` : "";
return `- ${photo.name} (${photo.id})${mark}${stars}${photo.colorLabel !== "NONE" ? ` ${photo.colorLabel}` : ""} · ${photo.status}${photo.delivery ? `/${photo.delivery}` : ""}${photo.developSeq ? " · edited" : ""}${players}${exposure ? ` · ${exposure}` : ""}`;
}
async function loadEvent(organization: string, eventId: string): Promise<PhotoSummary[]> {
const photos: PhotoSummary[] = [];
let offset = 0;
for (;;) {
const page = await api.listPhotos(organization, { event: eventId, offset, limit: 500 });
photos.push(...page.photos);
offset += page.photos.length;
if (page.photos.length === 0 || offset >= page.total || photos.length >= 1000) break;
}
return photos;
}
export function registerLibrary(server: Server): void {
server.registerTool(
"photoreport_list_photos",
{
title: "List photos",
description: "Photos of one event or the inbox. Filter by flag, minimum stars, or photos with no players. Returns names and ids for photoreport_photo, photoreport_set_photos and photoreport_send_photos. Example: the picks of event <id>.",
inputSchema: z.object({
organizationId: z.string().optional(),
eventId: z.string().describe("Event id, or inbox for photos no event claimed."),
flag: z.enum(["PICK", "REJECT", "NONE", "UNREJECTED"]).optional(),
minRating: z.number().int().min(0).max(5).optional(),
withoutPlayers: z.boolean().default(false),
status: z.enum(["PROCESSING", "READY", "FAILED"]).optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(80).default(40),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: PhotoQuery = { event: input.eventId, offset: input.offset, limit: input.limit };
if (input.flag) query.flag = input.flag;
if (input.minRating !== undefined) query.minRating = input.minRating;
if (input.withoutPlayers) query.withoutPlayers = true;
if (input.status) query.status = input.status;
const page = await api.listPhotos(id, query);
const lines = [`${page.photos.length} of ${page.total}, offset ${page.offset}`];
lines.push(...page.photos.map(line));
if (page.offset + page.photos.length < page.total) lines.push(`More: offset ${page.offset + page.photos.length}.`);
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_search",
{
title: "Search the library",
description: "Search across events by name, team, file name or a person id. Use photoreport_list_photos when the event is already known.",
inputSchema: z.object({
organizationId: z.string().optional(),
query: z.string().optional().describe("Text: name, team, competition, file name."),
personId: z.string().optional(),
limit: z.number().int().min(1).max(40).default(20),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const query: { q?: string; personId?: string; limit: number } = { limit: input.limit };
if (input.query) query.q = input.query;
if (input.personId) query.personId = input.personId;
const found = await api.search(id, query);
const lines = [`${found.total} photos`];
lines.push(...found.photos.map(line));
if (found.suggested.length) {
lines.push("Suggested (face, not confirmed):");
lines.push(...found.suggested.map(line));
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_review_event",
{
title: "Review an event",
description: "Looks through an event (up to 1000 photos) and says what still needs the photographer: unread files, failed deliveries, picks with no edit, frames not culled, photos with no player. It does not judge sharpness from pixels. For one frame, call photoreport_photo. For shirt numbers, call photoreport_jersey_queue. Example: are the photos of this match in good shape?",
inputSchema: z.object({
organizationId: z.string().optional(),
eventId: z.string(),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId, eventId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const photos = await loadEvent(id, eventId);
const report = reviewPhotos(photos);
const lines = [
`${report.total} photos · ${report.ready} ready · ${report.processing} processing · ${report.failed} failed`,
`${report.picks} picks · ${report.rejects} rejects · ${report.unrated} not culled`,
`${report.uneditedPicks} picks with no edit · ${report.withoutPlayers} without a player · ${report.deliveryFailed} deliveries failed · ${report.unsentPicks} picks not sent`,
];
if (report.lookAt.length === 0) lines.push("Nothing in the catalogue asks for a look. Sharpness and shirt numbers are separate tools.");
else {
lines.push("Look at:");
for (const note of report.lookAt) lines.push(`- ${note.name} (${note.id}): ${note.reasons.join("; ")}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_photo",
{
title: "One photo",
description: "One photo: exposure, marks, players, faces found on it, and whether it has been edited. Preview URL is included so a client that can open images can look. Use photoreport_edit_photo to change the develop settings.",
inputSchema: z.object({ photoId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ photoId }) =>
guard(async () => {
await ensureSession();
const [faces, develop, iptc] = await Promise.all([
api.photoFaces(photoId),
api.developState(photoId),
api.photoIptc(photoId).catch(() => null),
]);
const lines = [`Faces: ${faces.status}, ${faces.faces.length}`];
for (const face of faces.faces) {
const who = face.person?.name ?? (face.suggestion ? `${face.suggestion.name} (suggested)` : "unnamed");
const visible = face.inPreview ? "in the crop" : "cropped out";
lines.push(`- ${who} · ${visible} · box ${face.x0.toFixed(2)},${face.y0.toFixed(2)}–${face.x1.toFixed(2)},${face.y1.toFixed(2)}`);
}
lines.push(`Develop sequence ${develop.developSeq}. ${develop.ops.length} edits after the snapshot.`);
if (iptc && iptc.issues.length) {
lines.push("IPTC:");
for (const issue of iptc.issues) lines.push(`- ${issue.field}: ${issue.detail}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_set_photos",
{
title: "Mark photos",
description: "Sets the flag, stars, colour or players on one or many photos, or moves them to another event. This is the cull, not the develop edit (use photoreport_edit_photo for exposure and crop). Example: flag these ids as picks.",
inputSchema: z.object({
organizationId: z.string().optional(),
photoIds: z.array(z.string()).min(1).max(500),
flag: Flag.optional(),
rating: z.number().int().min(0).max(5).optional(),
color: Color.optional(),
players: z.array(z.string()).max(30).optional().describe("Replaces the player list."),
eventId: z.string().nullable().optional().describe("Move the photos to this event. Null sends them to the inbox."),
}),
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const patch: {
flag?: "PICK" | "REJECT" | "NONE";
rating?: number;
colorLabel?: "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
players?: string[];
eventId?: string | null;
} = {};
if (input.flag) patch.flag = input.flag;
if (input.rating !== undefined) patch.rating = input.rating;
if (input.color) patch.colorLabel = input.color;
if (input.players) patch.players = input.players;
if (input.eventId !== undefined) patch.eventId = input.eventId;
const result = await api.updatePhotos(id, input.photoIds, patch);
return text(`Updated ${result.updated} photos.`);
}),
);
server.registerTool(
"photoreport_squads",
{
title: "Event squads",
description: "The two teams of a match and whether each athlete has an enrolled face. Use this before naming faces or checking who is missing from the photos.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const squads = await api.eventSquads(eventId);
const lines: string[] = [];
for (const side of squads.sides) {
lines.push(`${side.team.name}`);
for (const player of side.players) {
const face = player.hasFace ? "face enrolled" : player.faceUrl ? "squad photo only" : "no face";
lines.push(`- ${player.number ?? "?"} ${player.name} (${face})`);
}
}
if (lines.length === 0) return text("No squad on this event. photoreport_sync_squads pulls the official list when the match is linked.");
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_sync_squads",
{
title: "Sync squads",
description: "Pulls the official squad for an event that is linked to a match. Does nothing useful when the event has no fixture.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const result = await api.syncEventSquads(eventId);
return text(`Squad sync: ${result.created} created, ${result.updated} updated, ${result.headshots} headshots.`);
}),
);
server.registerTool(
"photoreport_list_galleries",
{
title: "List galleries",
description: "Galleries of the organization. Use the id with photoreport_add_to_gallery.",
inputSchema: z.object({ organizationId: z.string().optional() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ organizationId }) =>
guard(async () => {
await ensureSession();
const id = await orgId(organizationId);
const { galleries } = await api.listGalleries(id);
if (galleries.length === 0) return text("No galleries.");
return text(galleries.slice(0, 40).map((gallery) => `- ${gallery.title} (${gallery.id}) · ${gallery.photoCount} photos${gallery.publishedAt ? " · published" : ""}`).join("\n"));
}),
);
server.registerTool(
"photoreport_add_to_gallery",
{
title: "Add photos to a gallery",
description: "Adds photos to a gallery. Does not publish it. Example: put these picks in the match gallery.",
inputSchema: z.object({
galleryId: z.string(),
photoIds: z.array(z.string()).min(1).max(500),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ galleryId, photoIds }) =>
guard(async () => {
await ensureSession();
await api.changeGalleryPhotos(galleryId, { add: photoIds });
return text(`Added ${photoIds.length} photos to the gallery.`);
}),
);
}
+59
View File
@@ -0,0 +1,59 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import type { DeskCommand } from "@photoreport/contracts";
import * as z from "zod/v4";
import { api, ensureSession } from "../session.js";
import { guard, text, type Server } from "../result.js";
const exec = promisify(execFile);
/** Brings the installed PhotoReport window forward. The command still goes to whichever copy is signed in. */
async function raiseApp(): Promise<string> {
try {
if (process.platform === "darwin") {
await exec("open", ["-a", "PhotoReport"]);
return "PhotoReport is in front.";
}
if (process.platform === "win32") {
await exec("cmd", ["/c", "start", "", "PhotoReport"]);
return "PhotoReport was asked to open.";
}
} catch {
return "PhotoReport is not installed under that name. Open it yourself. The signed-in window still follows.";
}
return "Open PhotoReport. The signed-in window still follows.";
}
const Modules = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
export function registerScreen(server: Server): void {
server.registerTool(
"photoreport_show",
{
title: "Open a PhotoReport window",
description:
"Opens the PhotoReport application on this computer and moves the signed-in window. Use it to change tabs and to open a photo. module is library, develop, metadata, delivery, shop, print, archive, faces, numbers, help, preferences or members. photoId opens that photo in Revelar. eventId opens that event in the library. tool crop, spot or wb opens that tool on the photo. section is a shop tab (orders, products) or a metadata section (iptc, codes, people, faces). Example: open this photo and start the crop. The photographer sees the window move. Do this before saying a photo was shown.",
inputSchema: z.object({
module: z.enum(Modules),
photoId: z.string().optional(),
eventId: z.string().optional(),
tool: z.enum(["crop", "spot", "wb"]).optional(),
section: z.string().max(40).optional(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const raised = await raiseApp();
const command: DeskCommand = { module: input.module };
if (input.photoId) command.photoId = input.photoId;
if (input.eventId) command.eventId = input.eventId;
if (input.tool) command.tool = input.tool;
if (input.section) command.section = input.section;
await api.desk(command);
const where = [input.module, input.photoId, input.eventId, input.tool, input.section].filter(Boolean).join(" · ");
return text(`${raised} Showing ${where}. If the window was signed out, sign in and call this again.`);
}),
);
}
+135
View File
@@ -0,0 +1,135 @@
import type { JerseySample } from "@photoreport/sdk";
import * as z from "zod/v4";
import { api, ensureSession, orgId } from "../session.js";
import { guard, text, textAndImages, type Server } from "../result.js";
async function cropImage(sample: JerseySample): Promise<{ data: string; mimeType: string } | null> {
try {
const response = await fetch(api.absolute(sample.crop), { signal: AbortSignal.timeout(15_000) });
if (!response.ok) return null;
const bytes = Buffer.from(await response.arrayBuffer());
if (bytes.length === 0 || bytes.length > 1_500_000) return null;
const mime = response.headers.get("content-type")?.split(";")[0] ?? "image/jpeg";
return { data: bytes.toString("base64"), mimeType: mime };
} catch {
return null;
}
}
export function registerTeach(server: Server): void {
server.registerTool(
"photoreport_jersey_queue",
{
title: "Shirt numbers to check",
description: "Crops of shirt numbers waiting to be taught, with the model's guess. The first few crops are attached as images so you can see whether the number is readable. Say the digits when they are clear, or illegible when the crop does not show a number, then call photoreport_jersey_review. Do not guess a number you cannot see. Example: show me numbers to teach.",
inputSchema: z.object({
organizationId: z.string().optional(),
status: z.enum(["PENDING", "CONFIRMED", "ILLEGIBLE", "SKIPPED"]).default("PENDING"),
limit: z.number().int().min(1).max(12).default(4),
}),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
const id = await orgId(input.organizationId);
const page = await api.jerseySamples(id, input.status, input.limit);
const counts = Object.entries(page.stats.counts).map(([status, count]) => `${status} ${count}`).join(" · ");
const lines = [`Collected ${page.collected}. ${counts || "No counts."}`];
const images: { data: string; mimeType: string }[] = [];
for (const sample of page.samples) {
lines.push(`- ${sample.id} · ${sample.region} · guess ${sample.suggested ?? "none"} · player ${sample.person ?? "unknown"}`);
const image = await cropImage(sample);
if (image) images.push(image);
}
if (page.samples.length === 0) lines.push("Nothing in this queue.");
else lines.push("The images follow in the same order. Confirm with photoreport_jersey_review.");
return textAndImages(lines.join("\n"), images);
}),
);
server.registerTool(
"photoreport_jersey_review",
{
title: "Teach a shirt number",
description: "Records what the crop shows. CONFIRMED needs the digits you can see (label). ILLEGIBLE means the number is not readable. SKIPPED leaves it out of the dataset. The sample id comes from photoreport_jersey_queue.",
inputSchema: z.object({
sampleId: z.string(),
status: z.enum(["CONFIRMED", "ILLEGIBLE", "SKIPPED"]),
label: z.string().max(4).optional().describe("The digits you can see. Required when status is CONFIRMED."),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
if (input.status === "CONFIRMED" && !input.label) throw new Error("A confirmed number needs the digits in label.");
const sample = await api.reviewJerseySample(input.sampleId, input.status, input.label ?? null);
return text(`Sample ${sample.id} is ${sample.status}${sample.label ? ` (${sample.label})` : ""}.`);
}),
);
server.registerTool(
"photoreport_face_groups",
{
title: "Faces in an event",
description: "People the faces worker grouped in one event, with the suggestion and how many photos. Unnamed groups are the ones to teach with photoreport_confirm_face.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const page = await api.faceGroups(eventId);
const lines = [`${page.groups.length} groups · ${page.pending} photos still running · ${page.unclear} unclear${page.available === false ? " · faces are off for this organization" : ""}`];
for (const group of page.groups.slice(0, 40)) {
const who = group.person?.name ?? (group.suggestion ? `${group.suggestion.name} suggested ${Math.round(group.suggestion.score * 100)}%` : "unnamed");
const number = group.number ? ` · shirt ${group.number.value}` : "";
lines.push(`- ${who} (${group.id}) · ${group.size} photos${number}${group.ignored ? " · ignored" : ""}`);
}
return text(lines.join("\n"));
}),
);
server.registerTool(
"photoreport_confirm_face",
{
title: "Name a face group",
description: "Names every photo in a face group as one person. Pass personId from the squad, or a name (and club, number) to create the person. The group id comes from photoreport_face_groups.",
inputSchema: z.object({
groupId: z.string(),
personId: z.string().optional(),
name: z.string().optional(),
club: z.string().optional(),
number: z.string().max(4).optional(),
}),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async (input) =>
guard(async () => {
await ensureSession();
if (!input.personId && !input.name) throw new Error("Pass personId or a name.");
const who = input.personId
? { personId: input.personId }
: { name: input.name as string, ...(input.club ? { club: input.club } : {}), ...(input.number ? { number: input.number } : {}) };
const result = await api.confirmFaceGroup(input.groupId, who);
return text(`Named as ${result.person.name}.`);
}),
);
server.registerTool(
"photoreport_analyse_faces",
{
title: "Analyse faces",
description: "Queues face detection for an event. The organization must have biometrics on. This does not name anyone; use photoreport_face_groups afterwards.",
inputSchema: z.object({ eventId: z.string() }),
annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },
},
async ({ eventId }) =>
guard(async () => {
await ensureSession();
const result = await api.analyseEventFaces(eventId);
return text(`Queued ${result.queued} photos for faces.`);
}),
);
}
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src",
"lib": ["ES2023"]
},
"include": ["src"]
}
+3 -1
View File
@@ -168,7 +168,9 @@ With autopilot "only the best", windows still shape the first pass (`apps/api/sr
- the match (from kick-off, its typical length by sport: football 115 min with the break, handball 80) is cut
into 5-minute windows; each window may add its share of the gallery, and a share it did not use (the break,
a quiet spell) carries forward, at most three windows' worth at once; at most 10% over the size in all;
a quiet spell) carries forward, at most three windows' worth at once. The size is a target (`galleryCeiling`):
a rich match may add about 15% (at least 2 frames, never more than 25 past the number) from frames at or above
the match's typical one; a thin match stays under;
- one candidate per burst (its best frame), ranked by game moment: the frame score, more with the ball in play
(×1.3), a duel or a celebration (several people in the subject), less when the subject is small (far away);
the photographer's stars count (+20% each), a rejected frame never goes;
+28
View File
@@ -0,0 +1,28 @@
import { z } from "zod";
/** Modules the assistant can open. `library` is the front page. */
export const DESK_MODULES = ["library", "develop", "metadata", "delivery", "shop", "print", "archive", "faces", "numbers", "help", "preferences", "members"] as const;
/**
* One instruction for the PhotoReport window that is open and signed in as this person.
* The API delivers it on the realtime socket. It does not change photos by itself.
*/
export const DeskCommand = z.object({
module: z.enum(DESK_MODULES),
photoId: z.uuid().optional(),
eventId: z.uuid().optional(),
/** Develop only: open that tool on the photo. */
tool: z.enum(["crop", "spot", "wb"]).optional(),
/** Shop tab or metadata section, when that module has one. */
section: z.string().max(40).optional(),
});
export type DeskCommand = z.infer<typeof DeskCommand>;
/** Where the window should go. Library is `/`, not `/library`. */
export function deskPath(command: DeskCommand): string {
if (command.module === "library") return "/";
if (command.module === "develop") return command.photoId ? `/develop/${command.photoId}` : "/develop";
if (command.module === "shop" && command.section) return `/shop?tab=${encodeURIComponent(command.section)}`;
if (command.module === "metadata" && command.section) return `/metadata?s=${encodeURIComponent(command.section)}`;
return `/${command.module}`;
}
+1
View File
@@ -1,4 +1,5 @@
export * from "./commands.js";
export * from "./desk.js";
export * from "./controls.js";
export * from "./library.js";
export * from "./shop.js";
+14
View File
@@ -69,6 +69,20 @@ export const AutopilotSettings = z.object({
*/
selection: z.enum(["bursts", "best"]).default("bursts"),
bestCount: z.number().int().min(5).max(300).default(30),
/**
* One gallery size per destination ("only the best"). The match is spread to the largest count; a smaller
* gallery receives its own spread, and those frames also go to every larger gallery. Empty: every destination
* shares `bestCount`, one frame of each burst each.
*/
galleries: z
.array(
z.object({
targetId: z.string().uuid(),
count: z.number().int().min(5).max(300),
}),
)
.max(10)
.optional(),
/**
* Legacy second export. With two destinations, each burst's best goes to `deliverTargetId` and the second best
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
+6 -1
View File
@@ -1,4 +1,4 @@
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DeskCommand, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, FaceRoster, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, RealEstateFrame, RealEstateGrouping, Role, ZerozeroGame } from "./types.js";
/**
@@ -241,6 +241,11 @@ export class ApiClient {
return this.request<Me>("GET", "/v1/me");
}
/** Asks the open PhotoReport of this person to show a module, a photo or a tool. */
desk(command: DeskCommand) {
return this.request<{ ok: true }>("POST", "/v1/me/desk", command);
}
updateEditorModules(editorModules: Module[]) {
return this.request<{ editorModules: Module[] }>("PUT", "/v1/me/preferences", { editorModules });
}
+1
View File
@@ -237,6 +237,7 @@ export interface PhotoQuery {
flag?: "PICK" | "REJECT" | "NONE" | "UNREJECTED";
minRating?: number;
withoutPlayers?: boolean;
status?: "PROCESSING" | "READY" | "FAILED";
offset?: number;
limit?: number;
}
+32
View File
@@ -212,6 +212,21 @@ importers:
specifier: ^2.12.2
version: 2.12.2
apps/mcp:
dependencies:
'@modelcontextprotocol/server':
specifier: ^2.3.1
version: 2.4.0
'@photoreport/contracts':
specifier: workspace:*
version: link:../../packages/contracts
'@photoreport/sdk':
specifier: workspace:*
version: link:../../packages/sdk
zod:
specifier: ^4.2.0
version: 4.6.5
apps/print-agent:
dependencies:
'@photoreport/contracts':
@@ -817,6 +832,14 @@ packages:
resolution: {integrity: sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==}
engines: {node: '>=8'}
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==}
engines: {node: '>=20'}
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==}
engines: {node: '>=20'}
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -3628,6 +3651,15 @@ snapshots:
'@lukeed/[email protected]': {}
'@modelcontextprotocol/[email protected]':
dependencies:
zod: 4.6.5
'@modelcontextprotocol/[email protected]':
dependencies:
'@modelcontextprotocol/core': 2.4.0
zod: 4.6.5
'@napi-rs/[email protected]':
optional: true