From e80cbaf388b78e528895b046ae8a96af693ad3ab Mon Sep 17 00:00:00 2001 From: spark Date: Sat, 7 Nov 2026 03:12:36 +0000 Subject: [PATCH] feat(mcp): open the PhotoReport window from the assistant photoreport_show brings the app forward and tells the signed-in window which module, event, photo and tool to open. --- apps/api/src/app.ts | 2 +- apps/api/src/me/routes.ts | 13 ++++++- apps/api/src/realtime.ts | 40 ++++++++++++++++++-- apps/app/src/desk.test.ts | 25 +++++++++++++ apps/app/src/desk.ts | 12 ++++++ apps/app/src/library/realtime.ts | 5 ++- apps/app/src/pages/DevelopPage.tsx | 8 ++-- apps/app/src/pages/LibraryPage.tsx | 9 +++++ apps/app/src/pages/Shell.tsx | 21 ++++++++++- apps/mcp/src/index.ts | 2 + apps/mcp/src/tools/screen.ts | 59 ++++++++++++++++++++++++++++++ packages/contracts/src/desk.ts | 28 ++++++++++++++ packages/contracts/src/index.ts | 1 + packages/sdk/src/client.ts | 7 +++- 14 files changed, 220 insertions(+), 12 deletions(-) create mode 100644 apps/app/src/desk.test.ts create mode 100644 apps/app/src/desk.ts create mode 100644 apps/mcp/src/tools/screen.ts create mode 100644 packages/contracts/src/desk.ts diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index a04ab67..b843cfd 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -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 }); diff --git a/apps/api/src/me/routes.ts b/apps/api/src/me/routes.ts index 5a487f6..2ba3cb7 100644 --- a/apps/api/src/me/routes.ts +++ b/apps/api/src/me/routes.ts @@ -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 }; + }); } diff --git a/apps/api/src/realtime.ts b/apps/api/src/realtime.ts index b8d26fd..07bb522 100644 --- a/apps/api/src/realtime.ts +++ b/apps/api/src/realtime.ts @@ -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; } -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 {} } @@ -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>(); + 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; diff --git a/apps/app/src/desk.test.ts b/apps/app/src/desk.test.ts new file mode 100644 index 0000000..cf62332 --- /dev/null +++ b/apps/app/src/desk.test.ts @@ -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 => ({ 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 }); + }); +}); diff --git a/apps/app/src/desk.ts b/apps/app/src/desk.ts new file mode 100644 index 0000000..443df85 --- /dev/null +++ b/apps/app/src/desk.ts @@ -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; +} diff --git a/apps/app/src/library/realtime.ts b/apps/app/src/library/realtime.ts index 88785c4..090bb8f 100644 --- a/apps/app/src/library/realtime.ts +++ b/apps/app/src/library/realtime.ts @@ -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(); }; diff --git a/apps/app/src/pages/DevelopPage.tsx b/apps/app/src/pages/DevelopPage.tsx index 6667d88..c462072 100644 --- a/apps/app/src/pages/DevelopPage.tsx +++ b/apps/app/src/pages/DevelopPage.tsx @@ -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()); diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index e0021c9..cb6bd14 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -191,6 +191,15 @@ export function LibraryPage() { [api, orgId, state.scope], ); + useEffect(() => { + const onOpen = (ev: Event) => { + const id = (ev as CustomEvent).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; diff --git a/apps/app/src/pages/Shell.tsx b/apps/app/src/pages/Shell.tsx index 0bffde8..318a6e1 100644 --- a/apps/app/src/pages/Shell.tsx +++ b/apps/app/src/pages/Shell.tsx @@ -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() { + @@ -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).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+/) diff --git a/apps/mcp/src/index.ts b/apps/mcp/src/index.ts index 42d3a5a..947f5d9 100644 --- a/apps/mcp/src/index.ts +++ b/apps/mcp/src/index.ts @@ -10,11 +10,13 @@ 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); diff --git a/apps/mcp/src/tools/screen.ts b/apps/mcp/src/tools/screen.ts new file mode 100644 index 0000000..9b41814 --- /dev/null +++ b/apps/mcp/src/tools/screen.ts @@ -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 { + 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.`); + }), + ); +} diff --git a/packages/contracts/src/desk.ts b/packages/contracts/src/desk.ts new file mode 100644 index 0000000..12f0e04 --- /dev/null +++ b/packages/contracts/src/desk.ts @@ -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; + +/** 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}`; +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 2012ffa..228440e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -1,4 +1,5 @@ export * from "./commands.js"; +export * from "./desk.js"; export * from "./controls.js"; export * from "./library.js"; export * from "./shop.js"; diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 8c9ad69..5ca08bb 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -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("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 }); } -- 2.47.3