From f0470295fa581a801cf9b3ce4a2e63a8c1e1ad2c Mon Sep 17 00:00:00 2001 From: maxime Date: Wed, 25 Nov 2026 11:21:27 +0100 Subject: [PATCH] The Suggestions page: the support agent's draft replies (~/aimsight-support), read-only from Supabase Conversations (table and bucket suggestions): status, reason, the reply to copy and its figures to download; SUPABASE_CONVERSATIONS_* from the app's .env (the service's EnvironmentFile); nothing is sent from the app Co-Authored-By: Claude Opus 5.5 --- app/aimsight-app.service | 2 + app/server/check.py | 36 +++++++++++++++- app/server/server.py | 16 ++++++- app/server/suggestions.py | 45 ++++++++++++++++++++ app/web/src/App.jsx | 6 ++- app/web/src/pages/Suggestions.jsx | 69 +++++++++++++++++++++++++++++++ 6 files changed, 170 insertions(+), 4 deletions(-) create mode 100644 app/server/suggestions.py create mode 100644 app/web/src/pages/Suggestions.jsx diff --git a/app/aimsight-app.service b/app/aimsight-app.service index 170856f..1f1809f 100644 --- a/app/aimsight-app.service +++ b/app/aimsight-app.service @@ -7,6 +7,8 @@ WorkingDirectory=%h/aimsight-app # claude (Claude Code, subscription) is in ~/.local/bin, which a service does not get from the shell Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin # a restart rebuilds the page, so a change of the code needs only: systemctl --user restart aimsight-app +# SUPABASE_CONVERSATIONS_URL / _KEY for the Suggestions page (aimsight-app/.env, outside git; optional) +EnvironmentFile=-%h/aimsight-app/.env ExecStartPre=/bin/sh -c 'cd app/web && npm run build' ExecStart=%h/aimsight-app/.venv/bin/python app/server/server.py --no-browser Restart=on-failure diff --git a/app/server/check.py b/app/server/check.py index 39f65a7..ba913ae 100644 --- a/app/server/check.py +++ b/app/server/check.py @@ -448,8 +448,42 @@ def check_points(): validity.points.FOLDER = before +def check_suggestions(): + # the Suggestions page (suggestions.py): the support agent's rows read from Supabase Conversations, mocked here + import suggestions + saved = {k: os.environ.pop(k, None) for k in ("SUPABASE_CONVERSATIONS_URL", "SUPABASE_CONVERSATIONS_KEY")} + real_get = suggestions._get + try: + assert "SUPABASE_CONVERSATIONS" in refuses(suggestions.list_suggestions) + os.environ.update(SUPABASE_CONVERSATIONS_URL="https://x.supabase.co", SUPABASE_CONVERSATIONS_KEY="k") + asked = [] + + def fake(path): + asked.append(path) + if path.startswith("/rest/v1/suggestions"): + return json.dumps([{"id": 12, "conversation_uuid": "c1", "status": "ready", "reply": "Bonjour", + "figures": [{"path": "12/1.png", "caption": "glare"}]}]).encode() + if path.startswith("/rest/v1/conversations"): + return json.dumps([{"uuid": "c1", "reference_number": "151", "subject": "Crissier"}]).encode() + return b"png" + suggestions._get = fake + rows = suggestions.list_suggestions() + assert rows[0]["reference"] == "151" and rows[0]["subject"] == "Crissier" and rows[0]["reply"] == "Bonjour", rows + refuses(suggestions.figure, "../x") + refuses(suggestions.figure, "1/a.png") + assert suggestions.figure("12/1.png") == b"png" and asked[-1] == "/storage/v1/object/suggestions/12/1.png", asked + r = server.suggestion_figure("12/1.png") + assert r.media_type == "image/png" and r.headers["x-content-type-options"] == "nosniff" + finally: + suggestions._get = real_get + for k, v in saved.items(): + os.environ.pop(k, None) + if v is not None: + os.environ[k] = v + + CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations, - check_points] + check_points, check_suggestions] if __name__ == "__main__": name = sys.argv[1] if len(sys.argv) > 1 else None diff --git a/app/server/server.py b/app/server/server.py index 44cf119..531e3e3 100644 --- a/app/server/server.py +++ b/app/server/server.py @@ -17,10 +17,11 @@ from pathlib import Path import uvicorn from fastapi import FastAPI, Query, Request -from fastapi.responses import FileResponse, HTMLResponse, JSONResponse +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response import analysis import conversations +import suggestions import station import support import validity @@ -259,6 +260,19 @@ def conversation_file(reference: str, path: str): else FileResponse(f, filename=f.name, headers=headers) +# --- the Suggestions page (suggestions.py): the support agent's draft replies, read-only from Supabase Conversations + +@app.get("/api/suggestions") +def suggestions_list(): + return suggestions.list_suggestions() + + +@app.get("/api/suggestions/figure/{path:path}") +def suggestion_figure(path: str): + return Response(suggestions.figure(path), media_type="image/png", + headers={"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP}) + + if PAGE.is_dir(): app.mount("/", StaticFiles(directory=PAGE, html=True), name="page") else: diff --git a/app/server/suggestions.py b/app/server/suggestions.py new file mode 100644 index 0000000..c1749f6 --- /dev/null +++ b/app/server/suggestions.py @@ -0,0 +1,45 @@ +"""The Suggestions page: the support agent's suggestions (~/aimsight-support), read-only from the Supabase project +Conversations (table suggestions, bucket suggestions): per customer message, its status, the reason it was left to a +person, or the draft reply and its figures to paste into the mail. The person sends it from LibreDesk; nothing is sent +from here. SUPABASE_CONVERSATIONS_URL and SUPABASE_CONVERSATIONS_KEY come from the app's environment (.env through the +service's EnvironmentFile); standard library only. +""" +import json +import os +import re +import urllib.parse +import urllib.request + +import station + +FIGURE = re.compile(r"^\d+/\d+\.png$") # /.png, as the agent writes them +MISSING = "no SUPABASE_CONVERSATIONS_URL / SUPABASE_CONVERSATIONS_KEY in the app's environment (README)" + + +def _get(path: str) -> bytes: + url, key = os.environ.get("SUPABASE_CONVERSATIONS_URL"), os.environ.get("SUPABASE_CONVERSATIONS_KEY") + if not url or not key: + raise station.Refusal(MISSING) + r = urllib.request.Request(url.rstrip("/") + path, headers={"apikey": key}) + if key.startswith("eyJ"): # an old JWT key; a new sb_secret_ key goes only in apikey + r.add_header("Authorization", f"Bearer {key}") + with urllib.request.urlopen(r, timeout=30) as answer: + return answer.read() + + +def list_suggestions() -> list[dict]: + """The latest 200 suggestions, newest first, each with its conversation's reference and subject.""" + if not os.environ.get("SUPABASE_CONVERSATIONS_URL") or not os.environ.get("SUPABASE_CONVERSATIONS_KEY"): + raise station.Refusal(MISSING) + rows = json.loads(_get("/rest/v1/suggestions?select=*&order=created_at.desc&limit=200")) + uuids = ",".join(sorted({r["conversation_uuid"] for r in rows})) + convs = {c["uuid"]: c for c in json.loads(_get( + f"/rest/v1/conversations?select=uuid,reference_number,subject&uuid=in.({urllib.parse.quote(uuids)})"))} if rows else {} + return [r | {"reference": convs.get(r["conversation_uuid"], {}).get("reference_number", ""), + "subject": convs.get(r["conversation_uuid"], {}).get("subject", "")} for r in rows] + + +def figure(path: str) -> bytes: + if not FIGURE.match(path): + raise station.Refusal(f"not a suggestion figure: {path}") + return _get(f"/storage/v1/object/suggestions/{path}") diff --git a/app/web/src/App.jsx b/app/web/src/App.jsx index 506c4a8..3129923 100644 --- a/app/web/src/App.jsx +++ b/app/web/src/App.jsx @@ -3,13 +3,14 @@ import { ActionIcon, AppShell, Burger, ColorSwatch, Group, Loader, NavLink, ScrollArea, Text, Tooltip, useComputedColorScheme, useMantineColorScheme, } from "@mantine/core"; import { useDisclosure } from "@mantine/hooks"; -import { IconChartLine, IconCircleCheck, IconCircleDashed, IconFolder, IconMessages, IconMoon, IconPointFilled, IconSatellite, IconSun } from "@tabler/icons-react"; +import { IconChartLine, IconCircleCheck, IconCircleDashed, IconFolder, IconMessages, IconMailForward, IconMoon, IconPointFilled, IconSatellite, IconSun } from "@tabler/icons-react"; const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, loaded only here const Stations = lazy(() => import("./pages/Stations.jsx")); const Conversations = lazy(() => import("./pages/Conversations.jsx")); const Points = lazy(() => import("./pages/Points.jsx")); -const PAGES = [["data", "Data", IconChartLine], ["points", "Points", IconPointFilled], ["stations", "Stations", IconSatellite], ["conversations", "Conversations", IconMessages]]; +const Suggestions = lazy(() => import("./pages/Suggestions.jsx")); +const PAGES = [["data", "Data", IconChartLine], ["points", "Points", IconPointFilled], ["stations", "Stations", IconSatellite], ["conversations", "Conversations", IconMessages], ["suggestions", "Suggestions", IconMailForward]]; // The address: #/?station=…&start=…&end=…; reloading keeps the page and the selection, Back works; without dates, the // last 5 UTC days, today included (end excluded: tomorrow) @@ -145,6 +146,7 @@ export default function App() { }> {page === "stations" ? : page === "conversations" ? + : page === "suggestions" ? : page === "points" ? : } diff --git a/app/web/src/pages/Suggestions.jsx b/app/web/src/pages/Suggestions.jsx new file mode 100644 index 0000000..d49c5fd --- /dev/null +++ b/app/web/src/pages/Suggestions.jsx @@ -0,0 +1,69 @@ +import { useEffect, useState } from "react"; +import { Anchor, Badge, Button, Card, CopyButton, Group, Image, ScrollArea, SimpleGrid, Stack, Table, Text, Textarea, Title } from "@mantine/core"; +import { call } from "../common.jsx"; + +const when = t => (t ? t.slice(0, 16).replace("T", " ") : ""); +const COLORS = { ready: "green", needs_human: "orange", failed: "red", skipped: "gray" }; + +// The support agent's suggestions (~/aimsight-support), read-only from Supabase Conversations: one per customer message, +// newest first; a click shows the draft reply (to copy into the mail in LibreDesk) and its figures (to download and paste) +export default function Suggestions() { + const [list, setList] = useState([]), [open, setOpen] = useState(null); + const read = () => call("/api/suggestions").then(l => l && setList(l)); + useEffect(() => { read(); }, []); + const s = list.find(r => r.id === open); + return ( + +
+ Suggestions + The support agent's draft replies to the customers' questions about their data. Nothing is sent from + here: copy the reply and the figures into the mail in LibreDesk, adapt it, send it. +
+ + + + {list.length ? ( + + + Ref.SubjectStatus + ReasonUpdated (UTC) + + {list.map(r => ( + setOpen(r.id)} style={{ cursor: "pointer" }} + bg={open === r.id ? "var(--mantine-primary-color-light)" : undefined}> + {r.reference}{r.subject} + {r.status} + {r.error || r.triage?.reason || ""}{when(r.updated_at)} + + ))} + +
+
+ ) : No suggestion yet.} +
+
+ {s && ( + + + #{s.reference} {s.subject} · station {s.triage?.station || "?"} · days {(s.triage?.range || []).join(" → ")} + {s.reply ? ( + <> +