Files
aimsight-app/docs/superpowers/plans/2026-11-18-conversations-tab.md
T

258 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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_API_KEY`, `LIBREDESK_API_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_API_KEY`, `LIBREDESK_API_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_API_KEY=…` / `export LIBREDESK_API_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`.