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 <noreply@anthropic.com>
This commit is contained in:
1 parent
54bcce1281
commit
f0470295fa
6 files changed
+170
-4
No files matched your search
@@ -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
|
# 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
|
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
|
# 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'
|
ExecStartPre=/bin/sh -c 'cd app/web && npm run build'
|
||||||
ExecStart=%h/aimsight-app/.venv/bin/python app/server/server.py --no-browser
|
ExecStart=%h/aimsight-app/.venv/bin/python app/server/server.py --no-browser
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
|
|||||||
+35
-1
@@ -448,8 +448,42 @@ def check_points():
|
|||||||
validity.points.FOLDER = before
|
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,
|
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations,
|
||||||
check_points]
|
check_points, check_suggestions]
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
name = sys.argv[1] if len(sys.argv) > 1 else None
|
name = sys.argv[1] if len(sys.argv) > 1 else None
|
||||||
|
|||||||
+15
-1
@@ -17,10 +17,11 @@ from pathlib import Path
|
|||||||
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
from fastapi import FastAPI, Query, Request
|
from fastapi import FastAPI, Query, Request
|
||||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
||||||
|
|
||||||
import analysis
|
import analysis
|
||||||
import conversations
|
import conversations
|
||||||
|
import suggestions
|
||||||
import station
|
import station
|
||||||
import support
|
import support
|
||||||
import validity
|
import validity
|
||||||
@@ -259,6 +260,19 @@ def conversation_file(reference: str, path: str):
|
|||||||
else FileResponse(f, filename=f.name, headers=headers)
|
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():
|
if PAGE.is_dir():
|
||||||
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -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$") # <suggestion id>/<n>.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}")
|
||||||
+4
-2
@@ -3,13 +3,14 @@ import {
|
|||||||
ActionIcon, AppShell, Burger, ColorSwatch, Group, Loader, NavLink, ScrollArea, Text, Tooltip, useComputedColorScheme, useMantineColorScheme,
|
ActionIcon, AppShell, Burger, ColorSwatch, Group, Loader, NavLink, ScrollArea, Text, Tooltip, useComputedColorScheme, useMantineColorScheme,
|
||||||
} from "@mantine/core";
|
} from "@mantine/core";
|
||||||
import { useDisclosure } from "@mantine/hooks";
|
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 Data = lazy(() => import("./pages/Data.jsx")); // Plotly, loaded only here
|
||||||
const Stations = lazy(() => import("./pages/Stations.jsx"));
|
const Stations = lazy(() => import("./pages/Stations.jsx"));
|
||||||
const Conversations = lazy(() => import("./pages/Conversations.jsx"));
|
const Conversations = lazy(() => import("./pages/Conversations.jsx"));
|
||||||
const Points = lazy(() => import("./pages/Points.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: #/<page>?station=…&start=…&end=…; reloading keeps the page and the selection, Back works; without dates, the
|
// The address: #/<page>?station=…&start=…&end=…; reloading keeps the page and the selection, Back works; without dates, the
|
||||||
// last 5 UTC days, today included (end excluded: tomorrow)
|
// last 5 UTC days, today included (end excluded: tomorrow)
|
||||||
@@ -145,6 +146,7 @@ export default function App() {
|
|||||||
<Suspense fallback={<Loader m="xl" />}>
|
<Suspense fallback={<Loader m="xl" />}>
|
||||||
{page === "stations" ? <Stations selection={selection} />
|
{page === "stations" ? <Stations selection={selection} />
|
||||||
: page === "conversations" ? <Conversations />
|
: page === "conversations" ? <Conversations />
|
||||||
|
: page === "suggestions" ? <Suggestions />
|
||||||
: page === "points" ? <Points selection={selection} choose={choose} />
|
: page === "points" ? <Points selection={selection} choose={choose} />
|
||||||
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
|
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
|
||||||
support={support} setSupport={setSupport} />}
|
support={support} setSupport={setSupport} />}
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<Stack gap="lg" maw={1200}>
|
||||||
|
<div>
|
||||||
|
<Title order={2}>Suggestions</Title>
|
||||||
|
<Text c="dimmed">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.</Text>
|
||||||
|
</div>
|
||||||
|
<Card shadow="sm" withBorder>
|
||||||
|
<Stack gap="md">
|
||||||
|
<Group><Button variant="default" onClick={read}>Refresh</Button></Group>
|
||||||
|
{list.length ? (
|
||||||
|
<ScrollArea.Autosize mah={400}>
|
||||||
|
<Table highlightOnHover verticalSpacing={4} stickyHeader>
|
||||||
|
<Table.Thead><Table.Tr><Table.Th>Ref.</Table.Th><Table.Th>Subject</Table.Th><Table.Th>Status</Table.Th>
|
||||||
|
<Table.Th>Reason</Table.Th><Table.Th>Updated (UTC)</Table.Th></Table.Tr></Table.Thead>
|
||||||
|
<Table.Tbody>
|
||||||
|
{list.map(r => (
|
||||||
|
<Table.Tr key={r.id} onClick={() => setOpen(r.id)} style={{ cursor: "pointer" }}
|
||||||
|
bg={open === r.id ? "var(--mantine-primary-color-light)" : undefined}>
|
||||||
|
<Table.Td ff="monospace">{r.reference}</Table.Td><Table.Td>{r.subject}</Table.Td>
|
||||||
|
<Table.Td><Badge color={COLORS[r.status] || "blue"} variant="light">{r.status}</Badge></Table.Td>
|
||||||
|
<Table.Td>{r.error || r.triage?.reason || ""}</Table.Td><Table.Td ff="monospace">{when(r.updated_at)}</Table.Td>
|
||||||
|
</Table.Tr>
|
||||||
|
))}
|
||||||
|
</Table.Tbody>
|
||||||
|
</Table>
|
||||||
|
</ScrollArea.Autosize>
|
||||||
|
) : <Text c="dimmed" size="sm">No suggestion yet.</Text>}
|
||||||
|
</Stack>
|
||||||
|
</Card>
|
||||||
|
{s && (
|
||||||
|
<Card shadow="sm" withBorder>
|
||||||
|
<Stack gap="md">
|
||||||
|
<Text size="sm" c="dimmed">#{s.reference} {s.subject} · station {s.triage?.station || "?"} · days {(s.triage?.range || []).join(" → ")}</Text>
|
||||||
|
{s.reply ? (
|
||||||
|
<>
|
||||||
|
<Textarea value={s.reply} readOnly autosize minRows={6} />
|
||||||
|
<Group><CopyButton value={s.reply}>{({ copied, copy }) => <Button onClick={copy}>{copied ? "Copied" : "Copy the reply"}</Button>}</CopyButton></Group>
|
||||||
|
<SimpleGrid cols={{ base: 1, md: 2 }}>
|
||||||
|
{s.figures.map(f => (
|
||||||
|
<Stack key={f.path} gap={4}>
|
||||||
|
<Image src={`/api/suggestions/figure/${f.path}`} alt={f.caption} />
|
||||||
|
<Group justify="space-between"><Text size="xs">{f.caption}</Text>
|
||||||
|
<Anchor size="xs" href={`/api/suggestions/figure/${f.path}`} download={f.path.replace("/", "_")}>Download</Anchor></Group>
|
||||||
|
</Stack>
|
||||||
|
))}
|
||||||
|
</SimpleGrid>
|
||||||
|
</>
|
||||||
|
) : <Text size="sm">{s.error || "In progress: " + s.status}</Text>}
|
||||||
|
</Stack>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user