22 KiB
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 theattachments[].urlthe 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 insnippets/envoyer.py); attachments on another host (S3) downloaded without it.- Key:
LIBREDESK_API_KEY,LIBREDESK_API_SECRETin~/aimsight-libredesk/.env; URLLIBREDESK_URL, defaulthttps://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 thenCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>. Nothing pushed. - Nothing committed in
~/aimsight-labelingby this plan: the user commitsauto/conversations/after looking at the first range.
Review Focus
- An attachment name with
/,.., or an empty name → stays insideattachments/(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_numberthat is not[A-Za-z0-9_-]+→ folder named by the conversation'suuid. Test in Task 2. - A pumping cut halfway (exception after some conversations) →
pumped.jsonunchanged, the next run fetches the rest. Test in Task 2. - A client mail with
<script>, an<img src=https://…>pixel, or an.svg/.htmlattachment → 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(frommain; the user's uncommitteddocs/architecture.drawiostays untouched and uncommitted). - Step 2:
cd ~/aimsight-app && git switch -c feat/conversations(fromfeat/weather-meteoswiss, which carries the Support tab; the user's uncommittedinstructions/analyst.mdstays 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>)
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.quoted. Text: text_content if non-empty, else texte(content).
- Step 1: Write the failing tests
class TestTexte(unittest.TestCase):
def test_paragraphes_et_entites(self):
self.assertEqual(texte("<p>Bonjour & 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("<script>"), "<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("", 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
textewithhtml.parser.HTMLParser(newline atbr; blank line aroundp,div,li,tr,h1–h6,blockquote; skipscript/styledata; collapse 3+ newlines to 2; strip), andtranscriptper the format above. Times throughdatetime.fromisoformat(...).astimezone(timezone.utc). - Step 4: Same command → PASS.
- Step 5: Commit
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=descuntilpage >= total_pages),messages(uuid: str) -> list[dict](every page of/api/v1/conversations/{uuid}/messages?page=N&page_size=100, then sorted bycreated_at),telecharger(url: str, chemin: Path) -> None(relative URL joined toself.url; header only if same scheme+host asself.url). HTTP errors raise (nosys.exitinside: 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], envLIBREDESK_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}; walkconversations(), stop at the first withupdated_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 atupdated_at < depuis;pumped.jsonuntouched. -
Per conversation: folder =
reference_numberifre.fullmatch(r"[A-Za-z0-9_-]+", str(ref)), elseuuid. Writeconversation.json(withoutprevious_conversations),messages.json(eachattachments[].urlreplaced byattachments/<local name>, and that URL replaced incontenttoo),transcript.md; JSON withensure_ascii=False, indent=1. -
Attachment local name:
re.sub(r"[^\w.\- ]", "_", Path(name).name).strip(" ."), empty → attachmentuuid; already taken by another attachment of the conversation →<uuid>_<name>. Skip the download when the file exists with the samesize. -
journalgets one line per conversation (#<ref> <subject> : <n> messages, <k> pièces jointes) and a closing total. -
Step 1: Write the failing tests (
setUp: aFauxLibreDeskfor LibreDesk, a second one as "S3"; helperconv(ref, uuid, updated_at);reponses[("GET", "/api/v1/conversations/all")]= a callable paging on?page=)
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 (nopomper). - Step 3: Implement
Lecteur,pomperand the CLI inconversations/pomper.py;urllib.requestwithtimeout=60. - Step 4:
python3 -m unittest discover -s tests -v→ all PASS (the old tests too). - Step 5: Commit
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 ofextraction/pumping.py, shown in the app as they are) if only one date, a date notYYYY-MM-DD,depuis >= jusqu_a, orrunning(); runs[pomper.sh, "--sortie", sortie, *(["--depuis", depuis, "--jusqu-a", jusqu_a] if depuis else [])], cwd the repository root, stdio toDEVNULL.running() -> bool:out/conversations.lockheld (fcntl.flocknon-blocking, asextraction/pumping.py).log(lines: int = 40) -> list[str]: the end ofout/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", …)raiseValueError;running()isFalsewithout a lock file;log()returns the last lines of a temporaryout/conversations.log(pointpompage.ROOTat a temp folder). - Step 2:
python3 -m unittest tests.test_pompage -v→ FAIL. - Step 3: Implement
pompage.pyandpomper.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_allandmessages:read, the two.envlines, 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 totest_garde_fou_base.py's mention. Task « Conversations : pomper » intasks.json(bash conversations/pomper.sh --sortie ~/aimsight-labeling/auto/conversations). - Step 6: Commit
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, inCHECKS) - Link:
ln -s ~/aimsight-libredesk libredeskat the root (ignored: addlibredeskto.gitignorenext 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"))thenimport pompage.pump(body: dict) -> dict:pompage.start(body.get("start") or "", body.get("end") or "", str(FOLDER)),ValueError→station.Refusal; returnspump_state().pump_state() -> {"running": bool, "log": list[str]}.list_conversations() -> list[dict]: per folder with aconversation.json:{"reference", "subject", "contact" (name, else email), "status", "last" (the last message'screated_at, elseupdated_at), "messages" (count,activityexcluded), "attachments" (count)}, most recentlastfirst.transcript(reference: str, dark: bool) -> str:analysis._page(html.escape(text, quote=False), reference, dark)ofanalysis.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)iff.suffix.lower() in INLINE, elseFileResponse(f, filename=f.name)(attachment); both withX-Content-Type-Options: nosniff.
-
Step 1: Write
check_conversations(tempFOLDER, restored infinally): one folder42/withconversation.json,messages.json(2 messages, 1 activity),attachments/p.png,attachments/x.svg, and atranscript.mdcontaining<script>alert(1)</script>and. Assert:
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 "<script>" 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.pyand the routes (handler namesconversations_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 checkok. - Step 5: Commit
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(PAGESentry["conversations", "Conversations", IconMessages], lazy import, render branch),app/web/src/common.jsx(movePagehere fromData.jsx, exported;Data.jsximports it),README.md,app/README.md,CLAUDE.md,docs/architecture.drawio
Interfaces:
- Consumes: the routes of Task 4;
callandPagefromcommon.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, orsystemctl --user restart aimsight-appif the service runs) with the temp conversation of Task 4 copied intolabeling/auto/conversations/42/; openhttp://127.0.0.1:8770/#/conversations: the row shows, the transcript shows its image and the<script>as text,x.svgdownloads. Then removelabeling/auto/conversations/42/. - Step 3: Docs:
app/README.mda section "The Conversations page" (what it pumps, where, read-only, the key in~/aimsight-libredesk/.env, the protections);README.mdthe linklibredesk/in the table and theln -sline, a bullet for the page;CLAUDE.mdthe link in The links, a line in The processes (the Conversations page launcheslibredesk/conversations/pomper.sh, its output inlabeling/auto/conversations/<reference>/) and in The contracts (~/aimsight-libredesk/conversations/pompage.py);docs/architecture.drawioa 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→ allok. - Step 5: Commit
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_allandmessages:read, its API key, and addsexport 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
=== … finand no error; open two transcripts. - Step 3: On one
messages.json, confirm the attachment fields (name,content_type,size,url,uuid) and whetherupdated_atmoved with the last message; if a field differs, fixpomper.pyand the fake data oftest_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.