feat(web): "Assistants IA" page (tokens, connection help, action journal) (#205) #218

Open
maximus wants to merge 10 commits from issue-205-assistants-page into issue-204-mcp-list-tag-tools
28 changed files with 3043 additions and 62 deletions

View file

@ -83,16 +83,16 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
### Authentification
- L'identité vient de Logto (`auth.lacompagniemaximus.com`), et l'identifiant d'un compte est le `sub` Logto, partagé par toutes les apps du parc : jamais l'email ni un identifiant local. — `web/src/lib/auth.ts`, `web/src/db/migrations/0001_change_user_id_to_text.sql`
- Le middleware laisse passer **toute** requête `/api/*` qui porte un en-tête `Authorization: Bearer …`, sans vérifier le jeton : chaque route d'API appelle `requireAuth()` en premier, qui valide le jeton auprès de `/oidc/me` ; les routes de gestion des jetons d'agent appellent à sa place `requireAssistantsSession()`, plus stricte (voir plus bas). Une route qui n'appelle aucune de ces deux gardes est ouverte à quiconque envoie un `Bearer` quelconque. — `web/src/middleware.ts`, `web/src/lib/api.ts`, `web/src/lib/agentAccess.ts`
- Six routes n'appellent ni `requireAuth()` ni `requireAssistantsSession()`, et c'est voulu : `/api/health` (sonde, `SELECT 1`, ne renvoie aucune donnée) et `/api/logto/{sign-in,callback,sign-out}` (le flux de connexion lui-même) sont exclues du middleware ; `/api/debug` lit la session par `getLogtoContext` et ne renvoie que les données de l'appelant ; `/api/mcp` s'authentifie elle-même par `verifyAgentToken`, puis contrôle le pilote (`mcpAllowed`) : elle n'accepte qu'un jeton d'agent, et ces deux gardes lui ouvriraient ce qu'elle refuse, un cookie de session ou un jeton Logto (puce suivante). Aucune n'est un modèle pour une route qui lit ou écrit des données : une septième route sans l'une de ces deux gardes se justifie dans la PR. — `web/src/middleware.ts` (`config.matcher`), `web/src/app/api/health/route.ts`, `web/src/app/api/logto/`, `web/src/app/api/debug/route.ts`, `web/src/app/api/mcp/route.ts`
- Le middleware laisse passer **toute** requête `/api/*` qui porte un en-tête `Authorization: Bearer …`, sans vérifier le jeton : chaque route d'API appelle `requireAuth()` en premier, qui valide le jeton auprès de `/oidc/me` ; les routes de gestion des jetons d'agent et la route du journal des assistants appellent à sa place `requireAssistantsSession()`, plus stricte, ou, pour la révocation seule, `requireSiteSession()`, la même sans le contrôle du pilote (voir plus bas). Une route qui n'appelle aucune de ces trois gardes est ouverte à quiconque envoie un `Bearer` quelconque. — `web/src/middleware.ts`, `web/src/lib/api.ts`, `web/src/lib/agentAccess.ts`
- Six routes n'appellent ni `requireAuth()`, ni `requireAssistantsSession()`, ni `requireSiteSession()`, et c'est voulu : `/api/health` (sonde, `SELECT 1`, ne renvoie aucune donnée) et `/api/logto/{sign-in,callback,sign-out}` (le flux de connexion lui-même) sont exclues du middleware ; `/api/debug` lit la session par `getLogtoContext` et ne renvoie que les données de l'appelant ; `/api/mcp` s'authentifie elle-même par `verifyAgentToken`, puis contrôle le pilote (`mcpAllowed`) : elle n'accepte qu'un jeton d'agent, et ces deux gardes lui ouvriraient ce qu'elle refuse, un cookie de session ou un jeton Logto (puce suivante). Aucune n'est un modèle pour une route qui lit ou écrit des données : une septième route sans l'une de ces trois gardes se justifie dans la PR. — `web/src/middleware.ts` (`config.matcher`), `web/src/app/api/health/route.ts`, `web/src/app/api/logto/`, `web/src/app/api/debug/route.ts`, `web/src/app/api/mcp/route.ts`
- `POST /api/mcp` (seule méthode exportée, aucun en-tête CORS) sert le compte d'un jeton d'agent à un assistant IA. Ses contrôles se suivent dans cet ordre, et une requête refusée par l'un n'atteint pas le suivant : un en-tête `Origin` présent et hors de `ALLOWED_ORIGINS` répond 403 (un client qui n'est pas un navigateur n'en envoie pas, et continue) ; `verifyAgentToken` répond 401 `{ "error": "unauthorized" }` avec `WWW-Authenticate: Bearer`, sans métadonnée OAuth, parce qu'un client tenterait une connexion OAuth qui n'existe pas encore ; `mcpAllowed` répond 403 hors pilote, jeton valide compris ; la limite `mcp-http` répond 429 avec `Retry-After` ; puis le gestionnaire du SDK reçoit `authInfo`, qui porte le compte du jeton et jamais sa valeur (`token: ''`). La session n'est jamais lue. Le middleware laisse passer le chemin exact `/api/mcp` sans cookie ni `Bearer`, pour qu'un client sans jeton reçoive ce 401 et non une redirection vers `/auth` ; le chemin reste couvert par `config.matcher`. Une exception levée avant le gestionnaire répond 500 `{ "error": "internal_error" }`. Les lignes de journal du serveur (`at: 'mcp'` par requête, `'mcp-tool'` par appel d'outil, `'mcp-sdk'` pour une erreur que le SDK signale) portent un statut, une durée, l'identifiant du jeton, la méthode JSON-RPC quand elle a la forme d'un nom de méthode, le nom de l'outil, son code d'issue et le nom de classe d'une exception : jamais la valeur du jeton, le `sub`, un titre, une note ni un nom. Chaque test de `route.test.ts` se termine par ce contrôle, sur tout ce qu'il a reçu et journalisé. — `web/src/app/api/mcp/route.ts`, `web/src/lib/mcp/server.ts`, `web/src/middleware.ts`, `web/src/middleware.test.ts`, `web/src/app/api/mcp/route.test.ts`, #202
- Côté web, le middleware ne teste que la présence d'un cookie `logto_*`, pas sa validité : une page ou une route qui lit des données passe par `getAuthenticatedUser()` ou `requireAuth()`. — `web/src/middleware.ts`, `web/src/lib/auth.ts`
- L'app mobile s'authentifie par le client natif `sl-mobile-native`, avec la redirection `simplliste://callback` : changer le `scheme` d'`app.json` casse la connexion de toutes les installations. Le jeton n'est jamais persisté par l'app : `authToken.ts` garde une référence au `getAccessToken` du SDK. — `src/lib/logtoConfig.ts`, `src/lib/authToken.ts`, `app.json`
- Un identifiant reçu par une route (`app/task/[id].tsx`, `app/list/[id].tsx`, `app/task/new.tsx`) ou par une action du widget est validé par `isValidUUID` avant toute requête. — `src/lib/validation.ts`, `src/widgets/widgetTaskHandler.ts`
- Jetons d'agent : un assistant IA se relie à un compte par un jeton personnel, `slmcp_` suivi de 43 caractères base64url (32 octets aléatoires). La base n'en garde que l'empreinte SHA-256 et les quatre derniers caractères (`token_hash`, `hint`) : la valeur n'existe que dans la réponse du `POST /api/agent-tokens` qui la crée (`Cache-Control: no-store`), elle n'est ni journalisée, ni relue, ni renvoyée ailleurs. Aucune réponse ne porte l'empreinte ni le `sub` : `createAgentToken` et `listAgentTokens` nomment leurs colonnes, une colonne ajoutée à `sl_agent_tokens` n'apparaît dans une réponse que si elle y est nommée. Dix jetons au plus par compte, expirés compris, comptés puis insérés sous `lockAccount` (verrou consultatif de transaction par compte, première instruction de la transaction) ; révoquer supprime la ligne, et un identifiant d'un autre compte répond comme un identifiant inconnu. — `web/src/lib/agentTokens.ts`, `web/src/lib/accountLock.ts`, `web/src/app/api/agent-tokens/route.ts`, `web/src/app/api/agent-tokens/[id]/route.ts`, `web/src/app/api/agent-tokens/route.test.ts`, #199, #200
- Un jeton d'agent n'est accepté par aucune route existante : `requireAuth()` répond 401 à tout `Bearer` qui commence par `slmcp_`, avant tout appel à Logto, pour que la valeur ne quitte pas le companion. Ce refus se teste sur le vrai `requireAuth` (`api.test.ts`) et sur la vraie route `/api/sync` (`sync/agentToken.test.ts`), parce que tous les autres tests de route remplacent `requireAuth`. `verifyAgentToken`, que seule la route MCP appelle (#202), n'accepte que la forme exacte `Bearer slmcp_` suivie de 43 caractères base64url, lit la ligne par l'empreinte, refuse un jeton dès l'instant de son expiration et écrit `last_used_at` au plus une fois par minute, par un seul `UPDATE` conditionnel. Elle ne contrôle pas le pilote : la route qui l'appelle enchaîne `mcpAllowed`, pour que la future vérification OAuth passe par le même interrupteur. — `web/src/lib/api.ts`, `web/src/lib/agentTokens.ts`, `web/src/lib/api.test.ts`, `web/src/app/api/sync/agentToken.test.ts`, #200
- Les routes qui gèrent les jetons d'agent (`GET` et `POST /api/agent-tokens`, `DELETE /api/agent-tokens/[id]`) n'acceptent que la session du site (décision de Max du 2026-11-14) : derrière `requireAuth()`, un jeton de connexion Logto de courte durée, celui de l'app mobile ou d'une autre app du parc, suffirait à créer un jeton d'agent sans expiration. `requireAssistantsSession()` répond donc, dans cet ordre : 401 à tout en-tête `Authorization`, quel qu'il soit, avant toute autre chose ; 401 sans session ; 404 hors pilote. La route enchaîne la limite de débit, puis, pour une écriture, l'en-tête `Origin`, puis le corps. Une route qui gère les jetons ou lit le journal des assistants passe par cette garde, jamais par `requireAuth()`, et cet ordre ne s'assouplit pas. — `web/src/lib/agentAccess.ts`, `web/src/app/api/agent-tokens/route.ts`, `web/src/app/api/agent-tokens/[id]/route.ts`, `web/src/lib/agentAccess.test.ts`, `DECISIONS.md` « Assistants IA (MCP) », #200
- Pilote : `mcpAllowed(userId)` lit `MCP_ALLOWED_SUBS` à chaque appel. Absente ou vide : personne, pour qu'un oubli de variable au déploiement n'ouvre rien. `*` seul : tous les comptes. Sinon une liste de `sub` séparés par des virgules, espaces ignorés, où `*` n'ouvre rien. Vider la variable et redémarrer le conteneur ferme tout : c'est l'interrupteur d'urgence. Aucun `sub` n'est écrit dans le dépôt, ni dans un test. — `web/src/lib/agentAccess.ts`, `web/.env.template`, `web/src/lib/agentAccess.test.ts`, #200
- Les routes qui gèrent les jetons d'agent (`GET` et `POST /api/agent-tokens`, `DELETE /api/agent-tokens/[id]`) et celle qui lit le journal des assistants (`GET /api/agent-actions`, #205 : après la limite de débit, elle valide le curseur `?before=` et répond 400 s'il n'en est pas un) n'acceptent que la session du site (décision de Max du 2026-11-14) : derrière `requireAuth()`, un jeton de connexion Logto de courte durée, celui de l'app mobile ou d'une autre app du parc, suffirait à créer un jeton d'agent sans expiration. `requireAssistantsSession()` répond donc, dans cet ordre : 401 à tout en-tête `Authorization`, quel qu'il soit, avant toute autre chose ; 401 sans session ; 404 hors pilote. La route enchaîne la limite de débit, puis, pour une écriture, l'en-tête `Origin`, puis le corps. Une route qui gère les jetons ou lit le journal des assistants passe par cette garde, jamais par `requireAuth()`, et cet ordre ne s'assouplit pas. Une seule exception, voulue : `DELETE /api/agent-tokens/[id]` passe par `requireSiteSession()`, les deux premiers contrôles sans le troisième, pour qu'une révocation prenne effet même pilote fermé (décision de Max du 2026-11-19) : une page ouverte avant la coupure révoque encore, au lieu de recevoir un 404 qu'elle prendrait pour « déjà révoqué ». Le compte, l'`Origin` et la limite de débit restent contrôlés. — `web/src/lib/agentAccess.ts`, `web/src/app/api/agent-tokens/route.ts`, `web/src/app/api/agent-tokens/[id]/route.ts`, `web/src/app/api/agent-tokens/route.test.ts`, `web/src/app/api/agent-actions/route.ts`, `web/src/app/api/agent-actions/route.test.ts`, `web/src/lib/agentAccess.test.ts`, `DECISIONS.md` « Assistants IA (MCP) », #200, #205
- Pilote : `mcpAllowed(userId)` lit `MCP_ALLOWED_SUBS` à chaque appel. Absente ou vide : personne, pour qu'un oubli de variable au déploiement n'ouvre rien. `*` seul : tous les comptes. Sinon une liste de `sub` séparés par des virgules, espaces ignorés, où `*` n'ouvre rien. Vider la variable et redémarrer le conteneur ferme tout, sauf la révocation d'un jeton : c'est l'interrupteur d'urgence. Aucun `sub` n'est écrit dans le dépôt, ni dans un test. — `web/src/lib/agentAccess.ts`, `web/.env.template`, `web/src/lib/agentAccess.test.ts`, #200
- Origines : une seule liste, `ALLOWED_ORIGINS` de `origin.ts`, lue par la montée du WebSocket et par les écritures faites avec la session du site (`isAllowedOrigin` ; en-tête `Origin` exigé sur `POST /api/agent-tokens` et `DELETE /api/agent-tokens/[id]`, 403 sinon). Aucun contrôle d'origine ne se compare à `request.url` : en production son origine est celle du conteneur (`0.0.0.0:3000`), et les tests de route envoient leurs requêtes à cet hôte. `origin.ts` reste sans import : `server.ts` l'embarque avec `ws.ts`, dans un bundle à part des routes. — `web/src/lib/origin.ts`, `web/src/lib/ws.ts`, `web/src/lib/origin.test.ts`, `web/Dockerfile`, #200
### API et isolation des comptes
@ -113,7 +113,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
- Tout outil MCP se déclare par `register()` de `server.ts`, qui le place dans l'enveloppe commune ; aucun outil ne s'enregistre directement auprès du SDK, qui rendrait au modèle le message d'une exception (une erreur de drizzle porte la requête SQL et ses paramètres, dont le `sub`). Un refus voulu est une `ToolRefusal`, qui porte un code de `errors.ts` : le modèle lit `{ "error": "<code>", "message": "<message fixe>" }` dans un résultat `isError`, jamais une erreur JSON-RPC, et un message ne cite ni la requête ni la base. Toute autre exception devient `internal_error`, et le journal n'en garde que le nom de classe. Un succès rend `structuredContent` et le même objet en texte JSON, mis en forme par `shape.ts`, qui nomme chaque colonne : `user_id` et `deleted_at` n'y figurent jamais, et une colonne ajoutée à une table n'atteint un modèle que si elle y est nommée. Une ligne supprimée et une ligne d'un autre compte répondent comme une ligne inconnue (`not_found`, `list_not_found`). — `web/src/lib/mcp/server.ts`, `web/src/lib/mcp/errors.ts`, `web/src/lib/mcp/shape.ts`, `web/src/lib/mcp/readTools.ts`, `web/src/app/api/mcp/route.test.ts`, #202
- Lectures de compte des outils MCP : `readTools.ts` ne lance aucune requête à lui, il met en forme ce que rendent `queryAccountTasks`, `loadAccountTask`, `loadAccountLists`, `loadOpenTaskCounts`, `loadSubtasks`, `loadTaskTags` et `loadAccountTags`. `queryAccountTasks` et `loadAccountTask` filtrent une tâche deux fois sur le compte, par `sl_tasks.user_id` et par sa liste, qui doit être une liste active du compte ; les tests écrivent les lignes que la sync n'écrit jamais (une tâche d'un compte dans la liste d'un autre), pour que chaque filtre tombe seul sous sa mutation. `list_tasks` suit un ordre total, l'instant de création coupé à la milliseconde puis l'identifiant, et son curseur porte cette clé : `created_at` garde des microsecondes en base et une `Date` de JavaScript des millisecondes, un curseur comparé à la colonne brute rendrait deux fois la même ligne. Les bornes `due_before` et `due_after` sont incluses et passent par `dueDateSchema` (une date seule vaut 12:00 UTC) ; les filtres portent sur les tâches de premier niveau. — `web/src/lib/taskQueries.ts`, `web/src/lib/taskQueries.test.ts`, `web/src/lib/mcp/readTools.ts`, #202
- Écritures des outils MCP : les neuf outils d'écriture (`create_task`, `update_task`, `complete_task`, `reopen_task`, `set_task_tags`, et depuis #204 `create_list`, `update_list`, `create_tag`, `update_tag`) ne sont enregistrés que pour un jeton « Lecture et écriture », qui voit donc treize outils, et aucun ne supprime une tâche, une liste ni une étiquette (décision de Max du 2026-11-14) : `writeTools.ts` ne contient aucun `.delete(`, et le seul `delete` de `taskWrites.ts` porte sur `sl_task_tags`. Chacun se déclare par `registerWriteTool`, l'enveloppe unique des écritures, placée dans celle de tous les outils (`register`, limite `mcp-write`) : une transaction, l'appel d'une fonction de `taskWrites.ts`, puis, si elle a écrit (`changed`), la ligne de journal dans cette même transaction (`recordAction`, `entity_type` `task`, `list` ou `tag`) ; après le commit seulement, un seul `notifyUserChanged`, puis la réponse : une tâche relue par `renderTask`, une liste ou une étiquette mise en forme comme `list_lists` et `list_tags` les rendent (`shapeList`, `shapeTag`). Une insertion de journal qui échoue annule l'écriture : c'est le cas d'un jeton révoqué pendant sa requête, dont la ligne que vise `token_id` n'existe plus (`23503`) ; l'outil répond alors `internal_error`, et l'appel suivant reçoit 401. Un appel sans effet (`complete_task` rejoué, `reopen_task` sur une tâche ouverte, `set_task_tags` avec l'ensemble déjà en place, `create_tag` sur un nom déjà pris) n'écrit ni ligne de journal ni avis ; `update_task`, `update_list` et `update_tag` comptent comme une écriture dès qu'ils reçoivent un champ, même identique, et leur schéma refuse un appel sans champ. Si la relecture échoue après le commit, l'outil répond `internal_error` pour une écriture gardée, que sa ligne de journal montre. Un outil d'écriture ajouté passe par `registerWriteTool` et ajoute son nom à `WRITE_TOOL_NAMES`, que le journal affiche. — `web/src/lib/mcp/writeTools.ts`, `web/src/lib/mcp/server.ts`, `web/src/lib/taskWrites.ts`, `web/src/app/api/mcp/route.test.ts`, `DECISIONS.md` « Assistants IA (MCP) », #203, #204
- Références des outils d'écriture : `task_id`, `list_id`, `parent_id` et `tag_ids` sont vérifiés contre le compte du jeton dans la transaction de l'écriture, par les fonctions de `taskWrites.ts` (`createTask`, `updateTask`, `setTaskTags`, `completeTask`, `reopenTask`), dont chaque requête sur une tâche, une liste ou une étiquette filtre sur `userId` et écarte les lignes supprimées. Une ligne d'un autre compte répond comme une ligne absente : `null` pour la tâche (`not_found`), et pour le reste une `WriteRefusal` (`list_not_found`, `parent_not_found`, `tag_not_found`), qui hérite de `ToolRefusal` pour que l'enveloppe la rende, et qui annule la transaction avec ce que la fonction avait déjà écrit (l'Inbox créée, la tâche dont les étiquettes sont refusées). Chacun de ces quatre contrôles a ses tests, qui tombent quand on retire son filtre sur le compte ; la preuve d'un refus compare toutes les lignes des deux comptes avant et après. Un identifiant comparé en JavaScript est celui que la base rend, jamais celui de l'appel : le même identifiant en majuscules désigne la même ligne. Un compte sans Inbox active en reçoit une à sa première création sans liste (`name: 'Inbox'`), sous `lockAccount`, première instruction de la transaction ; `POST /api/sync` ne prend pas ce verrou, et la première sync d'un appareil qui croiserait cette création laisserait deux Inbox actives, que la prochaine Inbox créée par la sync absorbe. `updateTask` verrouille la ligne de la tâche avant de la lire ; aucun verrou ne tient la liste ni le parent entre leur contrôle et l'écriture, comme dans les routes REST (#208). Listes et étiquettes (#204) : `list_id` de `update_list` et `tag_id` de `update_tag` désignent la ligne modifiée, que `updateList` et `updateTag` lisent en la verrouillant (`FOR NO KEY UPDATE`), par une requête filtrée sur `userId` qui écarte les lignes supprimées ; ces deux fonctions ne rendent jamais `null`, que l'outil prendrait pour une tâche absente (`not_found`), mais refusent par `list_not_found` et `tag_not_found`. Les contrôles de `updateList` se suivent dans cet ordre : liste active du compte, puis Inbox (`inbox_not_editable`), puis couleur et icône ; l'Inbox d'un autre compte répond donc `list_not_found`. `createTag` ne cherche le nom que parmi les étiquettes actives du compte, sous `lockAccount`, première instruction de la transaction : le nom d'une étiquette d'un autre compte reste libre. Tombent chacun sous sa mutation : le filtre de compte de la lecture de `updateList`, de celle de `updateTag`, de la recherche de `createTag` et du calcul de position de `createList`. L'`UPDATE` de `updateList` et de `updateTag` écrit la ligne que la fonction vient de lire sous ce filtre et de verrouiller : son propre filtre de compte est une seconde barrière, redondante tant que la première tient, et aucun test ne la distingue de son absence (mutation verte, dite dans la PR #217). — `web/src/lib/taskWrites.ts`, `web/src/lib/taskWrites.test.ts`, `web/src/lib/accountLock.ts`, `web/src/app/api/mcp/route.test.ts`, #203, #204
- Références des outils d'écriture : `task_id`, `list_id`, `parent_id` et `tag_ids` sont vérifiés contre le compte du jeton dans la transaction de l'écriture, par les fonctions de `taskWrites.ts` (`createTask`, `updateTask`, `setTaskTags`, `completeTask`, `reopenTask`), dont chaque requête sur une tâche, une liste ou une étiquette filtre sur `userId` et écarte les lignes supprimées. Une ligne d'un autre compte répond comme une ligne absente : `null` pour la tâche (`not_found`), comme une tâche restée dans une liste supprimée ou rangée dans une liste d'un autre compte, que `get_task` ne voit pas non plus (`visibleTask`, décision de Max du 2026-11-19 : supprimer une liste ne marque que la liste, et ses tâches restent actives) ; `completeTask` et `reopenTask` ne l'appliquent que sur la portée `visible` que passent les outils, et le `PUT` du site garde la portée `account`, et pour le reste une `WriteRefusal` (`list_not_found`, `parent_not_found`, `tag_not_found`), qui hérite de `ToolRefusal` pour que l'enveloppe la rende, et qui annule la transaction avec ce que la fonction avait déjà écrit (l'Inbox créée, la tâche dont les étiquettes sont refusées). Chacun de ces quatre contrôles a ses tests, qui tombent quand on retire son filtre sur le compte ; la preuve d'un refus compare toutes les lignes des deux comptes avant et après. Un identifiant comparé en JavaScript est celui que la base rend, jamais celui de l'appel : le même identifiant en majuscules désigne la même ligne. Un compte sans Inbox active en reçoit une à sa première création sans liste (`name: 'Inbox'`), sous `lockAccount`, première instruction de la transaction ; `POST /api/sync` ne prend pas ce verrou, et la première sync d'un appareil qui croiserait cette création laisserait deux Inbox actives, que la prochaine Inbox créée par la sync absorbe. `updateTask` verrouille la ligne de la tâche avant de la lire ; aucun verrou ne tient la liste ni le parent entre leur contrôle et l'écriture, comme dans les routes REST (#208). Listes et étiquettes (#204) : `list_id` de `update_list` et `tag_id` de `update_tag` désignent la ligne modifiée, que `updateList` et `updateTag` lisent en la verrouillant (`FOR NO KEY UPDATE`), par une requête filtrée sur `userId` qui écarte les lignes supprimées ; ces deux fonctions ne rendent jamais `null`, que l'outil prendrait pour une tâche absente (`not_found`), mais refusent par `list_not_found` et `tag_not_found`. Les contrôles de `updateList` se suivent dans cet ordre : liste active du compte, puis Inbox (`inbox_not_editable`), puis couleur et icône ; l'Inbox d'un autre compte répond donc `list_not_found`. `createTag` ne cherche le nom que parmi les étiquettes actives du compte, sous `lockAccount`, première instruction de la transaction : le nom d'une étiquette d'un autre compte reste libre. Tombent chacun sous sa mutation : le filtre de compte de la lecture de `updateList`, de celle de `updateTag`, de la recherche de `createTag` et du calcul de position de `createList`. L'`UPDATE` de `updateList` et de `updateTag` écrit la ligne que la fonction vient de lire sous ce filtre et de verrouiller : son propre filtre de compte est une seconde barrière, redondante tant que la première tient, et aucun test ne la distingue de son absence (mutation verte, dite dans la PR #217). — `web/src/lib/taskWrites.ts`, `web/src/lib/taskWrites.test.ts`, `web/src/lib/accountLock.ts`, `web/src/app/api/mcp/route.test.ts`, #203, #204
- Écarts voulus entre l'API REST et les outils MCP, à ne pas rapprocher dans une revue (le spec exclut la refonte des routes REST, décisions de planification du 2026-11-14) : `update_task` déplace une tâche avec ses sous-tâches actives, là où `PUT /api/tasks/[id]` ne déplace que la tâche ; une tâche créée ou déplacée par un outil va en fin de liste (la plus grande position des tâches actives de même rang, plus un, comme dans l'app), là où `POST /api/tasks` laisse la position à 0 ; un outil refuse de changer la liste d'une sous-tâche (`subtask_not_movable`), ce que le `PUT` accepte ; `create_task` sans liste va dans l'Inbox, alors que `POST /api/tasks` exige `listId`, et avec `parent_id` il ignore `list_id` ; `update_task` ne prend ni `completed`, ni `parent_id`, ni `position`. Les deux chemins partagent `completeTask` et `reopenTask`. Listes et étiquettes (#204) : `create_tag` rend l'étiquette active du compte qui porte déjà le nom, telle quelle (`created: false`, rien d'écrit, la couleur demandée non appliquée), là où `POST /api/tags` et l'app créent un doublon ; deux noms sont les mêmes une fois rognés, ramenés à leur forme composée (NFC) et mis en minuscules, donc sans tenir compte de la casse mais en tenant compte des accents (« Épicerie » et « épicerie » sont un nom, « Epicerie » en est un autre), et de plusieurs étiquettes actives du nom, la plus ancienne est rendue. La comparaison se fait en JavaScript, sur les étiquettes lues sous `lockAccount`, jamais par `lower()` : en SQL elle suivrait la locale de la base (sous `C`, « É » n'est pas mis en minuscule), et aucun test PGlite ne verrait l'écart avec la production. Ni `POST /api/tags` ni `POST /api/sync` ne prennent ce verrou : une étiquette créée au même instant par le site ou par l'app peut encore faire un doublon. `create_list` place la liste en fin de liste (la plus grande position des listes actives du compte, Inbox comprise, plus un, comme dans l'app), là où `POST /api/lists` laisse la position à 0 ; `update_list` refuse l'Inbox (`inbox_not_editable`), ne prend ni `position` ni `isInbox`, que `PUT /api/lists/[id]` accepte, et retire l'icône par `null` sans jamais retirer la couleur ; `update_tag` vers un nom déjà pris est permis, comme sur le site. Les outils rognent les noms, pas les routes. Couleurs et icônes des outils viennent de `palette.ts` (les sept couleurs et les vingt icônes de l'app), que `palette.test.ts` compare aux sources de l'app (`LIST_COLORS` et les clés d'`ICON_MAP` de `app/(tabs)/lists.tsx`, `TAG_COLORS` de `app/(tabs)/settings.tsx`) et qui tombe si l'app change sans le companion : une valeur hors palette est refusée (`invalid_color`, `invalid_icon`), une couleur est comparée sans la casse et enregistrée dans la graphie de la palette, celle que les sélecteurs de l'app comparent lettre pour lettre, une icône est comparée lettre pour lettre, là où les routes REST acceptent tout texte de 20 ou 50 caractères. `palette.ts` reste sans import, comme `dueDate.ts` : `tagEditing.ts` le réexporte, et `TagManager.tsx` le charge dans le navigateur. — `web/src/lib/taskWrites.ts`, `web/src/lib/mcp/writeTools.ts`, `web/src/lib/palette.ts`, `web/src/lib/palette.test.ts`, `web/src/lib/tagEditing.ts`, `web/src/app/api/tasks/route.ts`, `web/src/app/api/tasks/[id]/route.ts`, `web/src/app/api/lists/route.ts`, `web/src/app/api/lists/[id]/route.ts`, `web/src/app/api/tags/route.ts`, #203, #204
- Journal des assistants : `sl_agent_actions` garde une ligne par écriture réussie d'un outil (l'outil, le type et l'identifiant de la ligne touchée, le jeton et son nom au moment de l'appel), jamais un titre ni un contenu, pendant 90 jours comptés depuis l'instant de l'écriture (90 fois 24 heures, sans jour civil : aucun fuseau en jeu). `listActions` ne rend que les lignes du compte de moins de 90 jours, purgées ou non, de la plus récente à la plus ancienne, par pages de 100 au plus, avec un curseur sur l'instant coupé à la milliseconde puis l'identifiant ; le nom affiché est lu sur la ligne active du compte (tâche, liste ou étiquette), nul si elle est supprimée, absente ou d'un autre compte, et `tokenRevoked` signale un `token_id` nul. `purgeOldActions` supprime les lignes plus vieilles, tous comptes confondus. `web/server.ts` lance la purge après les migrations et hors de leur bloc `try`, sans l'attendre, puis toutes les 24 heures (`setInterval(…).unref()` : un intervalle depuis le démarrage, pas une heure du jour), sur un `Pool` à elle (`max: 1`, avec son écouteur d'erreur) et par `safePurge`, qui attrape tout et ne journalise que le nom de classe de l'erreur : une purge en échec n'arrête jamais le serveur. `agentJournal.ts` n'importe pas `@/db/client` et garde des imports relatifs, parce que `server.ts` l'embarque dans son bundle, à part des routes : chaque fonction reçoit la base sur laquelle elle tourne. `server.ts` échappe à vitest et à `next build` : son câblage se prouve par la commande esbuild de `web/Dockerfile`, rejouée par la revue, et par le test qui relit sa source. — `web/src/lib/agentJournal.ts`, `web/src/lib/agentJournal.test.ts`, `web/server.ts`, `web/Dockerfile`, `web/scripts/probe.sql` (contrôle `journal_plus_de_90_jours`), `DECISIONS.md` « Assistants IA (MCP) », #199, #203
- WebSocket : ticket à usage unique de 30 s, origines autorisées listées (`origin.ts`, liste partagée avec les routes, voir « Authentification »), revalidation toutes les 15 min ; aucun paramètre de requête de `/ws` n'est journalisé. — `web/src/lib/ws.ts`, `web/src/lib/origin.ts`, `web/src/app/api/ws-ticket/route.ts`, `web/server.ts`
@ -188,7 +188,7 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm
< web/scripts/probe.sql
```
- Lecture du résultat : une ligne `controle|nombre` par contrôle, douze lignes, des noms et des nombres seulement ; les lignes `BEGIN` et `ROLLBACK` que psql affiche autour ne sont pas des contrôles. L'en-tête de `probe.sql` décrit chaque contrôle et sa gravité : `tache_liste_autre_compte`, `sous_tache_parent_autre_compte`, `lien_etiquette_autre_compte` et `journal_autre_compte` sont critiques (fuite possible entre comptes), les autres sont des anomalies. Les deux derniers contrôles lisent le journal des assistants IA (`sl_agent_actions`, #199) : `journal_plus_de_90_jours` compte les lignes de plus de 91 jours (anomalie : le journal se garde 90 jours, une ligne plus vieille veut dire que la purge quotidienne, livrée par #203, n'a pas tourné), et `journal_autre_compte` compte les lignes dont le jeton ou l'élément touché (tâche, liste ou étiquette, supprimé ou non) appartient à un autre compte (critique) ; une ligne dont le jeton a été révoqué ou dont l'élément n'a plus de ligne en base ne compte pas. `lien_tache_supprimee` n'est pas nul en temps normal : la suppression d'une tâche garde ses liens, il se lit par rapport à la base de départ postée en commentaire de #176. Une erreur, ou moins de douze lignes, veut dire que la sonde n'a pas tourné, pas que la base est saine.
- Lecture du résultat : une ligne `controle|nombre` par contrôle, douze lignes, des noms et des nombres seulement ; les lignes `BEGIN` et `ROLLBACK` que psql affiche autour ne sont pas des contrôles. L'en-tête de `probe.sql` décrit chaque contrôle et sa gravité : `tache_liste_autre_compte`, `sous_tache_parent_autre_compte`, `lien_etiquette_autre_compte` et `journal_autre_compte` sont critiques (fuite possible entre comptes), les autres sont des anomalies. Les deux derniers contrôles lisent le journal des assistants IA (`sl_agent_actions`, #199) : `journal_plus_de_90_jours` compte les lignes de plus de 91 jours (anomalie : le journal se garde 90 jours, une ligne plus vieille veut dire que la purge quotidienne, livrée par #203, n'a pas tourné), et `journal_autre_compte` compte les lignes dont le jeton ou l'élément touché (tâche, liste ou étiquette, supprimé ou non) appartient à un autre compte (critique) ; une ligne dont le jeton a été révoqué n'est jugée que sur son élément, et une ligne dont l'élément n'a plus de ligne en base que sur son jeton : aucun des deux cas ne fait compter une ligne, ni ne l'en empêche. `lien_tache_supprimee` est attendu à 0 depuis #196 (la suppression d'une tâche retire ses liens, et la migration 0004 a retiré les anciens) : un nombre non nul veut dire que le défaut est revenu. Une erreur, ou moins de douze lignes, veut dire que la sonde n'a pas tourné, pas que la base est saine.
- Suite d'une anomalie : la session explique à Max chaque compteur non nul (ce qu'il mesure, la cause probable, la gravité), puis un échange de questions et réponses décide s'il faut ouvrir une issue. Pas d'issue automatique, pas de retour arrière du déploiement.
- Une PR qui modifie `probe.sql` garde le contrat que vérifie `web/src/test/probe.test.ts` : une transaction `READ ONLY` ouverte en premier, `ROLLBACK` en dernière instruction, aucune méta-commande psql, aucun `COMMIT`, `END` ni `READ WRITE`, et une sortie limitée à `controle` et `nombre`.

View file

@ -40,8 +40,10 @@
-- another user_id. CRITICAL
-- A line counts once, even when both its token and its row belong to
-- another account. A line without a token (token_id is null once the token
-- is revoked) or whose row matches nothing does not count; a soft-deleted
-- row of another account counts, as in controls 7 to 9.
-- is revoked) is judged by its row alone, and a line whose row matches
-- nothing by its token alone: neither case makes a line count, nor keeps
-- it from counting. A soft-deleted row of another account counts, as in
-- controls 7 to 9.
--
-- Foreign keys with ON DELETE CASCADE make a link to a missing list, task or
-- tag impossible; only parent_id and the journal's entity_id, which have no

View file

@ -0,0 +1,328 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID as u } from 'node:crypto';
import { isValidElement, type ReactElement, type ReactNode } from 'react';
import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// The server side of the « Assistants IA » page (#205): the real page and the
// real layout of the app, called as functions, against an in-memory Postgres
// (PGlite) with the companion migrations. The real pilot, the real token and
// journal queries run. Nothing is rendered: the tests read the element each
// function returns, that is, what the server sends to the client components.
// Replaced: the Logto session helper, next/headers (agentAccess.ts imports
// it), redirect() and notFound(), which throw here as they do in Next, and
// the client components, which only serve as markers.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
// logto.ts reads the variable once, when it is first loaded.
const initialBaseUrl = process.env.LOGTO_BASE_URL;
process.env.LOGTO_BASE_URL = 'https://liste.example.test/ignored/path';
return {
pg: new PGlite() as PGlite,
session: null as { userId: string; name?: string } | null,
initialBaseUrl,
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
vi.mock('next/headers', () => ({ headers: async () => new Headers() }));
vi.mock('next/navigation', () => ({
redirect: (to: string) => {
throw new Error(`REDIRECT ${to}`);
},
notFound: () => {
throw new Error('NOT_FOUND');
},
}));
vi.mock('@/components/AssistantsPanel', () => ({ AssistantsPanel: () => null }));
vi.mock('@/components/Sidebar', () => ({ Sidebar: () => null }));
vi.mock('@/components/Header', () => ({ Header: () => null }));
vi.mock('@/components/AppShell', () => ({ AppShell: () => null }));
const { default: AssistantsPage } = await import('./page');
const { default: AppLayout } = await import('../layout');
const { AssistantsPanel } = await import('@/components/AssistantsPanel');
const { Header } = await import('@/components/Header');
const { db } = await import('@/db/client');
const { recordAction } = await import('@/lib/agentJournal');
const { MAX_AGENT_TOKENS } = await import('@/lib/agentTokens');
const MINUTE_MS = 60 * 1000;
const DAY_MS = 24 * 60 * MINUTE_MS;
type TokenProps = {
id: string; name: string; scope: string; hint: string;
createdAt: string; lastUsedAt: string | null; expiresAt: string | null; expired: boolean;
};
type LineProps = { id: string; tool: string; tokenName: string; tokenRevoked: boolean; entityName: string | null; createdAt: string };
type PanelProps = {
tokens: TokenProps[];
atLimit: boolean;
journal: { actions: LineProps[]; nextCursor: string | null };
serverUrl: string;
};
const initialPilot = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Each test creates its own accounts (#148), with invented ids.
const newAccount = () => `user-${u()}`;
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
type TokenFields = { name?: string; scope?: string; createdAt?: Date; lastUsedAt?: Date; expiresAt?: Date };
// A token row written straight to the table; returns its id and its hash.
async function seedToken(userId: string, fields: TokenFields = {}) {
const [id, hash] = [u(), sha256(u())];
await h.pg.query(
'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope, created_at, last_used_at, expires_at) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)',
[
id, userId, fields.name ?? 'Assistant', hash, hash.slice(0, 4), fields.scope ?? 'read',
(fields.createdAt ?? new Date()).toISOString(), fields.lastUsedAt?.toISOString() ?? null, fields.expiresAt?.toISOString() ?? null,
],
);
return { id, hash };
}
async function seedTask(userId: string, title: string): Promise<string> {
const [listId, id] = [u(), u()];
await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [listId, userId, 'List']);
await h.pg.query('insert into sl_tasks (id, user_id, title, list_id) values ($1, $2, $3, $4)', [id, userId, title, listId]);
return id;
}
// `count` journal lines of the account, a minute apart, the newest a minute ago.
async function seedLines(userId: string, count: number, entityId: string = u(), tokenName = 'Assistant'): Promise<string[]> {
for (let i = 0; i < count; i++) {
await recordAction(db, { userId, tokenId: null, tokenName, tool: 'update_task', entityType: 'task', entityId }, new Date(Date.now() - (i + 1) * MINUTE_MS));
}
const { rows } = await h.pg.query<{ id: string }>(
"select id from sl_agent_actions where user_id = $1 order by date_trunc('milliseconds', created_at) desc, id desc", [userId]);
return rows.map((row) => row.id);
}
// The element of this type in what a server component returned, null without one.
function find(node: ReactNode, type: unknown): ReactElement | null {
if (Array.isArray(node)) {
for (const child of node) {
const found = find(child, type);
if (found) return found;
}
return null;
}
if (!isValidElement(node)) return null;
if (node.type === type) return node;
return find((node.props as { children?: ReactNode }).children, type);
}
// What the page sends to the panel, for the session of `userId`.
async function panelOf(userId: string): Promise<PanelProps> {
h.session = { userId };
const element = await AssistantsPage();
expect(isValidElement(element)).toBe(true);
expect(element.type).toBe(AssistantsPanel);
return element.props as PanelProps;
}
// Whether the layout shows the menu entry to the session of `userId`.
async function menuEntryOf(userId: string): Promise<unknown> {
h.session = { userId, name: 'Someone' };
const header = find(await AppLayout({ children: null }), Header);
expect(header).not.toBeNull();
return (header!.props as { showAssistants?: unknown }).showAssistants;
}
beforeAll(async () => {
const dir = path.join(__dirname, '../../../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
beforeEach(() => {
pilot('*');
h.session = null;
});
afterEach(() => {
vi.restoreAllMocks();
});
afterAll(() => {
pilot(initialPilot);
if (h.initialBaseUrl === undefined) delete process.env.LOGTO_BASE_URL;
else process.env.LOGTO_BASE_URL = h.initialBaseUrl;
});
describe('the page', () => {
it('redirects to /auth without a session', async () => {
h.session = null;
await expect(AssistantsPage()).rejects.toThrow('REDIRECT /auth');
});
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('does not exist when MCP_ALLOWED_SUBS is %s: notFound(), before anything is read', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
await seedToken(A);
await seedLines(A, 2);
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
h.session = { userId: A };
const queries = [vi.spyOn(h.pg, 'query'), vi.spyOn(h.pg, 'transaction'), vi.spyOn(h.pg, 'exec')];
await expect(AssistantsPage()).rejects.toThrow('NOT_FOUND');
expect(queries.map((spy) => spy.mock.calls.length)).toEqual([0, 0, 0]);
// Control: for an account of the pilot, the same spies see the page read.
pilot(A);
await AssistantsPage();
expect(queries[0].mock.calls.length).toBeGreaterThan(0);
});
it('exists for an account of the list, and for no other', async () => {
const [A, B] = [newAccount(), newAccount()];
pilot(` ${A} , ${newAccount()}`);
expect((await panelOf(A)).tokens).toEqual([]);
h.session = { userId: B };
await expect(AssistantsPage()).rejects.toThrow('NOT_FOUND');
});
it('sends the tokens of the account, named fields only, instants as ISO strings', async () => {
const [A, B] = [newAccount(), newAccount()];
const created = new Date(Date.now() - 100 * DAY_MS);
const used = new Date(Date.now() - 5 * MINUTE_MS);
const old = await seedToken(A, {
name: 'Hermes', scope: 'write', createdAt: created, lastUsedAt: used, expiresAt: new Date(created.getTime() + 90 * DAY_MS),
});
const recent = await seedToken(A, { name: 'Claude Code', expiresAt: new Date(Date.now() + 365 * DAY_MS) });
const never = await seedToken(A, { name: 'Sans fin', createdAt: new Date(Date.now() - DAY_MS) });
const foreign = await seedToken(B, { name: `Jeton de B ${u()}` });
const props = await panelOf(A);
// Newest first.
expect(props.tokens.map((token) => token.id)).toEqual([recent.id, never.id, old.id]);
expect(props.tokens[2]).toEqual({
id: old.id,
name: 'Hermes',
scope: 'write',
hint: old.hash.slice(0, 4),
createdAt: created.toISOString(),
lastUsedAt: used.toISOString(),
expiresAt: new Date(created.getTime() + 90 * DAY_MS).toISOString(),
// Expired ten days ago.
expired: true,
});
expect(props.tokens[0]).toMatchObject({ name: 'Claude Code', scope: 'read', lastUsedAt: null, expired: false });
expect(props.tokens[1]).toMatchObject({ name: 'Sans fin', expiresAt: null, expired: false });
expect(props.atLimit).toBe(false);
// Neither a hash, nor the account, nor anything of another account.
const sent = JSON.stringify(props);
for (const hidden of [A, B, old.hash, recent.hash, never.hash, foreign.id, foreign.hash]) expect(sent).not.toContain(hidden);
expect(sent).not.toContain('Jeton de B');
// What the server sends is plain data: nothing is lost on the way to the browser.
expect(JSON.parse(sent)).toEqual(props);
});
it('says when the account holds as many tokens as it may, expired ones counted', async () => {
const A = newAccount();
await seedToken(A, { expiresAt: new Date(Date.now() - DAY_MS) });
for (let i = 1; i < MAX_AGENT_TOKENS - 1; i++) await seedToken(A);
expect((await panelOf(A)).atLimit).toBe(false);
await seedToken(A);
const props = await panelOf(A);
expect(props.tokens).toHaveLength(10);
expect(props.atLimit).toBe(true);
});
it('sends the first 50 lines of the journal of the account, and the cursor of the next ones', async () => {
const [A, B] = [newAccount(), newAccount()];
const title = `Tâche de A ${u()}`;
const ids = await seedLines(A, 55, await seedTask(A, title), 'Hermes');
const foreignTitle = `Tâche de B ${u()}`;
const foreignIds = await seedLines(B, 3, await seedTask(B, foreignTitle), `Jeton de B ${u()}`);
const { journal } = await panelOf(A);
expect(journal.actions.map((line) => line.id)).toEqual(ids.slice(0, 50));
expect(journal.actions[0]).toEqual({
id: ids[0], tool: 'update_task', tokenName: 'Hermes', tokenRevoked: true, entityName: title, createdAt: journal.actions[0].createdAt,
});
const last = journal.actions[49];
expect(journal.nextCursor).toBe(`${Date.parse(last.createdAt)}_${last.id}`);
const sent = JSON.stringify(journal);
for (const hidden of [A, B, foreignTitle, 'Jeton de B', ...foreignIds]) expect(sent).not.toContain(hidden);
expect(JSON.parse(sent)).toEqual(journal);
});
it('leaves out the lines older than 90 days', async () => {
const A = newAccount();
await recordAction(db, { userId: A, tokenId: null, tokenName: 'Assistant', tool: 'create_task', entityType: 'task', entityId: u() }, new Date(Date.now() - 90 * DAY_MS - 60 * MINUTE_MS));
await recordAction(db, { userId: A, tokenId: null, tokenName: 'Assistant', tool: 'update_task', entityType: 'task', entityId: u() }, new Date(Date.now() - 90 * DAY_MS + 60 * MINUTE_MS));
const { journal } = await panelOf(A);
expect(journal.actions.map((line) => line.tool)).toEqual(['update_task']);
expect(journal.nextCursor).toBeNull();
});
it('gives the address of the MCP server: the origin of the site, then the route', async () => {
expect((await panelOf(newAccount())).serverUrl).toBe('https://liste.example.test/api/mcp');
});
});
describe('the account menu', () => {
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('has no entry when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const A = newAccount();
pilot(value === 'others' ? `${newAccount()}, ${newAccount()}` : value);
expect(await menuEntryOf(A)).toBe(false);
});
it('has the entry for every account when the pilot is open, and for the accounts of a list', async () => {
const [A, B] = [newAccount(), newAccount()];
expect(await menuEntryOf(A)).toBe(true);
pilot(`${newAccount()},${A}`);
expect(await menuEntryOf(A)).toBe(true);
expect(await menuEntryOf(B)).toBe(false);
});
it('redirects to /auth without a session', async () => {
h.session = null;
await expect(AppLayout({ children: null })).rejects.toThrow('REDIRECT /auth');
});
// The menu only opens on a click, which nothing renders here: its source is read instead.
it('Header.tsx draws the entry inside the `showAssistants` condition, above the sign-out link', () => {
const source = fs.readFileSync(path.join(__dirname, '../../../components/Header.tsx'), 'utf8');
const entry = source.indexOf('{showAssistants && (');
const link = source.indexOf('href="/assistants"');
const end = source.indexOf('</Link>', link);
const signOut = source.indexOf('href="/api/logto/sign-out"');
expect(entry).toBeGreaterThan(-1);
expect(source.match(/href="\/assistants"/g)).toHaveLength(1);
expect(source.match(/<Link\b/g)).toHaveLength(1);
// The condition opens on the link, and closes right after it.
expect(source.slice(entry, link)).toMatch(/^\{showAssistants && \(\s*<Link\s+$/);
expect(source.slice(end + '</Link>'.length)).toMatch(/^\s*\)\}/);
expect(source.slice(link, end)).toContain('t("assistants.title")');
expect(end).toBeLessThan(signOut);
});
});

View file

@ -0,0 +1,43 @@
export const dynamic = "force-dynamic";
import { notFound, redirect } from "next/navigation";
import { getAuthenticatedUser } from "@/lib/auth";
import { db } from "@/db/client";
import { mcpAllowed } from "@/lib/agentAccess";
import { listActions } from "@/lib/agentJournal";
import { listAgentTokens, MAX_AGENT_TOKENS } from "@/lib/agentTokens";
import { JOURNAL_PAGE_SIZE, journalPageView, mcpServerUrl, tokenView } from "@/lib/assistants";
import { logtoConfig } from "@/lib/logto";
import { AssistantsPanel } from "@/components/AssistantsPanel";
// The « Assistants IA » page (#205): the agent tokens of the signed-in
// account, how to connect an assistant, and what the tokens wrote. It exists
// for an account of the pilot only (MCP_ALLOWED_SUBS): for any other, it
// answers like a page that does not exist, before anything is read.
export default async function AssistantsPage() {
const user = await getAuthenticatedUser();
if (!user) redirect("/auth");
const userId = user.userId;
if (!mcpAllowed(userId)) notFound();
// One instant for the whole page: the 90 days of the journal and « Expiré »
// are decided on it, here, so that the browser has no clock to read. The
// dates themselves leave as instants and are formatted in the browser, in
// the user's time zone (this container runs in UTC).
const now = new Date();
const [tokens, journal] = await Promise.all([
listAgentTokens(userId),
listActions(db, userId, { limit: JOURNAL_PAGE_SIZE }, now),
]);
return (
<AssistantsPanel
tokens={tokens.map((token) => tokenView(token, now))}
// Expired tokens count, as in createAgentToken.
atLimit={tokens.length >= MAX_AGENT_TOKENS}
journal={journalPageView(journal)}
serverUrl={mcpServerUrl(logtoConfig.baseUrl)}
/>
);
}

View file

@ -2,6 +2,7 @@ export const dynamic = "force-dynamic";
import { redirect } from "next/navigation";
import { getAuthenticatedUser } from "@/lib/auth";
import { mcpAllowed } from "@/lib/agentAccess";
import { db } from "@/db/client";
import { slLists, slTags } from "@/db/schema";
import { eq, isNull, and, asc } from "drizzle-orm";
@ -37,7 +38,10 @@ export default async function AppLayout({
<div className="flex h-screen overflow-hidden">
<Sidebar lists={lists} tags={tags} />
<div className="flex-1 flex flex-col min-w-0">
<Header userName={user.name || user.email || ""} />
<Header
userName={user.name || user.email || ""}
showAssistants={mcpAllowed(user.userId)}
/>
<main className="flex-1 overflow-y-auto p-4 md:p-6">{children}</main>
</div>
</div>

View file

@ -0,0 +1,531 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash, randomUUID as u } from 'node:crypto';
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest';
import type { PGlite } from 'electric-sql-pglite';
// GET /api/agent-actions (#205): the real route, the real guard
// (requireAssistantsSession), the real pilot, the real journal queries and the
// real clock, against an in-memory Postgres (PGlite) with the companion
// migrations. Three modules are replaced, as in the test of the agent-token
// routes:
// - the Logto session helper gives the account of the test;
// - headers() of next/headers gives the headers of the test request
// (it throws outside a request);
// - the rate limiter records its calls and refuses on demand.
// Journal lines are written by the real recordAction, at an instant counted
// back from the real clock: the route reads the journal at the current time.
// Every request is sent to the container's host, as in production.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
return {
pg: new PGlite() as PGlite,
session: null as { userId: string } | null,
headers: new Headers(),
limits: [] as [userId: string, category: string][],
limited: false,
};
});
vi.mock('@/db/client', async () => {
const { drizzle } = await import('drizzle-orm/pglite');
const schema = await import('@/db/schema');
return { db: drizzle(h.pg, { schema }) };
});
vi.mock('@/lib/auth', () => ({ getAuthenticatedUser: async () => h.session }));
vi.mock('next/headers', () => ({ headers: async () => h.headers }));
vi.mock('@/lib/rateLimit', () => ({
rateLimit: (userId: string, category: string) => {
h.limits.push([userId, category]);
return h.limited ? Response.json({ error: 'Too many requests' }, { status: 429 }) : null;
},
}));
const { GET } = await import('./route');
const { db } = await import('@/db/client');
const { listActions, recordAction } = await import('@/lib/agentJournal');
const { createAgentToken } = await import('@/lib/agentTokens');
const { JOURNAL_PAGE_SIZE, journalPageView, readJournalPage } = await import('@/lib/assistants');
// Origin of `request.url` in production: the container's, not the site's.
const CONTAINER = 'http://0.0.0.0:3000';
const MINUTE_MS = 60 * 1000;
const DAY_MS = 24 * 60 * MINUTE_MS;
const UNAUTHORIZED = { status: 401, json: { error: 'Unauthorized' } };
const NOT_FOUND = { status: 404, json: { error: 'Not found' } };
const INVALID_CURSOR = { status: 400, json: { error: 'Invalid cursor' } };
// Authorization headers the route refuses whatever they hold: a Logto access
// token (the mobile app's), a well-formed agent token, another scheme.
const AUTHORIZATIONS: [label: string, value: string][] = [
['a Logto access token', 'Bearer logto-access-token-of-the-test'],
['a well-formed agent token', `Bearer slmcp_${'A'.repeat(43)}`],
['another scheme', 'Basic not-a-credential'],
];
type Send = { authorization?: string; origin?: string };
type Answer = { status: number; text: string; json: unknown; headers: Headers };
type Line = { id: string; tool: string; tokenName: string; tokenRevoked: boolean; entityName: string | null; createdAt: string };
type Page = { actions: Line[]; nextCursor: string | null };
type Entry = {
tokenId?: string | null;
tokenName?: string;
tool?: string;
entityType?: 'task' | 'list' | 'tag';
entityId?: string;
};
const initialPilot = process.env.MCP_ALLOWED_SUBS;
function pilot(value: string | undefined) {
if (value === undefined) delete process.env.MCP_ALLOWED_SUBS;
else process.env.MCP_ALLOWED_SUBS = value;
}
// Each test creates its own accounts (#148): the file passes in any order.
// Invented ids: no real `sub` in the repository.
const newAccount = () => `user-${u()}`;
// An instant `minutes` before the real clock.
const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * MINUTE_MS);
// The request of a session (`userId`, null without one), and the headers that
// next/headers gives the guard: the same object.
function request(userId: string | null, query: string, send: Send): Request {
h.session = userId === null ? null : { userId };
const headers = new Headers();
if (send.origin !== undefined) headers.set('origin', send.origin);
if (send.authorization !== undefined) headers.set('authorization', send.authorization);
h.headers = headers;
return new Request(`${CONTAINER}/api/agent-actions${query}`, { headers });
}
async function get(userId: string | null, query = '', send: Send = {}): Promise<Answer> {
const res = await GET(request(userId, query, send));
const text = await res.text();
return { status: res.status, text, json: text === '' ? null : JSON.parse(text) as unknown, headers: res.headers };
}
// One page of the journal of a session; `cursor` is the `nextCursor` of the page before.
async function page(userId: string, cursor?: string): Promise<Page> {
const a = await get(userId, cursor === undefined ? '' : `?before=${encodeURIComponent(cursor)}`);
expect(a.status).toBe(200);
return a.json as Page;
}
// Every page of the journal of a session, read as the « Plus anciennes » button reads them.
async function pagesOf(userId: string): Promise<Page[]> {
const pages = [await page(userId)];
while (pages[pages.length - 1].nextCursor !== null && pages.length < 20) {
pages.push(await page(userId, pages[pages.length - 1].nextCursor!));
}
return pages;
}
const idsOf = (pages: Page[]) => pages.flatMap((p) => p.actions.map((line) => line.id));
// A token row written straight to the table.
async function seedToken(userId: string, name = 'Assistant'): Promise<string> {
const id = u();
await h.pg.query(
'insert into sl_agent_tokens (id, user_id, name, token_hash, hint, scope) values ($1, $2, $3, $4, $5, $6)',
[id, userId, name, createHash('sha256').update(u()).digest('hex'), 'seed', 'write'],
);
return id;
}
async function seedTask(userId: string, title: string): Promise<string> {
const [listId, id] = [u(), u()];
await h.pg.query('insert into sl_lists (id, user_id, name) values ($1, $2, $3)', [listId, userId, 'List']);
await h.pg.query('insert into sl_tasks (id, user_id, title, list_id) values ($1, $2, $3, $4)', [id, userId, title, listId]);
return id;
}
// A journal line of the account, written by the real recordAction at `at`.
async function write(userId: string, at: Date, entry: Entry = {}): Promise<void> {
await recordAction(db, {
userId,
tokenId: entry.tokenId ?? null,
tokenName: entry.tokenName ?? 'Assistant',
tool: entry.tool ?? 'update_task',
entityType: entry.entityType ?? 'task',
entityId: entry.entityId ?? u(),
}, at);
}
// The ids of every line of an account as the table holds them, in the order
// the journal is read: the instant cut to the millisecond, then the id, both
// descending. Lines older than 90 days included.
async function stored(userId: string): Promise<string[]> {
const { rows } = await h.pg.query<{ id: string }>(
"select id from sl_agent_actions where user_id = $1 order by date_trunc('milliseconds', created_at) desc, id desc",
[userId],
);
return rows.map((row) => row.id);
}
beforeAll(async () => {
const dir = path.join(__dirname, '../../../db/migrations');
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) {
for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) {
if (stmt.trim()) await h.pg.exec(stmt);
}
}
});
beforeEach(() => {
pilot('*');
h.session = null;
h.headers = new Headers();
h.limits = [];
h.limited = false;
});
afterAll(() => pilot(initialPilot));
describe('GET /api/agent-actions', () => {
it('returns the journal of the session, newest first, named fields only', async () => {
const A = newAccount();
const tokenId = await seedToken(A, 'Hermes');
const taskId = await seedTask(A, 'Acheter du lait');
const gone = u();
const [first, second, third] = [minutesAgo(30), minutesAgo(20), minutesAgo(10)];
await write(A, first, { tokenId, tokenName: 'Hermes', tool: 'create_task', entityId: taskId });
// A list that no longer exists, written by a token revoked since.
await write(A, second, { tokenId: null, tokenName: 'Ancien', tool: 'update_list', entityType: 'list', entityId: gone });
await write(A, third, { tokenId, tokenName: 'Hermes', tool: 'complete_task', entityId: taskId });
const ids = await stored(A);
const a = await get(A);
expect(a.status).toBe(200);
expect(a.json).toEqual({
actions: [
{ id: ids[0], tool: 'complete_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'Acheter du lait', createdAt: third.toISOString() },
{ id: ids[1], tool: 'update_list', tokenName: 'Ancien', tokenRevoked: true, entityName: null, createdAt: second.toISOString() },
{ id: ids[2], tool: 'create_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'Acheter du lait', createdAt: first.toISOString() },
],
nextCursor: null,
});
// Neither the account, nor the touched rows, nor the token id leave.
for (const hidden of [A, taskId, gone, tokenId]) expect(a.text).not.toContain(hidden);
expect(h.limits).toEqual([[A, 'read']]);
// The journal component accepts the answer as it is.
expect(readJournalPage(a.json)).toEqual(a.json);
});
it('gives the first page the same shape as the page the server component reads', async () => {
const A = newAccount();
for (let i = 0; i < 3; i++) await write(A, minutesAgo(i + 1));
expect(await page(A)).toEqual(journalPageView(await listActions(db, A, { limit: JOURNAL_PAGE_SIZE })));
});
it('answers an account without a line with an empty page', async () => {
expect(await page(newAccount())).toEqual({ actions: [], nextCursor: null });
});
it('is a read: no Origin is asked for, and no CORS header is sent', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
for (const origin of [undefined, 'https://liste.lacompagniemaximus.com', 'https://evil.example']) {
const a = await get(A, '', { origin });
expect(a.status).toBe(200);
expect(a.headers.get('access-control-allow-origin')).toBeNull();
}
});
});
describe('the session of the site only', () => {
it.each(AUTHORIZATIONS)('answers 401 to %s in an Authorization header, session or not', async (_label, authorization) => {
const A = newAccount();
await write(A, minutesAgo(1));
expect(await get(A, '', { authorization })).toMatchObject(UNAUTHORIZED);
expect(await get(null, '', { authorization })).toMatchObject(UNAUTHORIZED);
// Refused before the rate limiter is asked.
expect(h.limits).toEqual([]);
});
it('answers 401 to a live agent token of the account: a token cannot read the journal', async () => {
const A = newAccount();
const created = await createAgentToken(A, { name: 'Hermes', scope: 'write', duration: 'never' });
if (!created.ok) throw new Error('token not created');
await write(A, minutesAgo(1), { tokenId: created.row.id, tokenName: 'Hermes' });
const authorization = `Bearer ${created.token}`;
expect(await get(A, '', { authorization })).toMatchObject(UNAUTHORIZED);
expect(await get(null, '', { authorization })).toMatchObject(UNAUTHORIZED);
});
it('answers 401 without a session', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
const a = await get(null);
expect(a).toMatchObject(UNAUTHORIZED);
expect(a.text).not.toContain('actions');
expect(h.limits).toEqual([]);
});
});
describe('outside the pilot', () => {
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('answers 404 when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
await write(A, minutesAgo(1));
const [id] = await stored(A);
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
const a = await get(A);
expect(a).toMatchObject(NOT_FOUND);
expect(a.text).not.toContain(id);
// With a cursor too, well-formed or not: the pilot is checked first.
expect(await get(A, `?before=${Date.now()}_${id}`)).toMatchObject(NOT_FOUND);
expect(await get(A, '?before=nonsense')).toMatchObject(NOT_FOUND);
// The rate limiter was never asked.
expect(h.limits).toEqual([]);
});
it('opens to the accounts of the list, and to no other', async () => {
const [A, B] = [newAccount(), newAccount()];
await write(A, minutesAgo(1));
await write(B, minutesAgo(1));
pilot(` ${A} , ${newAccount()}`);
expect((await get(A)).status).toBe(200);
expect(await get(B)).toMatchObject(NOT_FOUND);
});
it('answers 401, not 404, to an Authorization header and to a missing session', async () => {
const A = newAccount();
pilot('');
expect(await get(A, '', { authorization: AUTHORIZATIONS[0][1] })).toMatchObject(UNAUTHORIZED);
expect(await get(null)).toMatchObject(UNAUTHORIZED);
});
});
describe('rate limit', () => {
it('counts a read of the account, and answers 429 when the limit is reached', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
expect((await get(A)).status).toBe(200);
h.limited = true;
const a = await get(A);
expect(a.status).toBe(429);
expect(a.text).not.toContain('actions');
expect(h.limits).toEqual([[A, 'read'], [A, 'read']]);
});
it('checks the session, then the rate limit, then the cursor', async () => {
const A = newAccount();
h.limited = true;
// Everything wrong at once: the Authorization header decides, before the
// rate limiter is even asked.
expect((await get(A, '?before=nonsense', { authorization: AUTHORIZATIONS[0][1] })).status).toBe(401);
expect(h.limits).toEqual([]);
// The rate limit before the cursor.
expect((await get(A, '?before=nonsense')).status).toBe(429);
h.limited = false;
// The cursor last.
expect((await get(A, '?before=nonsense')).status).toBe(400);
expect(h.limits).toEqual([[A, 'read'], [A, 'read']]);
});
});
describe('two accounts', () => {
it('never see the lines of each other', async () => {
// An account with a task and a token of its own, named like no other.
const account = async () => {
const userId = newAccount();
const [title, tokenName] = [`Tâche ${u()}`, `Jeton ${u()}`];
return { userId, title, tokenName, taskId: await seedTask(userId, title), tokenId: await seedToken(userId, tokenName) };
};
const [A, B] = [await account(), await account()];
// Sixty lines each, written at the same instants: more than a page.
for (let i = 0; i < 60; i++) {
const at = minutesAgo(i + 1);
for (const { userId, tokenId, tokenName, taskId } of [A, B]) {
await write(userId, at, { tokenId, tokenName, entityId: taskId });
}
}
const ids = new Map([[A, await stored(A.userId)], [B, await stored(B.userId)]]);
expect(ids.get(A)).toHaveLength(60);
expect(ids.get(B)).toHaveLength(60);
for (const [self, other] of [[A, B], [B, A]]) {
const first = await get(self.userId);
const firstPage = first.json as Page;
const second = await get(self.userId, `?before=${encodeURIComponent(firstPage.nextCursor!)}`);
const secondPage = second.json as Page;
// Its own sixty lines, in order, and nothing else.
expect([...firstPage.actions, ...secondPage.actions].map((line) => line.id)).toEqual(ids.get(self));
expect(secondPage.nextCursor).toBeNull();
const text = first.text + second.text;
for (const hidden of [other.userId, other.title, other.tokenName, other.taskId, other.tokenId, ...ids.get(other)!]) {
expect(text).not.toContain(hidden);
}
// Control: its own names are there, on every line.
expect(text.split(self.title)).toHaveLength(61);
expect(text.split(self.tokenName)).toHaveLength(61);
}
});
it('a cursor taken from the journal of another account opens none of its lines', async () => {
const [A, B] = [newAccount(), newAccount()];
for (let i = 0; i < 55; i++) {
await write(A, minutesAgo(2 * i + 1));
await write(B, minutesAgo(2 * i + 2));
}
const [idsA, idsB] = [await stored(A), await stored(B)];
const cursorOfA = (await page(A)).nextCursor!;
expect(cursorOfA).toContain(idsA[49]);
// B sends the cursor of A: it is a position in B's own journal. The 50th
// line of A was written 99 minutes ago: the lines of B older than that.
const answer = await page(B, cursorOfA);
expect(answer.actions.map((line) => line.id)).toEqual(idsB.slice(49));
for (const id of idsA) expect(JSON.stringify(answer)).not.toContain(id);
});
it('a line that names the row of another account shows no name', async () => {
const [A, B] = [newAccount(), newAccount()];
const title = `Tâche de B ${u()}`;
// No tool writes such a line: the journal still joins on the account.
await write(A, minutesAgo(1), { entityId: await seedTask(B, title) });
const a = await get(A);
expect((a.json as Page).actions).toMatchObject([{ entityName: null }]);
expect(a.text).not.toContain(title);
});
});
describe('pages', () => {
it('reads 50 lines per page, without a gap or a repeat, across lines of the same instant', async () => {
const A = newAccount();
// 30 lines a minute apart, then 90 at one instant, then 10 older ones.
const same = minutesAgo(100);
for (let i = 0; i < 30; i++) await write(A, minutesAgo(i + 1));
for (let i = 0; i < 90; i++) await write(A, same);
for (let i = 0; i < 10; i++) await write(A, minutesAgo(200 + i));
const ids = await stored(A);
expect(ids).toHaveLength(130);
const pages = await pagesOf(A);
expect(pages.map((p) => p.actions.length)).toEqual([50, 50, 30]);
expect(idsOf(pages)).toEqual(ids);
expect(new Set(idsOf(pages)).size).toBe(130);
expect(pages[2].nextCursor).toBeNull();
// Both page breaks fall among the lines of the same instant.
for (const [before, after] of [[pages[0], pages[1]], [pages[1], pages[2]]]) {
expect(before.actions[49].createdAt).toBe(same.toISOString());
expect(after.actions[0].createdAt).toBe(same.toISOString());
}
// Newest first, all the way.
const instants = pages.flatMap((p) => p.actions.map((line) => Date.parse(line.createdAt)));
expect(instants).toEqual([...instants].sort((x, y) => y - x));
});
it('gives a cursor only when older lines follow', async () => {
const A = newAccount();
for (let i = 0; i < JOURNAL_PAGE_SIZE; i++) await write(A, minutesAgo(i + 1));
// Exactly one page: no cursor.
expect(await page(A)).toMatchObject({ nextCursor: null });
expect((await page(A)).actions).toHaveLength(50);
// One line more: a cursor, and a second page of one line.
await write(A, minutesAgo(500));
const ids = await stored(A);
const first = await page(A);
expect(first.actions.map((line) => line.id)).toEqual(ids.slice(0, 50));
const last = first.actions[49];
// The cursor is the position of the last line: its instant in milliseconds, then its id.
expect(first.nextCursor).toBe(`${Date.parse(last.createdAt)}_${last.id}`);
expect(await page(A, first.nextCursor!)).toEqual({
actions: [expect.objectContaining({ id: ids[50] })],
nextCursor: null,
});
});
it('a cursor is a position: before everything it gives nothing, after everything the first page', async () => {
const A = newAccount();
for (let i = 0; i < 3; i++) await write(A, minutesAgo(i + 1));
const ids = await stored(A);
const id = u();
expect(await page(A, `0_${id}`)).toEqual({ actions: [], nextCursor: null });
expect((await page(A, `${Date.now() + DAY_MS}_${id}`)).actions.map((line) => line.id)).toEqual(ids);
// The last instant a cursor may carry.
expect((await page(A, `253402300799999_${id}`)).actions.map((line) => line.id)).toEqual(ids);
});
});
describe('90 days', () => {
it('shows a line written less than 90 days ago, and no older one, on any page', async () => {
const A = newAccount();
const kept = new Date(Date.now() - 90 * DAY_MS + 60 * MINUTE_MS);
await write(A, minutesAgo(1), { tool: 'create_task' });
await write(A, kept, { tool: 'update_task' });
await write(A, new Date(Date.now() - 90 * DAY_MS - 60 * MINUTE_MS), { tool: 'create_list', entityType: 'list' });
await write(A, new Date(Date.now() - 200 * DAY_MS), { tool: 'create_tag', entityType: 'tag' });
const ids = await stored(A);
expect(ids).toHaveLength(4);
const a = await get(A);
const first = a.json as Page;
expect(first.actions.map((line) => line.tool)).toEqual(['create_task', 'update_task']);
expect(first.actions[1].createdAt).toBe(kept.toISOString());
expect(first.nextCursor).toBeNull();
for (const id of ids.slice(2)) expect(a.text).not.toContain(id);
// A cursor placed on the last line shown does not reach the older ones.
const beyond = await get(A, `?before=${kept.getTime()}_${ids[1]}`);
expect(beyond.json).toEqual({ actions: [], nextCursor: null });
});
it('does not count the old lines in a page', async () => {
const A = newAccount();
// 50 recent lines and 20 old ones: one full page, and no cursor.
for (let i = 0; i < 50; i++) await write(A, minutesAgo(i + 1));
for (let i = 0; i < 20; i++) await write(A, new Date(Date.now() - 91 * DAY_MS - i * MINUTE_MS));
const pages = await pagesOf(A);
expect(pages.map((p) => p.actions.length)).toEqual([50]);
expect(idsOf(pages)).toEqual((await stored(A)).slice(0, 50));
});
});
describe('a cursor that is not one', () => {
const ID = '22222222-2222-4222-8222-222222222222';
it.each([
['an empty value', ''],
['a word', 'nonsense'],
['an instant alone', '1794670330123'],
['an id alone', ID],
['an id that is not a uuid', '1794670330123_not-a-uuid'],
['an instant that is not a number', `NaN_${ID}`],
['an ISO instant', `2026-11-14T15:32:10.123Z_${ID}`],
['a negative instant', `-1_${ID}`],
['the first millisecond of year 10000', `253402300800000_${ID}`],
['an instant no Date can hold', `999999999999999_${ID}`],
['an instant of sixteen digits', `8640000000000001_${ID}`],
['SQL in the id', `1794670330123_${ID}' OR '1'='1`],
['a cursor sent twice', `1794670330123_${ID},1794670330123_${ID}`],
])('answers 400 to %s, never 500', async (_label, value) => {
const A = newAccount();
await write(A, minutesAgo(1));
const a = await get(A, `?before=${encodeURIComponent(value)}`);
expect(a).toMatchObject(INVALID_CURSOR);
expect(a.text).not.toContain('actions');
});
it('reads the first `before` of the query, and refuses it when it is not a cursor', async () => {
const A = newAccount();
await write(A, minutesAgo(1));
const [id] = await stored(A);
expect(await get(A, `?before=nonsense&before=${Date.now()}_${id}`)).toMatchObject(INVALID_CURSOR);
// Another parameter is ignored.
expect((await get(A, '?after=nonsense&limit=1000')).json).toMatchObject({ actions: [{ id }] });
});
});

View file

@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { requireAssistantsSession } from '@/lib/agentAccess';
import { listActions } from '@/lib/agentJournal';
import { JOURNAL_PAGE_SIZE, decodeJournalCursor, journalPageView } from '@/lib/assistants';
import { rateLimit } from '@/lib/rateLimit';
// The journal of what the agent tokens of the signed-in account wrote (#205),
// by pages of 50 lines, newest first: the « Assistants IA » page reads its
// first page itself and asks this route for the older ones.
//
// Like the routes of the agent tokens, it does not call requireAuth():
// requireAssistantsSession() takes the session of the site only, refuses any
// Authorization header, and answers 404 outside the pilot. Order of the
// checks: session, rate limit, cursor.
export async function GET(request: Request) {
const auth = await requireAssistantsSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'read');
if (rl) return rl;
// `?before=` is the `nextCursor` of the previous page. It comes back from
// the client: listActions would throw on a cursor that is not one.
const before = new URL(request.url).searchParams.get('before');
const cursor = before === null ? null : decodeJournalCursor(before);
if (before !== null && cursor === null) {
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 });
}
// listActions filters on the account and on the 90 days; journalPageView
// names the fields that leave.
const page = await listActions(db, auth.userId, { before: cursor, limit: JOURNAL_PAGE_SIZE });
return NextResponse.json(journalPageView(page));
}

View file

@ -1,16 +1,19 @@
import { NextResponse } from 'next/server';
import { requireAssistantsSession } from '@/lib/agentAccess';
import { requireSiteSession } from '@/lib/agentAccess';
import { revokeAgentToken } from '@/lib/agentTokens';
import { isAllowedOrigin } from '@/lib/origin';
import { rateLimit } from '@/lib/rateLimit';
// Revoke an agent token of the signed-in account (#200). Same guard and same
// order as POST /api/agent-tokens: session of the site, rate limit, Origin.
// Revoke an agent token of the signed-in account (#200). Same order as POST
// /api/agent-tokens: session of the site, rate limit, Origin. Unlike it, the
// pilot is not checked (requireSiteSession): a revocation takes effect even
// while MCP_ALLOWED_SUBS is emptied, from a page opened before (decision of
// Max, 2026-11-19).
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAssistantsSession();
const auth = await requireSiteSession();
if (auth.error) return auth.error;
const rl = rateLimit(auth.userId, 'create');
if (rl) return rl;

View file

@ -7,9 +7,10 @@ import type { PGlite } from 'electric-sql-pglite';
// Management routes of the agent tokens (#200): the real GET and POST
// /api/agent-tokens and DELETE /api/agent-tokens/[id], against an in-memory
// Postgres (PGlite) with the companion migrations. The real guard
// (requireAssistantsSession), the real pilot, the real Origin check, the real
// parseBody and the real schema run. Three modules are replaced:
// Postgres (PGlite) with the companion migrations. The real guards
// (requireAssistantsSession for GET and POST, requireSiteSession for DELETE,
// which does not check the pilot), the real pilot, the real Origin check, the
// real parseBody and the real schema run. Three modules are replaced:
// - the Logto session helper gives the account of the test;
// - headers() of next/headers gives the headers of the test request
// (it throws outside a request);
@ -587,11 +588,13 @@ describe('DELETE /api/agent-tokens/[id]', () => {
});
describe('outside the pilot', () => {
it.each([
const OUTSIDE = [
['absent', undefined],
['empty', ''],
['a list without the account', 'others'],
])('the three routes answer 404 when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
] as const;
it.each(OUTSIDE)('GET and POST answer 404 when MCP_ALLOWED_SUBS is %s', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
// Created while the pilot was open to everyone.
const { id } = await create(A);
@ -600,14 +603,50 @@ describe('outside the pilot', () => {
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
expect(await list(A)).toMatchObject(NOT_FOUND);
expect(await post(A)).toMatchObject(NOT_FOUND);
expect(await del(A, id)).toMatchObject(NOT_FOUND);
// Nothing was written, and the rate limiter was never asked.
expect((await rowsOf(A)).map((r) => r.id)).toEqual([id]);
expect(h.limits).toEqual([]);
});
it('opens the three routes to the accounts of the list, and to no other', async () => {
// The emergency switch closes the server, never the way to revoke a token
// (decision of Max of 2026-11-19): from a page opened before the switch, a
// revocation takes effect.
it.each(OUTSIDE)('DELETE still revokes when MCP_ALLOWED_SUBS is %s: 200, the row is gone, the value refused', async (_label, value) => {
const [A, B] = [newAccount(), newAccount()];
const [kept, revoked] = [await create(A), await create(A)];
h.limits = [];
pilot(value === 'others' ? `${B}, ${newAccount()}` : value);
const a = await del(A, revoked.id);
expect(a.status).toBe(200);
expect(a.json).toEqual({ ok: true });
expect(h.limits).toEqual([[A, 'create']]);
expect((await rowsOf(A)).map((r) => r.id)).toEqual([kept.id]);
expect(await verifyAgentToken(`Bearer ${revoked.token}`)).toBeNull();
// Reopened, the pilot does not bring the revoked token back.
pilot('*');
expect(((await list(A)).json as Json[]).map((t) => t.id)).toEqual([kept.id]);
expect(await verifyAgentToken(`Bearer ${revoked.token}`)).toBeNull();
});
it('DELETE outside the pilot keeps every other check: account, Origin, Authorization header, session', async () => {
const [A, B] = [newAccount(), newAccount()];
const [a, b] = [await create(A), await create(B)];
const before = [await rowOf(a.id), await rowOf(b.id)];
pilot('');
expect(await del(A, b.id)).toMatchObject(NOT_FOUND);
expect(await del(A, u())).toMatchObject(NOT_FOUND);
expect(await del(A, a.id, { origin: 'https://evil.example' })).toMatchObject(FORBIDDEN);
expect(await del(A, a.id, { authorization: AUTHORIZATIONS[0][1] })).toMatchObject(UNAUTHORIZED);
expect(await del(A, a.id, { authorization: `Bearer ${a.token}` })).toMatchObject(UNAUTHORIZED);
expect(await del(null, a.id)).toMatchObject(UNAUTHORIZED);
expect([await rowOf(a.id), await rowOf(b.id)]).toEqual(before);
});
it('opens GET and POST to the accounts of the list, and to no other', async () => {
const [A, B] = [newAccount(), newAccount()];
pilot(` ${A} , ${newAccount()}`);

View file

@ -1485,6 +1485,51 @@ describe('the write tools and the other accounts', () => {
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
});
// Deleting a list marks the list alone: its tasks stay live, and get_task no
// longer sees them. The write tools answer as get_task does (decision of Max
// of 2026-11-19), and so for a task of the account in a list of another.
it.each(ERAS)('a task left in a deleted list answers not_found to every write tool, as to get_task (%s)', async (era) => {
const [a, b] = [await connected('write'), await connected('write')];
const tag = await newTag(a);
const gone = await newList(a, { deletedAt: GONE });
const recurring = { dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly' };
const open = [await newTask(a, { list: gone, ...recurring }), await newTask(b, { userId: a.userId, ...recurring })];
const done = [
await newTask(a, { list: gone, completed: true, completedAt: '2026-03-02T00:00:00Z' }),
await newTask(b, { userId: a.userId, completed: true, completedAt: '2026-03-02T00:00:00Z' }),
];
const before = await state(a, b);
const NOT_FOUND = { error: 'not_found', message: 'No task with this id exists in this account.' };
for (const task_id of [...open, ...done]) {
expect(await refused(a.token, 'get_task', { task_id }, 'not_found', { era }), `get_task ${task_id}`).toStrictEqual(NOT_FOUND);
}
for (const [name, args] of [
['update_task', { task_id: open[0], title: words('title') }],
// Not even moved back into a live list.
['update_task', { task_id: open[0], list_id: a.inbox }],
['update_task', { task_id: open[1], notes: null }],
['complete_task', { task_id: open[0] }],
['complete_task', { task_id: open[1] }],
['reopen_task', { task_id: done[0] }],
['reopen_task', { task_id: done[1] }],
['set_task_tags', { task_id: open[0], tag_ids: [tag] }],
['set_task_tags', { task_id: open[1], tag_ids: [] }],
] as const) {
expect(await refused(a.token, name, args, 'not_found', { era }), `${name} ${JSON.stringify(args)}`).toStrictEqual(NOT_FOUND);
}
for (const parent_id of open) {
expect(await refused(a.token, 'create_task', { title: words('title'), parent_id }, 'parent_not_found', { era }))
.toStrictEqual({ error: 'parent_not_found', message: TOOL_ERROR_MESSAGES.parent_not_found });
}
// Nothing written, not even a next occurrence, and no journal line.
expect(await state(a, b)).toEqual(before);
expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]);
// Control: once its list is live again, the same calls go through.
await h.pg.query('UPDATE sl_lists SET deleted_at = NULL WHERE id = $1', [gone]);
expect(await ok(a.token, 'complete_task', { task_id: open[0] }, { era })).toMatchObject({ changed: true, task: { id: open[0] } });
});
it.each(ERAS)('no write tool writes, moves or links a row of another account (%s)', async (era) => {
const [a, b] = [await connected('write'), await connected('write')];
const [titleB, notesB] = [words('title'), words('notes')];

View file

@ -0,0 +1,102 @@
"use client";
import { useTranslation } from "react-i18next";
import {
TOKEN_PLACEHOLDER,
claudeCodeTemplate,
codeSpans,
genericTemplate,
hermesTemplate,
} from "@/lib/assistants";
// Block 4 of the « Assistants IA » page (#205): the address of the MCP
// server and four collapsible connection helps. While a token has just been
// created, the templates carry it (`token`); otherwise they carry the
// placeholder, and a sentence says to replace it.
// A text whose code parts are written between backticks (assistants.ts).
function CodeText({ text }: { text: string }) {
return (
<>
{codeSpans(text).map((part, index) =>
part.code ? (
<code key={index} className="font-mono text-xs">
{part.text}
</code>
) : (
<span key={index}>{part.text}</span>
),
)}
</>
);
}
// A block to copy. It scrolls sideways inside its frame instead of widening
// the page.
function Template({ text }: { text: string }) {
return (
<pre className="overflow-x-auto border border-border-light dark:border-border-dark rounded p-2 font-mono text-xs bg-surface-light dark:bg-surface-dark">
<code>{text}</code>
</pre>
);
}
function Help({ title, children }: { title: string; children: React.ReactNode }) {
return (
<details className="border border-border-light dark:border-border-dark rounded-lg px-3 py-2 space-y-2">
<summary className="cursor-pointer text-sm font-medium">{title}</summary>
<div className="space-y-2 text-sm">{children}</div>
</details>
);
}
interface AssistantsConnectProps {
serverUrl: string;
// The token that was just created, null otherwise.
token: string | null;
}
export function AssistantsConnect({ serverUrl, token }: AssistantsConnectProps) {
const { t } = useTranslation();
const value = token ?? TOKEN_PLACEHOLDER;
return (
<section className="space-y-3">
<h3 className="font-semibold">{t("assistants.connect.heading")}</h3>
<div className="space-y-1">
<p className="text-xs text-foreground/50">{t("assistants.connect.url")}</p>
<Template text={serverUrl} />
</div>
{token === null && (
<p className="text-sm text-foreground/60">
<CodeText text={t("assistants.connect.replace")} />
</p>
)}
<Help title={t("assistants.connect.hermes")}>
<p>
<CodeText text={t("assistants.connect.hermesHint")} />
</p>
<Template text={hermesTemplate(serverUrl, value)} />
</Help>
<Help title={t("assistants.connect.claudeCode")}>
<p>{t("assistants.connect.claudeCodeHint")}</p>
<Template text={claudeCodeTemplate(serverUrl, value)} />
</Help>
<Help title={t("assistants.connect.claude")}>
<p>{t("assistants.connect.claudeSteps")}</p>
</Help>
<Help title={t("assistants.connect.generic")}>
<p>{t("assistants.connect.genericHint")}</p>
<Template text={genericTemplate(serverUrl, value)} />
</Help>
<p className="text-xs text-foreground/50">{t("assistants.connect.chatgpt")}</p>
</section>
);
}

View file

@ -0,0 +1,48 @@
"use client";
import { useRef, useState } from "react";
import { Check, Copy } from "lucide-react";
import { useTranslation } from "react-i18next";
// Block 3 of the « Assistants IA » page (#205): the value of the token that
// was just created, shown once. It arrives as a prop from the state of
// AssistantsPanel and is copied nowhere else. The panel keys this component
// by the token: a second creation starts again from « Copier ».
export function AssistantsCreated({ token }: { token: string }) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const value = useRef<HTMLParagraphElement>(null);
const copy = async () => {
try {
// navigator.clipboard only exists in a secure context (https, or
// localhost), and the browser may refuse the write.
await navigator.clipboard.writeText(token);
setCopied(true);
} catch {
// No text was validated for a copy that fails: the button keeps
// « Copier », and the value is selected, ready to be copied by hand.
setCopied(false);
if (value.current) window.getSelection()?.selectAllChildren(value.current);
}
};
return (
<section className="border border-bleu rounded-lg p-4 space-y-3 bg-surface-light dark:bg-surface-dark">
<h3 className="font-semibold">{t("assistants.created.heading")}</h3>
{/* One tap selects the whole value (select-all); it wraps instead of widening the page. */}
<p ref={value} className="font-mono text-sm break-all select-all">
{token}
</p>
<p className="text-sm">{t("assistants.created.once")}</p>
<button
type="button"
onClick={copy}
className="inline-flex items-center gap-2 px-3 py-1.5 text-sm bg-bleu text-white rounded-lg hover:bg-bleu/90 transition-colors"
>
{copied ? <Check size={14} /> : <Copy size={14} />}
{t(copied ? "assistants.created.copied" : "assistants.created.copy")}
</button>
</section>
);
}

View file

@ -0,0 +1,132 @@
"use client";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
actionLabelKey,
formatDayTime,
readJournalPage,
type DateLocale,
type JournalLine,
type JournalPageView,
} from "@/lib/assistants";
// Block 5 of the « Assistants IA » page (#205): what the tokens of the
// account wrote, newest first, 50 lines at a time. The first page comes from
// the server component and follows router.refresh(); « Plus anciennes » asks
// GET /api/agent-actions for the next ones. The panel keys this component
// (journalKey): when the first page or the tokens change, it starts again
// from the first page, and an answer still on its way is dropped with the
// component that asked for it.
interface AssistantsJournalProps {
first: JournalPageView;
locale: DateLocale;
// null until the browser's zone is known: no date is shown before.
timeZone: string | null;
}
export function AssistantsJournal({ first, locale, timeZone }: AssistantsJournalProps) {
const { t } = useTranslation();
const [older, setOlder] = useState<JournalLine[]>([]);
// Where the next page starts; null once the last one is shown.
const [cursor, setCursor] = useState(first.nextCursor);
const [busy, setBusy] = useState(false);
const [loadError, setLoadError] = useState(false);
const loadOlder = async () => {
if (busy || cursor === null) return;
setBusy(true);
setLoadError(false);
try {
const res = await fetch(`/api/agent-actions?before=${encodeURIComponent(cursor)}`);
if (!res.ok) {
setLoadError(true);
return;
}
const page = readJournalPage(await res.json());
if (page === null) {
setLoadError(true);
return;
}
setOlder((lines) => [...lines, ...page.actions]);
setCursor(page.nextCursor);
} catch {
setLoadError(true);
} finally {
setBusy(false);
}
};
const lines = [...first.actions, ...older];
return (
<section className="space-y-3">
<div className="space-y-1">
<h3 className="font-semibold">{t("assistants.journal.heading")}</h3>
<p className="text-xs text-foreground/50">{t("assistants.journal.retention")}</p>
</div>
{lines.length === 0 ? (
<p className="text-sm text-foreground/40">{t("assistants.journal.empty")}</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-xs text-left">
<thead>
<tr className="border-b border-border-light dark:border-border-dark text-foreground/50">
<th className="py-1 pr-3 font-medium">{t("assistants.journal.date")}</th>
<th className="py-1 pr-3 font-medium">{t("assistants.journal.token")}</th>
<th className="py-1 pr-3 font-medium">{t("assistants.journal.action")}</th>
<th className="py-1 font-medium">{t("assistants.journal.item")}</th>
</tr>
</thead>
<tbody>
{lines.map((line) => {
const labelKey = actionLabelKey(line.tool);
return (
<tr key={line.id} className="border-b border-border-light dark:border-border-dark align-top">
<td className="py-1.5 pr-3 whitespace-nowrap">
{timeZone && formatDayTime(line.createdAt, locale, timeZone)}
</td>
<td className="py-1.5 pr-3">
<span className="flex flex-wrap gap-1">
<span>{line.tokenName}</span>
{line.tokenRevoked && (
<span className="text-foreground/50">{t("assistants.journal.revoked")}</span>
)}
</span>
</td>
{/* A tool without a label is shown by its name, as the journal holds it. */}
<td className="py-1.5 pr-3">{labelKey ? t(labelKey) : line.tool}</td>
<td className="py-1.5">
{line.entityName ?? (
<span className="italic text-foreground/50">{t("assistants.journal.deleted")}</span>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{loadError && (
<p role="alert" className="text-xs text-rouge">
{t("assistants.journal.loadError")}
</p>
)}
{cursor !== null && (
<button
type="button"
onClick={loadOlder}
disabled={busy}
className="text-xs text-bleu hover:underline disabled:opacity-50"
>
{t("assistants.journal.older")}
</button>
)}
</section>
);
}

View file

@ -0,0 +1,94 @@
"use client";
import { useState, useSyncExternalStore } from "react";
import { useTranslation } from "react-i18next";
import {
dateLocale,
journalKey,
type JournalPageView,
type TokenView,
} from "@/lib/assistants";
import { AssistantsTokens } from "./AssistantsTokens";
import { AssistantsCreated } from "./AssistantsCreated";
import { AssistantsConnect } from "./AssistantsConnect";
import { AssistantsJournal } from "./AssistantsJournal";
// The « Assistants IA » page (#205): five blocks, from top to bottom. The
// server component (app/(app)/assistants/page.tsx) reads the tokens and the
// first page of the journal; these components call the routes, then
// router.refresh(). Logic lives in web/src/lib/assistants.ts (tested); this
// JSX is not covered by tests.
// The value of a token that was just created, with the id of its row.
export type CreatedToken = { id: string; token: string };
// The time zone of the browser. React renders these components once on the
// server, in a container that runs in UTC, then hydrates that HTML: both
// passes read `null` here and format no date, so the first HTML never shows
// a UTC time and hydration finds the markup it expects. The zone is read
// right after, and the dates appear in the user's local time.
const subscribeToNothing = () => () => {};
const browserTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
const noTimeZone = () => null;
interface AssistantsPanelProps {
tokens: TokenView[];
// The account holds as many tokens as it may (MAX_AGENT_TOKENS).
atLimit: boolean;
// First page of the journal.
journal: JournalPageView;
// Address of the MCP server.
serverUrl: string;
}
export function AssistantsPanel({ tokens, atLimit, journal, serverUrl }: AssistantsPanelProps) {
const { t, i18n } = useTranslation();
// The only place the value of a token lives once POST /api/agent-tokens has
// answered: this state. It is never written to the address bar nor to any
// browser storage, and the server component never sends it. The page
// renders this component at a fixed place and without a key, so
// router.refresh() keeps the state; reloading the page erases it.
const [created, setCreated] = useState<CreatedToken | null>(null);
const timeZone = useSyncExternalStore<string | null>(subscribeToNothing, browserTimeZone, noTimeZone);
const locale = dateLocale(i18n.resolvedLanguage);
return (
<div className="max-w-2xl mx-auto w-full space-y-6">
<h2 className="text-xl font-semibold">{t("assistants.title")}</h2>
{/* 1. Warning, always visible */}
<p
role="note"
className="border border-border-light dark:border-border-dark border-l-[3px] border-l-sable rounded-lg p-4 text-sm bg-surface-light dark:bg-surface-dark"
>
{t("assistants.warning")}
</p>
{/* 2. Tokens and creation form */}
<AssistantsTokens
tokens={tokens}
atLimit={atLimit}
locale={locale}
timeZone={timeZone}
onCreated={setCreated}
// A token revoked right after its creation leaves the page with its row.
onRevoked={(id) => setCreated((current) => (current?.id === id ? null : current))}
/>
{/* 3. The token that was just created, shown once */}
{created && <AssistantsCreated key={created.id} token={created.token} />}
{/* 4. Connection help; its templates carry the new token while it is known */}
<AssistantsConnect serverUrl={serverUrl} token={created?.token ?? null} />
{/* 5. Journal. Keyed: the older pages it loaded are dropped when the
first page or the tokens change (journalKey). */}
<AssistantsJournal
key={journalKey(journal, tokens)}
first={journal}
locale={locale}
timeZone={timeZone}
/>
</div>
);
}

View file

@ -0,0 +1,262 @@
"use client";
import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
DEFAULT_TOKEN_DURATION,
DEFAULT_TOKEN_SCOPE,
DURATION_LABEL_KEYS,
SCOPE_LABEL_KEYS,
TOKEN_DURATIONS,
TOKEN_SCOPES,
formatDay,
formatDayTime,
validateTokenName,
type DateLocale,
type TokenDuration,
type TokenScope,
type TokenView,
} from "@/lib/assistants";
import type { CreatedToken } from "./AssistantsPanel";
// Block 2 of the « Assistants IA » page (#205): the tokens of the account,
// each with its « Révoquer » button, then the creation form, which the
// sentence `assistants.form.limit` replaces once the account holds ten.
const FIELD =
"bg-transparent border border-border-light dark:border-border-dark rounded px-2 py-1 text-sm focus:outline-none focus:border-bleu";
function TokenForm({ onCreated }: { onCreated: (created: CreatedToken) => void }) {
const { t } = useTranslation();
const router = useRouter();
const [name, setName] = useState("");
const [scope, setScope] = useState<TokenScope>(DEFAULT_TOKEN_SCOPE);
const [duration, setDuration] = useState<TokenDuration>(DEFAULT_TOKEN_DURATION);
// Key of the text to show, so that it follows the active language.
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const submit = async (event: FormEvent) => {
event.preventDefault();
if (busy) return;
const check = validateTokenName(name);
if (!check.ok) {
setError(check.reason === "empty" ? "assistants.form.nameRequired" : "assistants.form.nameTooLong");
return;
}
setBusy(true);
setError(null);
try {
const res = await fetch("/api/agent-tokens", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: check.name, scope, duration }),
});
if (res.status === 409) {
// The tenth token was created elsewhere since this page was read:
// the reloaded list replaces this form by the same sentence.
setError("assistants.form.limit");
router.refresh();
return;
}
if (!res.ok) {
setError("assistants.form.createError");
return;
}
const body = (await res.json()) as { id?: unknown; token?: unknown };
if (typeof body.id !== "string" || typeof body.token !== "string") {
setError("assistants.form.createError");
return;
}
// The only copy of the value: it goes to the state of the panel.
onCreated({ id: body.id, token: body.token });
setName("");
setScope(DEFAULT_TOKEN_SCOPE);
setDuration(DEFAULT_TOKEN_DURATION);
// Reloads the server data: the list shows the new token.
router.refresh();
} catch {
setError("assistants.form.createError");
} finally {
setBusy(false);
}
};
return (
<form
onSubmit={submit}
className="border border-border-light dark:border-border-dark rounded-lg p-4 space-y-3 bg-surface-light dark:bg-surface-dark"
>
<h4 className="text-sm font-semibold">{t("assistants.form.heading")}</h4>
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.name")}
<input
value={name}
onChange={(e) => {
setName(e.target.value);
setError(null);
}}
placeholder={t("assistants.form.namePlaceholder")}
className={`w-full text-foreground placeholder:text-foreground/40 ${FIELD}`}
/>
</label>
<div className="flex flex-wrap items-center gap-3">
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.scope")}
<select
value={scope}
onChange={(e) => setScope(e.target.value as TokenScope)}
className={`text-foreground ${FIELD}`}
>
{TOKEN_SCOPES.map((value) => (
<option key={value} value={value}>
{t(SCOPE_LABEL_KEYS[value])}
</option>
))}
</select>
</label>
<label className="flex flex-col gap-1 text-xs text-foreground/50">
{t("assistants.form.duration")}
<select
value={duration}
onChange={(e) => setDuration(e.target.value as TokenDuration)}
className={`text-foreground ${FIELD}`}
>
{TOKEN_DURATIONS.map((value) => (
<option key={value} value={value}>
{t(DURATION_LABEL_KEYS[value])}
</option>
))}
</select>
</label>
</div>
{error && (
<p role="alert" className="text-xs text-rouge">
{t(error)}
</p>
)}
<div className="flex justify-end">
<button
type="submit"
disabled={busy}
className="px-3 py-1.5 text-sm bg-bleu text-white rounded-lg hover:bg-bleu/90 disabled:opacity-50 transition-colors"
>
{t("assistants.form.submit")}
</button>
</div>
</form>
);
}
interface AssistantsTokensProps {
tokens: TokenView[];
atLimit: boolean;
locale: DateLocale;
// null until the browser's zone is known: no date is shown before.
timeZone: string | null;
onCreated: (created: CreatedToken) => void;
onRevoked: (tokenId: string) => void;
}
export function AssistantsTokens({ tokens, atLimit, locale, timeZone, onCreated, onRevoked }: AssistantsTokensProps) {
const { t } = useTranslation();
const router = useRouter();
const [busyId, setBusyId] = useState<string | null>(null);
const [revokeError, setRevokeError] = useState(false);
const revoke = async (token: TokenView) => {
if (busyId) return;
if (!window.confirm(t("assistants.tokens.revokeConfirm", { name: token.name }))) return;
setBusyId(token.id);
setRevokeError(false);
try {
const res = await fetch(`/api/agent-tokens/${token.id}`, { method: "DELETE" });
// 404: the token is already gone (revoked from another tab). The
// reloaded list says so better than an error would.
if (!res.ok && res.status !== 404) {
setRevokeError(true);
return;
}
onRevoked(token.id);
router.refresh();
} catch {
setRevokeError(true);
} finally {
setBusyId(null);
}
};
return (
<section className="space-y-3">
<h3 className="font-semibold">{t("assistants.tokens.heading")}</h3>
{tokens.length === 0 ? (
<p className="text-sm text-foreground/40">{t("assistants.tokens.empty")}</p>
) : (
<ul className="space-y-2">
{tokens.map((token) => (
<li
key={token.id}
className="border border-border-light dark:border-border-dark rounded-lg p-4 space-y-2 bg-surface-light dark:bg-surface-dark"
>
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium truncate">{token.name}</span>
<button
type="button"
onClick={() => revoke(token)}
disabled={busyId !== null}
className="shrink-0 text-xs text-rouge hover:underline disabled:opacity-50"
>
{t("assistants.tokens.revoke")}
</button>
</div>
<div className="flex flex-wrap gap-3 text-xs text-foreground/50">
<span>{t(SCOPE_LABEL_KEYS[token.scope])}</span>
<span>{t("assistants.tokens.hint", { hint: token.hint })}</span>
</div>
<div className="flex flex-wrap gap-3 text-xs text-foreground/50">
{timeZone && (
<span>{t("assistants.tokens.created", { date: formatDay(token.createdAt, locale, timeZone) })}</span>
)}
{token.lastUsedAt === null ? (
<span>{t("assistants.tokens.neverUsed")}</span>
) : (
timeZone && (
<span>
{t("assistants.tokens.lastUsed", { date: formatDayTime(token.lastUsedAt, locale, timeZone) })}
</span>
)
)}
{token.expiresAt === null ? (
<span>{t("assistants.tokens.noExpiry")}</span>
) : (
timeZone && (
// `expired` was decided by the server on the instant, not on the day shown.
<span className={token.expired ? "text-rouge" : undefined}>
{t(token.expired ? "assistants.tokens.expired" : "assistants.tokens.expires", {
date: formatDay(token.expiresAt, locale, timeZone),
})}
</span>
)
)}
</div>
</li>
))}
</ul>
)}
{revokeError && (
<p role="alert" className="text-xs text-rouge">
{t("assistants.tokens.revokeError")}
</p>
)}
{atLimit ? (
<p className="text-sm text-foreground/60">{t("assistants.form.limit")}</p>
) : (
<TokenForm onCreated={onCreated} />
)}
</section>
);
}

View file

@ -1,15 +1,19 @@
"use client";
import { ThemeToggle } from "./ThemeToggle";
import { User, LogOut } from "lucide-react";
import { Bot, User, LogOut } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useTranslation } from "react-i18next";
interface HeaderProps {
userName: string;
// The account is in the pilot of the AI assistants (#205): outside it, the
// menu has no entry for a page that answers 404.
showAssistants: boolean;
}
export function Header({ userName }: HeaderProps) {
export function Header({ userName, showAssistants }: HeaderProps) {
const { t } = useTranslation();
const [menuOpen, setMenuOpen] = useState(false);
@ -47,6 +51,16 @@ export function Header({ userName }: HeaderProps) {
<div className="px-3 py-2 text-xs text-foreground/50 truncate">
{userName}
</div>
{showAssistants && (
<Link
href="/assistants"
className="flex items-center gap-2 px-3 py-2 text-sm hover:bg-black/5 dark:hover:bg-white/10 transition-colors"
onClick={() => setMenuOpen(false)}
>
<Bot size={14} />
{t("assistants.title")}
</Link>
)}
<a
href="/api/logto/sign-out"
className="flex items-center gap-2 px-3 py-2 text-sm text-rouge hover:bg-rouge/10 transition-colors"

View file

@ -98,5 +98,88 @@
"title": "Welcome to Simpl-Liste",
"message": "Create your first list using the button in the sidebar.",
"loading": "Loading..."
},
"assistants": {
"title": "AI assistants",
"warning": "An AI assistant connected with this token can read your lists, your tasks (titles, notes, due dates) and your tags. With a \"Read and write\" token it can also add and edit them; it cannot delete anything, but its changes cannot be undone. What the assistant reads is sent to the provider of its AI model: you choose that assistant, Simpl-Liste sends nothing by itself. You can revoke this token at any time.",
"tokens": {
"heading": "Access tokens",
"empty": "No token yet.",
"hint": "ends with {{hint}}",
"created": "Created on {{date}}",
"lastUsed": "Last used: {{date}}",
"neverUsed": "Last used: never",
"expires": "Expires on {{date}}",
"noExpiry": "No expiration",
"expired": "Expired on {{date}}",
"revoke": "Revoke",
"revokeConfirm": "Revoke the token \"{{name}}\"? The assistant using it will lose access immediately.",
"revokeError": "The token could not be revoked."
},
"form": {
"heading": "Create a token",
"name": "Name",
"namePlaceholder": "For example: Hermes, Claude Code",
"scope": "Access level",
"duration": "Duration",
"submit": "Create token",
"nameRequired": "The name cannot be empty.",
"nameTooLong": "The name cannot exceed 100 characters.",
"createError": "The token could not be created.",
"limit": "You have 10 tokens, the maximum. Revoke one to create another."
},
"scope": {
"read": "Read only",
"write": "Read and write"
},
"duration": {
"90d": "90 days",
"1y": "1 year",
"never": "No expiration"
},
"created": {
"heading": "Your new token",
"once": "Copy it now: this token will not be shown again. Keep it like a password.",
"copy": "Copy",
"copied": "Copied"
},
"connect": {
"heading": "Connect an assistant",
"url": "Server address",
"replace": "Replace `slmcp_…` with your token.",
"hermes": "Hermes",
"claudeCode": "Claude Code",
"claude": "Claude (custom connector)",
"generic": "Other MCP client",
"chatgpt": "ChatGPT is not supported yet: it requires an account sign-in, planned for later.",
"hermesHint": "In `~/.hermes/config.yaml`:",
"claudeCodeHint": "In a terminal:",
"claudeSteps": "In Claude, open Customize, then Connectors, then \"Add custom connector\". Enter a name and the server address. At the \"Request headers\" step, add the Authorization header with the value Bearer followed by your token.",
"genericHint": "HTTP transport, at the server address above, with the header Authorization: Bearer followed by your token."
},
"journal": {
"heading": "Action log",
"retention": "What your assistants wrote, kept for 90 days.",
"empty": "No action yet.",
"date": "Date",
"token": "Token",
"action": "Action",
"item": "Item",
"revoked": "(revoked)",
"deleted": "deleted",
"older": "Older",
"loadError": "The log could not be loaded."
},
"action": {
"create_task": "Task created",
"update_task": "Task edited",
"complete_task": "Task completed",
"reopen_task": "Task reopened",
"set_task_tags": "Task tags changed",
"create_list": "List created",
"update_list": "List edited",
"create_tag": "Tag created",
"update_tag": "Tag edited"
}
}
}

View file

@ -98,5 +98,88 @@
"title": "Bienvenue sur Simpl-Liste",
"message": "Créez votre première liste en utilisant le bouton dans la barre latérale.",
"loading": "Chargement..."
},
"assistants": {
"title": "Assistants IA",
"warning": "Un assistant IA relié par ce jeton peut lire vos listes, vos tâches (titres, notes, échéances) et vos étiquettes. Avec un jeton « Lecture et écriture », il peut aussi en ajouter et les modifier ; il ne peut rien supprimer, mais ses modifications ne s'annulent pas. Ce que l'assistant lit est transmis au fournisseur de son modèle d'IA : c'est vous qui choisissez cet assistant, Simpl-Liste n'envoie rien de lui-même. Vous pouvez révoquer ce jeton à tout moment.",
"tokens": {
"heading": "Jetons d'accès",
"empty": "Aucun jeton pour le moment.",
"hint": "se termine par {{hint}}",
"created": "Créé le {{date}}",
"lastUsed": "Dernière utilisation : {{date}}",
"neverUsed": "Dernière utilisation : jamais",
"expires": "Expire le {{date}}",
"noExpiry": "Sans expiration",
"expired": "Expiré le {{date}}",
"revoke": "Révoquer",
"revokeConfirm": "Révoquer le jeton « {{name}} » ? L'assistant qui l'utilise perdra l'accès tout de suite.",
"revokeError": "Le jeton n'a pas pu être révoqué."
},
"form": {
"heading": "Créer un jeton",
"name": "Nom",
"namePlaceholder": "Par exemple : Hermes, Claude Code",
"scope": "Niveau",
"duration": "Durée",
"submit": "Créer le jeton",
"nameRequired": "Le nom ne peut pas être vide.",
"nameTooLong": "Le nom ne peut pas dépasser 100 caractères.",
"createError": "Le jeton n'a pas pu être créé.",
"limit": "Vous avez 10 jetons, le maximum. Révoquez-en un pour en créer un autre."
},
"scope": {
"read": "Lecture seule",
"write": "Lecture et écriture"
},
"duration": {
"90d": "90 jours",
"1y": "1 an",
"never": "Sans expiration"
},
"created": {
"heading": "Votre nouveau jeton",
"once": "Copiez-le maintenant : ce jeton ne sera plus affiché. Conservez-le comme un mot de passe.",
"copy": "Copier",
"copied": "Copié"
},
"connect": {
"heading": "Relier un assistant",
"url": "Adresse du serveur",
"replace": "Remplacez `slmcp_…` par votre jeton.",
"hermes": "Hermes",
"claudeCode": "Claude Code",
"claude": "Claude (connecteur personnalisé)",
"generic": "Autre client MCP",
"chatgpt": "ChatGPT n'est pas encore pris en charge : il exige une connexion par compte, prévue plus tard.",
"hermesHint": "Dans `~/.hermes/config.yaml` :",
"claudeCodeHint": "Dans un terminal :",
"claudeSteps": "Dans Claude, ouvrez Customize, puis Connectors, puis « Add custom connector ». Saisissez un nom et l'adresse du serveur. À l'étape « Request headers », ajoutez l'en-tête Authorization avec la valeur Bearer suivie de votre jeton.",
"genericHint": "Transport HTTP, à l'adresse du serveur ci-dessus, avec l'en-tête Authorization : Bearer suivi de votre jeton."
},
"journal": {
"heading": "Journal des actions",
"retention": "Ce que vos assistants ont écrit, conservé 90 jours.",
"empty": "Aucune action pour le moment.",
"date": "Date",
"token": "Jeton",
"action": "Action",
"item": "Élément",
"revoked": "(révoqué)",
"deleted": "supprimé",
"older": "Plus anciennes",
"loadError": "Le journal n'a pas pu être chargé."
},
"action": {
"create_task": "Tâche créée",
"update_task": "Tâche modifiée",
"complete_task": "Tâche complétée",
"reopen_task": "Tâche rouverte",
"set_task_tags": "Étiquettes de la tâche modifiées",
"create_list": "Liste créée",
"update_list": "Liste modifiée",
"create_tag": "Étiquette créée",
"update_tag": "Étiquette modifiée"
}
}
}

View file

@ -0,0 +1,49 @@
import { describe, it, expect } from 'vitest';
import fr from './fr.json';
import en from './en.json';
// The texts of the site (#205): fr.json and en.json hold the same keys, and
// no key is left without a text. Every failure names the keys in fault, in
// the message of its assertion.
// Every leaf of a file, by its dotted key (`assistants.tokens.heading`).
function leaves(node: unknown, prefix = ''): [key: string, value: unknown][] {
if (node === null || typeof node !== 'object' || Array.isArray(node)) return [[prefix, node]];
return Object.entries(node).flatMap(([key, value]) => leaves(value, prefix === '' ? key : `${prefix}.${key}`));
}
// The interpolation variables of a text, sorted: `{{name}}` gives `name`.
function variables(text: unknown): string[] {
if (typeof text !== 'string') return [];
return [...text.matchAll(/\{\{\s*([^}\s]+)\s*\}\}/g)].map((match) => match[1]).sort();
}
const FILES = { fr: new Map(leaves(fr)), en: new Map(leaves(en)) };
describe('fr.json and en.json', () => {
it('hold the same keys', () => {
const frOnly = [...FILES.fr.keys()].filter((key) => !FILES.en.has(key));
const enOnly = [...FILES.en.keys()].filter((key) => !FILES.fr.has(key));
expect(frOnly, `keys of fr.json missing in en.json: ${frOnly.join(', ')}`).toEqual([]);
expect(enOnly, `keys of en.json missing in fr.json: ${enOnly.join(', ')}`).toEqual([]);
// Control: the comparison had something to read.
expect(FILES.fr.size).toBeGreaterThan(50);
});
it('hold no empty value: every key has a text', () => {
const empty = Object.entries(FILES).flatMap(([file, texts]) =>
[...texts]
.filter(([, value]) => typeof value !== 'string' || value.trim() === '')
.map(([key]) => `${file}.json: ${key}`));
expect(empty, `keys without a text: ${empty.join(', ')}`).toEqual([]);
});
it('use the same interpolation variables in both languages', () => {
const different = [...FILES.fr]
.filter(([key, text]) => variables(text).join() !== variables(FILES.en.get(key)).join())
.map(([key, text]) => `${key} (fr: ${variables(text)}; en: ${variables(FILES.en.get(key))})`);
expect(different, `keys whose variables differ: ${different.join(', ')}`).toEqual([]);
// Control: some texts do carry a variable.
expect([...FILES.fr.values()].filter((text) => variables(text).length > 0).length).toBeGreaterThan(10);
});
});

View file

@ -20,7 +20,7 @@ vi.mock('@/lib/auth', () => ({
},
}));
const { mcpAllowed, requireAssistantsSession } = await import('./agentAccess');
const { mcpAllowed, requireAssistantsSession, requireSiteSession } = await import('./agentAccess');
const initial = process.env.MCP_ALLOWED_SUBS;
@ -169,3 +169,44 @@ describe('requireAssistantsSession', () => {
expect(await requireAssistantsSession()).toEqual({ userId: A });
});
});
// The guard of the revocation (decision of Max of 2026-11-19): the session of
// the site, whatever the pilot.
describe('requireSiteSession', () => {
async function refusal(userId?: string) {
const r = await requireSiteSession();
expect(r.userId).toBeUndefined();
const text = await r.error!.text();
if (userId) expect(text).not.toContain(userId);
return { status: r.error!.status, body: JSON.parse(text) as unknown };
}
it.each([
['absent', undefined],
['empty', ''],
['a list without the account', `${newUser()}, ${newUser()}`],
['`*`', '*'],
])('returns the account of the site session whatever the pilot (variable %s)', async (_label, value) => {
const A = newUser();
pilot(value);
h.session = { userId: A };
expect(await requireSiteSession()).toEqual({ userId: A });
});
it.each([
['an agent token', `Bearer slmcp_${'A'.repeat(43)}`],
['a Logto access token', 'Bearer logto-access-token-of-the-test'],
['an empty value', ''],
])('answers 401 to an Authorization header (%s), before reading the session', async (_label, authorization) => {
const A = newUser();
h.session = { userId: A };
h.headers = new Headers({ authorization });
expect(await refusal(A)).toEqual({ status: 401, body: { error: 'Unauthorized' } });
expect(h.sessionReads).toBe(0);
});
it('answers 401 without a session', async () => {
pilot('*');
expect(await refusal()).toEqual({ status: 401, body: { error: 'Unauthorized' } });
});
});

View file

@ -23,20 +23,24 @@ export function mcpAllowed(userId: string): boolean {
});
}
type SessionGuard =
| { userId: string; error?: never }
| { userId?: never; error: NextResponse };
/**
* Guard of the routes that manage agent tokens and read the agent journal.
* They take the session of the site only (decision of Max, 2026-11-14): a
* The session of the site, and only it (decision of Max, 2026-11-14): a
* short-lived Logto access token, the mobile app's or another app's, must not
* be able to mint a token that never expires. In this order:
* 1. an Authorization header, whatever it holds: 401, before anything else;
* 2. no session of the site: 401;
* 3. an account outside the pilot: 404, as if the route did not exist.
* 2. no session of the site: 401.
* The pilot is not checked: this is the guard of DELETE /api/agent-tokens/[id],
* so that revoking a token always takes effect, even while the pilot is
* closed (decision of Max, 2026-11-19): the emergency switch closes the
* server, never the way to revoke a token that leaked. Every other route of
* the assistants goes through requireAssistantsSession().
* Returns `{ userId }` or `{ error }`, like requireAuth().
*/
export async function requireAssistantsSession(): Promise<
| { userId: string; error?: never }
| { userId?: never; error: NextResponse }
> {
export async function requireSiteSession(): Promise<SessionGuard> {
const headersList = await headers();
if (headersList.get('authorization') !== null) {
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
@ -47,9 +51,22 @@ export async function requireAssistantsSession(): Promise<
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
}
if (!mcpAllowed(user.userId)) {
return { userId: user.userId };
}
/**
* Guard of the routes that list and create agent tokens and read the agent
* journal: requireSiteSession(), then
* 3. an account outside the pilot: 404, as if the route did not exist.
* Returns `{ userId }` or `{ error }`, like requireAuth().
*/
export async function requireAssistantsSession(): Promise<SessionGuard> {
const session = await requireSiteSession();
if (session.error) return session;
if (!mcpAllowed(session.userId)) {
return { error: NextResponse.json({ error: 'Not found' }, { status: 404 }) };
}
return { userId: user.userId };
return session;
}

View file

@ -0,0 +1,587 @@
import fs from 'node:fs';
import path from 'node:path';
import { describe, it, expect, vi } from 'vitest';
import fr from '@/i18n/fr.json';
import en from '@/i18n/en.json';
import type { JournalPage } from './agentJournal';
import type { AgentToken } from './agentTokens';
import {
ACTION_LABEL_KEYS, DEFAULT_TOKEN_DURATION, DEFAULT_TOKEN_SCOPE, DURATION_LABEL_KEYS, JOURNAL_PAGE_SIZE,
SCOPE_LABEL_KEYS, TOKEN_DURATIONS, TOKEN_NAME_MAX, TOKEN_PLACEHOLDER, TOKEN_SCOPES,
actionLabelKey, claudeCodeTemplate, codeSpans, dateLocale, decodeJournalCursor, encodeJournalCursor,
formatDay, formatDayTime, genericTemplate, hermesTemplate, isExpired, journalKey, journalPageView,
mcpServerUrl, readJournalPage, tokenView, validateTokenName,
type JournalPageView, type TokenView,
} from './assistants';
// Helpers of the « Assistants IA » page (#205). assistants.ts goes to the
// browser, so it only imports types; this file may load the server modules
// it is compared with. WRITE_TOOL_NAMES lives in a module that imports the
// database client and the WebSocket notice: both are replaced, nothing here
// runs a query.
vi.mock('@/db/client', () => ({ db: {} }));
vi.mock('@/lib/ws', () => ({ notifyUserChanged: () => {} }));
const { WRITE_TOOL_NAMES } = await import('./mcp/writeTools');
const { createAgentTokenSchema } = await import('./validators');
const SOURCE = fs.readFileSync(path.join(__dirname, 'assistants.ts'), 'utf8');
const COMPONENTS = path.join(__dirname, '../components');
// The address of the site in production, and a token of the real shape.
const SERVER = 'https://liste.lacompagniemaximus.com/api/mcp';
const TOKEN = `slmcp_${'aB3-_xYz'.repeat(5)}Q9w`;
// The two blocks of issue #205, as Max validated them, comment line included.
const HERMES_BLOCK = `# Hermes — ~/.hermes/config.yaml
mcp_servers:
simpl-liste:
url: "https://liste.lacompagniemaximus.com/api/mcp"
headers:
Authorization: "Bearer slmcp_…"`;
const CLAUDE_CODE_BLOCK = `# Claude Code
claude mcp add --transport http simpl-liste https://liste.lacompagniemaximus.com/api/mcp --header "Authorization: Bearer slmcp_…"`;
const TEMPLATES = [
['hermesTemplate', hermesTemplate],
['claudeCodeTemplate', claudeCodeTemplate],
['genericTemplate', genericTemplate],
] as const;
type Texts = { [key: string]: string | Texts };
// The text of a dotted key in a language file, undefined when it has none.
function textOf(file: Texts, key: string): unknown {
return key.split('.').reduce<unknown>(
(node, part) => (node !== null && typeof node === 'object' ? (node as Texts)[part] : undefined),
file,
);
}
// Every dotted key under `assistants` in a language file.
function keysOf(node: Texts, prefix: string): string[] {
return Object.entries(node).flatMap(([key, value]) =>
typeof value === 'string' ? [`${prefix}.${key}`] : keysOf(value, `${prefix}.${key}`));
}
// Spaces as the test writes them: Intl may answer with no-break spaces.
const plain = (text: string) => text.replace(/\s/g, ' ');
const occurrences = (text: string, part: string) => text.split(part).length - 1;
function token(fields: Partial<AgentToken> = {}): AgentToken {
return {
id: '11111111-1111-4111-8111-111111111111',
name: 'Hermes',
scope: 'read',
hint: 'Q9w0',
createdAt: new Date('2026-11-14T15:32:10.123Z'),
lastUsedAt: null,
expiresAt: null,
...fields,
};
}
describe('what the browser loads', () => {
it('imports types only: zod, the database and the MCP server must not follow it to the browser', () => {
const imports = SOURCE.match(/^[ \t]*import\s[^;]*;/gm) ?? [];
// Control: the module does import the type of the write tool names.
expect(imports.some((line) => line.includes("'./mcp/writeTools'"))).toBe(true);
expect(imports.filter((line) => !/^import type \{[^}]*\} from '\.\/[A-Za-z/]+';$/.test(line))).toEqual([]);
expect(SOURCE).not.toMatch(/\bimport\(|\brequire\(|^\s*export\s.*\bfrom\s+['"]/m);
});
});
describe('creation form', () => {
it('offers the scopes and the durations of the schema, in the order of the form', () => {
expect([...TOKEN_SCOPES]).toEqual(createAgentTokenSchema.shape.scope.options);
expect([...TOKEN_DURATIONS]).toEqual(createAgentTokenSchema.shape.duration.options);
});
// Decision of Max, 2026-11-14.
it('preselects « Lecture seule » and « 1 an »', () => {
expect(DEFAULT_TOKEN_SCOPE).toBe('read');
expect(DEFAULT_TOKEN_DURATION).toBe('1y');
expect(textOf(fr, SCOPE_LABEL_KEYS[DEFAULT_TOKEN_SCOPE])).toBe('Lecture seule');
expect(textOf(fr, DURATION_LABEL_KEYS[DEFAULT_TOKEN_DURATION])).toBe('1 an');
});
it('has a label in both languages for every scope and every duration', () => {
expect(Object.keys(SCOPE_LABEL_KEYS)).toEqual([...TOKEN_SCOPES]);
expect(Object.keys(DURATION_LABEL_KEYS)).toEqual([...TOKEN_DURATIONS]);
for (const key of [...Object.values(SCOPE_LABEL_KEYS), ...Object.values(DURATION_LABEL_KEYS)]) {
expect(textOf(fr, key), key).toEqual(expect.stringMatching(/\S/));
expect(textOf(en, key), key).toEqual(expect.stringMatching(/\S/));
}
});
it.each([
['an empty name', '', 'empty'],
['a name made of spaces', ' \t ', 'empty'],
['a name of 101 characters', 'x'.repeat(101), 'tooLong'],
])('refuses %s, as the schema does', (_label, raw, reason) => {
expect(validateTokenName(raw)).toEqual({ ok: false, reason });
expect(createAgentTokenSchema.safeParse({ name: raw, scope: 'read', duration: '1y' }).success).toBe(false);
});
it.each([
['one character', 'x', 'x'],
['100 characters', 'x'.repeat(100), 'x'.repeat(100)],
['100 characters between spaces', ` ${'x'.repeat(100)}\t`, 'x'.repeat(100)],
['spaces inside the name', ' Claude Code ', 'Claude Code'],
])('accepts %s and trims it, as the schema does', (_label, raw, name) => {
expect(validateTokenName(raw)).toEqual({ ok: true, name });
expect(createAgentTokenSchema.parse({ name: raw, scope: 'read', duration: '1y' }).name).toBe(name);
});
it('bounds the name as the texts say', () => {
expect(TOKEN_NAME_MAX).toBe(100);
expect(textOf(fr, 'assistants.form.nameTooLong')).toContain(String(TOKEN_NAME_MAX));
expect(textOf(en, 'assistants.form.nameTooLong')).toContain(String(TOKEN_NAME_MAX));
});
});
describe('journal labels', () => {
it('has one label key per write tool of the MCP server', () => {
expect(Object.keys(ACTION_LABEL_KEYS).sort()).toEqual([...WRITE_TOOL_NAMES].sort());
// Control: the list of the server is the one this PR was written for.
expect(WRITE_TOOL_NAMES).toHaveLength(9);
});
it.each([...WRITE_TOOL_NAMES])('%s has its label in both languages', (tool) => {
const key = actionLabelKey(tool);
expect(key).toBe(`assistants.action.${tool}`);
expect(textOf(fr, key!)).toEqual(expect.stringMatching(/\S/));
expect(textOf(en, key!)).toEqual(expect.stringMatching(/\S/));
});
it('gives each tool a label of its own', () => {
for (const file of [fr, en]) {
const labels = WRITE_TOOL_NAMES.map((tool) => textOf(file, ACTION_LABEL_KEYS[tool]));
expect(new Set(labels).size).toBe(WRITE_TOOL_NAMES.length);
}
});
it.each(['delete_task', '', 'constructor', 'toString', '__proto__', 'CREATE_TASK'])(
'has no label for %j: the page shows the name of the tool',
(tool) => {
expect(actionLabelKey(tool)).toBeNull();
},
);
});
describe('connection templates', () => {
it('the Hermes template is the block of the issue, without its comment line', () => {
const [comment, ...block] = HERMES_BLOCK.split('\n');
expect(comment).toMatch(/^# Hermes /);
expect(hermesTemplate(SERVER)).toBe(block.join('\n'));
expect(block).toHaveLength(5);
});
it('the Claude Code template is the block of the issue, without its comment line', () => {
const [comment, ...block] = CLAUDE_CODE_BLOCK.split('\n');
expect(comment).toBe('# Claude Code');
expect(claudeCodeTemplate(SERVER)).toBe(block.join('\n'));
expect(block).toHaveLength(1);
});
it('the generic template is the address, then the Authorization header', () => {
expect(genericTemplate(SERVER)).toBe(`${SERVER}\nAuthorization: Bearer ${TOKEN_PLACEHOLDER}`);
});
it('the placeholder is the one the texts tell the user to replace', () => {
expect([...TOKEN_PLACEHOLDER].map((c) => c.codePointAt(0))).toEqual([
...[...'slmcp_'].map((c) => c.codePointAt(0)),
0x2026,
]);
for (const file of [fr, en]) {
const code = codeSpans(textOf(file, 'assistants.connect.replace') as string).filter((part) => part.code);
expect(code).toEqual([{ text: TOKEN_PLACEHOLDER, code: true }]);
}
});
it.each(TEMPLATES)('%s carries the placeholder once when no token is given', (_name, template) => {
expect(occurrences(template(SERVER), TOKEN_PLACEHOLDER)).toBe(1);
expect(template(SERVER)).toBe(template(SERVER, TOKEN_PLACEHOLDER));
});
it.each(TEMPLATES)('%s carries the token in the place of the placeholder, and nowhere else', (_name, template) => {
const filled = template(SERVER, TOKEN);
expect(filled).toBe(template(SERVER).split(TOKEN_PLACEHOLDER).join(TOKEN));
expect(occurrences(filled, TOKEN)).toBe(1);
expect(filled).not.toContain(TOKEN_PLACEHOLDER);
// The token follows `Bearer `, as the Authorization header wants it.
expect(filled).toContain(`Authorization: ${template === hermesTemplate ? '"' : ''}Bearer ${TOKEN}`);
});
it.each(TEMPLATES)('%s carries the address it is given, once', (_name, template) => {
const local = 'http://localhost:3000/api/mcp';
expect(occurrences(template(local, TOKEN), local)).toBe(1);
expect(template(local, TOKEN)).not.toContain('lacompagniemaximus');
expect(template(local, TOKEN)).toBe(template(SERVER, TOKEN).split(SERVER).join(local));
});
it('no other export takes a token: its value appears in the templates only', () => {
const takesToken = [...SOURCE.matchAll(/^export function (\w+)\(([^)]*)\)/gm)]
.filter((match) => /\btoken: string\b/.test(match[2]))
.map((match) => match[1]);
expect(takesToken.sort()).toEqual(['claudeCodeTemplate', 'genericTemplate', 'hermesTemplate']);
});
});
describe('mcpServerUrl', () => {
it.each([
['https://liste.lacompagniemaximus.com', SERVER],
['https://liste.lacompagniemaximus.com/', SERVER],
['https://liste.lacompagniemaximus.com/some/path?x=1#y', SERVER],
['http://localhost:3000', 'http://localhost:3000/api/mcp'],
['http://localhost:3150/', 'http://localhost:3150/api/mcp'],
])('the origin of %s, then the route', (baseUrl, expected) => {
expect(mcpServerUrl(baseUrl)).toBe(expected);
});
});
describe('code spans of a text', () => {
it('splits a text on its backticks', () => {
expect(codeSpans('Dans `~/.hermes/config.yaml` :')).toEqual([
{ text: 'Dans ', code: false },
{ text: '~/.hermes/config.yaml', code: true },
{ text: ' :', code: false },
]);
expect(codeSpans('`a` then `b`')).toEqual([
{ text: 'a', code: true },
{ text: ' then ', code: false },
{ text: 'b', code: true },
]);
});
it('leaves a text without backticks whole', () => {
expect(codeSpans('Dans un terminal :')).toEqual([{ text: 'Dans un terminal :', code: false }]);
expect(codeSpans('')).toEqual([]);
});
it('loses no character but the backticks', () => {
for (const file of [fr, en]) {
for (const key of ['assistants.connect.replace', 'assistants.connect.hermesHint']) {
const text = textOf(file, key) as string;
expect(codeSpans(text).map((part) => part.text).join('')).toBe(text.split('`').join(''));
expect(codeSpans(text).filter((part) => part.code)).toHaveLength(1);
}
}
});
});
describe('tokens sent to the browser', () => {
const NOW = new Date('2026-11-14T15:32:10.123Z');
it('names its fields, and sends instants as ISO strings', () => {
const view = tokenView(token({
scope: 'write',
lastUsedAt: new Date('2026-11-14T16:00:00.000Z'),
expiresAt: new Date('2027-11-14T15:32:10.123Z'),
}), NOW);
expect(view).toEqual({
id: '11111111-1111-4111-8111-111111111111',
name: 'Hermes',
scope: 'write',
hint: 'Q9w0',
createdAt: '2026-11-14T15:32:10.123Z',
lastUsedAt: '2026-11-14T16:00:00.000Z',
expiresAt: '2027-11-14T15:32:10.123Z',
expired: false,
});
expect(tokenView(token(), NOW)).toMatchObject({ lastUsedAt: null, expiresAt: null, expired: false });
});
it('leaves out a field it does not name', () => {
const row = { ...token(), tokenHash: 'not-for-the-browser', userId: 'not-for-the-browser' };
const view = tokenView(row, NOW);
expect(Object.keys(view).sort()).toEqual([
'createdAt', 'expired', 'expiresAt', 'hint', 'id', 'lastUsedAt', 'name', 'scope',
]);
expect(JSON.stringify(view)).not.toContain('not-for-the-browser');
});
// The comparison of verifyAgentToken: refused from the instant of expires_at.
it.each([
['one millisecond before its expiry', -1, false],
['at the very instant of its expiry', 0, true],
['one millisecond after its expiry', 1, true],
['a day after its expiry', 24 * 60 * 60 * 1000, true],
['a day before its expiry', -24 * 60 * 60 * 1000, false],
])('a token read %s: expired is %s', (_label, offset, expired) => {
const expiresAt = new Date('2026-11-15T04:59:59.999Z');
const now = new Date(expiresAt.getTime() + offset);
expect(isExpired(expiresAt, now)).toBe(expired);
expect(tokenView(token({ expiresAt }), now).expired).toBe(expired);
});
it('a token without expiry never expires', () => {
expect(isExpired(null, new Date('9999-12-31T23:59:59.999Z'))).toBe(false);
});
// The instant decides, not the day: this token expires at 23:59:59.999 in
// Toronto on November 14, which is already November 15 in UTC.
it('decides on the instant, whatever day it is in a time zone', () => {
const expiresAt = new Date('2026-11-15T04:59:59.999Z');
expect(formatDay(expiresAt.toISOString(), 'fr-CA', 'America/Toronto')).toBe('14 nov. 2026');
expect(formatDay(expiresAt.toISOString(), 'fr-CA', 'UTC')).toBe('15 nov. 2026');
// Earlier the same day in Toronto: not expired. A minute later, already
// the next day there: expired.
expect(isExpired(expiresAt, new Date('2026-11-14T13:00:00.000Z'))).toBe(false);
expect(isExpired(expiresAt, new Date('2026-11-15T05:00:59.999Z'))).toBe(true);
});
});
describe('journal sent to the browser', () => {
const ID = '22222222-2222-4222-8222-222222222222';
const page: JournalPage = {
actions: [{
id: ID,
tool: 'create_task',
entityType: 'task',
entityId: '33333333-3333-4333-8333-333333333333',
entityName: 'Acheter du lait',
tokenId: '44444444-4444-4444-8444-444444444444',
tokenName: 'Hermes',
tokenRevoked: false,
createdAt: new Date('2026-11-14T15:32:10.123Z'),
}],
nextCursor: { createdAt: new Date('2026-11-14T15:32:10.123Z'), id: ID },
};
it('names the fields of a line: neither the touched row, nor its type, nor the token id', () => {
const view = journalPageView(page);
expect(view).toEqual({
actions: [{
id: ID,
tool: 'create_task',
tokenName: 'Hermes',
tokenRevoked: false,
entityName: 'Acheter du lait',
createdAt: '2026-11-14T15:32:10.123Z',
}],
nextCursor: `1794670330123_${ID}`,
});
expect(JSON.stringify(view)).not.toContain('33333333');
expect(JSON.stringify(view)).not.toContain('44444444');
});
it('keeps a deleted item, a revoked token and the last page as they are', () => {
const view = journalPageView({
actions: [{ ...page.actions[0], entityName: null, tokenId: null, tokenRevoked: true }],
nextCursor: null,
});
expect(view.actions[0]).toMatchObject({ entityName: null, tokenRevoked: true });
expect(view.nextCursor).toBeNull();
expect(journalPageView({ actions: [], nextCursor: null })).toEqual({ actions: [], nextCursor: null });
});
it('shows 50 lines per page', () => {
expect(JOURNAL_PAGE_SIZE).toBe(50);
});
it('reads back the page it sent, and leaves behind what a line does not name', () => {
const view = journalPageView(page);
expect(readJournalPage(JSON.parse(JSON.stringify(view)))).toEqual(view);
expect(readJournalPage({ actions: [], nextCursor: null })).toEqual({ actions: [], nextCursor: null });
const padded = {
...view,
extra: 'not a field',
actions: view.actions.map((line) => ({ ...line, entityId: 'not a field', nested: { deep: true } })),
};
expect(readJournalPage(padded)).toEqual(view);
expect(readJournalPage({ actions: [{ ...view.actions[0], entityName: null }], nextCursor: null })?.actions[0].entityName).toBeNull();
});
// What must never reach the JSX or the date formatter.
const LINE = journalPageView(page).actions[0];
it.each([
['nothing', null],
['a text', 'page'],
['a list', [LINE]],
['the body of an error', { error: 'Too many requests' }],
['no cursor at all', { actions: [LINE] }],
['a cursor that is a number', { actions: [LINE], nextCursor: 5 }],
['actions that are not a list', { actions: { 0: LINE }, nextCursor: null }],
['a line that is a text', { actions: [LINE, 'line'], nextCursor: null }],
['a line that is null', { actions: [null], nextCursor: null }],
['a line without an id', { actions: [{ ...LINE, id: undefined }], nextCursor: null }],
['a tool that is a number', { actions: [{ ...LINE, tool: 7 }], nextCursor: null }],
['a token name that is an object', { actions: [{ ...LINE, tokenName: { name: 'Hermes' } }], nextCursor: null }],
['an item name that is an object', { actions: [{ ...LINE, entityName: { title: 'x' } }], nextCursor: null }],
['an item name that is missing', { actions: [{ ...LINE, entityName: undefined }], nextCursor: null }],
['a revoked flag that is a text', { actions: [{ ...LINE, tokenRevoked: 'false' }], nextCursor: null }],
['a date that is a number', { actions: [{ ...LINE, createdAt: 1794670330123 }], nextCursor: null }],
['a date that is not one', { actions: [{ ...LINE, createdAt: 'yesterday' }], nextCursor: null }],
])('refuses an answer with %s', (_label, value) => {
expect(readJournalPage(value)).toBeNull();
});
it('a cursor survives the round trip, to the millisecond', () => {
const cursor = { createdAt: new Date('2026-11-14T15:32:10.123Z'), id: ID };
const encoded = encodeJournalCursor(cursor);
expect(encoded).toBe(`1794670330123_${ID}`);
expect(encodeURIComponent(encoded)).toBe(encoded);
const decoded = decodeJournalCursor(encoded);
expect(decoded).toEqual(cursor);
expect(decoded!.createdAt.toISOString()).toBe('2026-11-14T15:32:10.123Z');
});
it.each([
['the epoch', `0_${ID}`, '1970-01-01T00:00:00.000Z'],
['the last millisecond of year 9999', `253402300799999_${ID}`, '9999-12-31T23:59:59.999Z'],
['an id in capitals', `1794670330123_${ID.replace('2222-4222', 'ABCD-4EF2')}`, '2026-11-14T15:32:10.123Z'],
])('reads %s', (_label, value, iso) => {
const decoded = decodeJournalCursor(value);
expect(decoded?.createdAt.toISOString()).toBe(iso);
expect(decoded?.id).toBe(value.split('_')[1]);
});
it.each([
['an empty value', ''],
['a word', 'cursor'],
['an instant alone', '1794670330123'],
['an id alone', ID],
['an id that is not a uuid', '1794670330123_not-a-uuid'],
['an id one character short', `1794670330123_${ID.slice(0, -1)}`],
['an id one character long', `1794670330123_${ID}0`],
['an instant that is not a number', `NaN_${ID}`],
['an ISO instant', `2026-11-14T15:32:10.123Z_${ID}`],
['a negative instant', `-1_${ID}`],
['an instant with a fraction', `1794670330123.5_${ID}`],
['an instant in exponent form', `1e12_${ID}`],
['an instant with a leading zero', `01794670330123_${ID}`],
['the first millisecond of year 10000', `253402300800000_${ID}`],
['an instant no Date can hold', `999999999999999_${ID}`],
['an instant of sixteen digits', `1794670330123000_${ID}`],
['a space before', ` 1794670330123_${ID}`],
['a line break after', `1794670330123_${ID}\n`],
['two cursors', `1794670330123_${ID},1794670330123_${ID}`],
['SQL in the id', `1794670330123_${ID}' OR '1'='1`],
])('refuses %s', (_label, value) => {
expect(decodeJournalCursor(value)).toBeNull();
});
it('never returns an invalid Date', () => {
for (const digits of ['0', '1', '999999999999999', '253402300799999', '253402300800000', '8640000000000001']) {
const decoded = decodeJournalCursor(`${digits}_${ID}`);
if (decoded !== null) expect(Number.isNaN(decoded.createdAt.getTime())).toBe(false);
}
});
});
describe('journalKey', () => {
const line = (id: string) => ({
id, tool: 'create_task', tokenName: 'Hermes', tokenRevoked: false, entityName: 'x', createdAt: '2026-11-14T15:32:10.123Z',
});
const first: JournalPageView = { actions: [line('a'), line('b')], nextCursor: '1_b' };
const tokens: TokenView[] = [tokenView(token({ id: 't1' }), new Date(0)), tokenView(token({ id: 't2' }), new Date(0))];
const key = journalKey(first, tokens);
it('stays the same while the first page and the tokens are the same', () => {
expect(journalKey({ ...first, actions: [...first.actions] }, [...tokens])).toBe(key);
// What a refresh changes without touching the journal: a token was used, a name changed.
expect(journalKey(
{ ...first, actions: [{ ...line('a'), entityName: 'renamed' }, line('b')] },
tokens.map((t) => ({ ...t, lastUsedAt: '2026-11-15T00:00:00.000Z' })),
)).toBe(key);
});
it.each([
['a new line', { ...first, actions: [line('c'), line('a')] }, tokens],
['a line less', { ...first, actions: [line('a')] }, tokens],
['another cursor', { ...first, nextCursor: '1_c' }, tokens],
['no older page left', { ...first, nextCursor: null }, tokens],
['a token revoked', first, tokens.slice(1)],
['a token created', first, [...tokens, tokenView(token({ id: 't3' }), new Date(0))]],
] as [string, JournalPageView, TokenView[]][])('changes with %s', (_label, page, held) => {
expect(journalKey(page, held)).not.toBe(key);
});
it('does not confuse a line with a token', () => {
expect(journalKey({ actions: [line('a')], nextCursor: null }, []))
.not.toBe(journalKey({ actions: [], nextCursor: null }, [tokenView(token({ id: 'a' }), new Date(0))]));
});
});
// The zone is always given: the result must not depend on the zone of the
// machine that runs the test, nor on the container's (UTC).
describe('dates', () => {
it('follows the active language of the site: English, or French by default', () => {
expect(dateLocale('fr')).toBe('fr-CA');
expect(dateLocale('fr-CA')).toBe('fr-CA');
expect(dateLocale('en')).toBe('en-CA');
expect(dateLocale('en-US')).toBe('en-CA');
expect(dateLocale('EN')).toBe('en-CA');
expect(dateLocale(undefined)).toBe('fr-CA');
expect(dateLocale('de')).toBe('fr-CA');
expect(dateLocale('')).toBe('fr-CA');
});
// 03:30 UTC is the evening of the day before in Toronto: 23:30 in July
// (UTC-4), 22:30 in December (UTC-5).
it.each([
['July, America/Toronto', '2026-07-15T03:30:00.000Z', 'America/Toronto', '14 juill. 2026', '14 juill. 2026, 23 h 30', 'Jul 14, 2026', 'Jul 14, 2026, 11:30 p.m.'],
['December, America/Toronto', '2026-12-15T03:30:00.000Z', 'America/Toronto', '14 déc. 2026', '14 déc. 2026, 22 h 30', 'Dec 14, 2026', 'Dec 14, 2026, 10:30 p.m.'],
['July, UTC', '2026-07-15T03:30:00.000Z', 'UTC', '15 juill. 2026', '15 juill. 2026, 03 h 30', 'Jul 15, 2026', 'Jul 15, 2026, 3:30 a.m.'],
['December, UTC', '2026-12-15T03:30:00.000Z', 'UTC', '15 déc. 2026', '15 déc. 2026, 03 h 30', 'Dec 15, 2026', 'Dec 15, 2026, 3:30 a.m.'],
['December, Asia/Tokyo', '2026-12-15T03:30:00.000Z', 'Asia/Tokyo', '15 déc. 2026', '15 déc. 2026, 12 h 30', 'Dec 15, 2026', 'Dec 15, 2026, 12:30 p.m.'],
// Ten minutes around midnight UTC: the same evening in Toronto, two days in UTC.
['just before midnight UTC, America/Toronto', '2026-11-14T23:55:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 18 h 55', 'Nov 14, 2026', 'Nov 14, 2026, 6:55 p.m.'],
['just after midnight UTC, America/Toronto', '2026-11-15T00:05:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 19 h 05', 'Nov 14, 2026', 'Nov 14, 2026, 7:05 p.m.'],
['just before midnight UTC, UTC', '2026-11-14T23:55:00.000Z', 'UTC', '14 nov. 2026', '14 nov. 2026, 23 h 55', 'Nov 14, 2026', 'Nov 14, 2026, 11:55 p.m.'],
['just after midnight UTC, UTC', '2026-11-15T00:05:00.000Z', 'UTC', '15 nov. 2026', '15 nov. 2026, 00 h 05', 'Nov 15, 2026', 'Nov 15, 2026, 12:05 a.m.'],
['just after midnight UTC, Asia/Tokyo', '2026-11-15T00:05:00.000Z', 'Asia/Tokyo', '15 nov. 2026', '15 nov. 2026, 09 h 05', 'Nov 15, 2026', 'Nov 15, 2026, 9:05 a.m.'],
// Midnight in Toronto, winter and summer.
['midnight in Toronto, winter', '2026-11-14T05:00:00.000Z', 'America/Toronto', '14 nov. 2026', '14 nov. 2026, 00 h 00', 'Nov 14, 2026', 'Nov 14, 2026, 12:00 a.m.'],
['midnight in Toronto, summer', '2026-07-14T04:00:00.000Z', 'America/Toronto', '14 juill. 2026', '14 juill. 2026, 00 h 00', 'Jul 14, 2026', 'Jul 14, 2026, 12:00 a.m.'],
])('%s', (_label, iso, zone, frDay, frDayTime, enDay, enDayTime) => {
expect(plain(formatDay(iso, 'fr-CA', zone))).toBe(frDay);
expect(plain(formatDayTime(iso, 'fr-CA', zone))).toBe(frDayTime);
expect(plain(formatDay(iso, 'en-CA', zone))).toBe(enDay);
expect(plain(formatDayTime(iso, 'en-CA', zone))).toBe(enDayTime);
});
it('a token created for one year shows the same local day a year later, summer and winter', () => {
// expiresAtFor('1y'): the same instant of the next year, in UTC.
for (const created of ['2026-07-15T02:00:00.000Z', '2026-12-15T03:00:00.000Z']) {
const expires = new Date(created);
expires.setUTCFullYear(expires.getUTCFullYear() + 1);
const day = (iso: string) => plain(formatDay(iso, 'fr-CA', 'America/Toronto'));
expect(day(expires.toISOString())).toBe(day(created).replace('2026', '2027'));
// In UTC both are a day later: the zone decides the day shown.
expect(plain(formatDay(created, 'fr-CA', 'UTC'))).not.toBe(day(created));
}
});
});
describe('texts of the page', () => {
const sources = [
...fs.readdirSync(COMPONENTS).filter((file) => /^Assistants.*\.tsx$/.test(file)).map((file) => path.join(COMPONENTS, file)),
path.join(COMPONENTS, 'Header.tsx'),
path.join(__dirname, 'assistants.ts'),
];
const used = new Set(sources.flatMap((file) =>
[...fs.readFileSync(file, 'utf8').matchAll(/["'](assistants\.[A-Za-z0-9_.]+)["']/g)].map((match) => match[1])));
it('every key the page asks for has a text in both languages', () => {
// Control: the five component files and the keys were found.
expect(sources.length).toBeGreaterThanOrEqual(7);
expect(used.size).toBeGreaterThan(60);
expect([...used].filter((key) => typeof textOf(fr, key) !== 'string' || typeof textOf(en, key) !== 'string')).toEqual([]);
});
it('every text of `assistants` is shown by the page', () => {
const keys = keysOf(fr.assistants, 'assistants');
expect(keys).toHaveLength(65);
expect(keys.filter((key) => !used.has(key))).toEqual([]);
});
it('no component keeps the value of a token outside its state', () => {
for (const file of sources.filter((source) => /Assistants.*\.tsx$/.test(source))) {
const source = fs.readFileSync(file, 'utf8');
expect(source, file).not.toMatch(/localStorage|sessionStorage|document\.cookie|indexedDB|history\.(push|replace)State|router\.(push|replace)\(/);
}
});
});

295
web/src/lib/assistants.ts Normal file
View file

@ -0,0 +1,295 @@
// Pure helpers of the « Assistants IA » page (#205), kept out of the JSX so
// vitest covers them without a DOM, as tagEditing.ts: label keys, connection
// templates, what the page and GET /api/agent-actions send to the browser,
// the journal cursor and the dates.
//
// The client components import this module: whatever it loads at run time
// goes to the browser. Its imports are type-only, erased at build, and
// assistants.test.ts fails on any other import: the database client, zod and
// the MCP server must not follow it there (see dueDate.ts).
import type { JournalCursor, JournalPage } from './agentJournal';
import type { AgentToken, AgentTokenDuration, AgentTokenScope } from './agentTokens';
import type { WriteToolName } from './mcp/writeTools';
export type TokenScope = AgentTokenScope;
export type TokenDuration = AgentTokenDuration;
// --- Creation form -------------------------------------------------------
// The choices of the form, in the order it shows them, and the ones it
// preselects (decision of Max, 2026-11-14: « Lecture seule » and « 1 an »).
// A test compares both lists with createAgentTokenSchema.
export const TOKEN_SCOPES: readonly TokenScope[] = ['read', 'write'];
export const TOKEN_DURATIONS: readonly TokenDuration[] = ['90d', '1y', 'never'];
export const DEFAULT_TOKEN_SCOPE: TokenScope = 'read';
export const DEFAULT_TOKEN_DURATION: TokenDuration = '1y';
export const SCOPE_LABEL_KEYS: Record<TokenScope, string> = {
read: 'assistants.scope.read',
write: 'assistants.scope.write',
};
export const DURATION_LABEL_KEYS: Record<TokenDuration, string> = {
'90d': 'assistants.duration.90d',
'1y': 'assistants.duration.1y',
never: 'assistants.duration.never',
};
// Same bound as createAgentTokenSchema in validators.ts (a test compares them).
export const TOKEN_NAME_MAX = 100;
export type TokenNameCheck =
| { ok: true; name: string }
| { ok: false; reason: 'empty' | 'tooLong' };
// The name sent to POST /api/agent-tokens: trimmed, neither empty nor made of
// spaces, at most TOKEN_NAME_MAX characters once trimmed.
export function validateTokenName(raw: string): TokenNameCheck {
const name = raw.trim();
if (name.length === 0) return { ok: false, reason: 'empty' };
if (name.length > TOKEN_NAME_MAX) return { ok: false, reason: 'tooLong' };
return { ok: true, name };
}
// --- Journal labels ------------------------------------------------------
// One label per write tool of the MCP server. `Record<WriteToolName, …>`
// makes tsc refuse a write tool without a label, and assistants.test.ts
// compares these keys with WRITE_TOOL_NAMES at run time. The import above is
// a type: writeTools.ts itself never reaches the browser.
export const ACTION_LABEL_KEYS: Record<WriteToolName, string> = {
create_task: 'assistants.action.create_task',
update_task: 'assistants.action.update_task',
complete_task: 'assistants.action.complete_task',
reopen_task: 'assistants.action.reopen_task',
set_task_tags: 'assistants.action.set_task_tags',
create_list: 'assistants.action.create_list',
update_list: 'assistants.action.update_list',
create_tag: 'assistants.action.create_tag',
update_tag: 'assistants.action.update_tag',
};
// The label key of a journal line, or null for a tool this version has no
// label for (a line written by a later version): the page then shows the
// name of the tool as the journal holds it.
export function actionLabelKey(tool: string): string | null {
return Object.prototype.hasOwnProperty.call(ACTION_LABEL_KEYS, tool)
? ACTION_LABEL_KEYS[tool as WriteToolName]
: null;
}
// --- Connection help -----------------------------------------------------
// What a template shows where the token goes, until one has just been
// created. The texts `assistants.connect.replace` name the same value.
export const TOKEN_PLACEHOLDER = 'slmcp_…';
const MCP_PATH = '/api/mcp';
// The address of the MCP server: the origin of the site (LOGTO_BASE_URL, the
// address the site is reached at), then the route. A path or a trailing
// slash in the base URL is dropped.
export function mcpServerUrl(baseUrl: string): string {
return new URL(baseUrl).origin + MCP_PATH;
}
// The three templates take the address of the server and the token, which
// appears nowhere else on the page than in their output, in the place of
// TOKEN_PLACEHOLDER. They are the blocks of issue #205, checked against the
// documentation of each client on 2026-11-14, without the comment line that
// names the client there: the page says it above each block
// (`assistants.connect.hermesHint`, `claudeCodeHint`), and a `#` line pasted
// into a terminal is not a comment for every shell.
// For ~/.hermes/config.yaml.
export function hermesTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return [
'mcp_servers:',
' simpl-liste:',
` url: "${serverUrl}"`,
' headers:',
` Authorization: "Bearer ${token}"`,
].join('\n');
}
// For a terminal.
export function claudeCodeTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return `claude mcp add --transport http simpl-liste ${serverUrl} --header "Authorization: Bearer ${token}"`;
}
// For any other MCP client: the address, then the header, one per line.
export function genericTemplate(serverUrl: string, token: string = TOKEN_PLACEHOLDER): string {
return [serverUrl, `Authorization: Bearer ${token}`].join('\n');
}
// A text of fr.json or en.json may hold code between backticks, as the
// Markdown of the issue Max validated it in: the page shows these parts as
// code, without the backticks.
export type TextPart = { text: string; code: boolean };
export function codeSpans(text: string): TextPart[] {
return text
.split('`')
.map((part, index) => ({ text: part, code: index % 2 === 1 }))
.filter((part) => part.text !== '');
}
// --- What the browser receives -------------------------------------------
// A token as the page shows it. Fields named one by one: a field added to
// AgentToken reaches the browser only if it is named here. Instants are ISO
// strings: the browser formats them (the container runs in UTC).
export type TokenView = {
id: string;
name: string;
scope: TokenScope;
hint: string;
createdAt: string;
lastUsedAt: string | null;
expiresAt: string | null;
expired: boolean;
};
// Whether a token is refused at `now`: from the very instant of its expiry,
// the comparison verifyAgentToken makes (agentTokens.ts). Two instants are
// compared, never two calendar days: no time zone is involved.
export function isExpired(expiresAt: Date | null, now: Date): boolean {
return expiresAt !== null && expiresAt.getTime() <= now.getTime();
}
export function tokenView(token: AgentToken, now: Date): TokenView {
return {
id: token.id,
name: token.name,
scope: token.scope,
hint: token.hint,
createdAt: token.createdAt.toISOString(),
lastUsedAt: token.lastUsedAt === null ? null : token.lastUsedAt.toISOString(),
expiresAt: token.expiresAt === null ? null : token.expiresAt.toISOString(),
expired: isExpired(token.expiresAt, now),
};
}
// Lines of the journal per page, on the page and in GET /api/agent-actions.
export const JOURNAL_PAGE_SIZE = 50;
// A journal line as the page shows it: what it displays, and its id as a
// React key. Neither the id of the touched row, nor its type, nor the id of
// the token leaves the server.
export type JournalLine = {
id: string;
tool: string;
tokenName: string;
tokenRevoked: boolean;
entityName: string | null;
createdAt: string;
};
// The same shape for the first page, which the server component reads, and
// for the next ones, which the route returns.
export type JournalPageView = {
actions: JournalLine[];
// To send back as `?before=` to read the older lines; null on the last page.
nextCursor: string | null;
};
export function journalPageView(page: JournalPage): JournalPageView {
return {
actions: page.actions.map((action) => ({
id: action.id,
tool: action.tool,
tokenName: action.tokenName,
tokenRevoked: action.tokenRevoked,
entityName: action.entityName,
createdAt: action.createdAt.toISOString(),
})),
nextCursor: page.nextCursor === null ? null : encodeJournalCursor(page.nextCursor),
};
}
// The answer of GET /api/agent-actions as the journal component may use it,
// or null when it does not have the shape of a page. Each field is read as
// the scalar it must be and nothing else of the answer is kept: what is not
// a text never reaches the JSX, and a date that is not one never reaches the
// formatter, which would throw.
export function readJournalPage(value: unknown): JournalPageView | null {
if (value === null || typeof value !== 'object') return null;
const { actions, nextCursor } = value as { actions?: unknown; nextCursor?: unknown };
if (!Array.isArray(actions)) return null;
if (nextCursor !== null && typeof nextCursor !== 'string') return null;
const lines: JournalLine[] = [];
for (const action of actions as unknown[]) {
if (action === null || typeof action !== 'object') return null;
const { id, tool, tokenName, tokenRevoked, entityName, createdAt } = action as Record<string, unknown>;
if (typeof id !== 'string' || typeof tool !== 'string' || typeof tokenName !== 'string') return null;
if (typeof tokenRevoked !== 'boolean') return null;
if (entityName !== null && typeof entityName !== 'string') return null;
if (typeof createdAt !== 'string' || Number.isNaN(Date.parse(createdAt))) return null;
lines.push({ id, tool, tokenName, tokenRevoked, entityName, createdAt });
}
return { actions: lines, nextCursor };
}
// The cursor of listActions (agentJournal.ts) as a query parameter: the
// instant in milliseconds since the epoch, an underscore, the id of the line.
const CURSOR = /^(0|[1-9]\d{0,14})_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
// The last millisecond of year 9999 in UTC: a later instant is still a valid
// Date, but PostgreSQL may refuse it in the query.
const CURSOR_MAX_MS = Date.UTC(9999, 11, 31, 23, 59, 59, 999);
export function encodeJournalCursor(cursor: JournalCursor): string {
return `${cursor.createdAt.getTime()}_${cursor.id}`;
}
// The cursor a client sent back, or null when it is not one: listActions
// throws on an invalid Date, and PostgreSQL on an id that is not a uuid. A
// well-formed cursor is only a position in the journal of the caller: it
// gives no access to a line (listActions filters on the account).
export function decodeJournalCursor(value: string): JournalCursor | null {
const match = CURSOR.exec(value);
if (!match) return null;
const ms = Number(match[1]);
if (ms > CURSOR_MAX_MS) return null;
return { createdAt: new Date(ms), id: match[2] };
}
// What the older pages of the journal were read after: the lines of the
// first page and its cursor, and the tokens of the account (revoking one
// changes how its lines read). The journal component is keyed by this value,
// so that the older pages it has loaded are dropped when it changes: kept,
// they could miss a line or show a revoked token as a live one.
export function journalKey(first: JournalPageView, tokens: readonly TokenView[]): string {
return [
first.nextCursor ?? '',
first.actions.map((action) => action.id).join(','),
tokens.map((token) => token.id).join(','),
].join('|');
}
// --- Dates ---------------------------------------------------------------
// Every date of the page is formatted in the browser, in the time zone of
// the user: these functions take the zone, and the components only have one
// once they run in a browser (AssistantsPanel.tsx). The container runs in
// UTC and formats nothing.
export type DateLocale = 'fr-CA' | 'en-CA';
// The locale of the dates for the active language of the site: English, or
// French, its default language.
export function dateLocale(language: string | undefined): DateLocale {
return language !== undefined && language.toLowerCase().startsWith('en') ? 'en-CA' : 'fr-CA';
}
// A day, « 14 nov. 2026 »: the day it is in `timeZone` at that instant.
export function formatDay(iso: string, locale: DateLocale, timeZone: string): string {
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone }).format(new Date(iso));
}
// A day and a time, « 14 nov. 2026, 10 h 32 », in `timeZone`.
export function formatDayTime(iso: string, locale: DateLocale, timeZone: string): string {
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso));
}

View file

@ -8,7 +8,10 @@
// No tool removes a task, a list or a tag (DECISIONS.md, 2026-11-14), and a
// change cannot be undone: the journal (agentJournal.ts) is its only trace.
// A task that was deleted, or that belongs to another account, answers like
// one that never existed, and so do a list, a parent and a tag.
// one that never existed, and so do a list, a parent and a tag. So does a task
// left in a deleted list, which get_task and list_tasks do not see either
// (decision of Max of 2026-11-19): every tool on an existing task works on
// the `visible` tasks of taskWrites.ts.
import { z } from 'zod';
import { db } from '@/db/client';
@ -291,7 +294,7 @@ export function registerWriteTools(register: RegisterTool): void {
annotations: { destructiveHint: false, idempotentHint: true },
// One journal line, for the task that was completed: its next occurrence
// has none.
write: async (tx, input, { userId }) => onTask(found(await completeTask(tx, userId, input.task_id))),
write: async (tx, input, { userId }) => onTask(found(await completeTask(tx, userId, input.task_id, new Date(), 'visible'))),
render: async (result, { userId }) => ({
task: await renderTask(userId, result.task),
next_occurrence: result.changed && result.next ? await renderTask(userId, result.next) : null,
@ -304,7 +307,7 @@ export function registerWriteTools(register: RegisterTool): void {
description: 'Marks a completed task as not completed and returns it. The next occurrence that completing a recurring task created stays. When the task was not completed, nothing happens and changed is false.',
inputSchema: taskInput,
annotations: { destructiveHint: false, idempotentHint: true },
write: async (tx, input, { userId }) => onTask(found(await reopenTask(tx, userId, input.task_id))),
write: async (tx, input, { userId }) => onTask(found(await reopenTask(tx, userId, input.task_id, new Date(), 'visible'))),
render: async (result, { userId }) => ({
task: await renderTask(userId, result.task),
changed: result.changed,

View file

@ -7,14 +7,17 @@
// in two cases:
// - across a clock change (in Quebec, the second Sunday of March and the first
// Sunday of November), the local time of a recurrence computed here moves by
// one hour, where the app keeps it. A due date typed without a time is
// stored at noon UTC (dueDate.ts) and stays there: 7:00 in winter, 8:00 in
// summer;
// one hour, where the app keeps it. Near midnight that hour also moves the
// day: a daily task due on March 7, 2026 at 23:30 comes back here on March 9
// at 0:30, in the app on March 8 at 23:30. A due date typed without a time
// is stored at noon UTC (dueDate.ts) and stays there: 7:00 in winter, 8:00
// in summer;
// - the day of the month is read in UTC. A due date set in the evening in
// Quebec (from 19:00 in winter, 20:00 in summer) is already the next day in
// UTC: at the end of a month, a monthly or yearly recurrence computed here
// can then fall a day away from the one the app computes (March 30 at 23:00
// gives April 29 at 23:00 here, April 30 at 23:00 in the app).
// Max accepted both gaps on 2026-11-19 (DECISIONS.md, « Compte et sync »).
//
// Ends of months follow date-fns (addMonths, addYears): the day of the month
// is kept when the target month has it, and the last day of that month is

View file

@ -11,9 +11,9 @@ import { LIST_COLORS, LIST_ICONS, TAG_COLORS } from './palette';
// tools calls them: in a transaction of the caller, against an
// in-memory Postgres (PGlite) with the companion migrations. completeTask and
// reopenTask are tested with the route that shares them
// (../app/api/tasks/route.test.ts). The database client is replaced by
// PGlite: taskWrites.ts never imports it, taskDelete.ts (lockTaskForLinks)
// does.
// (../app/api/tasks/route.test.ts); only their `visible` scope, the one of the
// MCP tools, is tested here. The database client is replaced by PGlite:
// taskWrites.ts never imports it, taskDelete.ts (lockTaskForLinks) does.
const h = await vi.hoisted(async () => {
const { PGlite } = await import('electric-sql-pglite');
@ -28,10 +28,11 @@ vi.mock('@/db/client', async () => {
const { db } = await import('@/db/client');
const {
createTask, updateTask, setTaskTags, createList, updateList, createTag, updateTag, WriteRefusal,
completeTask, reopenTask, createTask, updateTask, setTaskTags, createList, updateList, createTag, updateTag, WriteRefusal,
} = await import('./taskWrites');
const { ToolRefusal } = await import('./mcp/errors');
type Scope = Parameters<typeof completeTask>[4];
type CreateInput = Parameters<typeof createTask>[2];
type Patch = Parameters<typeof updateTask>[3];
type ListInput = Parameters<typeof createList>[2];
@ -186,6 +187,8 @@ async function everything() {
};
}
const complete = (userId: string, taskId: string, scope?: Scope) => db.transaction((tx) => completeTask(tx, userId, taskId, NOW, scope));
const reopen = (userId: string, taskId: string, scope?: Scope) => db.transaction((tx) => reopenTask(tx, userId, taskId, NOW, scope));
const create = (userId: string, input: CreateInput) => db.transaction((tx) => createTask(tx, userId, input, NOW));
const update = (userId: string, taskId: string, patch: Patch) => db.transaction((tx) => updateTask(tx, userId, taskId, patch, NOW));
const setTags = (userId: string, taskId: string, tagIds: string[]) => db.transaction((tx) => setTaskTags(tx, userId, taskId, tagIds, NOW));
@ -330,6 +333,17 @@ describe('createTask', () => {
expect(await refusal(() => create(A.userId, { title: 'Orphan', parentId: foreignSubtask }))).toBe('parent_not_found');
});
it('refuses a parent left in a deleted list or in a list of another account, as get_task does not see it', async () => {
const [A, B] = [await newAccount(), await newAccount()];
const gone = await newList(A.userId, { deletedAt: GONE });
for (const parentId of [await newTask(A, { list: gone }), await newTask(misplaced(A, B.inbox))]) {
expect(await refusal(() => create(A.userId, { title: 'Orphan', parentId })), parentId).toBe('parent_not_found');
}
// Control: the same parent in a live list of the account takes the subtask.
const live = await newTask(A, { list: await newList(A.userId) });
expect(await create(A.userId, { title: 'Child', parentId: live })).toMatchObject({ changed: true, task: { parentId: live } });
});
it('links the tags of the account, each once, whatever the letter case of their ids', async () => {
const A = await newAccount();
const [red, blue] = [await newTag(A.userId), await newTag(A.userId)];
@ -465,6 +479,23 @@ describe('updateTask', () => {
// Its own account writes it.
expect(await update(B.userId, foreign, { title: 'Mine' })).toMatchObject({ changed: true, task: { id: foreign, title: 'Mine' } });
});
it('answers null for a task left in a deleted list or in a list of another account, and writes nothing', async () => {
const [A, B] = [await newAccount(), await newAccount()];
const target = await newList(A.userId);
const gone = await newList(A.userId, { deletedAt: GONE });
const left = await newTask(A, { list: gone });
await newTask(A, { list: gone, parentId: left });
for (const id of [left, await newTask(misplaced(A, B.inbox))]) {
await absent(() => update(A.userId, id, { title: 'Taken' }));
// Not even moved back into a live list.
await absent(() => update(A.userId, id, { listId: target }));
await absent(() => update(A.userId, id, {}));
}
// Control: once its list is live again, the task is written.
await h.pg.query('update sl_lists set deleted_at = null where id = $1', [gone]);
expect(await update(A.userId, left, { title: 'Back' })).toMatchObject({ changed: true, task: { id: left, title: 'Back' } });
});
});
describe('setTaskTags', () => {
@ -540,6 +571,57 @@ describe('setTaskTags', () => {
}
expect(await tagsOf(foreign)).toEqual([tagB]);
});
it('answers null for a task left in a deleted list or in a list of another account, and writes nothing', async () => {
const [A, B] = [await newAccount(), await newAccount()];
const [red, blue] = [await newTag(A.userId), await newTag(A.userId)];
const left = await newTask(A, { list: await newList(A.userId, { deletedAt: GONE }) });
await link(left, red);
for (const id of [left, await newTask(misplaced(A, B.inbox))]) {
await absent(() => setTags(A.userId, id, [blue]));
await absent(() => setTags(A.userId, id, []));
}
expect(await tagsOf(left)).toEqual([red]);
});
});
describe('completeTask and reopenTask: the scope of the MCP tools', () => {
// A recurring task with a due date, left open in a deleted list, and a done
// one beside it; the same two in a list of another account.
async function invisible() {
const [A, B] = [await newAccount(), await newAccount()];
const gone = await newList(A.userId, { deletedAt: GONE });
const recurring = { dueDate: '2026-11-20T12:00:00.000Z', recurrence: 'weekly' };
const open = [await newTask(A, { list: gone, ...recurring }), await newTask(misplaced(A, B.inbox), recurring)];
const done = [await newTask(A, { list: gone }), await newTask(misplaced(A, B.inbox))];
for (const id of done) await h.pg.query('update sl_tasks set completed = true, completed_at = $2 where id = $1', [id, SEEDED]);
return { A, open, done };
}
it('with `visible`, answer null for a task left in a deleted list or in a list of another account: nothing completed, no occurrence', async () => {
const { A, open, done } = await invisible();
for (const id of open) await absent(() => complete(A.userId, id, 'visible'));
for (const id of done) await absent(() => reopen(A.userId, id, 'visible'));
// Already done or already open: still null, never `changed: false`.
for (const id of done) await absent(() => complete(A.userId, id, 'visible'));
for (const id of open) await absent(() => reopen(A.userId, id, 'visible'));
});
it('without a scope, as PUT /api/tasks/[id] calls them, still complete and reopen such a task', async () => {
const { A, open, done } = await invisible();
const result = await complete(A.userId, open[0]);
expect(result).toMatchObject({ changed: true, task: { id: open[0], completed: true } });
expect(result && 'next' in result && result.next).toMatchObject({ dueDate: new Date('2026-11-27T12:00:00.000Z') });
expect(await reopen(A.userId, done[0])).toMatchObject({ changed: true, task: { id: done[0], completed: false } });
});
it('with `visible`, complete and reopen a task of a live list of the account', async () => {
const A = await newAccount();
const id = await newTask(A, { list: await newList(A.userId) });
expect(await complete(A.userId, id, 'visible')).toMatchObject({ changed: true, task: { id, completed: true }, next: null });
expect(await complete(A.userId, id, 'visible')).toMatchObject({ changed: false, task: { id } });
expect(await reopen(A.userId, id, 'visible')).toMatchObject({ changed: true, task: { id, completed: false } });
});
});
describe('createList', () => {
@ -970,10 +1052,10 @@ describe('the contract of the module', () => {
before(body('setTaskTags'), 'await liveTagIds(tx, userId, tagIds);', 'tx.delete(slTaskTags)');
before(body('setTaskTags'), 'tx.delete(slTaskTags)', 'tx.insert(slTaskTags)');
// The account of the task is checked before its row is locked.
before(body('setTaskTags'), 'where(ownTask(userId, taskId))', 'await lockTaskForLinks(tx, own.id);');
before(body('setTaskTags'), 'where(visibleTask(tx, userId, taskId))', 'await lockTaskForLinks(tx, own.id);');
// The tags are read FOR SHARE, and updateTask reads the row it locks.
expect(source).toMatch(/async function liveTagIds\([\s\S]*?\.for\('share'\);/);
expect(body('updateTask')).toContain(".where(ownTask(userId, taskId)).for('no key update');");
expect(body('updateTask')).toContain(".where(visibleTask(tx, userId, taskId)).for('no key update');");
expect(source.match(/\.for\('share'\)/g)).toHaveLength(1);
// createTag (#204) looks for the tag of the name under the account lock,

View file

@ -24,7 +24,9 @@ import { lockTaskForLinks, type Tx } from './taskDelete';
// in the account;
// - the result is `{ changed, ... }`, and `changed: false` means that nothing
// was written. A function on a task answers null when the task does not
// exist, is deleted or belongs to another account. A function on a list or
// exist, is deleted or belongs to another account, and, for the MCP tools,
// when it sits in a list that is not a live list of the account (TaskScope,
// decision of Max of 2026-11-19). A function on a list or
// on a tag (#204) never answers null: it refuses, with the code that names
// what is missing (`list_not_found`, `tag_not_found`), as the task
// functions refuse a list or a tag their input names. A caller cannot take
@ -125,6 +127,37 @@ function ownTask(userId: string, taskId: string) {
return and(eq(slTasks.id, taskId), eq(slTasks.userId, userId), isNull(slTasks.deletedAt));
}
// The ids of the live lists of the account, as a subquery built on `tx`.
function liveListIds(tx: Tx, userId: string) {
return tx
.select({ id: slLists.id })
.from(slLists)
.where(and(eq(slLists.userId, userId), isNull(slLists.deletedAt)));
}
// The live task `taskId` of the account, in a live list of the account: a task
// the MCP tools see (decision of Max of 2026-11-19, DECISIONS.md). Deleting a
// list marks the list alone, in the app as on the site, and its tasks stay
// live; get_task and list_tasks no longer return them (loadAccountTask,
// taskQueries.ts), and the write tools answer for them as for a missing task.
// The list is matched on the account too: a task of the account left in a
// list of another account, a row the sync never writes, is not seen either.
function visibleTask(tx: Tx, userId: string, taskId: string) {
return and(ownTask(userId, taskId), inArray(slTasks.listId, liveListIds(tx, userId)));
}
// Which tasks completeTask and reopenTask work on, the two functions the site
// shares with the MCP tools. `account`: every live task of the account, as
// PUT /api/tasks/[id] has always written them, a task left in a deleted list
// included. `visible`: the tasks the MCP tools see (visibleTask). createTask,
// updateTask and setTaskTags serve the tools alone, and only ever see
// `visible` tasks.
export type TaskScope = 'account' | 'visible';
function scopedTask(tx: Tx, scope: TaskScope, userId: string, taskId: string) {
return scope === 'visible' ? visibleTask(tx, userId, taskId) : ownTask(userId, taskId);
}
// The live top-level tasks of a list of the account, done or not.
function topLevelOf(userId: string, listId: string) {
return and(
@ -252,11 +285,16 @@ async function liveTagIds(tx: Tx, userId: string, tagIds: string[]): Promise<str
// gives an occurrence that may be overdue too. It goes to the end of the list.
// A recurrence outside RECURRENCES creates nothing, and so does an occurrence
// that would fall after the year 9999.
//
// `scope` says which tasks it sees (TaskScope): the site passes nothing, the
// MCP tools pass `visible`, and a task left in a deleted list then answers
// null, with nothing completed and no occurrence created.
export async function completeTask(
tx: Tx,
userId: string,
taskId: string,
now = new Date(),
scope: TaskScope = 'account',
): Promise<CompleteTaskResult | null> {
// The move from open to done is this single statement. Of two calls for the
// same task, replayed or concurrent, only one gets the row back (the second
@ -264,12 +302,12 @@ export async function completeTask(
// creates the next occurrence.
const [task] = await tx.update(slTasks)
.set({ completed: true, completedAt: now, updatedAt: now })
.where(and(ownTask(userId, taskId), eq(slTasks.completed, false)))
.where(and(scopedTask(tx, scope, userId, taskId), eq(slTasks.completed, false)))
.returning();
if (!task) {
// Already done, or not a live task of the account.
const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId));
// Already done, or not a task of the account that `scope` sees.
const [current] = await tx.select().from(slTasks).where(scopedTask(tx, scope, userId, taskId));
return current ? { changed: false, task: current } : null;
}
@ -303,29 +341,31 @@ export async function completeTask(
// Reopen a task: `completed` false, `completedAt` null. The next occurrence
// that completeTask created stays, as in the app: nothing links the two tasks.
// `scope` as for completeTask.
export async function reopenTask(
tx: Tx,
userId: string,
taskId: string,
now = new Date(),
scope: TaskScope = 'account',
): Promise<ReopenTaskResult | null> {
const [task] = await tx.update(slTasks)
.set({ completed: false, completedAt: null, updatedAt: now })
.where(and(ownTask(userId, taskId), eq(slTasks.completed, true)))
.where(and(scopedTask(tx, scope, userId, taskId), eq(slTasks.completed, true)))
.returning();
if (task) return { changed: true, task };
// Already open, or not a live task of the account.
const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId));
// Already open, or not a task of the account that `scope` sees.
const [current] = await tx.select().from(slTasks).where(scopedTask(tx, scope, userId, taskId));
return current ? { changed: false, task: current } : null;
}
// Create a task (#203), at the end of its list or of the subtasks of its
// parent, as the app does. Where it goes:
// - with `parentId`: under that task, which must be a live task of the
// account (`parent_not_found`) and not a subtask itself
// (`parent_is_subtask`). The subtask takes the list of its parent, and
// `listId` is not even read;
// account in a live list of the account (`parent_not_found`, visibleTask)
// and not a subtask itself (`parent_is_subtask`). The subtask takes the
// list of its parent, and `listId` is not even read;
// - with `listId` alone: in that list, which must be a live list of the
// account (`list_not_found`);
// - with neither: in the live Inbox of the account, created when the account
@ -355,7 +395,7 @@ export async function createTask(
const [parent] = await tx
.select({ id: slTasks.id, listId: slTasks.listId, parentId: slTasks.parentId })
.from(slTasks)
.where(ownTask(userId, input.parentId));
.where(visibleTask(tx, userId, input.parentId));
if (!parent) throw new WriteRefusal('parent_not_found');
// Two levels at most, as the app and the site show them.
if (parent.parentId !== null) throw new WriteRefusal('parent_is_subtask');
@ -399,8 +439,9 @@ export async function createTask(
return { changed: true, task };
}
// Change fields of a live task of the account (#203); null for any other
// task. Only the keys of the patch are written, and `updatedAt` moves on
// Change fields of a live task of the account, in a live list of the account
// (#203, visibleTask); null for any other task. Only the keys of the patch
// are written, and `updatedAt` moves on
// every row written. A patch that names at least one key is a write, even
// when every value is the one the row already had; a patch without a key
// writes nothing (`changed: false`).
@ -422,7 +463,7 @@ export async function updateTask(
patch: UpdateTaskPatch,
now = new Date(),
): Promise<UpdateTaskResult | null> {
const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId)).for('no key update');
const [current] = await tx.select().from(slTasks).where(visibleTask(tx, userId, taskId)).for('no key update');
if (!current) return null;
// Every column is named: a key the patch should not carry is not written.
@ -459,8 +500,9 @@ export async function updateTask(
return { changed: true, task };
}
// Replace the tags of a live task of the account by `tagIds` (#203); null for
// any other task. Every id must be a live tag of the account
// Replace the tags of a live task of the account, in a live list of the
// account, by `tagIds` (#203, visibleTask); null for any other task. Every id
// must be a live tag of the account
// (`tag_not_found`, nothing written). The set the task already has, in any
// order, writes nothing (`changed: false`); otherwise the links that are not
// wanted are removed, the missing ones are added, and `updatedAt` of the task
@ -480,7 +522,7 @@ export async function setTaskTags(
tagIds: string[],
now = new Date(),
): Promise<SetTaskTagsResult | null> {
const [own] = await tx.select({ id: slTasks.id }).from(slTasks).where(ownTask(userId, taskId));
const [own] = await tx.select({ id: slTasks.id }).from(slTasks).where(visibleTask(tx, userId, taskId));
if (!own) return null;
const locked = await lockTaskForLinks(tx, own.id);
// Deleted between the check and the lock.

View file

@ -323,6 +323,21 @@ describe('web/scripts/probe.sql: each control detects its seeded anomaly', () =>
await action(A.userId, B.token, B.task);
expect(await counts()).toEqual(expected({ journal_autre_compte: 1 }));
});
// A revoked token (token_id is null since) neither makes a line count on its
// own nor keeps it from counting: the row it touched is the only trace left.
it.each(['task', 'list', 'tag'] as const)('journal_autre_compte: a line of A on a %s of B, written with a token revoked since', async (type) => {
const { A, B } = await healthyBase();
await action(A.userId, null, B[type], { type });
expect(await counts()).toEqual(expected({ journal_autre_compte: 1 }));
});
// And a row that matches nothing leaves the token as the only trace.
it('journal_autre_compte: a line of A written with a token of B on a row that matches nothing', async () => {
const { A, B } = await healthyBase();
await action(A.userId, B.token, u());
expect(await counts()).toEqual(expected({ journal_autre_compte: 1 }));
});
});
// Controls 7 to 9 and 12 are isolation checks: a cross-account row is a leak