Conversations: pump LibreDesk through aimsight-libredesk, list and show the transcripts safely

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-18 15:10:48 +01:00
1 parent ca2f66ce3d
commit 3544f29d85
6 files changed
+449 -2

No files matched your search

+1
View File
@@ -11,3 +11,4 @@ tools
agents agents
optimizer optimizer
models models
libredesk
+37 -1
View File
@@ -377,7 +377,43 @@ def check_support():
support.supports.clear() support.supports.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support] def check_conversations():
# the Conversations page (conversations.py): the list, the transcript rendered safely, the files, the pumping refused
# on a bad range; without LibreDesk (the pumping is libredesk/conversations/, tested there)
import conversations
root, before = temp_folder(), conversations.FOLDER
conversations.FOLDER = root
try:
c = root / "42"
(c / "attachments").mkdir(parents=True)
(c / "conversation.json").write_text(json.dumps({"reference_number": "42", "subject": "A jump", "status": "Open",
"updated_at": "2026-11-18T09:00:00Z", "contact": {"first_name": "Jean", "last_name": "", "email": "j@x.ch"}}))
(c / "messages.json").write_text(json.dumps([
{"type": "incoming", "created_at": "2026-11-18T08:00:00Z", "attachments": [{"url": "attachments/p.png"}]},
{"type": "activity", "created_at": "2026-11-18T08:05:00Z", "attachments": []},
{"type": "outgoing", "created_at": "2026-11-18T08:10:00Z", "attachments": [{"url": "attachments/x.svg"}]}]))
(c / "transcript.md").write_text("# A jump\n\n<script>alert(1)</script>\n\n![p](attachments/p.png)\n")
(c / "attachments" / "p.png").write_bytes(b"png")
(c / "attachments" / "x.svg").write_text("<svg onload='alert(1)'/>")
(root / "pumped.json").write_text("{}") # not a conversation
assert conversations.list_conversations() == [{"reference": "42", "subject": "A jump", "contact": "Jean",
"status": "Open", "last": "2026-11-18T08:10:00Z", "messages": 2, "attachments": 2}], conversations.list_conversations()
page = conversations.transcript("42", False)
assert "<script>" not in page and "&lt;script&gt;" in page and '<img alt="p" src="attachments/p.png"' in page, page
assert server.conversation_file("42", "attachments/x.svg").headers["content-disposition"].startswith("attachment")
png = server.conversation_file("42", "attachments/p.png").headers
assert "content-disposition" not in png and png["x-content-type-options"] == "nosniff"
assert "img-src 'self'" in server.conversation_transcript("42").headers["content-security-policy"]
refuses(conversations.transcript, "../analyses", False)
refuses(server.conversation_file, "42", "../../etc/passwd")
assert "From and To" in refuses(conversations.pump, {"start": "2026-11-01"})
assert set(conversations.pump_state()) == {"running", "log"}
finally:
conversations.FOLDER = before
shutil.rmtree(root)
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations]
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
+54
View File
@@ -0,0 +1,54 @@
"""The Conversations page: the LibreDesk conversations, pumped read-only by ~/aimsight-libredesk (link libredesk/,
conversations/pompage.py, called as it is; its key stays in its .env) into labeling/auto/conversations/<reference>/
(conversation.json, messages.json, attachments/, transcript.md). The app lists them and shows a transcript safely: the text
escaped before Markdown (a client's <script> stays text), served with a strict CSP (no script, no remote image), the
attachments other than plain images as downloads.
"""
import html
import json
import sys
import analysis
import station
FOLDER = station.LABELS / "auto" / "conversations"
LIBREDESK = station.ROOT / "libredesk"
sys.path.insert(0, str(LIBREDESK / "conversations"))
import pompage # noqa: E402
INLINE = {".png", ".jpg", ".jpeg", ".gif", ".webp"} # shown in the page; any other attachment is downloaded
def pump_state():
return {"running": pompage.running(), "log": pompage.log()}
def pump(body):
try:
pompage.start(body.get("start") or "", body.get("end") or "", str(FOLDER))
except ValueError as e:
raise station.Refusal(str(e)) from e
return pump_state()
def list_conversations():
"""Each pumped conversation, the most recent message first."""
out = []
for f in FOLDER.glob("*/conversation.json"):
c = json.loads(f.read_text(encoding="utf-8"))
m = f.with_name("messages.json")
messages = json.loads(m.read_text(encoding="utf-8")) if m.exists() else []
contact = c.get("contact") or {}
out.append({"reference": f.parent.name, "subject": c.get("subject") or "", "status": c.get("status") or "",
"contact": " ".join(x for x in (contact.get("first_name"), contact.get("last_name")) if x)
or contact.get("email") or "",
"last": max((x["created_at"] for x in messages), default=c.get("updated_at") or ""),
"messages": sum(x.get("type") != "activity" for x in messages),
"attachments": sum(len(x.get("attachments") or []) for x in messages)})
return sorted(out, key=lambda c: c["last"], reverse=True)
def transcript(reference, dark):
"""transcript.md in HTML, escaped first: what a client wrote is shown, never run."""
text = analysis.file(reference, "transcript.md", FOLDER).read_text(encoding="utf-8")
return analysis._page(html.escape(text, quote=False), reference, dark)
+37 -1
View File
@@ -2,7 +2,8 @@
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api. The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
optimization of the detectors (analysis.py); its Support tab, the support (support.py). optimization of the detectors (analysis.py); its Support tab, the support (support.py). The Conversations page, the
LibreDesk conversations pumped by ~/aimsight-libredesk (conversations.py).
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770). Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
""" """
import json import json
@@ -19,6 +20,7 @@ from fastapi import FastAPI, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
import analysis import analysis
import conversations
import station import station
import support import support
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
@@ -200,6 +202,40 @@ def support_file(name: str, path: str):
return FileResponse(analysis.file(name, path, support.FOLDER)) return FileResponse(analysis.file(name, path, support.FOLDER))
# --- the Conversations page (conversations.py): the LibreDesk conversations, pumped read-only, and their transcripts
CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'" # a client's mail: no script, no remote image
@app.get("/api/conversations/pump")
def conversations_pump_state():
return conversations.pump_state()
@app.post("/api/conversations/pump")
def conversations_pump(body: dict):
return conversations.pump(body)
@app.get("/api/conversations")
def conversations_list():
return conversations.list_conversations()
@app.get("/api/conversations/{reference}/report.html")
def conversation_transcript(reference: str, dark: bool = False):
return HTMLResponse(conversations.transcript(reference, dark), headers={"Content-Security-Policy": CSP})
@app.get("/api/conversations/{reference}/{path:path}")
def conversation_file(reference: str, path: str):
"""A plain image inline; any other attachment (an .html, an .svg) as a download: it never runs at the app's address."""
f = analysis.file(reference, path, conversations.FOLDER)
headers = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP}
return FileResponse(f, headers=headers) if f.suffix.lower() in conversations.INLINE \
else FileResponse(f, filename=f.name, headers=headers)
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,257 @@
# Conversations Tab Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Pump every LibreDesk conversation, read-only, into `labeling/auto/conversations/<reference>/` (JSON, attachments, a readable transcript), launched and shown from a new **Conversations** page of the app.
**Architecture:** The pumping lives in `~/aimsight-libredesk/conversations/` (standard library, French, its own `.env` key, a guard test: `GET` only). The app reaches it through a new link `libredesk/` and calls `conversations/pompage.py` as `station.py` calls `extraction/pumping.py`; it lists the pumped folders and renders `transcript.md` safely (escaped, CSP, sandboxed frame, non-image attachments as downloads).
**Tech Stack:** Python 3 stdlib (`urllib`, `html.parser`, `unittest`) in aimsight-libredesk; FastAPI + `markdown` and React/Mantine in the app.
**Spec:** `docs/superpowers/specs/2026-11-18-conversations-tab-design.md`
## Global Constraints
- LibreDesk: only `GET`, only `/api/v1/conversations/all`, `/api/v1/conversations/{uuid}/messages`, and the `attachments[].url` the messages carry; never a URL found in a message's text.
- `Authorization: token <key>:<secret>` only to the LibreDesk host (`add_unredirected_header`, host compared as in `snippets/envoyer.py`); attachments on another host (S3) downloaded without it.
- Key: `LIBREDESK_LECTURE_KEY`, `LIBREDESK_LECTURE_SECRET` in `~/aimsight-libredesk/.env`; URL `LIBREDESK_URL`, default `https://helpdesk.sensima.ch`. Claude never reads a `.env`.
- Every conversation: all inboxes, all statuses, private notes included, no filter.
- `~/aimsight-libredesk`: standard library only, code/comments/commits in French. The app: English.
- Every time in UTC. Commits by path, never `git add -A`; each message ends with a blank line then `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Nothing pushed.
- Nothing committed in `~/aimsight-labeling` by this plan: the user commits `auto/conversations/` after looking at the first range.
## Review Focus
- An attachment name with `/`, `..`, or an empty name → stays inside `attachments/` (sanitized, uuid fallback). Test in Task 2.
- Two attachments with the same name in one conversation → both kept (second prefixed by its uuid). Test in Task 2.
- A `reference_number` that is not `[A-Za-z0-9_-]+` → folder named by the conversation's `uuid`. Test in Task 2.
- A pumping cut halfway (exception after some conversations) → `pumped.json` unchanged, the next run fetches the rest. Test in Task 2.
- A client mail with `<script>`, an `<img src=https://…>` pixel, or an `.svg`/`.html` attachment → shown as text, not loaded, downloaded rather than rendered. Test in Task 4.
---
### Task 0: Branches
- [ ] **Step 1:** `cd ~/aimsight-libredesk && git switch -c feat/conversations` (from `main`; the user's uncommitted `docs/architecture.drawio` stays untouched and uncommitted).
- [ ] **Step 2:** `cd ~/aimsight-app && git switch -c feat/conversations` (from `feat/weather-meteoswiss`, which carries the Support tab; the user's uncommitted `instructions/analyst.md` stays untouched).
### Task 1: The transcript (aimsight-libredesk)
**Files:**
- Create: `~/aimsight-libredesk/conversations/__init__.py` (empty), `~/aimsight-libredesk/conversations/transcript.py`
- Test: `~/aimsight-libredesk/tests/test_transcript.py`
**Interfaces:**
- Produces: `texte(contenu_html: str) -> str`; `transcript(conversation: dict, messages: list[dict]) -> str` (messages already in local form: `attachments[].url` = `attachments/<name>`, oldest first).
The format (exact):
```
# <subject> (#<reference_number>)
Contact : <first_name> <last_name> <email> · Boîte : <inbox_name> · Statut : <status> · Créée : <YYYY-MM-DD HH:MM> UTC
## <YYYY-MM-DD HH:MM> UTC — <author first_name last_name, or "Client"/"Agent"> (client | agent | note privée)
<text>
![<name>](attachments/<quoted name>)
[<name>](attachments/<quoted name>)
```
`activity` messages: one line `*<YYYY-MM-DD HH:MM> UTC — <text>*`. Role: `private` → `note privée`; else `sender_type == "contact"` → `client`; else `agent`. Image = `content_type` starting `image/` and not `image/svg+xml`. Link targets `urllib.parse.quote`d. Text: `text_content` if non-empty, else `texte(content)`.
- [ ] **Step 1: Write the failing tests**
```python
class TestTexte(unittest.TestCase):
def test_paragraphes_et_entites(self):
self.assertEqual(texte("<p>Bonjour&nbsp;&amp; merci</p><p>L1<br>L2</p>"), "Bonjour\xa0& merci\n\nL1\nL2")
def test_script_et_style_retires(self):
self.assertEqual(texte("<style>p{}</style><script>x()</script><div>ok</div>"), "ok")
def test_balise_echappee_reste_du_texte(self): # l'app échappe à l'affichage, pas ici
self.assertEqual(texte("&lt;script&gt;"), "<script>")
class TestTranscript(unittest.TestCase):
# CONV: subject "Saut", reference_number "42", contact Jean Dupont j@x.ch, inbox "Support", status "Open",
# created_at "2026-11-18T08:00:00Z"; MESSAGES: incoming contact at 08:00 with attachments photo 1.jpg (image/jpeg)
# and r.pdf, an activity at 08:05 "Assigned to Max", a private agent note at 08:10
def test_entete(self):
self.assertTrue(transcript(CONV, MESSAGES).startswith(
"# Saut (#42)\n\nContact : Jean Dupont j@x.ch · Boîte : Support · Statut : Open · Créée : 2026-11-18 08:00 UTC\n"))
def test_messages(self):
t = transcript(CONV, MESSAGES)
self.assertIn("## 2026-11-18 08:00 UTC — Jean Dupont (client)", t)
self.assertIn("![photo 1.jpg](attachments/photo%201.jpg)", t)
self.assertIn("[r.pdf](attachments/r.pdf)", t)
self.assertIn("*2026-11-18 08:05 UTC — Assigned to Max*", t)
self.assertIn("(note privée)", t)
def test_svg_en_lien(self): # an svg is a link, never an inline image
self.assertNotIn("![", transcript(CONV, [msg_with_attachment("a.svg", "image/svg+xml")]))
```
- [ ] **Step 2:** `cd ~/aimsight-libredesk && python3 -m unittest tests.test_transcript -v` → FAIL (`ModuleNotFoundError: conversations`).
- [ ] **Step 3:** Implement `texte` with `html.parser.HTMLParser` (newline at `br`; blank line around `p`, `div`, `li`, `tr`, `h1`–`h6`, `blockquote`; skip `script`/`style` data; collapse 3+ newlines to 2; strip), and `transcript` per the format above. Times through `datetime.fromisoformat(...).astimezone(timezone.utc)`.
- [ ] **Step 4:** Same command → PASS.
- [ ] **Step 5: Commit**
```bash
git add conversations/__init__.py conversations/transcript.py tests/test_transcript.py
git commit -m "Conversations : le transcript lisible d'une conversation (texte seul, pièces jointes en lien)"
```
### Task 2: The pumping (aimsight-libredesk)
**Files:**
- Create: `~/aimsight-libredesk/conversations/pomper.py`
- Modify: `~/aimsight-libredesk/tests/faux_libredesk.py` (only if a raw-bytes response needs another Content-Type; keep it backward compatible)
- Test: `~/aimsight-libredesk/tests/test_pomper.py`, `~/aimsight-libredesk/tests/test_garde_fou_conversations.py`
**Interfaces:**
- Consumes: `transcript(conversation, messages)` (Task 1).
- Produces:
- `class Lecteur(url: str, cle: str, secret: str)`: `conversations() -> Iterator[dict]` (pages of `/api/v1/conversations/all?page=N&page_size=100&order_by=updated_at&order=desc` until `page >= total_pages`), `messages(uuid: str) -> list[dict]` (every page of `/api/v1/conversations/{uuid}/messages?page=N&page_size=100`, then sorted by `created_at`), `telecharger(url: str, chemin: Path) -> None` (relative URL joined to `self.url`; header only if same scheme+host as `self.url`). HTTP errors raise (no `sys.exit` inside: the caller decides).
- `pomper(lecteur: Lecteur, sortie: Path, depuis: str | None = None, jusqu_a: str | None = None, journal=print) -> int` (number of conversations written).
- CLI: `python3 -m conversations.pomper --sortie <folder> [--depuis YYYY-MM-DD --jusqu-a YYYY-MM-DD]`, env `LIBREDESK_URL`, `LIBREDESK_LECTURE_KEY`, `LIBREDESK_LECTURE_SECRET`; exit 1 with a one-line message on a missing key or an HTTP error.
Rules of `pomper` (from the spec):
- No range: mark = `sortie/pumped.json` `{"until": ISO}`; walk `conversations()`, stop at the first with `updated_at < until - 1 h`; at the end only, write `{"until": <UTC time at the start of the run>}`. No file: walk everything.
- Range: skip `updated_at >= jusqu_a`, stop at `updated_at < depuis`; `pumped.json` untouched.
- Per conversation: folder = `reference_number` if `re.fullmatch(r"[A-Za-z0-9_-]+", str(ref))`, else `uuid`. Write `conversation.json` (without `previous_conversations`), `messages.json` (each `attachments[].url` replaced by `attachments/<local name>`, and that URL replaced in `content` too), `transcript.md`; JSON with `ensure_ascii=False, indent=1`.
- Attachment local name: `re.sub(r"[^\w.\- ]", "_", Path(name).name).strip(" .")`, empty → attachment `uuid`; already taken by another attachment of the conversation → `<uuid>_<name>`. Skip the download when the file exists with the same `size`.
- `journal` gets one line per conversation (`#<ref> <subject> : <n> messages, <k> pièces jointes`) and a closing total.
- [ ] **Step 1: Write the failing tests** (`setUp`: a `FauxLibreDesk` for LibreDesk, a second one as "S3"; helper `conv(ref, uuid, updated_at)`; `reponses[("GET", "/api/v1/conversations/all")]` = a callable paging on `?page=`)
```python
def test_tout_au_premier_pompage(self): # 3 conversations over 2 pages → 3 folders, pumped.json written
def test_incremental_s_arrete_sous_le_repere(self): # pumped.json until=10:00; convs at 12:00, 09:30, 08:00
# → 12:00 and 09:30 (margin 1 h) fetched, 08:00 not; messages of 08:00 never requested
def test_interrompu_le_repere_ne_bouge_pas(self): # messages of the 2nd conv answer 500 → raises, pumped.json unchanged
def test_plage_ne_touche_pas_le_repere(self): # depuis/jusqu_a: only the convs in range, pumped.json absent after
def test_pieces_jointes_locales(self):
# messages.json url == "attachments/photo.jpg", content's URL replaced, the file's bytes on disk
def test_nom_de_piece_jointe_assaini(self): # name "../../x.sh" → attachments/x.sh, inside the folder
def test_noms_en_double(self): # two "a.png" → a.png and <uuid>_a.png
def test_deja_telechargee_pas_de_requete(self): # second run, same size → no GET on /uploads/
def test_reference_bizarre_dossier_par_uuid(self): # reference_number "../42" → folder <uuid>
def test_cle_seulement_vers_libredesk(self):
# attachment url on the "S3" fake: downloaded, and no "Authorization" in its entetes; LibreDesk's entetes have it
def test_aucune_ecriture(self): # after a full run: self.faux.ecritures() == []
```
`test_garde_fou_conversations.py`, as `test_garde_fou_snippets.py`: in every `conversations/*.py`, the `/api/v1/...` routes ⊆ `{"/api/v1/conversations/all", "/api/v1/conversations/{uuid}/messages"}`; none of `"POST"`, `"PUT"`, `"DELETE"`, `"PATCH"`, `method=` appears; and `pomper.py` exists.
- [ ] **Step 2:** `python3 -m unittest tests.test_pomper tests.test_garde_fou_conversations -v` → FAIL (no `pomper`).
- [ ] **Step 3:** Implement `Lecteur`, `pomper` and the CLI in `conversations/pomper.py`; `urllib.request` with `timeout=60`.
- [ ] **Step 4:** `python3 -m unittest discover -s tests -v` → all PASS (the old tests too).
- [ ] **Step 5: Commit**
```bash
git add conversations/pomper.py tests/test_pomper.py tests/test_garde_fou_conversations.py tests/faux_libredesk.py
git commit -m "Conversations : le pompage en lecture seule (incrémental, pièces jointes, garde-fou GET)"
```
### Task 3: Launching it (aimsight-libredesk)
**Files:**
- Create: `~/aimsight-libredesk/conversations/pomper.sh` (executable), `~/aimsight-libredesk/conversations/pompage.py`
- Modify: `~/aimsight-libredesk/README.md`, `~/aimsight-libredesk/.vscode/tasks.json`, `~/aimsight-libredesk/.gitignore` (`out/`)
- Test: `~/aimsight-libredesk/tests/test_pompage.py`
**Interfaces:**
- Produces (imported by the app as a plain module, `sys.path` = `conversations/`; no package-relative import):
- `start(depuis: str, jusqu_a: str, sortie: str) -> subprocess.Popen`: `ValueError("a range: From and To, YYYY-MM-DD, From before To")` (the words of `extraction/pumping.py`, shown in the app as they are) if only one date, a date not `YYYY-MM-DD`, `depuis >= jusqu_a`, or `running()`; runs `[pomper.sh, "--sortie", sortie, *(["--depuis", depuis, "--jusqu-a", jusqu_a] if depuis else [])]`, cwd the repository root, stdio to `DEVNULL`.
- `running() -> bool`: `out/conversations.lock` held (`fcntl.flock` non-blocking, as `extraction/pumping.py`).
- `log(lines: int = 40) -> list[str]`: the end of `out/conversations.log`.
`pomper.sh`, modelled on `~/aimsight-data/extraction/pump.sh`: `mkdir -p out`, `flock -n` on `out/conversations.lock`, `=== <UTC> pomper <args>` and `=== <UTC> fin` around `(set -a +u && . ./.env && set +a -u && python3 -m conversations.pomper "$@")`, all `2>&1 | tee -a out/conversations.log`.
- [ ] **Step 1: Write the failing tests:** `start("2026-11-01", "", "/tmp/x")`, `start("2026-11-02", "2026-11-01", …)`, `start("1.11.2026", "2026-11-02", …)` raise `ValueError`; `running()` is `False` without a lock file; `log()` returns the last lines of a temporary `out/conversations.log` (point `pompage.ROOT` at a temp folder).
- [ ] **Step 2:** `python3 -m unittest tests.test_pompage -v` → FAIL.
- [ ] **Step 3:** Implement `pompage.py` and `pomper.sh`; `chmod +x conversations/pomper.sh`.
- [ ] **Step 4:** `python3 -m unittest discover -s tests -v` → PASS; `bash -n conversations/pomper.sh` → no output.
- [ ] **Step 5:** README: a section « Pomper les conversations » (what, where it writes, read-only, the agent « Lecture conversations » with only `conversations:read_all` and `messages:read`, the two `.env` lines, the command, the app's page); the line « Aucun code de ce dépôt n'écrit dans une conversation » stays true, add the guard test next to `test_garde_fou_base.py`'s mention. Task « Conversations : pomper » in `tasks.json` (`bash conversations/pomper.sh --sortie ~/aimsight-labeling/auto/conversations`).
- [ ] **Step 6: Commit**
```bash
git add conversations/pomper.sh conversations/pompage.py tests/test_pompage.py README.md .vscode/tasks.json .gitignore
git commit -m "Conversations : pomper.sh (.env, verrou, journal) et pompage.py, appelé par aimsight-app"
```
### Task 4: The server side (aimsight-app)
**Files:**
- Create: `app/server/conversations.py`
- Modify: `app/server/server.py` (routes, docstring), `app/server/check.py` (`check_conversations`, in `CHECKS`)
- Link: `ln -s ~/aimsight-libredesk libredesk` at the root (ignored: add `libredesk` to `.gitignore` next to the other links)
**Interfaces:**
- Consumes: `pompage.start/running/log` (Task 3).
- Produces (module `conversations`):
- `FOLDER = station.LABELS / "auto" / "conversations"`; `LIBREDESK = station.ROOT / "libredesk"`; `sys.path.insert(0, str(LIBREDESK / "conversations"))` then `import pompage`.
- `pump(body: dict) -> dict`: `pompage.start(body.get("start") or "", body.get("end") or "", str(FOLDER))`, `ValueError` → `station.Refusal`; returns `pump_state()`.
- `pump_state() -> {"running": bool, "log": list[str]}`.
- `list_conversations() -> list[dict]`: per folder with a `conversation.json`: `{"reference", "subject", "contact" (name, else email), "status", "last" (the last message's `created_at`, else `updated_at`), "messages" (count, `activity` excluded), "attachments" (count)}`, most recent `last` first.
- `transcript(reference: str, dark: bool) -> str`: `analysis._page(html.escape(text, quote=False), reference, dark)` of `analysis.file(reference, "transcript.md", FOLDER)`.
- `INLINE = {".png", ".jpg", ".jpeg", ".gif", ".webp"}`.
- Routes in `server.py`, a new section `# --- the Conversations page (conversations.py)`:
- `GET /api/conversations/pump` → `pump_state()`; `POST /api/conversations/pump` → `pump(body)`;
- `GET /api/conversations` → `list_conversations()`;
- `GET /api/conversations/{reference}/report.html` → `HTMLResponse(transcript(...), headers={"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'"})`;
- `GET /api/conversations/{reference}/{path:path}` → `f = analysis.file(reference, path, FOLDER)`; `FileResponse(f)` if `f.suffix.lower() in INLINE`, else `FileResponse(f, filename=f.name)` (attachment); both with `X-Content-Type-Options: nosniff`.
- [ ] **Step 1: Write `check_conversations`** (temp `FOLDER`, restored in `finally`): one folder `42/` with `conversation.json`, `messages.json` (2 messages, 1 activity), `attachments/p.png`, `attachments/x.svg`, and a `transcript.md` containing `<script>alert(1)</script>` and `![p](attachments/p.png)`. Assert:
```python
assert [c["reference"] for c in conversations.list_conversations()] == ["42"]
assert conversations.list_conversations()[0]["messages"] == 2
page = conversations.transcript("42", False)
assert "<script>" not in page and "&lt;script&gt;" in page and '<img alt="p" src="attachments/p.png"' in page
r = server.conversation_file("42", "attachments/x.svg")
assert r.headers["content-disposition"].startswith("attachment")
assert "content-disposition" not in server.conversation_file("42", "attachments/p.png").headers
assert "img-src 'self'" in server.conversation_transcript("42").headers["content-security-policy"]
refuses(conversations.transcript, "../analyses", False)
assert "From and To" in refuses(conversations.pump, {"start": "2026-11-01"}) # message of pompage's ValueError
```
(the last line launches nothing: `pompage.start` refuses before launching).
- [ ] **Step 2:** `.venv/bin/python app/server/check.py check_conversations` → FAIL.
- [ ] **Step 3:** Implement `conversations.py` and the routes (handler names `conversations_pump_state`, `conversations_pump`, `conversations_list`, `conversation_transcript(reference, dark=False)`, `conversation_file(reference, path)`).
- [ ] **Step 4:** `.venv/bin/python app/server/check.py` → every check `ok`.
- [ ] **Step 5: Commit**
```bash
git add app/server/conversations.py app/server/server.py app/server/check.py .gitignore docs/superpowers/specs/2026-11-18-conversations-tab-design.md docs/superpowers/plans/2026-11-18-conversations-tab.md
git commit -m "Conversations: pump LibreDesk through aimsight-libredesk, list and show the transcripts safely"
```
### Task 5: The page and the docs (aimsight-app)
**Files:**
- Create: `app/web/src/pages/Conversations.jsx`
- Modify: `app/web/src/App.jsx` (`PAGES` entry `["conversations", "Conversations", IconMessages]`, lazy import, render branch), `app/web/src/common.jsx` (move `Page` here from `Data.jsx`, exported; `Data.jsx` imports it), `README.md`, `app/README.md`, `CLAUDE.md`, `docs/architecture.drawio`
**Interfaces:**
- Consumes: the routes of Task 4; `call` and `Page` from `common.jsx`.
The page, modelled on `Stations.jsx`: title "Conversations" and a dimmed line ("The LibreDesk conversations, pumped read-only into labeling/auto/conversations/"); a card "Pump" with From/To (`type="date"`, empty by default), the button `Pump` (`loading` while running), the hint "Without dates: what changed since the last pumping; the first time, the whole history.", the log read every 2 s (`GET /api/conversations/pump`) in a `ScrollArea` + `Code block`; a card with a `TextInput` "Search" (subject, contact, reference; case-insensitive) and a `Table` (Reference, Subject, Contact, Status, Last message `YYYY-MM-DD HH:MM`, Messages, Attachments), the list read again when a pumping ends; a click on a row shows `<Page title="Transcript" src={`/api/conversations/${ref}/report.html?dark=${dark}`} />` under the table.
- [ ] **Step 1:** Implement; `cd app/web && npm run build` → builds without error.
- [ ] **Step 2:** Launch the server (`.venv/bin/python app/server/server.py`, or `systemctl --user restart aimsight-app` if the service runs) with the temp conversation of Task 4 copied into `labeling/auto/conversations/42/`; open `http://127.0.0.1:8770/#/conversations`: the row shows, the transcript shows its image and the `<script>` as text, `x.svg` downloads. Then remove `labeling/auto/conversations/42/`.
- [ ] **Step 3:** Docs: `app/README.md` a section "The Conversations page" (what it pumps, where, read-only, the key in `~/aimsight-libredesk/.env`, the protections); `README.md` the link `libredesk/` in the table and the `ln -s` line, a bullet for the page; `CLAUDE.md` the link in **The links**, a line in **The processes** (the Conversations page launches `libredesk/conversations/pomper.sh`, its output in `labeling/auto/conversations/<reference>/`) and in **The contracts** (`~/aimsight-libredesk/conversations/pompage.py`); `docs/architecture.drawio` a box "aimsight-libredesk" in the style of its neighbours (French, like the diagram), an arrow app → aimsight-libredesk ("pompage des conversations") and aimsight-libredesk → aimsight-labeling ("auto/conversations/").
- [ ] **Step 4:** `.venv/bin/python app/server/check.py` → all `ok`.
- [ ] **Step 5: Commit**
```bash
git add app/web/src/pages/Conversations.jsx app/web/src/App.jsx app/web/src/common.jsx app/web/src/pages/Data.jsx README.md app/README.md CLAUDE.md docs/architecture.drawio
git commit -m "Conversations page: pump, search, read the transcript; docs and the libredesk link"
```
### Task 6: The first real pumping (gated on the user)
- [ ] **Step 1:** The user creates in LibreDesk the agent « Lecture conversations », a role with only `conversations:read_all` and `messages:read`, its API key, and adds `export LIBREDESK_LECTURE_KEY=…` / `export LIBREDESK_LECTURE_SECRET=…` to `~/aimsight-libredesk/.env`. Wait for their word.
- [ ] **Step 2:** From the page, a range of the last 3 days. Check the log ends with `=== … fin` and no error; open two transcripts.
- [ ] **Step 3:** On one `messages.json`, confirm the attachment fields (`name`, `content_type`, `size`, `url`, `uuid`) and whether `updated_at` moved with the last message; if a field differs, fix `pomper.py` and the fake data of `test_pomper.py`, rerun the tests, commit in aimsight-libredesk.
- [ ] **Step 4:** Hand over to the user: the folders to look at, and that the whole history (Pump without dates) is for a quiet hour, then their commit of `auto/conversations/` in `~/aimsight-labeling`.
@@ -0,0 +1,63 @@
# The Conversations tab: pumping the LibreDesk conversations
2026-11-18. Two repositories: `~/aimsight-libredesk` (the pumping) and `aimsight-app` (the tab).
## Intent
The client requests arrive by mail in LibreDesk (`helpdesk.sensima.ch`, v2.9.0). The user wants their conversations on the workstation, in full (the messages, the inline images, the attachments), for two uses: to help the support (a conversation read next to the station's data, the analyses and the support answers), and as training data. Nothing is ever written to LibreDesk.
## Goals, non-goals, anti-goals
- **Goals**: a **Conversations** page in the app that pumps the conversations on demand and shows them; each conversation stored in `labeling/auto/conversations/<reference>/`, committed in `~/aimsight-labeling` like the analyses and the support answers; the second pumping fetches only what changed.
- **Non-goals (for now)**: linking a conversation to its stations (later: `acces/` of `~/aimsight-libredesk` maps a contact's e-mail to its serials); teaching the support agent to read `labeling/auto/conversations/` (`agents/agents/support.md`, a later change in `~/aimsight-agents`); turning the conversations into a training set (a later step; the raw material comes first); a scheduled pumping.
- **Anti-goals**: any request to LibreDesk other than a `GET`; the API key passing through the app or read by Claude; the HTML of a client's mail rendered as HTML in the page (a mail can carry scripts or tracking pixels).
## Constraints
- Read-only on LibreDesk, enforced by a guard test in `~/aimsight-libredesk`, like `tests/test_garde_fou_snippets.py` for the snippets.
- The key: a dedicated LibreDesk agent "Lecture conversations" whose role has only `conversations:read_all` and `messages:read`, created by the user; its key and secret in `~/aimsight-libredesk/.env` (`LIBREDESK_LECTURE_KEY`, `LIBREDESK_LECTURE_SECRET`), never read by Claude. The `Authorization: token <key>:<secret>` header goes only to the LibreDesk host (`add_unredirected_header`, as in `snippets/envoyer.py`).
- Standard library only in `~/aimsight-libredesk` (its rule); its code and docs in French (its language); the app in English.
- The app holds no domain logic: it calls the pumping of `~/aimsight-libredesk` as it calls `extraction/pumping.py` of `~/aimsight-data`.
- Every conversation, by the user's decision: all the inboxes, all the statuses, no filter.
- Committed in git, by the user's decision: the contacts' names and e-mails, and the attachments, go into the history of `~/aimsight-labeling`.
- Every time in UTC.
## Approaches
- **A. The pumping in `~/aimsight-libredesk`, called by the app** (chosen): all the LibreDesk code in one repository, the key never in the app, the guard test next to the existing one. Costs: two repositories touched, one more link in the app.
- **B. Everything in the app** (`app/server/conversations.py`): shorter, one repository; but the app would carry LibreDesk's logic and the API key, which the rule of the repository forbids.
- Dropped: a `claude` agent that pumps: too heavy for a download.
## The design
### `~/aimsight-libredesk/conversations/` (French)
- `pomper.py`: the client restricted to three routes, all `GET`: `/api/v1/conversations/all` (`page`, `page_size` up to 500, `order_by=updated_at`, `order=desc`), `/api/v1/conversations/{uuid}/messages` (every page, private notes included), and the attachment URLs that the messages carry (`attachments[].url`, signed: `/uploads/{uuid}?…` on LibreDesk, or a bucket's host if production stores in S3), downloaded wherever they point, the `Authorization` header only to the LibreDesk host; never a URL found in a message's text. `python3 -m conversations.pomper [--depuis YYYY-MM-DD --jusqu-a YYYY-MM-DD] --sortie <folder>`.
- **Incremental by default**: `<sortie>/pumped.json` (`{"until": <UTC time>}`, committed with the conversations) holds the start time of the last pumping that **completed**; a run walks the list from the most recently updated and stops below that mark (minus an hour of margin), and writes the new mark only at its end: a run cut short is caught up by the next one. No mark: the whole history. With `--depuis/--jusqu-a`, the conversations updated in that range (`--jusqu-a` excluded), stored ones fetched again; the mark untouched. *(Builder's call.)*
- A conversation is fetched in full each time it changed: `conversation.json` and `messages.json` rewritten, attachments already present not downloaded again (same name and size).
- `pomper.sh`: loads `.env` (`set -a`, as `extraction/pump.sh`), one pumping at a time (`flock` on `out/conversations.lock`), output appended to `out/conversations.log`.
- `pompage.py`: what the app calls, the twin of `extraction/pumping.py`: `start(depuis, jusqu_a, sortie)` → the process, `running()`, `log(lines)`.
- Tests (`tests/`, `unittest`, the fake server `tests/faux_libredesk.py` extended): only `GET`, the key never sent to another host, the incremental stop, the transcript (below), an attachment re-download skipped.
### One conversation: `labeling/auto/conversations/<reference_number>/`
- `conversation.json`: the conversation as the API gives it (subject, status, contact, inbox, dates, tags), `previous_conversations` removed.
- `messages.json`: the messages as the API gives them, the oldest first, attachment URLs replaced by their local path (`attachments/<name>`; a signed URL expires).
- `attachments/`: the files, under their name (a duplicate name prefixed by the attachment's uuid).
- `transcript.md`: the readable thread, written from `messages.json`: per message, a heading `## <UTC time> — <author> (<client | agent | private note>)`, the text (`text_content`, or the HTML reduced to text: tags removed, entities decoded, paragraphs kept), the images as `![name](attachments/<name>)`, the other attachments as links. The `activity` messages (assignments, status changes) on one line in italics. No raw HTML in it.
### The app: the **Conversations** page
- A link `libredesk/` → `~/aimsight-libredesk` (ignored by git, in the README's table and install line, and in `CLAUDE.md`'s links).
- `app/server/conversations.py`: imports `pompage` (as `station.py` imports `pumping`); `pump(body)` (optional From/To), `pump_state()` (`running`, `log`), `list()` (each folder of `labeling/auto/conversations/`: reference, subject, contact name, status, last message time, message and attachment counts, read from `conversation.json`/`messages.json`), `transcript(reference, dark)` (`transcript.md` HTML-escaped **before** Markdown, so a client's `<script>` stays text; the page sent with `Content-Security-Policy: default-src 'none'; img-src 'self'; style-src 'unsafe-inline'`: no script, no remote image or tracking pixel), and the files of the folder through `analysis.file(…, FOLDER)`, images inline, any other attachment as a download (`Content-Disposition: attachment`: an `.html` or `.svg` attachment never runs at the app's address). The frame of the transcript sandboxed. *(Builder's call: the protection in the app, `transcript.md` stays plain readable text for the agents and the training.)*
- `server.py`: `GET/POST /api/conversations/pump`, `GET /api/conversations`, `GET /api/conversations/{reference}/report.html`, `GET /api/conversations/{reference}/{path}`.
- `web/src/pages/Conversations.jsx`, a page of the header next to Data and Stations: a card "Pump" (From/To optional, empty: what changed since the last pumping; the button; the end of the log read every 2 s), a table of the pumped conversations (the most recent first, a search field on subject and contact), a click shows its transcript in a frame, as the report of an analysis.
- `check.py`: the list and the transcript on a temporary folder, without LibreDesk.
- Docs: `app/README.md` (the page), `README.md` (the link, the tab), `docs/architecture.drawio` (the arrow app → aimsight-libredesk → labeling); `~/aimsight-libredesk/README.md` (the pumping, the key's role).
## Left to the builder
- The exact fields of an attachment in v2.9.0 (`name`, `content_type`, `size`, `url`, `content_id` expected): confirm on the first real response; the fake server follows it.
- Whether `updated_at` moves on a new message; if not, compare `last_message_at` as well.
- The commit in `~/aimsight-labeling` after a pumping: by the user, by path (`auto/conversations/`), not by the app.
- The order of the work: everything against the fake server first; then the user creates the read-only agent and puts its key in `.env`; then a first real pumping on a short range (Claude may launch it: the key stays in the subprocess), which settles the two points above; the whole history after, at a quiet hour. Nothing committed in `~/aimsight-labeling` before the user has looked at that first range.