merge(workstate): intègre les actions contrôlées (Lot D) dans develop

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-20 19:52:00 +02:00
25 changed files with 1401 additions and 100 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
--- ---
upTo: 11b7df5e-f50e-4f4e-b680-37d5fb10af72 upTo: c269039f-212a-42a7-a520-2770cb7cc773
objective: [Ping inter-agent depuis Main] Test du pont MCP inter-agents. Si tu reçois ce message, réponds via idea_reply avec : (1) "DevFrontend OK — pont inter-agent fonctionnel", (2) le résultat de 144 ÷ 12, e objective: [Ping inter-agent depuis Main] Test du pont MCP inter-agents. Si tu reçois ce message, réponds via idea_reply avec : (1) "DevFrontend OK — pont inter-agent fonctionnel", (2) le résultat de 144 ÷ 12, e
--- ---
**Objectif :** [Ping inter-agent depuis Main] Test du pont MCP inter-agents. Si tu reçois ce message, réponds via idea_reply avec : (1) "DevFrontend OK — pont inter-agent fonctionnel", (2) le résultat de 144 ÷ 12, e **Objectif :** [Ping inter-agent depuis Main] Test du pont MCP inter-agents. Si tu reçois ce message, réponds via idea_reply avec : (1) "DevFrontend OK — pont inter-agent fonctionnel", (2) le résultat de 144 ÷ 12, e
@ -22,3 +22,5 @@ objective: [Ping inter-agent depuis Main] Test du pont MCP inter-agents. Si tu r
- **Response:** Lot B frontend `workstate delegation/queue snapshot` implémenté sur la branche active `feature/workstate-delegation-queue`. Aucun commit effectué. Fichiers modifiés: - `frontend/src/domain/index.ts` - `frontend/src/adapters/mock/index.ts` - `frontend/src/features/workstate/ProjectWorkStatePanel.tsx` - `frontend/src/features/workstate/useProjectWorkState.ts` - `frontend/src/features/workstate/workstate.test.tsx` Choix UI: - Sous-liste compacte uniquement pour les agents qui ont des tickets, sans bruit visuel pour les agents sans ticket. - Tickets triés par `position`, affichés en `#N In progress` / `#N Queued`. - Source humaine libellée `Human`; source agent affichée avec `requesterLabel` + id agent court quand disponible. - `taskPreview` affiché inline, avec suffixe léger `+N` si `taskLen > taskPreview.length`. - `ticketId` court en monospace avec `title` complet. Détails techniques: - Ajout des types `AgentTicketState`, `TicketWorkStatus`, `TicketWorkSource` et `AgentWorkState.tickets`. - `MockWorkStateGateway` accepte et normalise les états legacy sans `tickets` en `tickets: []`. - `useProjectWorkState` rafraîchit maintenant aussi sur lévénement domaine `delegationReady`, via linfrastructure `SystemGateway.onDomainEvent` déjà existante. Vérifications réelles: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `17 passed`. - `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur. Blocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé. - **Response:** Lot B frontend `workstate delegation/queue snapshot` implémenté sur la branche active `feature/workstate-delegation-queue`. Aucun commit effectué. Fichiers modifiés: - `frontend/src/domain/index.ts` - `frontend/src/adapters/mock/index.ts` - `frontend/src/features/workstate/ProjectWorkStatePanel.tsx` - `frontend/src/features/workstate/useProjectWorkState.ts` - `frontend/src/features/workstate/workstate.test.tsx` Choix UI: - Sous-liste compacte uniquement pour les agents qui ont des tickets, sans bruit visuel pour les agents sans ticket. - Tickets triés par `position`, affichés en `#N In progress` / `#N Queued`. - Source humaine libellée `Human`; source agent affichée avec `requesterLabel` + id agent court quand disponible. - `taskPreview` affiché inline, avec suffixe léger `+N` si `taskLen > taskPreview.length`. - `ticketId` court en monospace avec `title` complet. Détails techniques: - Ajout des types `AgentTicketState`, `TicketWorkStatus`, `TicketWorkSource` et `AgentWorkState.tickets`. - `MockWorkStateGateway` accepte et normalise les états legacy sans `tickets` en `tickets: []`. - `useProjectWorkState` rafraîchit maintenant aussi sur lévénement domaine `delegationReady`, via linfrastructure `SystemGateway.onDomainEvent` déjà existante. Vérifications réelles: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `17 passed`. - `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur. Blocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé.
- **Prompt:** Implémente le Lot C frontend `workstate conversation summaries` sur la branche active `feature/workstate-conversation-summaries`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend. Contexte backend disponible: - `ProjectWorkState` contient maintenant `conversations: ConversationWorkSummary[]` top-level. - `AgentTicketState.conversationId` existe déjà; le frontend doit joindre via `conversationId`. - DTO camelCase attendu: - `ConversationWorkSummary`: `conversationId`, `status` (`ready|missing|partial|unavailable`), `objectivePreview: string | null`, `summaryPreview: string | null`, `summaryLen`, `upTo: string | null`, `recentTurns: ConversationTurnWorkPreview[]`. - `ConversationTurnWorkPreview`: `role` (`prompt|response|toolActivity`), `source` (`{kind:'human'} | {kind:'agent'; agentId:string}`), `atMs`, `textPreview`, `textLen`. À faire: 1. Étendre les types frontend dans `frontend/src/domain/index.ts`: `ProjectWorkState.conversations`, `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview`. 2. Adapter le mock gateway pour accepter/normaliser les états legacy sans `conversations` en `conversations: []`. 3. Dans `ProjectWorkStatePanel.tsx`, construire une map `conversationId -> summary` et sous chaque ticket afficher une ligne compacte thread si summary disponible: - priorité: `Goal: <objectivePreview>` si présent; sinon `summaryPreview`; sinon dernier `recentTurn.textPreview` avec préfixe `Last:`; sinon rien de verbeux. - badge discret: `Summary` pour ready, `No summary` pour missing, `Partial`, `Unavailable`. - Ne pas afficher JSON brut, chemins, markdown volumineux, ni créer de modal/action. - Ne pas casser l'affichage ticket si aucune summary n'existe pour ce `conversationId`. 4. Mettre à jour/ajouter les tests Vitest: mock sans `conversations` normalisé; ticket avec `conversationId` affiche objectif/résumé; `partial`/`unavailable` ne masque pas le ticket; refresh existants restent verts. Contraintes: - Pas de nouvelle commande Tauri, pas d'action UX, pas de lecture logs/handoff côté frontend. - Respecte le style dense existant du panneau Work. - Ne committe pas. - Ignore dirty runtime `.ideai/*`. Vérifications demandées: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` - `cd frontend && npx tsc --noEmit` Retourne fichiers modifiés, choix UI, résultats réels des commandes, et tout blocage. - **Prompt:** Implémente le Lot C frontend `workstate conversation summaries` sur la branche active `feature/workstate-conversation-summaries`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend. Contexte backend disponible: - `ProjectWorkState` contient maintenant `conversations: ConversationWorkSummary[]` top-level. - `AgentTicketState.conversationId` existe déjà; le frontend doit joindre via `conversationId`. - DTO camelCase attendu: - `ConversationWorkSummary`: `conversationId`, `status` (`ready|missing|partial|unavailable`), `objectivePreview: string | null`, `summaryPreview: string | null`, `summaryLen`, `upTo: string | null`, `recentTurns: ConversationTurnWorkPreview[]`. - `ConversationTurnWorkPreview`: `role` (`prompt|response|toolActivity`), `source` (`{kind:'human'} | {kind:'agent'; agentId:string}`), `atMs`, `textPreview`, `textLen`. À faire: 1. Étendre les types frontend dans `frontend/src/domain/index.ts`: `ProjectWorkState.conversations`, `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview`. 2. Adapter le mock gateway pour accepter/normaliser les états legacy sans `conversations` en `conversations: []`. 3. Dans `ProjectWorkStatePanel.tsx`, construire une map `conversationId -> summary` et sous chaque ticket afficher une ligne compacte thread si summary disponible: - priorité: `Goal: <objectivePreview>` si présent; sinon `summaryPreview`; sinon dernier `recentTurn.textPreview` avec préfixe `Last:`; sinon rien de verbeux. - badge discret: `Summary` pour ready, `No summary` pour missing, `Partial`, `Unavailable`. - Ne pas afficher JSON brut, chemins, markdown volumineux, ni créer de modal/action. - Ne pas casser l'affichage ticket si aucune summary n'existe pour ce `conversationId`. 4. Mettre à jour/ajouter les tests Vitest: mock sans `conversations` normalisé; ticket avec `conversationId` affiche objectif/résumé; `partial`/`unavailable` ne masque pas le ticket; refresh existants restent verts. Contraintes: - Pas de nouvelle commande Tauri, pas d'action UX, pas de lecture logs/handoff côté frontend. - Respecte le style dense existant du panneau Work. - Ne committe pas. - Ignore dirty runtime `.ideai/*`. Vérifications demandées: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` - `cd frontend && npx tsc --noEmit` Retourne fichiers modifiés, choix UI, résultats réels des commandes, et tout blocage.
- **Response:** Lot C frontend `workstate conversation summaries` implémenté sur la branche active `feature/workstate-conversation-summaries`. Aucun commit effectué. Fichiers modifiés: - `frontend/src/domain/index.ts` - `frontend/src/adapters/mock/index.ts` - `frontend/src/features/workstate/ProjectWorkStatePanel.tsx` - `frontend/src/features/workstate/workstate.test.tsx` Choix UI: - `ProjectWorkStatePanel` construit une map `conversationId -> ConversationWorkSummary` au niveau du panel et joint les summaries sous chaque ticket. - La ligne thread reste compacte: badge discret (`Summary`, `No summary`, `Partial`, `Unavailable`) + texte court. - Priorité daffichage respectée: `Goal: <objectivePreview>`, sinon `summaryPreview`, sinon `Last: <recentTurn.textPreview>`, sinon aucune ligne summary. - Aucun JSON brut, chemin, markdown long, modal ou action UX ajouté. - Si un ticket na pas de summary correspondant, laffichage ticket reste inchangé. Détails techniques: - Ajout des types TS `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview` et `ProjectWorkState.conversations`. - `MockWorkStateGateway` normalise les états legacy sans `conversations` en `conversations: []`; létat vide par défaut renvoie aussi `{ agents: [], conversations: [] }`. - Tests ajoutés pour normalisation mock, objectif/résumé joint via `conversationId`, et badges `partial`/`unavailable` sans masquer les tickets. Vérifications réelles: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `19 passed`. - `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur. Blocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé. - **Response:** Lot C frontend `workstate conversation summaries` implémenté sur la branche active `feature/workstate-conversation-summaries`. Aucun commit effectué. Fichiers modifiés: - `frontend/src/domain/index.ts` - `frontend/src/adapters/mock/index.ts` - `frontend/src/features/workstate/ProjectWorkStatePanel.tsx` - `frontend/src/features/workstate/workstate.test.tsx` Choix UI: - `ProjectWorkStatePanel` construit une map `conversationId -> ConversationWorkSummary` au niveau du panel et joint les summaries sous chaque ticket. - La ligne thread reste compacte: badge discret (`Summary`, `No summary`, `Partial`, `Unavailable`) + texte court. - Priorité daffichage respectée: `Goal: <objectivePreview>`, sinon `summaryPreview`, sinon `Last: <recentTurn.textPreview>`, sinon aucune ligne summary. - Aucun JSON brut, chemin, markdown long, modal ou action UX ajouté. - Si un ticket na pas de summary correspondant, laffichage ticket reste inchangé. Détails techniques: - Ajout des types TS `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview` et `ProjectWorkState.conversations`. - `MockWorkStateGateway` normalise les états legacy sans `conversations` en `conversations: []`; létat vide par défaut renvoie aussi `{ agents: [], conversations: [] }`. - Tests ajoutés pour normalisation mock, objectif/résumé joint via `conversationId`, et badges `partial`/`unavailable` sans masquer les tickets. Vérifications réelles: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `19 passed`. - `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur. Blocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé.
- **Prompt:** Implémente le frontend du Lot D `workstate controlled actions` sur la branche active `feature/workstate-controlled-actions`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend. Contexte backend: - `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }` (contrat changé; plus de tableau). Zéro spawn. - `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }`. - `kind`: `"pty" | "structured"`. Périmètre frontend Lot D: 1. Adapter les ports/adapters TS au nouveau contrat attach + nouvelle commande stop. - Ne pas appeler `launchAgent` depuis Work. - Ne pas faire appeler `close_terminal` directement par le panneau Work pour stopper un agent. 2. Dans `ProjectWorkStatePanel`, ajouter actions minimales: - `Open` / `Go to cell` si agent live et `live.nodeId` visible dans le layout actif. Frontend-only focus/scroll/highlight si helper existant; sinon implémentation minimale testable suivant patterns existants. - `Attach` si agent live mais cellule non visible et cible déterministe existe. Si pas de cible, action désactivée/message court. Ne crée pas de session; appeler `attachLiveAgent`, puis mutation layout existante pour associer `sessionId`/agent si nécessaire. - `Stop` si agent live, avec confirmation. Si agent busy/inProgress, le texte de confirmation doit signaler que le tour sera interrompu. Appeler `stopLiveAgent`, puis refresh Work/layout. - `View` disclosure pour détails conversation Lot C (objectif, summaryPreview, recentTurns bornés déjà fournis), sans endpoint log. - `Copy` summary via clipboard, uniquement texte déjà exposé par Lot C; état bref `Copied`; désactivé si rien à copier. 3. Garder l'UI dense, pas de modal conversation, pas de log brut, pas de nouvelle commande Tauri. Contraintes: - Respecte patterns existants de gateways/layout/events. - Si certains helpers layout/focus n'existent pas, fais le minimum cohérent et explique l'écart. - Ne committe pas. - Ignore dirty runtime `.ideai/*`. Tests attendus: - `Open` focus une cellule visible et n'appelle pas launch. - `Attach` appelle `attachLiveAgent` puis mutation layout sur cible déterministe; désactivé sans cible. - `Stop` confirmation puis `stopLiveAgent`, refresh Work; warning si busy. - `View conversation` n'affiche que les champs Lot C. - `Copy summary` copie uniquement la preview exposée. - Non-régression des tests workstate/projects. Vérifications demandées: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` (ajoute autres tests ciblés si pertinents) - `cd frontend && npx tsc --noEmit` Retourne fichiers modifiés, choix UI/écarts, résultats réels, blocages.
- **Response:** Lot D frontend `workstate controlled actions` implémenté sur la branche active `feature/workstate-controlled-actions`. Aucun commit effectué. Fichiers modifiés: - `frontend/src/ports/index.ts` - `frontend/src/adapters/agent.ts` - `frontend/src/adapters/agent.test.ts` - `frontend/src/adapters/mock/index.ts` - `frontend/src/features/workstate/ProjectWorkStatePanel.tsx` - `frontend/src/features/workstate/workstate.test.tsx` - `frontend/src/features/layout/singletonAgent.test.tsx` - `frontend/src/features/layout/agentAlreadyRunning.test.tsx` Choix UI / comportement: - `attach_live_agent` adapté au nouveau contrat: retour direct `{ agentId, nodeId, sessionId, kind }`, plus de tableau. - Ajout du port/adapters `stopLiveAgent(projectId, agentId)` vers `stop_live_agent`; Work ne passe pas par `close_terminal`. - `LiveAgent.sessionId` est maintenant requis et `kind: "pty" | "structured"` est typé côté frontend. - Dans Work: - `Open` apparaît si lagent est live dans une cellule visible; action frontend-only qui scroll/focus/highlight via `data-node-id`. Aucun appel à `launchAgent`. - `Attach` apparaît si lagent est live mais hors layout visible; cible déterministe = première cellule visible vide (`!session && !agent`). Appelle `attachLiveAgent`, puis `attachLiveAgentToCell` pour associer session/agent au layout. Désactivé avec message court sil ny a pas de cellule vide visible. - `Stop` apparaît si agent live; confirmation native. Si lagent est busy ou a un ticket `inProgress`, le texte confirme que le tour courant sera interrompu. Appelle `stopLiveAgent`, refresh Work, et nettoie la session de la cellule visible si elle correspond. - `View` est un disclosure inline compact pour les champs Lot C déjà exposés: objectif, `summaryPreview`, `recentTurns`. Pas de log brut, pas de modal, pas dendpoint. - `Copy` copie uniquement le texte de preview déjà affiché (`Goal: ...`, `summaryPreview`, ou `Last: ...`) et montre brièvement `Copied`. Écart / limite assumée: - Il nexistait pas de helper focus exporté depuis `LayoutGrid`; jai repris le même mécanisme minimal DOM (`[data-node-id]`, scroll + outline temporaire) localement dans Work. - Il nexistait pas de méthode publique `refreshLayout` dans `useLayout`; après Stop, le layout visible est rafraîchi par mutation ciblée `setSession(..., null)` quand la cellule live est dans le layout actif, et Work est rafraîchi via `useProjectWorkState.refresh()`. Tests ajoutés/couverts: - `Open` focus cellule visible et nappelle pas `launchAgent`. - `Attach` appelle `attachLiveAgent` puis mutation layout sur cible déterministe; pas de `launchAgent` depuis Work. - `Attach` désactivé sans cible visible. - `Stop` confirme avec warning busy, appelle `stopLiveAgent`, refresh Work, nettoie la session visible. - `View conversation` naffiche que les previews Lot C. - `Copy summary` copie uniquement la preview exposée. - Tests adapter Tauri mis à jour pour attach retour direct + stop. Vérifications réelles: - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `25 passed`. - Test ciblé supplémentaire: `cd frontend && npx vitest run src/adapters/agent.test.ts` : OK, `1 passed`, `8 passed`. - `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur. Blocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé.

View File

@ -16,3 +16,5 @@
{"id":"7d70c87a-e7b5-468a-90c7-41decf1185bc","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781974090422,"source":{"kind":"agent","agentId":"af7f86da-76bc-48e1-9900-71f45a624800"},"role":"response","text":"Lot B frontend `workstate delegation/queue snapshot` implémenté sur la branche active `feature/workstate-delegation-queue`. Aucun commit effectué.\n\nFichiers modifiés:\n- `frontend/src/domain/index.ts`\n- `frontend/src/adapters/mock/index.ts`\n- `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`\n- `frontend/src/features/workstate/useProjectWorkState.ts`\n- `frontend/src/features/workstate/workstate.test.tsx`\n\nChoix UI:\n- Sous-liste compacte uniquement pour les agents qui ont des tickets, sans bruit visuel pour les agents sans ticket.\n- Tickets triés par `position`, affichés en `#N In progress` / `#N Queued`.\n- Source humaine libellée `Human`; source agent affichée avec `requesterLabel` + id agent court quand disponible.\n- `taskPreview` affiché inline, avec suffixe léger `+N` si `taskLen > taskPreview.length`.\n- `ticketId` court en monospace avec `title` complet.\n\nDétails techniques:\n- Ajout des types `AgentTicketState`, `TicketWorkStatus`, `TicketWorkSource` et `AgentWorkState.tickets`.\n- `MockWorkStateGateway` accepte et normalise les états legacy sans `tickets` en `tickets: []`.\n- `useProjectWorkState` rafraîchit maintenant aussi sur lévénement domaine `delegationReady`, via linfrastructure `SystemGateway.onDomainEvent` déjà existante.\n\nVérifications réelles:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `17 passed`.\n- `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur.\n\nBlocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé."} {"id":"7d70c87a-e7b5-468a-90c7-41decf1185bc","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781974090422,"source":{"kind":"agent","agentId":"af7f86da-76bc-48e1-9900-71f45a624800"},"role":"response","text":"Lot B frontend `workstate delegation/queue snapshot` implémenté sur la branche active `feature/workstate-delegation-queue`. Aucun commit effectué.\n\nFichiers modifiés:\n- `frontend/src/domain/index.ts`\n- `frontend/src/adapters/mock/index.ts`\n- `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`\n- `frontend/src/features/workstate/useProjectWorkState.ts`\n- `frontend/src/features/workstate/workstate.test.tsx`\n\nChoix UI:\n- Sous-liste compacte uniquement pour les agents qui ont des tickets, sans bruit visuel pour les agents sans ticket.\n- Tickets triés par `position`, affichés en `#N In progress` / `#N Queued`.\n- Source humaine libellée `Human`; source agent affichée avec `requesterLabel` + id agent court quand disponible.\n- `taskPreview` affiché inline, avec suffixe léger `+N` si `taskLen > taskPreview.length`.\n- `ticketId` court en monospace avec `title` complet.\n\nDétails techniques:\n- Ajout des types `AgentTicketState`, `TicketWorkStatus`, `TicketWorkSource` et `AgentWorkState.tickets`.\n- `MockWorkStateGateway` accepte et normalise les états legacy sans `tickets` en `tickets: []`.\n- `useProjectWorkState` rafraîchit maintenant aussi sur lévénement domaine `delegationReady`, via linfrastructure `SystemGateway.onDomainEvent` déjà existante.\n\nVérifications réelles:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `17 passed`.\n- `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur.\n\nBlocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé."}
{"id":"5a2a42de-9ce4-461b-8d08-5b282a7b4db2","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781976069973,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Implémente le Lot C frontend `workstate conversation summaries` sur la branche active `feature/workstate-conversation-summaries`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend.\n\nContexte backend disponible:\n- `ProjectWorkState` contient maintenant `conversations: ConversationWorkSummary[]` top-level.\n- `AgentTicketState.conversationId` existe déjà; le frontend doit joindre via `conversationId`.\n- DTO camelCase attendu:\n - `ConversationWorkSummary`: `conversationId`, `status` (`ready|missing|partial|unavailable`), `objectivePreview: string | null`, `summaryPreview: string | null`, `summaryLen`, `upTo: string | null`, `recentTurns: ConversationTurnWorkPreview[]`.\n - `ConversationTurnWorkPreview`: `role` (`prompt|response|toolActivity`), `source` (`{kind:'human'} | {kind:'agent'; agentId:string}`), `atMs`, `textPreview`, `textLen`.\n\nÀ faire:\n1. Étendre les types frontend dans `frontend/src/domain/index.ts`: `ProjectWorkState.conversations`, `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview`.\n2. Adapter le mock gateway pour accepter/normaliser les états legacy sans `conversations` en `conversations: []`.\n3. Dans `ProjectWorkStatePanel.tsx`, construire une map `conversationId -> summary` et sous chaque ticket afficher une ligne compacte thread si summary disponible:\n - priorité: `Goal: <objectivePreview>` si présent; sinon `summaryPreview`; sinon dernier `recentTurn.textPreview` avec préfixe `Last:`; sinon rien de verbeux.\n - badge discret: `Summary` pour ready, `No summary` pour missing, `Partial`, `Unavailable`.\n - Ne pas afficher JSON brut, chemins, markdown volumineux, ni créer de modal/action.\n - Ne pas casser l'affichage ticket si aucune summary n'existe pour ce `conversationId`.\n4. Mettre à jour/ajouter les tests Vitest: mock sans `conversations` normalisé; ticket avec `conversationId` affiche objectif/résumé; `partial`/`unavailable` ne masque pas le ticket; refresh existants restent verts.\n\nContraintes:\n- Pas de nouvelle commande Tauri, pas d'action UX, pas de lecture logs/handoff côté frontend.\n- Respecte le style dense existant du panneau Work.\n- Ne committe pas.\n- Ignore dirty runtime `.ideai/*`.\n\nVérifications demandées:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx`\n- `cd frontend && npx tsc --noEmit`\n\nRetourne fichiers modifiés, choix UI, résultats réels des commandes, et tout blocage."} {"id":"5a2a42de-9ce4-461b-8d08-5b282a7b4db2","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781976069973,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Implémente le Lot C frontend `workstate conversation summaries` sur la branche active `feature/workstate-conversation-summaries`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend.\n\nContexte backend disponible:\n- `ProjectWorkState` contient maintenant `conversations: ConversationWorkSummary[]` top-level.\n- `AgentTicketState.conversationId` existe déjà; le frontend doit joindre via `conversationId`.\n- DTO camelCase attendu:\n - `ConversationWorkSummary`: `conversationId`, `status` (`ready|missing|partial|unavailable`), `objectivePreview: string | null`, `summaryPreview: string | null`, `summaryLen`, `upTo: string | null`, `recentTurns: ConversationTurnWorkPreview[]`.\n - `ConversationTurnWorkPreview`: `role` (`prompt|response|toolActivity`), `source` (`{kind:'human'} | {kind:'agent'; agentId:string}`), `atMs`, `textPreview`, `textLen`.\n\nÀ faire:\n1. Étendre les types frontend dans `frontend/src/domain/index.ts`: `ProjectWorkState.conversations`, `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview`.\n2. Adapter le mock gateway pour accepter/normaliser les états legacy sans `conversations` en `conversations: []`.\n3. Dans `ProjectWorkStatePanel.tsx`, construire une map `conversationId -> summary` et sous chaque ticket afficher une ligne compacte thread si summary disponible:\n - priorité: `Goal: <objectivePreview>` si présent; sinon `summaryPreview`; sinon dernier `recentTurn.textPreview` avec préfixe `Last:`; sinon rien de verbeux.\n - badge discret: `Summary` pour ready, `No summary` pour missing, `Partial`, `Unavailable`.\n - Ne pas afficher JSON brut, chemins, markdown volumineux, ni créer de modal/action.\n - Ne pas casser l'affichage ticket si aucune summary n'existe pour ce `conversationId`.\n4. Mettre à jour/ajouter les tests Vitest: mock sans `conversations` normalisé; ticket avec `conversationId` affiche objectif/résumé; `partial`/`unavailable` ne masque pas le ticket; refresh existants restent verts.\n\nContraintes:\n- Pas de nouvelle commande Tauri, pas d'action UX, pas de lecture logs/handoff côté frontend.\n- Respecte le style dense existant du panneau Work.\n- Ne committe pas.\n- Ignore dirty runtime `.ideai/*`.\n\nVérifications demandées:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx`\n- `cd frontend && npx tsc --noEmit`\n\nRetourne fichiers modifiés, choix UI, résultats réels des commandes, et tout blocage."}
{"id":"11b7df5e-f50e-4f4e-b680-37d5fb10af72","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781976255451,"source":{"kind":"agent","agentId":"af7f86da-76bc-48e1-9900-71f45a624800"},"role":"response","text":"Lot C frontend `workstate conversation summaries` implémenté sur la branche active `feature/workstate-conversation-summaries`. Aucun commit effectué.\n\nFichiers modifiés:\n- `frontend/src/domain/index.ts`\n- `frontend/src/adapters/mock/index.ts`\n- `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`\n- `frontend/src/features/workstate/workstate.test.tsx`\n\nChoix UI:\n- `ProjectWorkStatePanel` construit une map `conversationId -> ConversationWorkSummary` au niveau du panel et joint les summaries sous chaque ticket.\n- La ligne thread reste compacte: badge discret (`Summary`, `No summary`, `Partial`, `Unavailable`) + texte court.\n- Priorité daffichage respectée: `Goal: <objectivePreview>`, sinon `summaryPreview`, sinon `Last: <recentTurn.textPreview>`, sinon aucune ligne summary.\n- Aucun JSON brut, chemin, markdown long, modal ou action UX ajouté.\n- Si un ticket na pas de summary correspondant, laffichage ticket reste inchangé.\n\nDétails techniques:\n- Ajout des types TS `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview` et `ProjectWorkState.conversations`.\n- `MockWorkStateGateway` normalise les états legacy sans `conversations` en `conversations: []`; létat vide par défaut renvoie aussi `{ agents: [], conversations: [] }`.\n- Tests ajoutés pour normalisation mock, objectif/résumé joint via `conversationId`, et badges `partial`/`unavailable` sans masquer les tickets.\n\nVérifications réelles:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `19 passed`.\n- `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur.\n\nBlocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé."} {"id":"11b7df5e-f50e-4f4e-b680-37d5fb10af72","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781976255451,"source":{"kind":"agent","agentId":"af7f86da-76bc-48e1-9900-71f45a624800"},"role":"response","text":"Lot C frontend `workstate conversation summaries` implémenté sur la branche active `feature/workstate-conversation-summaries`. Aucun commit effectué.\n\nFichiers modifiés:\n- `frontend/src/domain/index.ts`\n- `frontend/src/adapters/mock/index.ts`\n- `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`\n- `frontend/src/features/workstate/workstate.test.tsx`\n\nChoix UI:\n- `ProjectWorkStatePanel` construit une map `conversationId -> ConversationWorkSummary` au niveau du panel et joint les summaries sous chaque ticket.\n- La ligne thread reste compacte: badge discret (`Summary`, `No summary`, `Partial`, `Unavailable`) + texte court.\n- Priorité daffichage respectée: `Goal: <objectivePreview>`, sinon `summaryPreview`, sinon `Last: <recentTurn.textPreview>`, sinon aucune ligne summary.\n- Aucun JSON brut, chemin, markdown long, modal ou action UX ajouté.\n- Si un ticket na pas de summary correspondant, laffichage ticket reste inchangé.\n\nDétails techniques:\n- Ajout des types TS `ConversationWorkSummary`, `ConversationPreviewStatus`, `ConversationTurnWorkPreview` et `ProjectWorkState.conversations`.\n- `MockWorkStateGateway` normalise les états legacy sans `conversations` en `conversations: []`; létat vide par défaut renvoie aussi `{ agents: [], conversations: [] }`.\n- Tests ajoutés pour normalisation mock, objectif/résumé joint via `conversationId`, et badges `partial`/`unavailable` sans masquer les tickets.\n\nVérifications réelles:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `19 passed`.\n- `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur.\n\nBlocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé."}
{"id":"889dc0de-b092-4103-9650-e5f73c8b18e0","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781977298082,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Implémente le frontend du Lot D `workstate controlled actions` sur la branche active `feature/workstate-controlled-actions`, en t'appuyant sur le backend/Tauri déjà modifié par DevBackend.\n\nContexte backend:\n- `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }` (contrat changé; plus de tableau). Zéro spawn.\n- `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }`.\n- `kind`: `\"pty\" | \"structured\"`.\n\nPérimètre frontend Lot D:\n1. Adapter les ports/adapters TS au nouveau contrat attach + nouvelle commande stop.\n - Ne pas appeler `launchAgent` depuis Work.\n - Ne pas faire appeler `close_terminal` directement par le panneau Work pour stopper un agent.\n2. Dans `ProjectWorkStatePanel`, ajouter actions minimales:\n - `Open` / `Go to cell` si agent live et `live.nodeId` visible dans le layout actif. Frontend-only focus/scroll/highlight si helper existant; sinon implémentation minimale testable suivant patterns existants.\n - `Attach` si agent live mais cellule non visible et cible déterministe existe. Si pas de cible, action désactivée/message court. Ne crée pas de session; appeler `attachLiveAgent`, puis mutation layout existante pour associer `sessionId`/agent si nécessaire.\n - `Stop` si agent live, avec confirmation. Si agent busy/inProgress, le texte de confirmation doit signaler que le tour sera interrompu. Appeler `stopLiveAgent`, puis refresh Work/layout.\n - `View` disclosure pour détails conversation Lot C (objectif, summaryPreview, recentTurns bornés déjà fournis), sans endpoint log.\n - `Copy` summary via clipboard, uniquement texte déjà exposé par Lot C; état bref `Copied`; désactivé si rien à copier.\n3. Garder l'UI dense, pas de modal conversation, pas de log brut, pas de nouvelle commande Tauri.\n\nContraintes:\n- Respecte patterns existants de gateways/layout/events.\n- Si certains helpers layout/focus n'existent pas, fais le minimum cohérent et explique l'écart.\n- Ne committe pas.\n- Ignore dirty runtime `.ideai/*`.\n\nTests attendus:\n- `Open` focus une cellule visible et n'appelle pas launch.\n- `Attach` appelle `attachLiveAgent` puis mutation layout sur cible déterministe; désactivé sans cible.\n- `Stop` confirmation puis `stopLiveAgent`, refresh Work; warning si busy.\n- `View conversation` n'affiche que les champs Lot C.\n- `Copy summary` copie uniquement la preview exposée.\n- Non-régression des tests workstate/projects.\n\nVérifications demandées:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` (ajoute autres tests ciblés si pertinents)\n- `cd frontend && npx tsc --noEmit`\n\nRetourne fichiers modifiés, choix UI/écarts, résultats réels, blocages."}
{"id":"c269039f-212a-42a7-a520-2770cb7cc773","conversation":"09b15ec3-ce2f-0af2-2903-ef699df9de41","atMs":1781977717382,"source":{"kind":"agent","agentId":"af7f86da-76bc-48e1-9900-71f45a624800"},"role":"response","text":"Lot D frontend `workstate controlled actions` implémenté sur la branche active `feature/workstate-controlled-actions`. Aucun commit effectué.\n\nFichiers modifiés:\n- `frontend/src/ports/index.ts`\n- `frontend/src/adapters/agent.ts`\n- `frontend/src/adapters/agent.test.ts`\n- `frontend/src/adapters/mock/index.ts`\n- `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`\n- `frontend/src/features/workstate/workstate.test.tsx`\n- `frontend/src/features/layout/singletonAgent.test.tsx`\n- `frontend/src/features/layout/agentAlreadyRunning.test.tsx`\n\nChoix UI / comportement:\n- `attach_live_agent` adapté au nouveau contrat: retour direct `{ agentId, nodeId, sessionId, kind }`, plus de tableau.\n- Ajout du port/adapters `stopLiveAgent(projectId, agentId)` vers `stop_live_agent`; Work ne passe pas par `close_terminal`.\n- `LiveAgent.sessionId` est maintenant requis et `kind: \"pty\" | \"structured\"` est typé côté frontend.\n- Dans Work:\n - `Open` apparaît si lagent est live dans une cellule visible; action frontend-only qui scroll/focus/highlight via `data-node-id`. Aucun appel à `launchAgent`.\n - `Attach` apparaît si lagent est live mais hors layout visible; cible déterministe = première cellule visible vide (`!session && !agent`). Appelle `attachLiveAgent`, puis `attachLiveAgentToCell` pour associer session/agent au layout. Désactivé avec message court sil ny a pas de cellule vide visible.\n - `Stop` apparaît si agent live; confirmation native. Si lagent est busy ou a un ticket `inProgress`, le texte confirme que le tour courant sera interrompu. Appelle `stopLiveAgent`, refresh Work, et nettoie la session de la cellule visible si elle correspond.\n - `View` est un disclosure inline compact pour les champs Lot C déjà exposés: objectif, `summaryPreview`, `recentTurns`. Pas de log brut, pas de modal, pas dendpoint.\n - `Copy` copie uniquement le texte de preview déjà affiché (`Goal: ...`, `summaryPreview`, ou `Last: ...`) et montre brièvement `Copied`.\n\nÉcart / limite assumée:\n- Il nexistait pas de helper focus exporté depuis `LayoutGrid`; jai repris le même mécanisme minimal DOM (`[data-node-id]`, scroll + outline temporaire) localement dans Work.\n- Il nexistait pas de méthode publique `refreshLayout` dans `useLayout`; après Stop, le layout visible est rafraîchi par mutation ciblée `setSession(..., null)` quand la cellule live est dans le layout actif, et Work est rafraîchi via `useProjectWorkState.refresh()`.\n\nTests ajoutés/couverts:\n- `Open` focus cellule visible et nappelle pas `launchAgent`.\n- `Attach` appelle `attachLiveAgent` puis mutation layout sur cible déterministe; pas de `launchAgent` depuis Work.\n- `Attach` désactivé sans cible visible.\n- `Stop` confirme avec warning busy, appelle `stopLiveAgent`, refresh Work, nettoie la session visible.\n- `View conversation` naffiche que les previews Lot C.\n- `Copy summary` copie uniquement la preview exposée.\n- Tests adapter Tauri mis à jour pour attach retour direct + stop.\n\nVérifications réelles:\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` : OK, `2 passed`, `25 passed`.\n- Test ciblé supplémentaire: `cd frontend && npx vitest run src/adapters/agent.test.ts` : OK, `1 passed`, `8 passed`.\n- `cd frontend && npx tsc --noEmit` : OK, aucune sortie derreur.\n\nBlocage: aucun. Les fichiers runtime `.ideai/*` dirty et les changements backend existants ont été ignorés comme demandé."}

View File

@ -1,11 +1,9 @@
--- ---
upTo: c10a7683-5468-472c-adbb-37fb6fe8c470 upTo: e43c2b68-a855-4433-8067-64f6fc4fa59c
objective: Nouvelle feature cadrée par Architect, prête à démarrer le développement : « Gestion des limites de session des agents » (détection hiérarchique des limites de session + reprise auto annulable). C'est objective: Nouvelle feature cadrée par Architect, prête à démarrer le développement : « Gestion des limites de session des agents » (détection hiérarchique des limites de session + reprise auto annulable). C'est
--- ---
**Objectif :** Nouvelle feature cadrée par Architect, prête à démarrer le développement : « Gestion des limites de session des agents » (détection hiérarchique des limites de session + reprise auto annulable). C'est **Objectif :** Nouvelle feature cadrée par Architect, prête à démarrer le développement : « Gestion des limites de session des agents » (détection hiérarchique des limites de session + reprise auto annulable). C'est
- **Response:** Commits effectués localement sur `feature/agent-skill-awareness-v2` (aucun push). Décision : `lifecycle.rs` = intention distincte (la feature réelle de la branche) → commit séparé du hotfix. ## 3 commits atomiques (par intention) **1. `befff76` — feat(skills): injecte un paragraphe d'awareness skills dans le fichier de convention** - Inclus : `crates/application/src/agent/lifecycle.rs` - La feature de la branche : `compose_convention_file` émet l'awareness skills (assigné = contexte opérationnel, pas commande magique/sous-tâche ; capitalisation via `idea_create_skill` en MCP / `skill.create` en protocole fichier), sans injecter les corps des skills non assignés. **2. `018eb1a` — fix(input): fiabilise la livraison de délégation et journalise le submit** - Inclus : `crates/app-tauri/src/commands.rs`, `crates/application/src/orchestrator/service.rs`, `crates/infrastructure/src/input/mod.rs`, `frontend/src/adapters/input.ts`, `frontend/src/adapters/terminal.ts`, `frontend/src/domain/index.ts`, `frontend/src/features/terminals/useWritePortal.ts`, `useWritePortal.test.tsx` - Le hotfix livraison délégation + logs submit (bout-en-bout commande Tauri → orchestrateur → file infra → portail front). **3. `cc575ef` — chore(wip): état runtime .ideai (conversations, layouts, mémoire, checkpoint skill-awareness)** - Inclus : `.ideai/conversations/*` (handoff + log.jsonl ×5), `.ideai/layouts.json`, `.ideai/memory/MEMORY.md`, nouveau `.ideai/memory/checkpoint-delivery-submit-logging-fix.md` - État runtime non-code, isolé du code comme convenu. ## Exclus / hors commit Rien laissé de côté : working tree **propre** (`git status` vide). La réserve QA (tests loopback socket Unix réels non exécutables en sandbox — `UnixListener::bind` PermissionDenied, alternatives skips vertes) est consignée dans le message du commit `018eb1a`. ## État final - Branche : `feature/agent-skill-awareness-v2`, tip = `cc575ef`. - Base : toujours `develop` (`e832af5`) comme ancêtre direct, **pas de divergence** → merge `--no-ff` vers `develop` possible sans rebase dès que tu donnes le GO. - Aucune action sortante (pas de push). Dis-moi si tu veux que je merge vers `develop` maintenant ou si on garde sur la feature.
- **Prompt:** Tu viens de committer `feature/agent-skill-awareness-v2` avec QA vert accepté réserve environnementale. Selon les règles projet, Git décide les merges locaux sans demander à l'utilisateur. Merci de trancher maintenant: merge local `feature/agent-skill-awareness-v2` vers `develop` ou différer, avec justification. Si tu décides de merger, fais le merge local approprié sans push et retourne l'état final. Si tu différés, explique la condition restante précise. Ne demande pas de GO utilisateur.
- **Response:** Décision Git : **MERGE effectué** (local, sans push). Feature terminée et QA verte (réserve env. acceptable : seuls les tests loopback socket Unix non exécutables en sandbox, alternatives skips vertes) → rien ne justifiait de différer. ## Ce qui a été fait 1. Pendant l'opération, des écritures runtime live (`.ideai/conversations/6bc594e8…`) ont resurgi et bloquaient le checkout. Je les ai committées proprement sur la feature : - `8074aec` — chore(wip): état runtime .ideai (flux conversation live) 2. `git checkout develop` puis `git merge --no-ff feature/agent-skill-awareness-v2`. - Pas de rebase nécessaire : `develop` était ancêtre direct, historique non divergent. - Merge commit : **`63eb49a`** — merge(skills): intègre agent-skill-awareness-v2 dans develop. ## Historique résultant (develop) ``` * 63eb49a merge(skills): intègre agent-skill-awareness-v2 dans develop |\ | * 8074aec chore(wip): état runtime .ideai (flux conversation live) | * cc575ef chore(wip): état runtime .ideai (…checkpoint skill-awareness) | * 018eb1a fix(input): fiabilise la livraison de délégation et journalise le submit | * befff76 feat(skills): injecte un paragraphe d'awareness skills dans le fichier de convention |/ * e832af5 (base commune) ``` Merge sans conflit (stratégie ort), 22 fichiers / +575 -95. ## État final - Branche courante : **`develop`**, tip = `63eb49a`. - `develop` : **devant `origin/develop` de 15 commits** (local uniquement, aucun push — conforme). - Working tree propre au moment du merge (le flux runtime live peut le re-salir à tout instant, c'est normal). - Branche `feature/agent-skill-awareness-v2` **conservée** (entièrement fusionnée). Je ne la supprime pas : tu as parlé de « reprise de chantier », donc je la garde disponible. Dis-moi si tu veux que je la supprime maintenant qu'elle est intégrée. Aucune action sortante effectuée. Pour publier (`push origin develop`), il me faut ta validation explicite. - **Response:** Décision Git : **MERGE effectué** (local, sans push). Feature terminée et QA verte (réserve env. acceptable : seuls les tests loopback socket Unix non exécutables en sandbox, alternatives skips vertes) → rien ne justifiait de différer. ## Ce qui a été fait 1. Pendant l'opération, des écritures runtime live (`.ideai/conversations/6bc594e8…`) ont resurgi et bloquaient le checkout. Je les ai committées proprement sur la feature : - `8074aec` — chore(wip): état runtime .ideai (flux conversation live) 2. `git checkout develop` puis `git merge --no-ff feature/agent-skill-awareness-v2`. - Pas de rebase nécessaire : `develop` était ancêtre direct, historique non divergent. - Merge commit : **`63eb49a`** — merge(skills): intègre agent-skill-awareness-v2 dans develop. ## Historique résultant (develop) ``` * 63eb49a merge(skills): intègre agent-skill-awareness-v2 dans develop |\ | * 8074aec chore(wip): état runtime .ideai (flux conversation live) | * cc575ef chore(wip): état runtime .ideai (…checkpoint skill-awareness) | * 018eb1a fix(input): fiabilise la livraison de délégation et journalise le submit | * befff76 feat(skills): injecte un paragraphe d'awareness skills dans le fichier de convention |/ * e832af5 (base commune) ``` Merge sans conflit (stratégie ort), 22 fichiers / +575 -95. ## État final - Branche courante : **`develop`**, tip = `63eb49a`. - `develop` : **devant `origin/develop` de 15 commits** (local uniquement, aucun push — conforme). - Working tree propre au moment du merge (le flux runtime live peut le re-salir à tout instant, c'est normal). - Branche `feature/agent-skill-awareness-v2` **conservée** (entièrement fusionnée). Je ne la supprime pas : tu as parlé de « reprise de chantier », donc je la garde disponible. Dis-moi si tu veux que je la supprime maintenant qu'elle est intégrée. Aucune action sortante effectuée. Pour publier (`push origin develop`), il me faut ta validation explicite.
- **Prompt:** Inventaire des chantiers en cours après merge local `feature/agent-skill-awareness-v2` dans `develop` (`63eb49a`). Branches visibles: locales `feature/agent-skill-awareness`, `feature/agent-skills`, `fix/cold-start-delivery-race`, `feature/agent-skill-awareness-v2`; distante `origin/feature/agent-session-limits`; develop ahead origin/develop de 15; main ahead origin/main de 4. Merci de déterminer pour chaque branche si elle est déjà intégrée, superseded, encore active ou à conserver, sans suppression pour l'instant. Identifie les chantiers applicatifs réellement en cours/restants et la stratégie repo avant de reprendre le prochain. Ne committe/merge/supprime rien dans cette étape. - **Prompt:** Inventaire des chantiers en cours après merge local `feature/agent-skill-awareness-v2` dans `develop` (`63eb49a`). Branches visibles: locales `feature/agent-skill-awareness`, `feature/agent-skills`, `fix/cold-start-delivery-race`, `feature/agent-skill-awareness-v2`; distante `origin/feature/agent-session-limits`; develop ahead origin/develop de 15; main ahead origin/main de 4. Merci de déterminer pour chaque branche si elle est déjà intégrée, superseded, encore active ou à conserver, sans suppression pour l'instant. Identifie les chantiers applicatifs réellement en cours/restants et la stratégie repo avant de reprendre le prochain. Ne committe/merge/supprime rien dans cette étape.
- **Response:** Inventaire repo après merge `agent-skill-awareness-v2``develop` (`63eb49a`). **Aucune suppression / commit / merge fait** (lecture seule). Méthode : `git cherry` (patch-id) **+** vérification du contenu réel dans `develop`, car les branches sont anciennes et leurs patches ont été re-landés différemment (les patch-ids diffèrent même quand le contenu est présent). ## Statut par branche **`feature/agent-skill-awareness-v2`** — ✅ INTÉGRÉE (mergée à l'instant, `63eb49a`). Conserver tant que reprise possible, sinon supprimable. **`feature/agent-skill-awareness` (v1)** — 🟠 SUPERSEDED par v2. Ses commits uniques portent une **autre approche** : outil MCP `idea_skill_read` + manifeste de skills + brief « capacités IdeA » inconditionnel (`ab34363`, `566bff4`, `1a10d67`). Vérif : `idea_skill_read` **absent de develop** → v2 a délibérément retenu une autre voie (injection des corps de skills dans le fichier de convention + paragraphe d'awareness via `lifecycle.rs`). Son fix cold-start (`e93a2c1`) est déjà couvert par develop. ⇒ rien à récupérer sauf si tu veux ressusciter l'approche `idea_skill_read` (non recommandé, v2 a tranché). **À archiver/supprimer.** **`feature/agent-skills` (L12, `ef101db`)** — 🟢 INTÉGRÉE PAR ÉQUIVALENT. Le domaine skills est présent dans develop : `crates/domain/src/skill.rs`, `crates/application/src/skill/{mod,usecases}.rs`, `crates/infrastructure/src/store/skill.rs` (+ tests). Re-landé via un autre chemin. **Superseded en tant que branche.** **`fix/cold-start-delivery-race` (`9590eac`)** — 🟢 INTÉGRÉE PAR ÉQUIVALENT. La logique cold-start (`release_cold_start`, gate armé) est dans develop : `crates/infrastructure/src/input/mod.rs:341,895`. La branche traîne en plus de vieux `release(0.1.0)/(0.2.0)` → elle a divergé d'un vieux `main`. **Stale, supprimable.** **`origin/feature/agent-session-limits` (`3f3504e`)** — 🟢 MERGÉE (ancêtre de develop). Branche distante stale ; le feature session-limits est dans develop. **`origin/wip/p8c-checkpoint-before-codex`** — branche distante WIP fondations enforcement OS (permissions), non rattachée localement ; à clarifier si encore vivante (probablement absorbée par le chantier permissions/sandbox déjà livré en code). ## État publication (local-only, conforme « pas de push ») - `develop` : **ahead origin/develop de 15** (contient tout ce qui précède). - `main` : **ahead origin/main de 4** = `release(0.3.0)` mergée localement, jamais poussée. origin/main = encore 0.2.0. ## Chantiers applicatifs réellement restants (vs branches mortes) Les 4 branches non-mergées ne portent **aucun chantier vivant** : tout est soit intégré, soit superseded. Le travail restant est ailleurs (cf. mémoire projet, pas dans des branches) : 1. **Validation e2e réelle sur AppImage** — nombreux items « ✓ RÉSOLU EN CODE … valid. e2e restante » (socket MCP, MCP inter-agents au restart, MCP natif en structuré, modèle terminal natif). Bloqueur connu : `checkpoint-blocked-until-appimage-030` / blocage build AppImage 0.3.0. 2. **Enforcement permissions/sandbox** : résiduel `$HOME`/résume du chemin structuré (memory `permissions-sandbox-system-state`). 3. Optionnels persistance : P9 FileGuard, P10 résumé LLM. ## Stratégie repo recommandée avant le prochain chantier - **Nettoyage différé** (sur ton GO, étape suivante) : supprimer en local `feature/agent-skill-awareness`, `feature/agent-skills`, `fix/cold-start-delivery-race` (toutes superseded/intégrées) ; idem branches distantes stale `origin/feature/agent-session-limits` (suppression distante = action sortante → validation explicite requise). - **Prochaine branche** : repartir **de `develop`** (`63eb49a`) avec un `feature/<sujet>` neuf pour le prochain chantier (probablement la **validation e2e AppImage 0.3.0**, qui est le vrai bloqueur courant). - **Push** : `develop` (+15) et `main` (+4 / release 0.3.0) attendent une validation explicite avant publication — je ne pousse rien sans ton accord. Dis-moi quel chantier on reprend : je crée la branche adéquate depuis `develop`. - **Response:** Inventaire repo après merge `agent-skill-awareness-v2``develop` (`63eb49a`). **Aucune suppression / commit / merge fait** (lecture seule). Méthode : `git cherry` (patch-id) **+** vérification du contenu réel dans `develop`, car les branches sont anciennes et leurs patches ont été re-landés différemment (les patch-ids diffèrent même quand le contenu est présent). ## Statut par branche **`feature/agent-skill-awareness-v2`** — ✅ INTÉGRÉE (mergée à l'instant, `63eb49a`). Conserver tant que reprise possible, sinon supprimable. **`feature/agent-skill-awareness` (v1)** — 🟠 SUPERSEDED par v2. Ses commits uniques portent une **autre approche** : outil MCP `idea_skill_read` + manifeste de skills + brief « capacités IdeA » inconditionnel (`ab34363`, `566bff4`, `1a10d67`). Vérif : `idea_skill_read` **absent de develop** → v2 a délibérément retenu une autre voie (injection des corps de skills dans le fichier de convention + paragraphe d'awareness via `lifecycle.rs`). Son fix cold-start (`e93a2c1`) est déjà couvert par develop. ⇒ rien à récupérer sauf si tu veux ressusciter l'approche `idea_skill_read` (non recommandé, v2 a tranché). **À archiver/supprimer.** **`feature/agent-skills` (L12, `ef101db`)** — 🟢 INTÉGRÉE PAR ÉQUIVALENT. Le domaine skills est présent dans develop : `crates/domain/src/skill.rs`, `crates/application/src/skill/{mod,usecases}.rs`, `crates/infrastructure/src/store/skill.rs` (+ tests). Re-landé via un autre chemin. **Superseded en tant que branche.** **`fix/cold-start-delivery-race` (`9590eac`)** — 🟢 INTÉGRÉE PAR ÉQUIVALENT. La logique cold-start (`release_cold_start`, gate armé) est dans develop : `crates/infrastructure/src/input/mod.rs:341,895`. La branche traîne en plus de vieux `release(0.1.0)/(0.2.0)` → elle a divergé d'un vieux `main`. **Stale, supprimable.** **`origin/feature/agent-session-limits` (`3f3504e`)** — 🟢 MERGÉE (ancêtre de develop). Branche distante stale ; le feature session-limits est dans develop. **`origin/wip/p8c-checkpoint-before-codex`** — branche distante WIP fondations enforcement OS (permissions), non rattachée localement ; à clarifier si encore vivante (probablement absorbée par le chantier permissions/sandbox déjà livré en code). ## État publication (local-only, conforme « pas de push ») - `develop` : **ahead origin/develop de 15** (contient tout ce qui précède). - `main` : **ahead origin/main de 4** = `release(0.3.0)` mergée localement, jamais poussée. origin/main = encore 0.2.0. ## Chantiers applicatifs réellement restants (vs branches mortes) Les 4 branches non-mergées ne portent **aucun chantier vivant** : tout est soit intégré, soit superseded. Le travail restant est ailleurs (cf. mémoire projet, pas dans des branches) : 1. **Validation e2e réelle sur AppImage** — nombreux items « ✓ RÉSOLU EN CODE … valid. e2e restante » (socket MCP, MCP inter-agents au restart, MCP natif en structuré, modèle terminal natif). Bloqueur connu : `checkpoint-blocked-until-appimage-030` / blocage build AppImage 0.3.0. 2. **Enforcement permissions/sandbox** : résiduel `$HOME`/résume du chemin structuré (memory `permissions-sandbox-system-state`). 3. Optionnels persistance : P9 FileGuard, P10 résumé LLM. ## Stratégie repo recommandée avant le prochain chantier - **Nettoyage différé** (sur ton GO, étape suivante) : supprimer en local `feature/agent-skill-awareness`, `feature/agent-skills`, `fix/cold-start-delivery-race` (toutes superseded/intégrées) ; idem branches distantes stale `origin/feature/agent-session-limits` (suppression distante = action sortante → validation explicite requise). - **Prochaine branche** : repartir **de `develop`** (`63eb49a`) avec un `feature/<sujet>` neuf pour le prochain chantier (probablement la **validation e2e AppImage 0.3.0**, qui est le vrai bloqueur courant). - **Push** : `develop` (+15) et `main` (+4 / release 0.3.0) attendent une validation explicite avant publication — je ne pousse rien sans ton accord. Dis-moi quel chantier on reprend : je crée la branche adéquate depuis `develop`.
@ -24,3 +22,5 @@ objective: Nouvelle feature cadrée par Architect, prête à démarrer le dével
- **Prompt:** Lot C `workstate conversation summaries` est validé QA vert sur `feature/workstate-conversation-summaries`. Merci de gérer les commits atomiques et la décision de merge local, sans push. Contexte QA final: - `cargo fmt --all -- --check` OK - `cargo test -p application --test workstate` OK, 21 passed, aucun warning Rust - `cargo test -p app-tauri --test dto_agents` OK, 21 passed - `cargo check -p app-tauri` OK (validé avant nettoyage warning; le nettoyage ne touche qu'un test) - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 2 files / 19 tests (warnings Vite non bloquants) - `cd frontend && npx tsc --noEmit` OK Fichiers attendus: - Backend/Tauri: `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/dto.rs`, `crates/app-tauri/src/state.rs`, `crates/application/tests/workstate.rs`, `crates/app-tauri/tests/dto_agents.rs`. - Frontend: `frontend/src/domain/index.ts`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`, `frontend/src/features/workstate/workstate.test.tsx`. - Dirty runtime `.ideai/*` possible; isole-le si présent, ne mélange pas avec feature code. Décide: 1. commits atomiques, 2. merge local éventuel vers `develop`, 3. état final. Ne push pas, ne supprime pas de branche. Retourne commits créés, merge ou non, branche finale, status final. - **Prompt:** Lot C `workstate conversation summaries` est validé QA vert sur `feature/workstate-conversation-summaries`. Merci de gérer les commits atomiques et la décision de merge local, sans push. Contexte QA final: - `cargo fmt --all -- --check` OK - `cargo test -p application --test workstate` OK, 21 passed, aucun warning Rust - `cargo test -p app-tauri --test dto_agents` OK, 21 passed - `cargo check -p app-tauri` OK (validé avant nettoyage warning; le nettoyage ne touche qu'un test) - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 2 files / 19 tests (warnings Vite non bloquants) - `cd frontend && npx tsc --noEmit` OK Fichiers attendus: - Backend/Tauri: `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/dto.rs`, `crates/app-tauri/src/state.rs`, `crates/application/tests/workstate.rs`, `crates/app-tauri/tests/dto_agents.rs`. - Frontend: `frontend/src/domain/index.ts`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`, `frontend/src/features/workstate/workstate.test.tsx`. - Dirty runtime `.ideai/*` possible; isole-le si présent, ne mélange pas avec feature code. Décide: 1. commits atomiques, 2. merge local éventuel vers `develop`, 3. état final. Ne push pas, ne supprime pas de branche. Retourne commits créés, merge ou non, branche finale, status final.
- **Response:** Lot C `workstate conversation summaries` intégré. QA re-vérifié vert de mon côté avant tout commit (fmt OK ; application workstate 21, app-tauri dto_agents 21, aucun warning Rust ; vitest 2 fichiers/19 ; tsc clean). **3 commits atomiques** sur `feature/workstate-conversation-summaries` (code feature / runtime séparés) : - `e9edadc` feat(workstate): résumés de conversation dans le read-model (Lot C backend) — assemblage des résumés dans application + DTO camelCase et exposition app-tauri (dto.rs, state.rs). - `c50622e` feat(workstate): UI des résumés de conversation (Lot C frontend) — domaine/mock alignés, `ProjectWorkStatePanel` enrichi. - `78500d8` chore(wip): état runtime .ideai (flux conversation live) — runtime isolé, jamais mêlé au code feature. **Merge local** : feature TERMINÉE et VERTE → `git merge --no-ff feature/workstate-conversation-summaries` dans **develop** → commit de merge `6e1ba7e`. `--no-ff` pour garder la trace d'intégration du lot, cohérent avec Lot A (`3bfb932`) et Lot B (`64c2c14`). **Pas de push, aucune branche supprimée.** `feature/workstate-conversation-summaries` conservée (sur `e9edadc→78500d8`). **État final** : - Branche courante : `develop` (HEAD = `6e1ba7e`). - Working tree : propre (`git status` vide). - `feature/workstate-conversation-summaries` préservée et entièrement contenue dans `develop`. - `develop` en avance sur origin (rien poussé). - Trilogie workstate Lot A→B→C désormais intégrée dans `develop` ; prêt pour une future release `develop → main` sur ta validation explicite. - **Response:** Lot C `workstate conversation summaries` intégré. QA re-vérifié vert de mon côté avant tout commit (fmt OK ; application workstate 21, app-tauri dto_agents 21, aucun warning Rust ; vitest 2 fichiers/19 ; tsc clean). **3 commits atomiques** sur `feature/workstate-conversation-summaries` (code feature / runtime séparés) : - `e9edadc` feat(workstate): résumés de conversation dans le read-model (Lot C backend) — assemblage des résumés dans application + DTO camelCase et exposition app-tauri (dto.rs, state.rs). - `c50622e` feat(workstate): UI des résumés de conversation (Lot C frontend) — domaine/mock alignés, `ProjectWorkStatePanel` enrichi. - `78500d8` chore(wip): état runtime .ideai (flux conversation live) — runtime isolé, jamais mêlé au code feature. **Merge local** : feature TERMINÉE et VERTE → `git merge --no-ff feature/workstate-conversation-summaries` dans **develop** → commit de merge `6e1ba7e`. `--no-ff` pour garder la trace d'intégration du lot, cohérent avec Lot A (`3bfb932`) et Lot B (`64c2c14`). **Pas de push, aucune branche supprimée.** `feature/workstate-conversation-summaries` conservée (sur `e9edadc→78500d8`). **État final** : - Branche courante : `develop` (HEAD = `6e1ba7e`). - Working tree : propre (`git status` vide). - `feature/workstate-conversation-summaries` préservée et entièrement contenue dans `develop`. - `develop` en avance sur origin (rien poussé). - Trilogie workstate Lot A→B→C désormais intégrée dans `develop` ; prêt pour une future release `develop → main` sur ta validation explicite.
- **Prompt:** Prépare le dépôt pour le Lot D `workstate controlled actions` après Lot C mergé dans `develop` @ `6e1ba7e`. État probable: dirty runtime/memory lié au checkpoint Lot C (`.ideai/*`, nouvelle note mémoire). Merci de gérer ce dirty sans perte et sans le mélanger au futur code applicatif, puis créer/basculer sur une branche feature propre depuis `develop`. Nom suggéré: `feature/workstate-controlled-actions`. Contraintes: pas de push, pas de suppression de branche. Retourne commits éventuels, branche courante, status final. - **Prompt:** Prépare le dépôt pour le Lot D `workstate controlled actions` après Lot C mergé dans `develop` @ `6e1ba7e`. État probable: dirty runtime/memory lié au checkpoint Lot C (`.ideai/*`, nouvelle note mémoire). Merci de gérer ce dirty sans perte et sans le mélanger au futur code applicatif, puis créer/basculer sur une branche feature propre depuis `develop`. Nom suggéré: `feature/workstate-controlled-actions`. Contraintes: pas de push, pas de suppression de branche. Retourne commits éventuels, branche courante, status final.
- **Response:** Dépôt prêt pour le Lot D `workstate controlled actions`. **Dirty traité** : tout le dirty était runtime/mémoire (aucun code applicatif), commité tel quel sur `develop` : - `7c71544` chore(wip): état runtime .ideai + mémoire (checkpoint Lot C résumés conversation) — conversations live, layouts, `MEMORY.md` et nouvelle note `checkpoint-workstate-conversation-summaries-lot-c.md` (auparavant non suivie, désormais versionnée). Cohérent avec l'historique runtime. **Branche feature** : créée et basculée depuis `develop` (@ `7c71544`) : - `feature/workstate-controlled-actions` **Pas de push, aucune branche supprimée.** **État final** : - Branche courante : `feature/workstate-controlled-actions` (HEAD = `7c71544`, partagé avec `develop`). - Working tree : propre (`git status` vide). - `develop` en avance sur origin (checkpoint local, non poussé). Le dev Lot D peut démarrer. Reviens vers moi pour committer/merger une fois QA vert.
- **Prompt:** Lot D `workstate controlled actions` est validé QA vert sur `feature/workstate-controlled-actions`. Merci de gérer les commits atomiques et la décision de merge local, sans push. QA vert: - `cargo fmt --all -- --check` OK - `cargo test -p application --test workstate_actions` OK, 7 passed - `cargo test -p application --test workstate` OK, 21 passed - `cargo test -p app-tauri --test dto_agents` OK, 25 passed - `cargo test -p app-tauri --test list_live_agents_r0b` OK, 5 passed - `cargo check -p app-tauri` OK - `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 25 tests - `cd frontend && npx vitest run src/adapters/agent.test.ts` OK, 8 tests - `cd frontend && npx vitest run src/features/layout/singletonAgent.test.tsx src/features/layout/agentAlreadyRunning.test.tsx` OK, 9 tests - `cd frontend && npx tsc --noEmit` OK Fichiers attendus: - Backend/Tauri: `crates/application/src/workstate/actions.rs`, `crates/application/tests/workstate_actions.rs`, `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/{dto.rs,commands.rs,state.rs,lib.rs}`, `crates/app-tauri/tests/dto_agents.rs`. - Frontend: `frontend/src/ports/index.ts`, `frontend/src/adapters/{agent.ts,agent.test.ts}`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/{ProjectWorkStatePanel.tsx,workstate.test.tsx}`, `frontend/src/features/layout/{singletonAgent.test.tsx,agentAlreadyRunning.test.tsx}`. - Dirty runtime `.ideai/*` possible; isole-le si présent. Décide commits atomiques, merge local éventuel vers `develop`, état final. Ne push pas, ne supprime pas de branche.

View File

@ -55,3 +55,5 @@
{"id":"4a9ff50a-6ad3-410c-89a8-36cfee9adc94","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976486735,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Lot C `workstate conversation summaries` est validé QA vert sur `feature/workstate-conversation-summaries`. Merci de gérer les commits atomiques et la décision de merge local, sans push.\n\nContexte QA final:\n- `cargo fmt --all -- --check` OK\n- `cargo test -p application --test workstate` OK, 21 passed, aucun warning Rust\n- `cargo test -p app-tauri --test dto_agents` OK, 21 passed\n- `cargo check -p app-tauri` OK (validé avant nettoyage warning; le nettoyage ne touche qu'un test)\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 2 files / 19 tests (warnings Vite non bloquants)\n- `cd frontend && npx tsc --noEmit` OK\n\nFichiers attendus:\n- Backend/Tauri: `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/dto.rs`, `crates/app-tauri/src/state.rs`, `crates/application/tests/workstate.rs`, `crates/app-tauri/tests/dto_agents.rs`.\n- Frontend: `frontend/src/domain/index.ts`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`, `frontend/src/features/workstate/workstate.test.tsx`.\n- Dirty runtime `.ideai/*` possible; isole-le si présent, ne mélange pas avec feature code.\n\nDécide:\n1. commits atomiques,\n2. merge local éventuel vers `develop`,\n3. état final.\n\nNe push pas, ne supprime pas de branche. Retourne commits créés, merge ou non, branche finale, status final."} {"id":"4a9ff50a-6ad3-410c-89a8-36cfee9adc94","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976486735,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Lot C `workstate conversation summaries` est validé QA vert sur `feature/workstate-conversation-summaries`. Merci de gérer les commits atomiques et la décision de merge local, sans push.\n\nContexte QA final:\n- `cargo fmt --all -- --check` OK\n- `cargo test -p application --test workstate` OK, 21 passed, aucun warning Rust\n- `cargo test -p app-tauri --test dto_agents` OK, 21 passed\n- `cargo check -p app-tauri` OK (validé avant nettoyage warning; le nettoyage ne touche qu'un test)\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 2 files / 19 tests (warnings Vite non bloquants)\n- `cd frontend && npx tsc --noEmit` OK\n\nFichiers attendus:\n- Backend/Tauri: `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/dto.rs`, `crates/app-tauri/src/state.rs`, `crates/application/tests/workstate.rs`, `crates/app-tauri/tests/dto_agents.rs`.\n- Frontend: `frontend/src/domain/index.ts`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/ProjectWorkStatePanel.tsx`, `frontend/src/features/workstate/workstate.test.tsx`.\n- Dirty runtime `.ideai/*` possible; isole-le si présent, ne mélange pas avec feature code.\n\nDécide:\n1. commits atomiques,\n2. merge local éventuel vers `develop`,\n3. état final.\n\nNe push pas, ne supprime pas de branche. Retourne commits créés, merge ou non, branche finale, status final."}
{"id":"923ce31a-d68c-43ca-9781-3d0f3d33f922","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976561209,"source":{"kind":"agent","agentId":"cd0b4cf1-1bef-4fae-ade5-f0a6b49bbaf5"},"role":"response","text":"Lot C `workstate conversation summaries` intégré. QA re-vérifié vert de mon côté avant tout commit (fmt OK ; application workstate 21, app-tauri dto_agents 21, aucun warning Rust ; vitest 2 fichiers/19 ; tsc clean).\n\n**3 commits atomiques** sur `feature/workstate-conversation-summaries` (code feature / runtime séparés) :\n- `e9edadc` feat(workstate): résumés de conversation dans le read-model (Lot C backend) — assemblage des résumés dans application + DTO camelCase et exposition app-tauri (dto.rs, state.rs).\n- `c50622e` feat(workstate): UI des résumés de conversation (Lot C frontend) — domaine/mock alignés, `ProjectWorkStatePanel` enrichi.\n- `78500d8` chore(wip): état runtime .ideai (flux conversation live) — runtime isolé, jamais mêlé au code feature.\n\n**Merge local** : feature TERMINÉE et VERTE → `git merge --no-ff feature/workstate-conversation-summaries` dans **develop** → commit de merge `6e1ba7e`. `--no-ff` pour garder la trace d'intégration du lot, cohérent avec Lot A (`3bfb932`) et Lot B (`64c2c14`).\n\n**Pas de push, aucune branche supprimée.** `feature/workstate-conversation-summaries` conservée (sur `e9edadc→78500d8`).\n\n**État final** :\n- Branche courante : `develop` (HEAD = `6e1ba7e`).\n- Working tree : propre (`git status` vide).\n- `feature/workstate-conversation-summaries` préservée et entièrement contenue dans `develop`.\n- `develop` en avance sur origin (rien poussé).\n- Trilogie workstate Lot A→B→C désormais intégrée dans `develop` ; prêt pour une future release `develop → main` sur ta validation explicite."} {"id":"923ce31a-d68c-43ca-9781-3d0f3d33f922","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976561209,"source":{"kind":"agent","agentId":"cd0b4cf1-1bef-4fae-ade5-f0a6b49bbaf5"},"role":"response","text":"Lot C `workstate conversation summaries` intégré. QA re-vérifié vert de mon côté avant tout commit (fmt OK ; application workstate 21, app-tauri dto_agents 21, aucun warning Rust ; vitest 2 fichiers/19 ; tsc clean).\n\n**3 commits atomiques** sur `feature/workstate-conversation-summaries` (code feature / runtime séparés) :\n- `e9edadc` feat(workstate): résumés de conversation dans le read-model (Lot C backend) — assemblage des résumés dans application + DTO camelCase et exposition app-tauri (dto.rs, state.rs).\n- `c50622e` feat(workstate): UI des résumés de conversation (Lot C frontend) — domaine/mock alignés, `ProjectWorkStatePanel` enrichi.\n- `78500d8` chore(wip): état runtime .ideai (flux conversation live) — runtime isolé, jamais mêlé au code feature.\n\n**Merge local** : feature TERMINÉE et VERTE → `git merge --no-ff feature/workstate-conversation-summaries` dans **develop** → commit de merge `6e1ba7e`. `--no-ff` pour garder la trace d'intégration du lot, cohérent avec Lot A (`3bfb932`) et Lot B (`64c2c14`).\n\n**Pas de push, aucune branche supprimée.** `feature/workstate-conversation-summaries` conservée (sur `e9edadc→78500d8`).\n\n**État final** :\n- Branche courante : `develop` (HEAD = `6e1ba7e`).\n- Working tree : propre (`git status` vide).\n- `feature/workstate-conversation-summaries` préservée et entièrement contenue dans `develop`.\n- `develop` en avance sur origin (rien poussé).\n- Trilogie workstate Lot A→B→C désormais intégrée dans `develop` ; prêt pour une future release `develop → main` sur ta validation explicite."}
{"id":"c10a7683-5468-472c-adbb-37fb6fe8c470","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976728705,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Prépare le dépôt pour le Lot D `workstate controlled actions` après Lot C mergé dans `develop` @ `6e1ba7e`.\n\nÉtat probable: dirty runtime/memory lié au checkpoint Lot C (`.ideai/*`, nouvelle note mémoire). Merci de gérer ce dirty sans perte et sans le mélanger au futur code applicatif, puis créer/basculer sur une branche feature propre depuis `develop`.\n\nNom suggéré: `feature/workstate-controlled-actions`.\n\nContraintes: pas de push, pas de suppression de branche. Retourne commits éventuels, branche courante, status final."} {"id":"c10a7683-5468-472c-adbb-37fb6fe8c470","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976728705,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Prépare le dépôt pour le Lot D `workstate controlled actions` après Lot C mergé dans `develop` @ `6e1ba7e`.\n\nÉtat probable: dirty runtime/memory lié au checkpoint Lot C (`.ideai/*`, nouvelle note mémoire). Merci de gérer ce dirty sans perte et sans le mélanger au futur code applicatif, puis créer/basculer sur une branche feature propre depuis `develop`.\n\nNom suggéré: `feature/workstate-controlled-actions`.\n\nContraintes: pas de push, pas de suppression de branche. Retourne commits éventuels, branche courante, status final."}
{"id":"c5df55db-1dc4-465e-bb3a-512806489e73","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781976745549,"source":{"kind":"agent","agentId":"cd0b4cf1-1bef-4fae-ade5-f0a6b49bbaf5"},"role":"response","text":"Dépôt prêt pour le Lot D `workstate controlled actions`.\n\n**Dirty traité** : tout le dirty était runtime/mémoire (aucun code applicatif), commité tel quel sur `develop` :\n- `7c71544` chore(wip): état runtime .ideai + mémoire (checkpoint Lot C résumés conversation) — conversations live, layouts, `MEMORY.md` et nouvelle note `checkpoint-workstate-conversation-summaries-lot-c.md` (auparavant non suivie, désormais versionnée). Cohérent avec l'historique runtime.\n\n**Branche feature** : créée et basculée depuis `develop` (@ `7c71544`) :\n- `feature/workstate-controlled-actions`\n\n**Pas de push, aucune branche supprimée.**\n\n**État final** :\n- Branche courante : `feature/workstate-controlled-actions` (HEAD = `7c71544`, partagé avec `develop`).\n- Working tree : propre (`git status` vide).\n- `develop` en avance sur origin (checkpoint local, non poussé).\n\nLe dev Lot D peut démarrer. Reviens vers moi pour committer/merger une fois QA vert."}
{"id":"e43c2b68-a855-4433-8067-64f6fc4fa59c","conversation":"6bc594e8-a37c-0dbd-1de6-6e3b73002cb4","atMs":1781977881625,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Lot D `workstate controlled actions` est validé QA vert sur `feature/workstate-controlled-actions`. Merci de gérer les commits atomiques et la décision de merge local, sans push.\n\nQA vert:\n- `cargo fmt --all -- --check` OK\n- `cargo test -p application --test workstate_actions` OK, 7 passed\n- `cargo test -p application --test workstate` OK, 21 passed\n- `cargo test -p app-tauri --test dto_agents` OK, 25 passed\n- `cargo test -p app-tauri --test list_live_agents_r0b` OK, 5 passed\n- `cargo check -p app-tauri` OK\n- `cd frontend && npx vitest run src/features/workstate/workstate.test.tsx src/features/projects/projects.test.tsx` OK, 25 tests\n- `cd frontend && npx vitest run src/adapters/agent.test.ts` OK, 8 tests\n- `cd frontend && npx vitest run src/features/layout/singletonAgent.test.tsx src/features/layout/agentAlreadyRunning.test.tsx` OK, 9 tests\n- `cd frontend && npx tsc --noEmit` OK\n\nFichiers attendus:\n- Backend/Tauri: `crates/application/src/workstate/actions.rs`, `crates/application/tests/workstate_actions.rs`, `crates/application/src/workstate/mod.rs`, `crates/application/src/lib.rs`, `crates/app-tauri/src/{dto.rs,commands.rs,state.rs,lib.rs}`, `crates/app-tauri/tests/dto_agents.rs`.\n- Frontend: `frontend/src/ports/index.ts`, `frontend/src/adapters/{agent.ts,agent.test.ts}`, `frontend/src/adapters/mock/index.ts`, `frontend/src/features/workstate/{ProjectWorkStatePanel.tsx,workstate.test.tsx}`, `frontend/src/features/layout/{singletonAgent.test.tsx,agentAlreadyRunning.test.tsx}`.\n- Dirty runtime `.ideai/*` possible; isole-le si présent.\n\nDécide commits atomiques, merge local éventuel vers `develop`, état final. Ne push pas, ne supprime pas de branche."}

View File

@ -1,11 +1,9 @@
--- ---
upTo: 8e30c171-2d32-48ab-9971-c6d23a010052 upTo: ec87367b-50e1-44fb-b4dd-88c284f02cae
objective: IMPLÉMENTATION (code de production uniquement — PAS les nouveaux tests, c'est QA qui les écrit ; mais ne casse aucun test existant). Cadrage validé par l'Architect. Objectif : permettre la délégation objective: IMPLÉMENTATION (code de production uniquement — PAS les nouveaux tests, c'est QA qui les écrit ; mais ne casse aucun test existant). Cadrage validé par l'Architect. Objectif : permettre la délégation
--- ---
**Objectif :** IMPLÉMENTATION (code de production uniquement — PAS les nouveaux tests, c'est QA qui les écrit ; mais ne casse aucun test existant). Cadrage validé par l'Architect. Objectif : permettre la délégation **Objectif :** IMPLÉMENTATION (code de production uniquement — PAS les nouveaux tests, c'est QA qui les écrit ; mais ne casse aucun test existant). Cadrage validé par l'Architect. Objectif : permettre la délégation
- **Response:** LS8-backend (filet humain niveau 3) implémenté tel que cadré — verdict B. Build OK, tous tests verts, NON commité. ## Signatures domaine constatées (crates/domain/src/session_limit.rs) — RIEN ajouté - `RateLimitSource::{Structured, Pattern, Human}` (enum Copy). - `SessionLimit::new(resets_at_ms: Option<i64>, detected_at_ms: i64, source: RateLimitSource) -> Self` (const, ordre des args = (Option heure, now, source)). - `plan_resume(now_ms: i64, limit: &SessionLimit, conversation_id: Option<String>) -> ResumePlan`. - `ResumePlan::Scheduled { fire_at_ms: i64, conversation_id: Option<String> }` | `ResumePlan::HumanFallback`. Le clamp anti-passé (`fire_at_ms = resets_at_ms.max(now_ms)`) est dans `plan_resume` ⇒ heure saisie déjà passée = reprise immédiate, gratis. ## Fichiers modifiés 1. **crates/application/src/agent/session_limit.rs** - Factorisé la branche `ResumePlan::Scheduled` de `on_rate_limited` en privée `fn arm_scheduled(&self, agent_id, fire_at_ms, node_id, conversation_id, resets_at_ms: Option<i64>)`. `on_rate_limited` l'appelle pour son cas Scheduled → comportement identique (les 9 tests `session_limit_service` existants passent inchangés). - ⚠️ **Écart assumé vs signature suggérée** : j'ai ajouté un 5e param `resets_at_ms: Option<i64>` à `arm_scheduled`. Raison : l'événement `AgentRateLimited` d'origine publie l'**heure de reset brute** (l'Option d'entrée), PAS `fire_at_ms` (qui est clampé). Les deux diffèrent si le reset est passé. Pour garantir le « zéro régression » exigé, j'ai propagé l'heure de reset brute au lieu de republier `Some(fire_at_ms)`. Les deux appelants passent `Some(...)`. - Ajouté la publique `pub fn confirm_human_resume(&self, agent_id: AgentId, node_id: NodeId, conversation_id: Option<String>, resets_at_ms: i64)` : `SessionLimit::new(Some(resets_at_ms), now, RateLimitSource::Human)``plan_resume` → sur `Scheduled` appelle `arm_scheduled(..., Some(resets_at_ms))`. Cas `HumanFallback` traité en no-op défensif (inatteignable car `resets_at_ms` toujours `Some`). `execute_resume` et `cancel_resume` INCHANGÉS. 2. **crates/app-tauri/src/commands.rs** — ajout `#[tauri::command] pub async fn set_resume_at(agent_id: String, resets_at_ms: i64, state) -> Result<(), ErrorDto>`, miroir de `cancel_resume`. 3. **crates/app-tauri/src/lib.rs**`commands::set_resume_at` enregistrée juste après `commands::cancel_resume` dans le `generate_handler!`. ## Lookup agent→node utilisé (existant, rien ajouté) La registry des sessions vivantes expose déjà `node_for_agent`. `set_resume_at` résout : - `node_id = state.structured_sessions.node_for_agent(&id).or_else(|| state.terminal_sessions.node_for_agent(&id))` (structuré d'abord car il porte aussi la conv ; repli terminal/PTY). Aucune cellule vivante ⇒ `ErrorDto::from(AppError::NotFound(...))`. - `conversation_id` best-effort = `state.structured_sessions.session_for_agent(&id).and_then(|s| s.conversation_id())` (via `AgentSession::conversation_id() -> Option<String>`, ports.rs:549). `None` toléré. Méthodes constatées dans crates/application/src/terminal/registry.rs : `TerminalSessions::node_for_agent` (l.175), `StructuredSessions::node_for_agent` (l.375), `session_for_agent`, `meta_for_session`. ## Événements : AUCUN créé. `confirm_human_resume``arm_scheduled` réémet la paire existante `AgentRateLimited{Some(t)}` + `AgentResumeScheduled{fire_at_ms}`. Annulation/reprise par les voies inchangées (`AgentResumeCancelled`/`AgentResumed`). ## Compilation / tests - `cargo build -p application -p app-tauri` : Finished, 0 erreur/0 warning. - `cargo test -p domain -p application` : tout vert (domain 39, session_limit_service 9, session_limit_t4 7, + le reste). - `cargo test -p app-tauri` : tout vert (dont wiring 43). ## Pour QA (testabilité) - `confirm_human_resume` testable 100 % sans I/O via les fakes existants (Clock/Scheduler/EventBus) déjà utilisés dans `tests/session_limit_service.rs`. Cas à couvrir : (a) heure future ⇒ `AgentRateLimited{Some}` puis `AgentResumeScheduled{fire_at_ms=resets_at_ms}` + ScheduleId mémorisé ; (b) heure passée ⇒ `fire_at_ms == now` (reprise immédiate) ; (c) dédoublonnage : un `confirm_human_resume` après un armement existant annule le précédent (1 seule entrée armée) ; (d) annulabilité : `cancel_resume` après `confirm_human_resume` publie `AgentResumeCancelled` ; (e) parité auto/humain : même séquence d'événements que `on_rate_limited` cas Scheduled. - `set_resume_at` : `node_for_agent` None ⇒ NOT_FOUND.
- **Prompt:** Feature « Agent orchestrateur du projet », branche active `feature/orchestrator-designation`. Implémente le **ticket T1 — Fondation domaine** (pur, aucune I/O). Cadrage Architect ci-dessous, à respecter strictement. ## Modèle On ne persiste que la DÉVIATION au défaut : un champ projet `orchestrator: Option<AgentId>`. `None` = défaut « plus ancien agent » (= `entries.first()`). `Some(id)` = désignation explicite (radio). Ça rend l'état illégal « 2 orchestrateurs » non représentable et donne la rétro-compat gratuitement. ## À implémenter (domaine pur uniquement, T1) 1. **VO `OrchestratorDesignation`** (dans `crates/domain/src/fileguard.rs` ou un petit module dédié, à toi de voir le plus cohérent) : - `none() -> Self` (aucun agent désigné, humain seul) - `of(agent: AgentId) -> Self` - `designated(&self) -> Option<AgentId>` 2. **Politique `fileguard.rs`** — élargis les signatures : - `is_orchestrator(who: ConversationParty, d: &OrchestratorDesignation) -> bool` : `User => true` (humain permanent), `Agent{id} => d.designated() == Some(id)`. (Perd le `const`, OK.) - `may_write_directly(who, res, d: &OrchestratorDesignation) -> bool` : si `res.is_project_context()``is_orchestrator(who, d)`, sinon `true`. - **Préserve le test single-writer existant** en lui passant `&OrchestratorDesignation::none()` : l'agent reste refusé, l'humain reste autorisé. 3. **`AgentManifest` (`crates/domain/src/agent.rs`)** : - Champ `orchestrator: Option<AgentId>` avec `#[serde(default, skip_serializing_if = "Option::is_none")]`. - `effective_orchestrator(&self) -> Option<AgentId>` = `self.orchestrator.or_else(|| self.entries.first().map(|e| e.agent_id))` (adapte au vrai nom du champ id de l'entrée). - `orchestrator_designation(&self) -> OrchestratorDesignation` (fold de l'effectif vers le VO). - `designate(&mut self, id) -> Result<(), DomainError>` : sémantique radio (écrase), valide que `id` appartient à `entries`. - `on_agent_deleted(&mut self, removed: AgentId)` : si `orchestrator == Some(removed)``None`. - Validation dans le constructeur (`AgentManifest::new` ou équivalent) : `orchestrator == Some(id)``id` doit être présent dans `entries` ; `None` toujours valide. - **Invariant à documenter** : les entrées du manifeste sont en ordre de création (`entries.first()` = plus ancien). Pas de timestamp à ajouter. 4. **`events.rs`** : nouveau `DomainEvent::OrchestratorChanged { project_id, orchestrator: Option<AgentId> }` (adapte aux champs/conventions des variants existants). ## Tests unitaires (dans les modules, T1) - single-writer préservé avec `none()` (agent refusé / humain autorisé) ; - agent désigné autorisé à écrire le contexte projet ; - défaut « plus ancien » quand `orchestrator == None` ; - succession lazy : `on_agent_deleted` du désigné → retombe sur plus ancien ; - `designate` écrase (radio) + rejette un agent absent ; - validation référentielle du constructeur. Respecte l'archi hexagonale (domaine sans I/O), SOLID, le style existant. Compile + teste le crate domaine (`cargo test -p domain` ou le vrai nom du package). Quand c'est vert, réponds via `idea_reply` avec : fichiers touchés, signatures finales exactes (pour que les tickets aval s'y accrochent), et la sortie réelle des tests. Si rouge, donne la sortie d'erreur réelle.
- **Response:** ## T1 — Fondation domaine : VERT ✅ `cargo test -p domain` passe intégralement : **lib 175 passed; 0 failed** (dont 11 nouveaux tests), + toutes les suites d'intégration du crate (entities, serde_roundtrip, etc.) restent vertes. Aucune I/O introduite, domaine pur. ### Fichiers touchés (domaine pur uniquement) - `crates/domain/src/fileguard.rs` — VO `OrchestratorDesignation` + élargissement des signatures de politique + tests. - `crates/domain/src/agent.rs` — champ `orchestrator` sur `AgentManifest` + méthodes + tests (module `orchestrator_tests`). - `crates/domain/src/events.rs` — variant `DomainEvent::OrchestratorChanged` + test. - `crates/domain/src/lib.rs` — réexport de `OrchestratorDesignation`. ### Signatures finales exactes (points d'accroche pour les tickets aval) **`fileguard.rs`** (réexportées depuis `domain::`) : ```rust pub struct OrchestratorDesignation(/* private Option<AgentId> */); impl OrchestratorDesignation { pub const fn none() -> Self; pub const fn of(agent: AgentId) -> Self; pub const fn designated(&self) -> Option<AgentId>; } // dérive Debug, Clone, Copy, PartialEq, Eq pub fn is_orchestrator(who: ConversationParty, d: &OrchestratorDesignation) -> bool; pub fn may_write_directly( who: ConversationParty, res: &GuardedResource, d: &OrchestratorDesignation, ) -> bool; ``` Sémantique : `User => true` (humain permanent), `Agent{id} => d.designated() == Some(id)`. `may_write_directly` ⇒ `is_orchestrator` si `res.is_project_context()`, sinon `true`. Les deux perdent `const` (le `match` sur `who` n'est pas const-compatible ici). **`agent.rs` — `AgentManifest`** (nouveau champ `pub orchestrator: Option<AgentId>` avec `#[serde(default, skip_serializing_if = "Option::is_none")]`) : ```rust // constructeur historique inchangé (orchestrator = None, toujours valide) pub fn new(version: u32, entries: Vec<ManifestEntry>) -> Result<Self, DomainError>; // constructeur validant la désignation explicite (intégrité référentielle) pub fn with_orchestrator( version: u32, entries: Vec<ManifestEntry>, orchestrator: Option<AgentId>, ) -> Result<Self, DomainError>; pub fn effective_orchestrator(&self) -> Option<AgentId>; // designation || entries.first() pub fn orchestrator_designation(&self) -> OrchestratorDesignation; // fold de l'effectif vers le VO pub fn designate(&mut self, id: AgentId) -> Result<(), DomainError>; // radio, écrase, valide l'appartenance pub fn on_agent_deleted(&mut self, removed: AgentId); // Some(removed) -> None (succession lazy) ``` Choix d'implémentation à noter : `AgentManifest::new` garde **sa signature** (orchestrator = None) ; la validation référentielle du constructeur demandée est portée par `with_orchestrator` (`new` y délègue avec `None`). Ça évite de casser tous les appelants `AgentManifest::new(version, entries)` existants. La validation : `orchestrator == Some(id)` ⇒ `id ∈ entries`, sinon `DomainError::InconsistentManifest`. Invariant d'ordre documenté sur le doccomment du struct : `entries` en ordre de création, `entries.first()` = plus ancien, pas de timestamp. **`events.rs`** : ```rust DomainEvent::OrchestratorChanged { project_id: ProjectId, orchestrator: Option<AgentId>, } ``` ### Tests couverts (tous verts) - single-writer préservé avec `none()` (agent refusé / humain autorisé) ; - agent désigné autorisé à écrire le contexte projet (+ autre agent refusé, humain toujours OK) — testé côté `fileguard` ET via `AgentManifest::orchestrator_designation()` ; - défaut « plus ancien » quand `orchestrator == None` (+ manifeste vide ⇒ `None`) ; - succession lazy : `on_agent_deleted` du désigné → `None` → retombe sur plus ancien ; no-op si l'agent supprimé n'était pas le désigné ; - `designate` écrase (radio) + rejette un agent absent (et préserve la désignation valide précédente) ; - validation référentielle du constructeur (`with_orchestrator`) ; - `OrchestratorChanged` construit/compare. ### ⚠️ Impact aval à prévoir (hors scope T1, à câbler par les tickets suivants) La couche **infrastructure ne compile plus tel quel** — c'est attendu, le câblage est aval : 1. `crates/infrastructure/src/fileguard/mod.rs:93` appelle encore `may_write_directly(who, &res)` (2 args). L'adaptateur `RwFileGuard` doit recevoir/threader une `OrchestratorDesignation` (probablement injectée depuis le manifeste courant) et passer 3 args. 2. Le nouveau champ `orchestrator` casse les **littéraux de struct exhaustifs** `AgentManifest { version, entries }` (≈ infra `store/context.rs`, application `context_guard.rs`/tests, `app-tauri/state.rs`, plusieurs tests). Fix mécanique : ajouter `orchestrator: None` ou `..Default::default()`. `Default` est dérivé donc `..Default::default()` marche. `cargo test -p domain` étant le périmètre demandé, le crate domaine est vert et autonome ; ces deux points sont la surface de câblage des tickets T2+. - **Response:** ## T1 — Fondation domaine : VERT ✅ `cargo test -p domain` passe intégralement : **lib 175 passed; 0 failed** (dont 11 nouveaux tests), + toutes les suites d'intégration du crate (entities, serde_roundtrip, etc.) restent vertes. Aucune I/O introduite, domaine pur. ### Fichiers touchés (domaine pur uniquement) - `crates/domain/src/fileguard.rs` — VO `OrchestratorDesignation` + élargissement des signatures de politique + tests. - `crates/domain/src/agent.rs` — champ `orchestrator` sur `AgentManifest` + méthodes + tests (module `orchestrator_tests`). - `crates/domain/src/events.rs` — variant `DomainEvent::OrchestratorChanged` + test. - `crates/domain/src/lib.rs` — réexport de `OrchestratorDesignation`. ### Signatures finales exactes (points d'accroche pour les tickets aval) **`fileguard.rs`** (réexportées depuis `domain::`) : ```rust pub struct OrchestratorDesignation(/* private Option<AgentId> */); impl OrchestratorDesignation { pub const fn none() -> Self; pub const fn of(agent: AgentId) -> Self; pub const fn designated(&self) -> Option<AgentId>; } // dérive Debug, Clone, Copy, PartialEq, Eq pub fn is_orchestrator(who: ConversationParty, d: &OrchestratorDesignation) -> bool; pub fn may_write_directly( who: ConversationParty, res: &GuardedResource, d: &OrchestratorDesignation, ) -> bool; ``` Sémantique : `User => true` (humain permanent), `Agent{id} => d.designated() == Some(id)`. `may_write_directly` ⇒ `is_orchestrator` si `res.is_project_context()`, sinon `true`. Les deux perdent `const` (le `match` sur `who` n'est pas const-compatible ici). **`agent.rs` — `AgentManifest`** (nouveau champ `pub orchestrator: Option<AgentId>` avec `#[serde(default, skip_serializing_if = "Option::is_none")]`) : ```rust // constructeur historique inchangé (orchestrator = None, toujours valide) pub fn new(version: u32, entries: Vec<ManifestEntry>) -> Result<Self, DomainError>; // constructeur validant la désignation explicite (intégrité référentielle) pub fn with_orchestrator( version: u32, entries: Vec<ManifestEntry>, orchestrator: Option<AgentId>, ) -> Result<Self, DomainError>; pub fn effective_orchestrator(&self) -> Option<AgentId>; // designation || entries.first() pub fn orchestrator_designation(&self) -> OrchestratorDesignation; // fold de l'effectif vers le VO pub fn designate(&mut self, id: AgentId) -> Result<(), DomainError>; // radio, écrase, valide l'appartenance pub fn on_agent_deleted(&mut self, removed: AgentId); // Some(removed) -> None (succession lazy) ``` Choix d'implémentation à noter : `AgentManifest::new` garde **sa signature** (orchestrator = None) ; la validation référentielle du constructeur demandée est portée par `with_orchestrator` (`new` y délègue avec `None`). Ça évite de casser tous les appelants `AgentManifest::new(version, entries)` existants. La validation : `orchestrator == Some(id)` ⇒ `id ∈ entries`, sinon `DomainError::InconsistentManifest`. Invariant d'ordre documenté sur le doccomment du struct : `entries` en ordre de création, `entries.first()` = plus ancien, pas de timestamp. **`events.rs`** : ```rust DomainEvent::OrchestratorChanged { project_id: ProjectId, orchestrator: Option<AgentId>, } ``` ### Tests couverts (tous verts) - single-writer préservé avec `none()` (agent refusé / humain autorisé) ; - agent désigné autorisé à écrire le contexte projet (+ autre agent refusé, humain toujours OK) — testé côté `fileguard` ET via `AgentManifest::orchestrator_designation()` ; - défaut « plus ancien » quand `orchestrator == None` (+ manifeste vide ⇒ `None`) ; - succession lazy : `on_agent_deleted` du désigné → `None` → retombe sur plus ancien ; no-op si l'agent supprimé n'était pas le désigné ; - `designate` écrase (radio) + rejette un agent absent (et préserve la désignation valide précédente) ; - validation référentielle du constructeur (`with_orchestrator`) ; - `OrchestratorChanged` construit/compare. ### ⚠️ Impact aval à prévoir (hors scope T1, à câbler par les tickets suivants) La couche **infrastructure ne compile plus tel quel** — c'est attendu, le câblage est aval : 1. `crates/infrastructure/src/fileguard/mod.rs:93` appelle encore `may_write_directly(who, &res)` (2 args). L'adaptateur `RwFileGuard` doit recevoir/threader une `OrchestratorDesignation` (probablement injectée depuis le manifeste courant) et passer 3 args. 2. Le nouveau champ `orchestrator` casse les **littéraux de struct exhaustifs** `AgentManifest { version, entries }` (≈ infra `store/context.rs`, application `context_guard.rs`/tests, `app-tauri/state.rs`, plusieurs tests). Fix mécanique : ajouter `orchestrator: None` ou `..Default::default()`. `Default` est dérivé donc `..Default::default()` marche. `cargo test -p domain` étant le périmètre demandé, le crate domaine est vert et autonome ; ces deux points sont la surface de câblage des tickets T2+.
- **Prompt:** Suite de la feature orchestrateur, branche `feature/orchestrator-designation`. T1 (domaine) est vert. Implémente maintenant **T2 → T5** (infra + application backend) pour rétablir un workspace qui compile et tester. Suis le cadrage Architect, notamment l'**Alternative A** retenue. ### T2 — Infra : guard = verrou pur + serde rétro-compatible (dépend T1) - **Alternative A (RETENUE)** : `RwFileGuard::acquire_write` (`crates/infrastructure/src/fileguard/mod.rs`) NE fait plus le check d'identité orchestrateur. Il redevient un **verrou pur** (sérialise les writers, comme un rwlock). Donc retire l'appel `may_write_directly` côté guard (la ligne ~93). L'autorisation single-writer remonte dans `ProposeContext` (T3). `GuardError::Forbidden` n'est plus émis par le guard — vérifie ce que ça implique pour le port/les tests du guard (déplace/retire le test « Forbidden » qui n'a plus lieu d'être à ce niveau, documente que le guard est désormais un lock pur). Si la signature du port `FileGuard::acquire_write` portait un paramètre lié à l'identité, garde-la cohérente. - **Serde** : corrige tous les littéraux exhaustifs `AgentManifest { version, entries }` cassés par le nouveau champ (ajoute `orchestrator: None` ou `..Default::default()`). Test round-trip : un `agents.json` legacy SANS le champ `orchestrator` se désérialise → `None``effective_orchestrator()` = plus ancien. ### T3 — Application : autorisation propose (cœur MCP) (dépend T1, T2) Dans `ProposeContext` (`crates/application/.../context_guard.rs`), branche globale (target = None) : ``` let manifest = contexts.load_manifest(project).await?; let d = manifest.orchestrator_designation(); if may_write_directly(requester, &GuardedResource::ProjectContext, &d) { let _lease = guard.acquire_write(requester, ProjectContext).await?; // sérialise fs.write(project_context_file, content) -> Written } else { file_proposal(...) -> Proposed { path } // inchangé } ``` Conséquence : quand l'appelant `idea_context_propose` (sans target) EST l'orchestrateur désigné, l'écriture devient DIRECTE ; sinon proposition ; l'humain écrit toujours direct. Tests : agent désigné → write direct ; agent non-désigné → proposition ; humain → direct. ### T4 — Application : défaut + succession (dépend T1) - `DeleteAgent::execute` (`lifecycle.rs`) : après filtrage des entrées, appelle `manifest.on_agent_deleted(removed)` avant `save_manifest` ; émets `DomainEvent::OrchestratorChanged` si `effective_orchestrator()` a changé. - Défaut (Create scratch + template) : pas de logique à ajouter (modèle paresseux), mais ajoute les tests qui figent « 1er agent créé = orchestrateur effectif » et l'émission de `OrchestratorChanged` si l'effectif passe de None→1er. - Tests succession : désigné explicite supprimé → retombe sur plus ancien ; non-désigné supprimé → repointage paresseux. ### T5 — Application : `SetOrchestrator` + ListAgents output (dépend T1) - Nouveau use case `SetOrchestrator { project, agent_id }` : `load_manifest` → `manifest.designate(agent_id)` (radio, écrase) → `save_manifest` → publie `OrchestratorChanged`. `NotFound`/erreur domaine si l'agent n'existe pas. - Étends `ListAgentsOutput` avec `orchestrator: Option<AgentId>` (= `effective_orchestrator()`). - Tests (store mock) : écrasement radio, agent inconnu → erreur, output porte l'effectif. Respecte l'archi hexagonale, SOLID, le style existant, aucun nouveau port (compose FileGuard / AgentContextStore / EventBus existants). Compile et teste les crates infra + application (`cargo test -p infrastructure -p application` ou vrais noms). Quand vert, réponds via `idea_reply` : fichiers touchés, signatures publiques finales de `SetOrchestrator` et du champ ajouté à `ListAgentsOutput` (accroche pour T6), et la sortie réelle des tests. Si rouge, donne l'erreur réelle. - **Prompt:** Suite de la feature orchestrateur, branche `feature/orchestrator-designation`. T1 (domaine) est vert. Implémente maintenant **T2 → T5** (infra + application backend) pour rétablir un workspace qui compile et tester. Suis le cadrage Architect, notamment l'**Alternative A** retenue. ### T2 — Infra : guard = verrou pur + serde rétro-compatible (dépend T1) - **Alternative A (RETENUE)** : `RwFileGuard::acquire_write` (`crates/infrastructure/src/fileguard/mod.rs`) NE fait plus le check d'identité orchestrateur. Il redevient un **verrou pur** (sérialise les writers, comme un rwlock). Donc retire l'appel `may_write_directly` côté guard (la ligne ~93). L'autorisation single-writer remonte dans `ProposeContext` (T3). `GuardError::Forbidden` n'est plus émis par le guard — vérifie ce que ça implique pour le port/les tests du guard (déplace/retire le test « Forbidden » qui n'a plus lieu d'être à ce niveau, documente que le guard est désormais un lock pur). Si la signature du port `FileGuard::acquire_write` portait un paramètre lié à l'identité, garde-la cohérente. - **Serde** : corrige tous les littéraux exhaustifs `AgentManifest { version, entries }` cassés par le nouveau champ (ajoute `orchestrator: None` ou `..Default::default()`). Test round-trip : un `agents.json` legacy SANS le champ `orchestrator` se désérialise → `None``effective_orchestrator()` = plus ancien. ### T3 — Application : autorisation propose (cœur MCP) (dépend T1, T2) Dans `ProposeContext` (`crates/application/.../context_guard.rs`), branche globale (target = None) : ``` let manifest = contexts.load_manifest(project).await?; let d = manifest.orchestrator_designation(); if may_write_directly(requester, &GuardedResource::ProjectContext, &d) { let _lease = guard.acquire_write(requester, ProjectContext).await?; // sérialise fs.write(project_context_file, content) -> Written } else { file_proposal(...) -> Proposed { path } // inchangé } ``` Conséquence : quand l'appelant `idea_context_propose` (sans target) EST l'orchestrateur désigné, l'écriture devient DIRECTE ; sinon proposition ; l'humain écrit toujours direct. Tests : agent désigné → write direct ; agent non-désigné → proposition ; humain → direct. ### T4 — Application : défaut + succession (dépend T1) - `DeleteAgent::execute` (`lifecycle.rs`) : après filtrage des entrées, appelle `manifest.on_agent_deleted(removed)` avant `save_manifest` ; émets `DomainEvent::OrchestratorChanged` si `effective_orchestrator()` a changé. - Défaut (Create scratch + template) : pas de logique à ajouter (modèle paresseux), mais ajoute les tests qui figent « 1er agent créé = orchestrateur effectif » et l'émission de `OrchestratorChanged` si l'effectif passe de None→1er. - Tests succession : désigné explicite supprimé → retombe sur plus ancien ; non-désigné supprimé → repointage paresseux. ### T5 — Application : `SetOrchestrator` + ListAgents output (dépend T1) - Nouveau use case `SetOrchestrator { project, agent_id }` : `load_manifest` → `manifest.designate(agent_id)` (radio, écrase) → `save_manifest` → publie `OrchestratorChanged`. `NotFound`/erreur domaine si l'agent n'existe pas. - Étends `ListAgentsOutput` avec `orchestrator: Option<AgentId>` (= `effective_orchestrator()`). - Tests (store mock) : écrasement radio, agent inconnu → erreur, output porte l'effectif. Respecte l'archi hexagonale, SOLID, le style existant, aucun nouveau port (compose FileGuard / AgentContextStore / EventBus existants). Compile et teste les crates infra + application (`cargo test -p infrastructure -p application` ou vrais noms). Quand vert, réponds via `idea_reply` : fichiers touchés, signatures publiques finales de `SetOrchestrator` et du champ ajouté à `ListAgentsOutput` (accroche pour T6), et la sortie réelle des tests. Si rouge, donne l'erreur réelle.
- **Prompt:** Tâche ciblée sur la branche courante `feature/orchestrator-designation`. Contexte: - Git a décidé de finir le chantier courant `orchestrator-designation` sur cette branche, sans switch/stash. - Main ne code pas; tu es chargé de la correction backend Rust. - Tests ciblés verts: - `cargo test -p infrastructure input --lib`: 35 passed. - `cargo test -p application --test orchestrator_service`: 45 passed. - Frontend vert: - `cd frontend && npx vitest run`: 41 files, 384 tests passed. - `cd frontend && npx tsc --noEmit`: OK. Problème à corriger: `cargo test --workspace` échoue à la compilation sur `crates/application/src/orchestrator/context_guard.rs`. Sortie réelle: ```text error[E0061]: this function takes 3 arguments but 2 arguments were supplied --> crates/application/src/orchestrator/context_guard.rs:449:17 | 449 | if !may_write_directly(who, &res) { | ^^^^^^^^^^^^^^^^^^----------- argument #3 of type `&OrchestratorDesignation` is missing error[E0560]: struct `ManifestEntry` has no field named `orchestrator` --> crates/application/src/orchestrator/context_guard.rs:616:21 | 616 | orchestrator: None, | ^^^^^^^^^^^^ `ManifestEntry` does not have this field error[E0063]: missing field `orchestrator` in initializer of `AgentManifest` --> crates/application/src/orchestrator/context_guard.rs:613:23 | 613 | manifest: AgentManifest { | ^^^^^^^^^^^^^ missing `orchestrator` ``` Attendu: - Adapter `context_guard.rs` au nouveau modèle `AgentManifest { version, entries, orchestrator }` et à `may_write_directly(resource, designation)` sans contourner l'architecture. - Supprimer l'import inutilisé si nécessaire. - Garder le domaine propriétaire des règles de désignation orchestrateur. - Ne touche pas aux fichiers `.ideai/*` runtime. Validation minimale à exécuter après correction: 1. `cargo test -p application --test orchestrator_service` 2. `cargo test --workspace` si raisonnable. Réponds avec les fichiers modifiés et les commandes/test outputs réels. Si cette tâche arrive via IdeA, utilise impérativement `idea_reply`. - **Prompt:** Tâche ciblée sur la branche courante `feature/orchestrator-designation`. Contexte: - Git a décidé de finir le chantier courant `orchestrator-designation` sur cette branche, sans switch/stash. - Main ne code pas; tu es chargé de la correction backend Rust. - Tests ciblés verts: - `cargo test -p infrastructure input --lib`: 35 passed. - `cargo test -p application --test orchestrator_service`: 45 passed. - Frontend vert: - `cd frontend && npx vitest run`: 41 files, 384 tests passed. - `cd frontend && npx tsc --noEmit`: OK. Problème à corriger: `cargo test --workspace` échoue à la compilation sur `crates/application/src/orchestrator/context_guard.rs`. Sortie réelle: ```text error[E0061]: this function takes 3 arguments but 2 arguments were supplied --> crates/application/src/orchestrator/context_guard.rs:449:17 | 449 | if !may_write_directly(who, &res) { | ^^^^^^^^^^^^^^^^^^----------- argument #3 of type `&OrchestratorDesignation` is missing error[E0560]: struct `ManifestEntry` has no field named `orchestrator` --> crates/application/src/orchestrator/context_guard.rs:616:21 | 616 | orchestrator: None, | ^^^^^^^^^^^^ `ManifestEntry` does not have this field error[E0063]: missing field `orchestrator` in initializer of `AgentManifest` --> crates/application/src/orchestrator/context_guard.rs:613:23 | 613 | manifest: AgentManifest { | ^^^^^^^^^^^^^ missing `orchestrator` ``` Attendu: - Adapter `context_guard.rs` au nouveau modèle `AgentManifest { version, entries, orchestrator }` et à `may_write_directly(resource, designation)` sans contourner l'architecture. - Supprimer l'import inutilisé si nécessaire. - Garder le domaine propriétaire des règles de désignation orchestrateur. - Ne touche pas aux fichiers `.ideai/*` runtime. Validation minimale à exécuter après correction: 1. `cargo test -p application --test orchestrator_service` 2. `cargo test --workspace` si raisonnable. Réponds avec les fichiers modifiés et les commandes/test outputs réels. Si cette tâche arrive via IdeA, utilise impérativement `idea_reply`.
@ -24,3 +22,5 @@ objective: IMPLÉMENTATION (code de production uniquement — PAS les nouveaux t
- **Response:** Lot C backend/Tauri `workstate conversation summaries` **implémenté et vert** sur `feature/workstate-conversation-summaries`. **Rien commité.** ## Fichiers modifiés (6 ; aucun infra/domain — ports HandoffStore/ConversationLog réutilisés) - `crates/application/src/workstate/mod.rs` — modèle + algo best-effort - `crates/application/src/lib.rs` — re-exports - `crates/app-tauri/src/dto.rs` — DTO camelCase - `crates/app-tauri/src/state.rs` — wiring composition root - `crates/application/tests/workstate.rs` — fakes + 9 tests - `crates/app-tauri/tests/dto_agents.rs` — +1 test + 2 littéraux existants mis à jour ## Signatures/types ajoutés **Application :** - `ProjectWorkState.conversations: Vec<ConversationWorkSummary>` (top-level) - `ConversationWorkSummary { conversation_id, status, objective_preview: Option<String>, summary_preview: Option<String>, summary_len: usize, up_to: Option<TurnId>, recent_turns: Vec<ConversationTurnWorkPreview> }` - `enum ConversationPreviewStatus { Ready, Missing, Partial, Unavailable }` - `ConversationTurnWorkPreview { role: TurnRole, source: TicketWorkSource, at_ms: u64, text_preview: String, text_len: usize }` - `trait ConversationLogProvider { fn conversation_log_for(&self, root: &ProjectPath) -> Option<Arc<dyn ConversationLog>> }` (nouveau, jumeau de `HandoffProvider`) - `GetProjectWorkState::with_conversation_sources(handoffs: Arc<dyn HandoffProvider>, logs: Arc<dyn ConversationLogProvider>)` (builder) - Constantes : `HANDOFF_PREVIEW_MAX_CHARS=480`, `OBJECTIVE_PREVIEW_MAX_CHARS=160`, `RECENT_TURNS_MAX=3`, `TURN_PREVIEW_MAX_CHARS=220` **DTO Tauri :** `ProjectWorkStateDto.conversations`, `ConversationWorkSummaryDto`, `ConversationPreviewStatusDto` (`ready/missing/partial/unavailable`), `ConversationTurnWorkPreviewDto`. **state.rs :** `AppConversationLogProvider` (matérialise `FsConversationLog::new(root)`), câblé via `.with_conversation_sources(AppHandoffProvider, AppConversationLogProvider)`. ## Choix exacts / divergences 1. **Réutilisé `HandoffProvider` existant (P7)** comme source primaire + ajouté le jumeau `ConversationLogProvider` pour le repli. Résolus **par project root** (`input.project.root`) car `GetProjectWorkState` est singleton AppState alors que les `Fs*` figent leur racine à la construction — strictement parallèle au pattern P7/P8b. 2. **Builder `with_conversation_sources`** plutôt que d'étendre `new(...)` : sources OFF par défaut, zéro régression sur call sites/tests existants (best-effort absent = aucune summary). 3. **« provider non câblé » = handoff Absent (chemin Missing), jamais une erreur.** `Unavailable` strictement = handoff **erreur** ET log erreur/absent. `Missing` reste Missing même si le log échoue (alors recentTurns vide). Conforme aux étapes 4/5/6 du cadrage. 4. **Ready** ne remplit pas `recent_turns` (le handoff EST le résumé) ; recentTurns peuplé seulement en Missing/Partial. Re-cap défensif à `RECENT_TURNS_MAX` en plus de `log.last(_, 3)`. 5. **Dédup** des `conversation_id` sur tous les tickets projetés (humains inclus), **ordre first-seen** pour refléter l'ordre du panneau. 6. **`TurnRole` domaine réutilisé tel quel dans le DTO** (sérialise déjà camelCase `prompt/response/toolActivity`), cohérent avec le réemploi de `AgentBusyState` ; `source` du tour réutilise `TicketWorkSourceDto` (`kind: human/agent`). 7. **Champs preview optionnels sérialisés en `null`** quand absents (pas omis) — prévisible pour le front, aligné sur le pattern `live` (divergence assumée vs `ConversationDetailsDto` qui omet). 8. **Normalisation factorisée** : helper `preview(text, max)` partagé (trim + collapse whitespace + troncature char-safe), `task_preview` (Lot B) refactoré dessus. ## Commandes exécutées + résultats réels - `cargo fmt --all -- --check`**clean** (après `cargo fmt --all`). - `cargo test -p application --test workstate`**21 passed; 0 failed** (12 existants + 9 nouveaux : has_no_conversations, dedups, ready, missing+bounded(3), partial, unavailable, preview_failure_preserves_agents/live/busy/tickets, previews_truncated+normalised, turn_text_truncated). - `cargo test -p app-tauri --test dto_agents`**21 passed; 0 failed** (+1 `project_work_state_dto_serialises_conversations_camelcase`). - `cargo check -p app-tauri`**clean** (domain/application/infrastructure/app-tauri compilent). Pas d'adapter infra créé (réemploi de `FsHandoffStore`/`FsConversationLog` existants). Dirty runtime `.ideai/*` ignoré. Reste : types TS (DevFrontend) + commit/merge (Git) + validation e2e. - **Response:** Lot C backend/Tauri `workstate conversation summaries` **implémenté et vert** sur `feature/workstate-conversation-summaries`. **Rien commité.** ## Fichiers modifiés (6 ; aucun infra/domain — ports HandoffStore/ConversationLog réutilisés) - `crates/application/src/workstate/mod.rs` — modèle + algo best-effort - `crates/application/src/lib.rs` — re-exports - `crates/app-tauri/src/dto.rs` — DTO camelCase - `crates/app-tauri/src/state.rs` — wiring composition root - `crates/application/tests/workstate.rs` — fakes + 9 tests - `crates/app-tauri/tests/dto_agents.rs` — +1 test + 2 littéraux existants mis à jour ## Signatures/types ajoutés **Application :** - `ProjectWorkState.conversations: Vec<ConversationWorkSummary>` (top-level) - `ConversationWorkSummary { conversation_id, status, objective_preview: Option<String>, summary_preview: Option<String>, summary_len: usize, up_to: Option<TurnId>, recent_turns: Vec<ConversationTurnWorkPreview> }` - `enum ConversationPreviewStatus { Ready, Missing, Partial, Unavailable }` - `ConversationTurnWorkPreview { role: TurnRole, source: TicketWorkSource, at_ms: u64, text_preview: String, text_len: usize }` - `trait ConversationLogProvider { fn conversation_log_for(&self, root: &ProjectPath) -> Option<Arc<dyn ConversationLog>> }` (nouveau, jumeau de `HandoffProvider`) - `GetProjectWorkState::with_conversation_sources(handoffs: Arc<dyn HandoffProvider>, logs: Arc<dyn ConversationLogProvider>)` (builder) - Constantes : `HANDOFF_PREVIEW_MAX_CHARS=480`, `OBJECTIVE_PREVIEW_MAX_CHARS=160`, `RECENT_TURNS_MAX=3`, `TURN_PREVIEW_MAX_CHARS=220` **DTO Tauri :** `ProjectWorkStateDto.conversations`, `ConversationWorkSummaryDto`, `ConversationPreviewStatusDto` (`ready/missing/partial/unavailable`), `ConversationTurnWorkPreviewDto`. **state.rs :** `AppConversationLogProvider` (matérialise `FsConversationLog::new(root)`), câblé via `.with_conversation_sources(AppHandoffProvider, AppConversationLogProvider)`. ## Choix exacts / divergences 1. **Réutilisé `HandoffProvider` existant (P7)** comme source primaire + ajouté le jumeau `ConversationLogProvider` pour le repli. Résolus **par project root** (`input.project.root`) car `GetProjectWorkState` est singleton AppState alors que les `Fs*` figent leur racine à la construction — strictement parallèle au pattern P7/P8b. 2. **Builder `with_conversation_sources`** plutôt que d'étendre `new(...)` : sources OFF par défaut, zéro régression sur call sites/tests existants (best-effort absent = aucune summary). 3. **« provider non câblé » = handoff Absent (chemin Missing), jamais une erreur.** `Unavailable` strictement = handoff **erreur** ET log erreur/absent. `Missing` reste Missing même si le log échoue (alors recentTurns vide). Conforme aux étapes 4/5/6 du cadrage. 4. **Ready** ne remplit pas `recent_turns` (le handoff EST le résumé) ; recentTurns peuplé seulement en Missing/Partial. Re-cap défensif à `RECENT_TURNS_MAX` en plus de `log.last(_, 3)`. 5. **Dédup** des `conversation_id` sur tous les tickets projetés (humains inclus), **ordre first-seen** pour refléter l'ordre du panneau. 6. **`TurnRole` domaine réutilisé tel quel dans le DTO** (sérialise déjà camelCase `prompt/response/toolActivity`), cohérent avec le réemploi de `AgentBusyState` ; `source` du tour réutilise `TicketWorkSourceDto` (`kind: human/agent`). 7. **Champs preview optionnels sérialisés en `null`** quand absents (pas omis) — prévisible pour le front, aligné sur le pattern `live` (divergence assumée vs `ConversationDetailsDto` qui omet). 8. **Normalisation factorisée** : helper `preview(text, max)` partagé (trim + collapse whitespace + troncature char-safe), `task_preview` (Lot B) refactoré dessus. ## Commandes exécutées + résultats réels - `cargo fmt --all -- --check`**clean** (après `cargo fmt --all`). - `cargo test -p application --test workstate`**21 passed; 0 failed** (12 existants + 9 nouveaux : has_no_conversations, dedups, ready, missing+bounded(3), partial, unavailable, preview_failure_preserves_agents/live/busy/tickets, previews_truncated+normalised, turn_text_truncated). - `cargo test -p app-tauri --test dto_agents`**21 passed; 0 failed** (+1 `project_work_state_dto_serialises_conversations_camelcase`). - `cargo check -p app-tauri`**clean** (domain/application/infrastructure/app-tauri compilent). Pas d'adapter infra créé (réemploi de `FsHandoffStore`/`FsConversationLog` existants). Dirty runtime `.ideai/*` ignoré. Reste : types TS (DevFrontend) + commit/merge (Git) + validation e2e.
- **Prompt:** QA Lot C est verte mais signale un warning Rust non bloquant: `variant Absent is never constructed` dans `crates/application/tests/workstate.rs:173:5`, probablement un enum/fake de test `HandoffOutcome::Absent` inutilisé. Merci de nettoyer ce warning de façon minimale sans changer le comportement applicatif, puis relance au moins: - `cargo fmt --all -- --check` - `cargo test -p application --test workstate` Ne committe pas. Retourne le diff conceptuel, les fichiers modifiés, et les résultats réels. - **Prompt:** QA Lot C est verte mais signale un warning Rust non bloquant: `variant Absent is never constructed` dans `crates/application/tests/workstate.rs:173:5`, probablement un enum/fake de test `HandoffOutcome::Absent` inutilisé. Merci de nettoyer ce warning de façon minimale sans changer le comportement applicatif, puis relance au moins: - `cargo fmt --all -- --check` - `cargo test -p application --test workstate` Ne committe pas. Retourne le diff conceptuel, les fichiers modifiés, et les résultats réels.
- **Response:** Warning nettoyé. **Rien commité.** ## Diff conceptuel La variante `HandoffOutcome::Absent` du fake de test n'était jamais construite : l'absence de handoff était déjà modélisée en **ne configurant pas** la conversation (le `load` du fake retombait sur l'arm `_ => Ok(None)`). Correctif minimal, zéro impact applicatif (uniquement le fixture de test) : - Suppression de la variante `Absent` (+ doc-comment expliquant que l'absence = conversation non configurée). - Le match de `FakeHandoffStore::load` passe de `_ => Ok(None)` à `None => Ok(None)` (désormais exhaustif sur `Present`/`Error`/`None`, plus de wildcard). Aucun test ne référençait `Absent` (le test `missing` repose sur une conversation non configurée), donc aucune logique de test ni d'assertion modifiée. ## Fichier modifié - `crates/application/tests/workstate.rs` (uniquement) ## Résultats réels - `cargo fmt --all -- --check`**clean** (exit 0). - `cargo test -p application --test workstate`**21 passed; 0 failed**, **aucun warning** (le `variant Absent is never constructed` a disparu). - **Response:** Warning nettoyé. **Rien commité.** ## Diff conceptuel La variante `HandoffOutcome::Absent` du fake de test n'était jamais construite : l'absence de handoff était déjà modélisée en **ne configurant pas** la conversation (le `load` du fake retombait sur l'arm `_ => Ok(None)`). Correctif minimal, zéro impact applicatif (uniquement le fixture de test) : - Suppression de la variante `Absent` (+ doc-comment expliquant que l'absence = conversation non configurée). - Le match de `FakeHandoffStore::load` passe de `_ => Ok(None)` à `None => Ok(None)` (désormais exhaustif sur `Present`/`Error`/`None`, plus de wildcard). Aucun test ne référençait `Absent` (le test `missing` repose sur une conversation non configurée), donc aucune logique de test ni d'assertion modifiée. ## Fichier modifié - `crates/application/tests/workstate.rs` (uniquement) ## Résultats réels - `cargo fmt --all -- --check`**clean** (exit 0). - `cargo test -p application --test workstate`**21 passed; 0 failed**, **aucun warning** (le `variant Absent is never constructed` a disparu).
- **Prompt:** Implémente le backend/Tauri du Lot D `workstate controlled actions` sur la branche active `feature/workstate-controlled-actions`. Périmètre backend prioritaire: 1. Faire porter Attach par un contrat agent-level fiable, sans spawn: - Use case applicatif `AttachLiveAgent` si nécessaire. - Input: `project`, `agent_id`, `node_id`. - Output: `agent_id`, `node_id`, `session_id`, `kind: LiveSessionKind`. - Comportement: chercher la session live par agent dans PTY puis structured, rebind `node_id` sans créer de session, idempotent si déjà attaché à ce node, NOT_FOUND si agent non live. - Ne touche pas log/handoff/provider sessions. 2. Ajouter `StopLiveAgent` agent-level: - Input: `project`, `agent_id`. - Output: `agent_id`, `session_id`, `kind`. - Comportement: résoudre la session live par agent; si PTY déléguer à la primitive existante de fermeture/kill et retirer registry; si structured shutdown + retirer registry; NOT_FOUND si absent. - Ne supprime pas agent, tickets, conversation summary, handoff. - Publier/laisser publier les events existants d'exit si l'infra le fait déjà; ne pas inventer un bus si absent. 3. Tauri: - Commandes camelCase: - `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }` - `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }` - Réutiliser/enrichir DTO `LiveAgent` si cohérent, sinon DTO dédié. - Mapper INVALID ids et NOT_FOUND. Contraintes: - Ne pas lancer d'agent neuf, ne jamais appeler `launch_agent`. - Ne pas créer de cellule/layout côté backend pour Lot D. - Ne pas modifier le frontend. - Ne committe pas. - Ignore dirty runtime `.ideai/*`. Tests attendus: - Application Rust: attach PTY rebind sans changer `session_id`; attach structured; attach absent NOT_FOUND; attach même node idempotent; stop PTY retire session live; stop structured shutdown + retire; stop absent NOT_FOUND. - App-tauri tests DTO/command wiring: request/response camelCase, `kind`, INVALID/NOT_FOUND si conventions existantes le permettent. Commandes minimales: - `cargo fmt --all -- --check` - tests ciblés application pertinents (à choisir selon modules existants) - tests app-tauri pertinents - `cargo check -p app-tauri` Retourne fichiers modifiés, signatures/commandes ajoutées, résultats réels, et blocages/écarts éventuels.
- **Response:** Lot D `workstate controlled actions` **implémenté et vert** sur `feature/workstate-controlled-actions`. **Rien commité.** ## Fichiers modifiés / créés - **NOUVEAU** `crates/application/src/workstate/actions.rs` — use cases `AttachLiveAgent` + `StopLiveAgent` - **NOUVEAU** `crates/application/tests/workstate_actions.rs` — 7 tests - `crates/application/src/workstate/mod.rs``mod actions;` + re-exports - `crates/application/src/lib.rs` — re-exports crate-root - `crates/app-tauri/src/dto.rs` — DTO request/response - `crates/app-tauri/src/commands.rs` — commande `attach_live_agent` réécrite + `stop_live_agent` - `crates/app-tauri/src/state.rs` — wiring composition root + champs AppState - `crates/app-tauri/src/lib.rs` — enregistrement `stop_live_agent` dans le handler - `crates/app-tauri/tests/dto_agents.rs` — 4 tests DTO ## Signatures ajoutées **Application :** - `AttachLiveAgent::new(live: Arc<LiveSessions>)` ; `execute(AttachLiveAgentInput { project, agent_id, node_id }) -> Result<AttachLiveAgentOutput { agent_id, node_id, session_id, kind: LiveSessionKind }, AppError>` (sync — rebind pur). - `StopLiveAgent::new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>)` ; `async execute(StopLiveAgentInput { project, agent_id }) -> Result<StopLiveAgentOutput { agent_id, session_id, kind }, AppError>`. **Tauri (camelCase) :** - `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }` - `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }` - DTO dédiés `AttachLiveAgentResponseDto` / `StopLiveAgentRequestDto` / `StopLiveAgentResponseDto` ; `kind` réutilise `LiveWorkSessionKindDto` (`pty`/`structured`). ## Choix exacts / écarts 1. **Attach = use case dédié** (l'ancienne commande ne gérait que le PTY via `rebind_agent_node` direct) : désormais PTY **puis** structured, idempotent (rebind sur le même node = no-op renvoyant la même session), NOT_FOUND sinon. Zéro spawn, ne touche pas log/handoff/provider sessions. 2. **Stop polymorphe** : PTY → délègue à la primitive existante `CloseTerminal` (remove registry + kill) ; structured → `remove` puis `shutdown()`. Ne supprime ni agent, ni tickets, ni summary, ni handoff. Aucun bus inventé — l'event d'exit est laissé à l'infra existante (pump PTY / backend session). 3. **Ordre PTY-first** pour les deux (conforme au libellé cadrage « PTY puis structured » et à `LiveSessions::session_id_for_agent`) ; non ambigu par l'invariant « 1 session vivante/agent ». 4. **`project` accepté mais non utilisé pour la logique** (registres globaux par agent) — gardé pour la frontière/symétrie, pas de check manifest (le cadrage ne l'exige pas). 5. **⚠️ ÉCART contrat frontend** : `attach_live_agent` renvoyait `LiveAgentListDto` (tableau) ; il renvoie désormais l'objet `{ agentId, nodeId, sessionId, kind }` imposé par le cadrage. Je n'ai **pas** touché le frontend (consigne respectée) ⇒ **mismatch transitoire FE/BE à réconcilier par DevFrontend dans son Lot D**. À flaguer. 6. Pas de cellule/layout créée côté backend (hors périmètre Lot D). ## Résultats réels - `cargo fmt --all -- --check`**clean** (après `cargo fmt --all`). - `cargo test -p application --test workstate_actions`**7 passed; 0 failed** (attach PTY rebind sans changer session_id ; attach structured ; attach absent NOT_FOUND ; attach même node idempotent ; stop PTY kill+remove ; stop structured shutdown+remove ; stop absent NOT_FOUND). - `cargo test -p application --test workstate`**21 passed** (non-régression Lots A/B/C). - `cargo test -p app-tauri --test dto_agents`**25 passed** (+4 nouveaux : request/response camelCase + `kind` pour attach & stop ; pas de fuite snake_case). - `cargo test -p app-tauri --test list_live_agents_r0b`**5 passed** (non-régression de la liste live). - `cargo check -p app-tauri`**clean**. ## Blocages Aucun blocage technique. Seul point d'attention : l'écart de contrat (#5) qui requiert l'adaptation frontend (DevFrontend) + commit/merge (Git) + validation e2e. Dirty runtime `.ideai/*` ignoré.

View File

@ -76,3 +76,5 @@
{"id":"b9900b46-41ff-4276-a225-991520cf0923","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976051405,"source":{"kind":"agent","agentId":"73c853d1-c0fd-463b-ad17-1d24fefa371f"},"role":"response","text":"Lot C backend/Tauri `workstate conversation summaries` **implémenté et vert** sur `feature/workstate-conversation-summaries`. **Rien commité.**\n\n## Fichiers modifiés (6 ; aucun infra/domain — ports HandoffStore/ConversationLog réutilisés)\n- `crates/application/src/workstate/mod.rs` — modèle + algo best-effort\n- `crates/application/src/lib.rs` — re-exports\n- `crates/app-tauri/src/dto.rs` — DTO camelCase\n- `crates/app-tauri/src/state.rs` — wiring composition root\n- `crates/application/tests/workstate.rs` — fakes + 9 tests\n- `crates/app-tauri/tests/dto_agents.rs` — +1 test + 2 littéraux existants mis à jour\n\n## Signatures/types ajoutés\n**Application :**\n- `ProjectWorkState.conversations: Vec<ConversationWorkSummary>` (top-level)\n- `ConversationWorkSummary { conversation_id, status, objective_preview: Option<String>, summary_preview: Option<String>, summary_len: usize, up_to: Option<TurnId>, recent_turns: Vec<ConversationTurnWorkPreview> }`\n- `enum ConversationPreviewStatus { Ready, Missing, Partial, Unavailable }`\n- `ConversationTurnWorkPreview { role: TurnRole, source: TicketWorkSource, at_ms: u64, text_preview: String, text_len: usize }`\n- `trait ConversationLogProvider { fn conversation_log_for(&self, root: &ProjectPath) -> Option<Arc<dyn ConversationLog>> }` (nouveau, jumeau de `HandoffProvider`)\n- `GetProjectWorkState::with_conversation_sources(handoffs: Arc<dyn HandoffProvider>, logs: Arc<dyn ConversationLogProvider>)` (builder)\n- Constantes : `HANDOFF_PREVIEW_MAX_CHARS=480`, `OBJECTIVE_PREVIEW_MAX_CHARS=160`, `RECENT_TURNS_MAX=3`, `TURN_PREVIEW_MAX_CHARS=220`\n\n**DTO Tauri :** `ProjectWorkStateDto.conversations`, `ConversationWorkSummaryDto`, `ConversationPreviewStatusDto` (`ready/missing/partial/unavailable`), `ConversationTurnWorkPreviewDto`. **state.rs :** `AppConversationLogProvider` (matérialise `FsConversationLog::new(root)`), câblé via `.with_conversation_sources(AppHandoffProvider, AppConversationLogProvider)`.\n\n## Choix exacts / divergences\n1. **Réutilisé `HandoffProvider` existant (P7)** comme source primaire + ajouté le jumeau `ConversationLogProvider` pour le repli. Résolus **par project root** (`input.project.root`) car `GetProjectWorkState` est singleton AppState alors que les `Fs*` figent leur racine à la construction — strictement parallèle au pattern P7/P8b.\n2. **Builder `with_conversation_sources`** plutôt que d'étendre `new(...)` : sources OFF par défaut, zéro régression sur call sites/tests existants (best-effort absent = aucune summary).\n3. **« provider non câblé » = handoff Absent (chemin Missing), jamais une erreur.** `Unavailable` strictement = handoff **erreur** ET log erreur/absent. `Missing` reste Missing même si le log échoue (alors recentTurns vide). Conforme aux étapes 4/5/6 du cadrage.\n4. **Ready** ne remplit pas `recent_turns` (le handoff EST le résumé) ; recentTurns peuplé seulement en Missing/Partial. Re-cap défensif à `RECENT_TURNS_MAX` en plus de `log.last(_, 3)`.\n5. **Dédup** des `conversation_id` sur tous les tickets projetés (humains inclus), **ordre first-seen** pour refléter l'ordre du panneau.\n6. **`TurnRole` domaine réutilisé tel quel dans le DTO** (sérialise déjà camelCase `prompt/response/toolActivity`), cohérent avec le réemploi de `AgentBusyState` ; `source` du tour réutilise `TicketWorkSourceDto` (`kind: human/agent`).\n7. **Champs preview optionnels sérialisés en `null`** quand absents (pas omis) — prévisible pour le front, aligné sur le pattern `live` (divergence assumée vs `ConversationDetailsDto` qui omet).\n8. **Normalisation factorisée** : helper `preview(text, max)` partagé (trim + collapse whitespace + troncature char-safe), `task_preview` (Lot B) refactoré dessus.\n\n## Commandes exécutées + résultats réels\n- `cargo fmt --all -- --check` → **clean** (après `cargo fmt --all`).\n- `cargo test -p application --test workstate` → **21 passed; 0 failed** (12 existants + 9 nouveaux : has_no_conversations, dedups, ready, missing+bounded(3), partial, unavailable, preview_failure_preserves_agents/live/busy/tickets, previews_truncated+normalised, turn_text_truncated).\n- `cargo test -p app-tauri --test dto_agents` → **21 passed; 0 failed** (+1 `project_work_state_dto_serialises_conversations_camelcase`).\n- `cargo check -p app-tauri` → **clean** (domain/application/infrastructure/app-tauri compilent).\n\nPas d'adapter infra créé (réemploi de `FsHandoffStore`/`FsConversationLog` existants). Dirty runtime `.ideai/*` ignoré. Reste : types TS (DevFrontend) + commit/merge (Git) + validation e2e."} {"id":"b9900b46-41ff-4276-a225-991520cf0923","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976051405,"source":{"kind":"agent","agentId":"73c853d1-c0fd-463b-ad17-1d24fefa371f"},"role":"response","text":"Lot C backend/Tauri `workstate conversation summaries` **implémenté et vert** sur `feature/workstate-conversation-summaries`. **Rien commité.**\n\n## Fichiers modifiés (6 ; aucun infra/domain — ports HandoffStore/ConversationLog réutilisés)\n- `crates/application/src/workstate/mod.rs` — modèle + algo best-effort\n- `crates/application/src/lib.rs` — re-exports\n- `crates/app-tauri/src/dto.rs` — DTO camelCase\n- `crates/app-tauri/src/state.rs` — wiring composition root\n- `crates/application/tests/workstate.rs` — fakes + 9 tests\n- `crates/app-tauri/tests/dto_agents.rs` — +1 test + 2 littéraux existants mis à jour\n\n## Signatures/types ajoutés\n**Application :**\n- `ProjectWorkState.conversations: Vec<ConversationWorkSummary>` (top-level)\n- `ConversationWorkSummary { conversation_id, status, objective_preview: Option<String>, summary_preview: Option<String>, summary_len: usize, up_to: Option<TurnId>, recent_turns: Vec<ConversationTurnWorkPreview> }`\n- `enum ConversationPreviewStatus { Ready, Missing, Partial, Unavailable }`\n- `ConversationTurnWorkPreview { role: TurnRole, source: TicketWorkSource, at_ms: u64, text_preview: String, text_len: usize }`\n- `trait ConversationLogProvider { fn conversation_log_for(&self, root: &ProjectPath) -> Option<Arc<dyn ConversationLog>> }` (nouveau, jumeau de `HandoffProvider`)\n- `GetProjectWorkState::with_conversation_sources(handoffs: Arc<dyn HandoffProvider>, logs: Arc<dyn ConversationLogProvider>)` (builder)\n- Constantes : `HANDOFF_PREVIEW_MAX_CHARS=480`, `OBJECTIVE_PREVIEW_MAX_CHARS=160`, `RECENT_TURNS_MAX=3`, `TURN_PREVIEW_MAX_CHARS=220`\n\n**DTO Tauri :** `ProjectWorkStateDto.conversations`, `ConversationWorkSummaryDto`, `ConversationPreviewStatusDto` (`ready/missing/partial/unavailable`), `ConversationTurnWorkPreviewDto`. **state.rs :** `AppConversationLogProvider` (matérialise `FsConversationLog::new(root)`), câblé via `.with_conversation_sources(AppHandoffProvider, AppConversationLogProvider)`.\n\n## Choix exacts / divergences\n1. **Réutilisé `HandoffProvider` existant (P7)** comme source primaire + ajouté le jumeau `ConversationLogProvider` pour le repli. Résolus **par project root** (`input.project.root`) car `GetProjectWorkState` est singleton AppState alors que les `Fs*` figent leur racine à la construction — strictement parallèle au pattern P7/P8b.\n2. **Builder `with_conversation_sources`** plutôt que d'étendre `new(...)` : sources OFF par défaut, zéro régression sur call sites/tests existants (best-effort absent = aucune summary).\n3. **« provider non câblé » = handoff Absent (chemin Missing), jamais une erreur.** `Unavailable` strictement = handoff **erreur** ET log erreur/absent. `Missing` reste Missing même si le log échoue (alors recentTurns vide). Conforme aux étapes 4/5/6 du cadrage.\n4. **Ready** ne remplit pas `recent_turns` (le handoff EST le résumé) ; recentTurns peuplé seulement en Missing/Partial. Re-cap défensif à `RECENT_TURNS_MAX` en plus de `log.last(_, 3)`.\n5. **Dédup** des `conversation_id` sur tous les tickets projetés (humains inclus), **ordre first-seen** pour refléter l'ordre du panneau.\n6. **`TurnRole` domaine réutilisé tel quel dans le DTO** (sérialise déjà camelCase `prompt/response/toolActivity`), cohérent avec le réemploi de `AgentBusyState` ; `source` du tour réutilise `TicketWorkSourceDto` (`kind: human/agent`).\n7. **Champs preview optionnels sérialisés en `null`** quand absents (pas omis) — prévisible pour le front, aligné sur le pattern `live` (divergence assumée vs `ConversationDetailsDto` qui omet).\n8. **Normalisation factorisée** : helper `preview(text, max)` partagé (trim + collapse whitespace + troncature char-safe), `task_preview` (Lot B) refactoré dessus.\n\n## Commandes exécutées + résultats réels\n- `cargo fmt --all -- --check` → **clean** (après `cargo fmt --all`).\n- `cargo test -p application --test workstate` → **21 passed; 0 failed** (12 existants + 9 nouveaux : has_no_conversations, dedups, ready, missing+bounded(3), partial, unavailable, preview_failure_preserves_agents/live/busy/tickets, previews_truncated+normalised, turn_text_truncated).\n- `cargo test -p app-tauri --test dto_agents` → **21 passed; 0 failed** (+1 `project_work_state_dto_serialises_conversations_camelcase`).\n- `cargo check -p app-tauri` → **clean** (domain/application/infrastructure/app-tauri compilent).\n\nPas d'adapter infra créé (réemploi de `FsHandoffStore`/`FsConversationLog` existants). Dirty runtime `.ideai/*` ignoré. Reste : types TS (DevFrontend) + commit/merge (Git) + validation e2e."}
{"id":"0834676a-dc01-4cdf-97a4-37cff81bf3d2","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976363926,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"QA Lot C est verte mais signale un warning Rust non bloquant: `variant Absent is never constructed` dans `crates/application/tests/workstate.rs:173:5`, probablement un enum/fake de test `HandoffOutcome::Absent` inutilisé.\n\nMerci de nettoyer ce warning de façon minimale sans changer le comportement applicatif, puis relance au moins:\n- `cargo fmt --all -- --check`\n- `cargo test -p application --test workstate`\n\nNe committe pas. Retourne le diff conceptuel, les fichiers modifiés, et les résultats réels."} {"id":"0834676a-dc01-4cdf-97a4-37cff81bf3d2","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976363926,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"QA Lot C est verte mais signale un warning Rust non bloquant: `variant Absent is never constructed` dans `crates/application/tests/workstate.rs:173:5`, probablement un enum/fake de test `HandoffOutcome::Absent` inutilisé.\n\nMerci de nettoyer ce warning de façon minimale sans changer le comportement applicatif, puis relance au moins:\n- `cargo fmt --all -- --check`\n- `cargo test -p application --test workstate`\n\nNe committe pas. Retourne le diff conceptuel, les fichiers modifiés, et les résultats réels."}
{"id":"8e30c171-2d32-48ab-9971-c6d23a010052","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976412762,"source":{"kind":"agent","agentId":"73c853d1-c0fd-463b-ad17-1d24fefa371f"},"role":"response","text":"Warning nettoyé. **Rien commité.**\n\n## Diff conceptuel\nLa variante `HandoffOutcome::Absent` du fake de test n'était jamais construite : l'absence de handoff était déjà modélisée en **ne configurant pas** la conversation (le `load` du fake retombait sur l'arm `_ => Ok(None)`). Correctif minimal, zéro impact applicatif (uniquement le fixture de test) :\n- Suppression de la variante `Absent` (+ doc-comment expliquant que l'absence = conversation non configurée).\n- Le match de `FakeHandoffStore::load` passe de `_ => Ok(None)` à `None => Ok(None)` (désormais exhaustif sur `Present`/`Error`/`None`, plus de wildcard).\nAucun test ne référençait `Absent` (le test `missing` repose sur une conversation non configurée), donc aucune logique de test ni d'assertion modifiée.\n\n## Fichier modifié\n- `crates/application/tests/workstate.rs` (uniquement)\n\n## Résultats réels\n- `cargo fmt --all -- --check` → **clean** (exit 0).\n- `cargo test -p application --test workstate` → **21 passed; 0 failed**, **aucun warning** (le `variant Absent is never constructed` a disparu)."} {"id":"8e30c171-2d32-48ab-9971-c6d23a010052","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976412762,"source":{"kind":"agent","agentId":"73c853d1-c0fd-463b-ad17-1d24fefa371f"},"role":"response","text":"Warning nettoyé. **Rien commité.**\n\n## Diff conceptuel\nLa variante `HandoffOutcome::Absent` du fake de test n'était jamais construite : l'absence de handoff était déjà modélisée en **ne configurant pas** la conversation (le `load` du fake retombait sur l'arm `_ => Ok(None)`). Correctif minimal, zéro impact applicatif (uniquement le fixture de test) :\n- Suppression de la variante `Absent` (+ doc-comment expliquant que l'absence = conversation non configurée).\n- Le match de `FakeHandoffStore::load` passe de `_ => Ok(None)` à `None => Ok(None)` (désormais exhaustif sur `Present`/`Error`/`None`, plus de wildcard).\nAucun test ne référençait `Absent` (le test `missing` repose sur une conversation non configurée), donc aucune logique de test ni d'assertion modifiée.\n\n## Fichier modifié\n- `crates/application/tests/workstate.rs` (uniquement)\n\n## Résultats réels\n- `cargo fmt --all -- --check` → **clean** (exit 0).\n- `cargo test -p application --test workstate` → **21 passed; 0 failed**, **aucun warning** (le `variant Absent is never constructed` a disparu)."}
{"id":"6092e15f-2659-4986-960a-0a1b3bc705ff","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781976761247,"source":{"kind":"agent","agentId":"a6ced819-b893-4213-b003-9e9dc79b9641"},"role":"prompt","text":"Implémente le backend/Tauri du Lot D `workstate controlled actions` sur la branche active `feature/workstate-controlled-actions`.\n\nPérimètre backend prioritaire:\n1. Faire porter Attach par un contrat agent-level fiable, sans spawn:\n - Use case applicatif `AttachLiveAgent` si nécessaire.\n - Input: `project`, `agent_id`, `node_id`.\n - Output: `agent_id`, `node_id`, `session_id`, `kind: LiveSessionKind`.\n - Comportement: chercher la session live par agent dans PTY puis structured, rebind `node_id` sans créer de session, idempotent si déjà attaché à ce node, NOT_FOUND si agent non live.\n - Ne touche pas log/handoff/provider sessions.\n\n2. Ajouter `StopLiveAgent` agent-level:\n - Input: `project`, `agent_id`.\n - Output: `agent_id`, `session_id`, `kind`.\n - Comportement: résoudre la session live par agent; si PTY déléguer à la primitive existante de fermeture/kill et retirer registry; si structured shutdown + retirer registry; NOT_FOUND si absent.\n - Ne supprime pas agent, tickets, conversation summary, handoff.\n - Publier/laisser publier les events existants d'exit si l'infra le fait déjà; ne pas inventer un bus si absent.\n\n3. Tauri:\n - Commandes camelCase:\n - `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }`\n - `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }`\n - Réutiliser/enrichir DTO `LiveAgent` si cohérent, sinon DTO dédié.\n - Mapper INVALID ids et NOT_FOUND.\n\nContraintes:\n- Ne pas lancer d'agent neuf, ne jamais appeler `launch_agent`.\n- Ne pas créer de cellule/layout côté backend pour Lot D.\n- Ne pas modifier le frontend.\n- Ne committe pas.\n- Ignore dirty runtime `.ideai/*`.\n\nTests attendus:\n- Application Rust: attach PTY rebind sans changer `session_id`; attach structured; attach absent NOT_FOUND; attach même node idempotent; stop PTY retire session live; stop structured shutdown + retire; stop absent NOT_FOUND.\n- App-tauri tests DTO/command wiring: request/response camelCase, `kind`, INVALID/NOT_FOUND si conventions existantes le permettent.\n\nCommandes minimales:\n- `cargo fmt --all -- --check`\n- tests ciblés application pertinents (à choisir selon modules existants)\n- tests app-tauri pertinents\n- `cargo check -p app-tauri`\n\nRetourne fichiers modifiés, signatures/commandes ajoutées, résultats réels, et blocages/écarts éventuels."}
{"id":"ec87367b-50e1-44fb-b4dd-88c284f02cae","conversation":"d5068bc8-786e-0428-1d14-83b93961a15e","atMs":1781977281733,"source":{"kind":"agent","agentId":"73c853d1-c0fd-463b-ad17-1d24fefa371f"},"role":"response","text":"Lot D `workstate controlled actions` **implémenté et vert** sur `feature/workstate-controlled-actions`. **Rien commité.**\n\n## Fichiers modifiés / créés\n- **NOUVEAU** `crates/application/src/workstate/actions.rs` — use cases `AttachLiveAgent` + `StopLiveAgent`\n- **NOUVEAU** `crates/application/tests/workstate_actions.rs` — 7 tests\n- `crates/application/src/workstate/mod.rs` — `mod actions;` + re-exports\n- `crates/application/src/lib.rs` — re-exports crate-root\n- `crates/app-tauri/src/dto.rs` — DTO request/response\n- `crates/app-tauri/src/commands.rs` — commande `attach_live_agent` réécrite + `stop_live_agent`\n- `crates/app-tauri/src/state.rs` — wiring composition root + champs AppState\n- `crates/app-tauri/src/lib.rs` — enregistrement `stop_live_agent` dans le handler\n- `crates/app-tauri/tests/dto_agents.rs` — 4 tests DTO\n\n## Signatures ajoutées\n**Application :**\n- `AttachLiveAgent::new(live: Arc<LiveSessions>)` ; `execute(AttachLiveAgentInput { project, agent_id, node_id }) -> Result<AttachLiveAgentOutput { agent_id, node_id, session_id, kind: LiveSessionKind }, AppError>` (sync — rebind pur).\n- `StopLiveAgent::new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>)` ; `async execute(StopLiveAgentInput { project, agent_id }) -> Result<StopLiveAgentOutput { agent_id, session_id, kind }, AppError>`.\n\n**Tauri (camelCase) :**\n- `attach_live_agent({ request: { projectId, agentId, nodeId } }) -> { agentId, nodeId, sessionId, kind }`\n- `stop_live_agent({ request: { projectId, agentId } }) -> { agentId, sessionId, kind }`\n- DTO dédiés `AttachLiveAgentResponseDto` / `StopLiveAgentRequestDto` / `StopLiveAgentResponseDto` ; `kind` réutilise `LiveWorkSessionKindDto` (`pty`/`structured`).\n\n## Choix exacts / écarts\n1. **Attach = use case dédié** (l'ancienne commande ne gérait que le PTY via `rebind_agent_node` direct) : désormais PTY **puis** structured, idempotent (rebind sur le même node = no-op renvoyant la même session), NOT_FOUND sinon. Zéro spawn, ne touche pas log/handoff/provider sessions.\n2. **Stop polymorphe** : PTY → délègue à la primitive existante `CloseTerminal` (remove registry + kill) ; structured → `remove` puis `shutdown()`. Ne supprime ni agent, ni tickets, ni summary, ni handoff. Aucun bus inventé — l'event d'exit est laissé à l'infra existante (pump PTY / backend session).\n3. **Ordre PTY-first** pour les deux (conforme au libellé cadrage « PTY puis structured » et à `LiveSessions::session_id_for_agent`) ; non ambigu par l'invariant « 1 session vivante/agent ».\n4. **`project` accepté mais non utilisé pour la logique** (registres globaux par agent) — gardé pour la frontière/symétrie, pas de check manifest (le cadrage ne l'exige pas).\n5. **⚠️ ÉCART contrat frontend** : `attach_live_agent` renvoyait `LiveAgentListDto` (tableau) ; il renvoie désormais l'objet `{ agentId, nodeId, sessionId, kind }` imposé par le cadrage. Je n'ai **pas** touché le frontend (consigne respectée) ⇒ **mismatch transitoire FE/BE à réconcilier par DevFrontend dans son Lot D**. À flaguer.\n6. Pas de cellule/layout créée côté backend (hors périmètre Lot D).\n\n## Résultats réels\n- `cargo fmt --all -- --check` → **clean** (après `cargo fmt --all`).\n- `cargo test -p application --test workstate_actions` → **7 passed; 0 failed** (attach PTY rebind sans changer session_id ; attach structured ; attach absent NOT_FOUND ; attach même node idempotent ; stop PTY kill+remove ; stop structured shutdown+remove ; stop absent NOT_FOUND).\n- `cargo test -p application --test workstate` → **21 passed** (non-régression Lots A/B/C).\n- `cargo test -p app-tauri --test dto_agents` → **25 passed** (+4 nouveaux : request/response camelCase + `kind` pour attach & stop ; pas de fuite snake_case).\n- `cargo test -p app-tauri --test list_live_agents_r0b` → **5 passed** (non-régression de la liste live).\n- `cargo check -p app-tauri` → **clean**.\n\n## Blocages\nAucun blocage technique. Seul point d'attention : l'écart de contrat (#5) qui requiert l'adaptation frontend (DevFrontend) + commit/merge (Git) + validation e2e. Dirty runtime `.ideai/*` ignoré."}

View File

@ -9,19 +9,20 @@ use tauri::State;
use crate::dto::DismissEmbedderSuggestionRequestDto; use crate::dto::DismissEmbedderSuggestionRequestDto;
use application::{ use application::{
AppError, AssignSkillToAgentInput, ChangeAgentProfileInput, CloseProjectInput, AppError, AssignSkillToAgentInput, AttachLiveAgentInput, ChangeAgentProfileInput,
CreateAgentInput, CreateLayoutInput, CreateMemoryInput, CreateSkillInput, DeleteAgentInput, CloseProjectInput, CreateAgentInput, CreateLayoutInput, CreateMemoryInput, CreateSkillInput,
DeleteEmbedderProfileInput, DeleteLayoutInput, DeleteMemoryInput, DeleteSkillInput, DeleteAgentInput, DeleteEmbedderProfileInput, DeleteLayoutInput, DeleteMemoryInput,
DeleteTemplateInput, DetectAgentDriftInput, GetMemoryInput, GetProjectWorkStateInput, DeleteSkillInput, DeleteTemplateInput, DetectAgentDriftInput, GetMemoryInput,
GitBranchesInput, GitCheckoutInput, GitCommitInput, GitGraphInput, GitInitInput, GitLogInput, GetProjectWorkStateInput, GitBranchesInput, GitCheckoutInput, GitCommitInput, GitGraphInput,
GitStagePathInput, GitStatusInput, InspectConversationInput, LaunchAgentInput, ListAgentsInput, GitInitInput, GitLogInput, GitStagePathInput, GitStatusInput, InspectConversationInput,
ListLayoutsInput, ListMemoriesInput, ListResumableAgentsInput, ListSkillsInput, LiveSessions, LaunchAgentInput, ListAgentsInput, ListLayoutsInput, ListMemoriesInput,
LoadLayoutInput, McpRuntime, MutateLayoutInput, OpenProjectInput, ReadAgentContextInput, ListResumableAgentsInput, ListSkillsInput, LiveSessions, LoadLayoutInput, McpRuntime,
ReadMemoryIndexInput, ReadProjectContextInput, RecallMemoryInput, ReconcileLayoutsInput, MutateLayoutInput, OpenProjectInput, ReadAgentContextInput, ReadMemoryIndexInput,
RenameLayoutInput, ResolveAgentPermissionsInput, ResolveMemoryLinksInput, SetActiveLayoutInput, ReadProjectContextInput, RecallMemoryInput, ReconcileLayoutsInput, RenameLayoutInput,
SnapshotRunningAgentsInput, SyncAgentWithTemplateInput, UnassignSkillFromAgentInput, ResolveAgentPermissionsInput, ResolveMemoryLinksInput, SetActiveLayoutInput,
UpdateAgentContextInput, UpdateAgentPermissionsInput, UpdateMemoryInput, SnapshotRunningAgentsInput, StopLiveAgentInput, SyncAgentWithTemplateInput,
UpdateProjectContextInput, UpdateProjectPermissionsInput, UpdateSkillInput, UnassignSkillFromAgentInput, UpdateAgentContextInput, UpdateAgentPermissionsInput,
UpdateMemoryInput, UpdateProjectContextInput, UpdateProjectPermissionsInput, UpdateSkillInput,
}; };
use domain::ports::PtyHandle; use domain::ports::PtyHandle;
@ -29,11 +30,11 @@ use crate::dto::{
parse_agent_id, parse_close_terminal, parse_delete_profile, parse_layout_id, parse_memory_slug, parse_agent_id, parse_close_terminal, parse_delete_profile, parse_layout_id, parse_memory_slug,
parse_node_id, parse_profile_id, parse_project_id, parse_session_id, parse_skill_id, parse_node_id, parse_profile_id, parse_project_id, parse_session_id, parse_skill_id,
parse_template_id, parse_ticket_id, AgentDriftListDto, AgentDto, AgentListDto, parse_template_id, parse_ticket_id, AgentDriftListDto, AgentDto, AgentListDto,
AssignSkillRequestDto, AttachLiveAgentRequestDto, ChangeAgentProfileDto, AssignSkillRequestDto, AttachLiveAgentRequestDto, AttachLiveAgentResponseDto,
ChangeAgentProfileRequestDto, ConfigureProfilesRequestDto, ConversationDetailsDto, ChangeAgentProfileDto, ChangeAgentProfileRequestDto, ConfigureProfilesRequestDto,
CreateAgentFromTemplateRequestDto, CreateAgentRequestDto, CreateLayoutRequestDto, ConversationDetailsDto, CreateAgentFromTemplateRequestDto, CreateAgentRequestDto,
CreateLayoutResultDto, CreateMemoryRequestDto, CreateProjectRequestDto, CreateSkillRequestDto, CreateLayoutRequestDto, CreateLayoutResultDto, CreateMemoryRequestDto, CreateProjectRequestDto,
CreateTemplateRequestDto, DeleteLayoutRequestDto, DeleteLayoutResultDto, CreateSkillRequestDto, CreateTemplateRequestDto, DeleteLayoutRequestDto, DeleteLayoutResultDto,
DeliveredDelegationRequestDto, DetectProfilesRequestDto, DetectProfilesResponseDto, DeliveredDelegationRequestDto, DetectProfilesRequestDto, DetectProfilesResponseDto,
EffectivePermissionsDto, EmbedderEnginesDto, EmbedderProfileDto, EmbedderProfileListDto, EffectivePermissionsDto, EmbedderEnginesDto, EmbedderProfileDto, EmbedderProfileListDto,
ErrorDto, FirstRunStateDto, FrontAttachedRequestDto, GitBranchesDto, GitCheckoutRequestDto, ErrorDto, FirstRunStateDto, FrontAttachedRequestDto, GitBranchesDto, GitCheckoutRequestDto,
@ -46,7 +47,8 @@ use crate::dto::{
ReattachResultDto, RecallMemoryRequestDto, RenameLayoutRequestDto, ReplyChunk, ReattachResultDto, RecallMemoryRequestDto, RenameLayoutRequestDto, ReplyChunk,
ResizeTerminalRequestDto, ResolveAgentPermissionsRequestDto, ResumableAgentListDto, ResizeTerminalRequestDto, ResolveAgentPermissionsRequestDto, ResumableAgentListDto,
SaveEmbedderProfileRequestDto, SaveProfileRequestDto, SetActiveLayoutRequestDto, SkillDto, SaveEmbedderProfileRequestDto, SaveProfileRequestDto, SetActiveLayoutRequestDto, SkillDto,
SkillListDto, SyncAgentWithTemplateRequestDto, SyncResultDto, TemplateDto, TemplateListDto, SkillListDto, StopLiveAgentRequestDto, StopLiveAgentResponseDto,
SyncAgentWithTemplateRequestDto, SyncResultDto, TemplateDto, TemplateListDto,
TerminalClosedDto, TerminalSessionDto, UnassignSkillRequestDto, UpdateAgentContextRequestDto, TerminalClosedDto, TerminalSessionDto, UnassignSkillRequestDto, UpdateAgentContextRequestDto,
UpdateAgentPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto, UpdateAgentPermissionsRequestDto, UpdateMemoryRequestDto, UpdateProjectContextRequestDto,
UpdateProjectPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto, UpdateProjectPermissionsRequestDto, UpdateSkillRequestDto, UpdateTemplateRequestDto,
@ -1036,20 +1038,42 @@ pub fn list_live_agents(
pub async fn attach_live_agent( pub async fn attach_live_agent(
request: AttachLiveAgentRequestDto, request: AttachLiveAgentRequestDto,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> Result<LiveAgentListDto, ErrorDto> { ) -> Result<AttachLiveAgentResponseDto, ErrorDto> {
let _project = resolve_project(&request.project_id, &state).await?; let project = resolve_project(&request.project_id, &state).await?;
let agent_id = parse_agent_id(&request.agent_id)?; let agent_id = parse_agent_id(&request.agent_id)?;
let node_id = parse_node_id(&request.node_id)?; let node_id = parse_node_id(&request.node_id)?;
let session = state state
.terminal_sessions .attach_live_agent
.rebind_agent_node(&agent_id, node_id) .execute(AttachLiveAgentInput {
.ok_or_else(|| AppError::NotFound(format!("running session for agent {agent_id}")))?; project,
agent_id,
node_id,
})
.map(AttachLiveAgentResponseDto::from)
.map_err(ErrorDto::from)
}
Ok(LiveAgentListDto::from_pairs(vec![( /// `stop_live_agent` — tear down an already-running agent's live session by agent
agent_id, /// id, polymorphically (PTY kill or structured shutdown), without removing the
session.node_id, /// agent, its tickets, conversation summary or handoff.
session.id, ///
)])) /// # Errors
/// Returns an [`ErrorDto`] (`INVALID` for malformed ids, `NOT_FOUND` if the
/// project/agent is unknown or the agent has no live session, `PROCESS` on a
/// kill/shutdown failure).
#[tauri::command]
pub async fn stop_live_agent(
request: StopLiveAgentRequestDto,
state: State<'_, AppState>,
) -> Result<StopLiveAgentResponseDto, ErrorDto> {
let project = resolve_project(&request.project_id, &state).await?;
let agent_id = parse_agent_id(&request.agent_id)?;
state
.stop_live_agent
.execute(StopLiveAgentInput { project, agent_id })
.await
.map(StopLiveAgentResponseDto::from)
.map_err(ErrorDto::from)
} }
/// `read_agent_context` — read an agent's Markdown context. /// `read_agent_context` — read an agent's Markdown context.

View File

@ -9,10 +9,10 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use application::{ use application::{
AgentTicketState, AppError, ConversationPreviewStatus, ConversationTurnWorkPreview, AgentTicketState, AppError, AttachLiveAgentOutput, ConversationPreviewStatus,
ConversationWorkSummary, CreateProjectInput, CreateProjectOutput, GitGraphOutput, HealthInput, ConversationTurnWorkPreview, ConversationWorkSummary, CreateProjectInput, CreateProjectOutput,
HealthReport, LayoutKind, ListProjectsOutput, LiveSessionKind, OpenProjectOutput, GitGraphOutput, HealthInput, HealthReport, LayoutKind, ListProjectsOutput, LiveSessionKind,
ProjectWorkState, TicketWorkSource, TicketWorkStatus, OpenProjectOutput, ProjectWorkState, StopLiveAgentOutput, TicketWorkSource, TicketWorkStatus,
}; };
use domain::{AgentBusyState, Project, ProjectId, TurnRole}; use domain::{AgentBusyState, Project, ProjectId, TurnRole};
@ -1751,6 +1751,64 @@ pub struct AttachLiveAgentRequestDto {
pub node_id: String, pub node_id: String,
} }
/// Response DTO for `attach_live_agent`: the rebound live session's coordinates.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AttachLiveAgentResponseDto {
/// The rebound agent's id.
pub agent_id: String,
/// The node now hosting the session view.
pub node_id: String,
/// The (unchanged) live session id.
pub session_id: String,
/// Runtime family that owns the session (`pty`/`structured`).
pub kind: LiveWorkSessionKindDto,
}
impl From<AttachLiveAgentOutput> for AttachLiveAgentResponseDto {
fn from(out: AttachLiveAgentOutput) -> Self {
Self {
agent_id: out.agent_id.to_string(),
node_id: out.node_id.to_string(),
session_id: out.session_id.to_string(),
kind: out.kind.into(),
}
}
}
/// Request DTO for `stop_live_agent`: tear down an already-running agent's live
/// session by agent id (no spawn, agent entity preserved).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StopLiveAgentRequestDto {
/// Id of the owning project (validated for symmetry and future scoping).
pub project_id: String,
/// Id of the running agent to stop.
pub agent_id: String,
}
/// Response DTO for `stop_live_agent`: the torn-down session's coordinates.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StopLiveAgentResponseDto {
/// The stopped agent's id.
pub agent_id: String,
/// The id of the session that was torn down.
pub session_id: String,
/// Runtime family that owned the session (`pty`/`structured`).
pub kind: LiveWorkSessionKindDto,
}
impl From<StopLiveAgentOutput> for StopLiveAgentResponseDto {
fn from(out: StopLiveAgentOutput) -> Self {
Self {
agent_id: out.agent_id.to_string(),
session_id: out.session_id.to_string(),
kind: out.kind.into(),
}
}
}
/// Parses an agent-id string (UUID) coming from the frontend. /// Parses an agent-id string (UUID) coming from the frontend.
/// ///
/// # Errors /// # Errors

View File

@ -166,6 +166,7 @@ pub fn run() {
commands::get_project_work_state, commands::get_project_work_state,
commands::list_live_agents, commands::list_live_agents,
commands::attach_live_agent, commands::attach_live_agent,
commands::stop_live_agent,
commands::read_agent_context, commands::read_agent_context,
commands::update_agent_context, commands::update_agent_context,
commands::delete_agent, commands::delete_agent,

View File

@ -12,22 +12,23 @@ use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use application::{ use application::{
AgentResumer, AppError, AssignSkillToAgent, ChangeAgentProfile, CheckEmbedderSuggestion, AgentResumer, AppError, AssignSkillToAgent, AttachLiveAgent, ChangeAgentProfile,
CloseProject, CloseTab, CloseTerminal, ConfigureProfiles, ContextGuardUseCases, CheckEmbedderSuggestion, CloseProject, CloseTab, CloseTerminal, ConfigureProfiles,
CreateAgentFromScratch, CreateAgentFromTemplate, CreateLayout, CreateMemory, CreateProject, ContextGuardUseCases, CreateAgentFromScratch, CreateAgentFromTemplate, CreateLayout,
CreateSkill, CreateTemplate, DeleteAgent, DeleteEmbedderProfile, DeleteLayout, DeleteMemory, CreateMemory, CreateProject, CreateSkill, CreateTemplate, DeleteAgent, DeleteEmbedderProfile,
DeleteProfile, DeleteSkill, DeleteTemplate, DescribeEmbedderEngines, DetectAgentDrift, DeleteLayout, DeleteMemory, DeleteProfile, DeleteSkill, DeleteTemplate,
DetectProfiles, DismissEmbedderSuggestion, FirstRunState, GetMemory, GetProjectPermissions, DescribeEmbedderEngines, DetectAgentDrift, DetectProfiles, DismissEmbedderSuggestion,
GetProjectWorkState, GitBranches, GitCheckout, GitCommit, GitGraph, GitInit, GitLog, GitStage, FirstRunState, GetMemory, GetProjectPermissions, GetProjectWorkState, GitBranches, GitCheckout,
GitStatus, GitUnstage, HealthUseCase, InspectConversation, LaunchAgent, LaunchAgentInput, GitCommit, GitGraph, GitInit, GitLog, GitStage, GitStatus, GitUnstage, HealthUseCase,
ListAgents, ListAgentsInput, ListEmbedderProfiles, ListLayouts, ListMemories, ListProfiles, InspectConversation, LaunchAgent, LaunchAgentInput, ListAgents, ListAgentsInput,
ListProjects, ListResumableAgents, ListSkills, ListTemplates, LiveAgentRegistry, LiveSessions, ListEmbedderProfiles, ListLayouts, ListMemories, ListProfiles, ListProjects,
LoadLayout, McpRuntime, MoveTabToNewWindow, MutateLayout, OnnxModelView, OpenProject, ListResumableAgents, ListSkills, ListTemplates, LiveAgentRegistry, LiveSessions, LoadLayout,
OpenTerminal, OrchestratorService, PermissionProjectorRegistry, ProposeContext, McpRuntime, MoveTabToNewWindow, MutateLayout, OnnxModelView, OpenProject, OpenTerminal,
ReadAgentContext, ReadContext, ReadMemory, ReadMemoryIndex, ReadProjectContext, RecallMemory, OrchestratorService, PermissionProjectorRegistry, ProposeContext, ReadAgentContext,
ReconcileLayouts, RecordTurn, RecordTurnProvider, ReferenceProfiles, RenameLayout, ReadContext, ReadMemory, ReadMemoryIndex, ReadProjectContext, RecallMemory, ReconcileLayouts,
ResizeTerminal, ResolveAgentPermissions, ResolveMemoryLinks, SaveEmbedderProfile, SaveProfile, RecordTurn, RecordTurnProvider, ReferenceProfiles, RenameLayout, ResizeTerminal,
SessionLimitService, SetActiveLayout, SnapshotRunningAgents, StructuredSessions, ResolveAgentPermissions, ResolveMemoryLinks, SaveEmbedderProfile, SaveProfile,
SessionLimitService, SetActiveLayout, SnapshotRunningAgents, StopLiveAgent, StructuredSessions,
SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, UnassignSkillFromAgent, SuggestedThisSession, SyncAgentWithTemplate, TerminalSessions, UnassignSkillFromAgent,
UpdateAgentContext, UpdateAgentPermissions, UpdateMemory, UpdateProjectContext, UpdateAgentContext, UpdateAgentPermissions, UpdateMemory, UpdateProjectContext,
UpdateProjectPermissions, UpdateSkill, UpdateTemplate, WriteMemory, WriteToTerminal, UpdateProjectPermissions, UpdateSkill, UpdateTemplate, WriteMemory, WriteToTerminal,
@ -351,6 +352,10 @@ pub struct AppState {
pub list_resumable_agents: Arc<ListResumableAgents>, pub list_resumable_agents: Arc<ListResumableAgents>,
/// Read-only live/busy state for the project's manifest agents. /// Read-only live/busy state for the project's manifest agents.
pub get_project_work_state: Arc<GetProjectWorkState>, pub get_project_work_state: Arc<GetProjectWorkState>,
/// Rebinds an already-running agent's live session to a visible cell (Lot D).
pub attach_live_agent: Arc<AttachLiveAgent>,
/// Tears down an already-running agent's live session by agent id (Lot D).
pub stop_live_agent: Arc<StopLiveAgent>,
/// Best-effort inspection of a conversation (last topic + token indicator) /// Best-effort inspection of a conversation (last topic + token indicator)
/// for the resume popup (T7). Optional/extensible: backed by a `Vec` of /// for the resume popup (T7). Optional/extensible: backed by a `Vec` of
/// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty /// [`domain::ports::SessionInspector`]s; an empty/missing match yields empty
@ -1066,6 +1071,14 @@ impl AppState {
as Arc<dyn application::ConversationLogProvider>, as Arc<dyn application::ConversationLogProvider>,
), ),
); );
// Lot D — actions contrôlées agent-level sur les sessions vivantes : attach
// (rebind de la cellule-vue, zéro spawn) et stop (kill PTY via la primitive
// `CloseTerminal` existante / shutdown structuré). Aucune création de session.
let attach_live_agent = Arc::new(AttachLiveAgent::new(Arc::clone(&live_sessions)));
let stop_live_agent = Arc::new(StopLiveAgent::new(
Arc::clone(&live_sessions),
Arc::clone(&close_terminal),
));
// --- Limites de session des agents (ARCHITECTURE §21, LS7) --- // --- Limites de session des agents (ARCHITECTURE §21, LS7) ---
// Service pur-ports « détecter → planifier → reprendre » câblé sur l'existant : // Service pur-ports « détecter → planifier → reprendre » câblé sur l'existant :
@ -1233,6 +1246,8 @@ impl AppState {
change_agent_profile, change_agent_profile,
list_resumable_agents, list_resumable_agents,
get_project_work_state, get_project_work_state,
attach_live_agent,
stop_live_agent,
inspect_conversation, inspect_conversation,
project_store, project_store,
get_project_permissions, get_project_permissions,

View File

@ -552,3 +552,82 @@ fn launch_agent_output_propagates_assigned_conversation_id() {
"no snake_case leak" "no snake_case leak"
); );
} }
// ---------------------------------------------------------------------------
// Lot D — attach/stop live agent DTOs (controlled actions)
// ---------------------------------------------------------------------------
#[test]
fn attach_live_agent_request_deserialises_camelcase() {
use app_tauri_lib::dto::AttachLiveAgentRequestDto;
let raw = json!({
"projectId": Uuid::from_u128(1).to_string(),
"agentId": Uuid::from_u128(2).to_string(),
"nodeId": Uuid::from_u128(3).to_string()
});
let dto: AttachLiveAgentRequestDto = serde_json::from_value(raw).unwrap();
assert_eq!(dto.project_id, Uuid::from_u128(1).to_string());
assert_eq!(dto.agent_id, Uuid::from_u128(2).to_string());
assert_eq!(dto.node_id, Uuid::from_u128(3).to_string());
}
#[test]
fn attach_live_agent_response_serialises_camelcase_with_kind() {
use app_tauri_lib::dto::AttachLiveAgentResponseDto;
use application::{AttachLiveAgentOutput, LiveSessionKind};
let agent = AgentId::from_uuid(Uuid::from_u128(11));
let node = NodeId::from_uuid(Uuid::from_u128(12));
let session = SessionId::from_uuid(Uuid::from_u128(13));
let dto = AttachLiveAgentResponseDto::from(AttachLiveAgentOutput {
agent_id: agent,
node_id: node,
session_id: session,
kind: LiveSessionKind::Pty,
});
let v = serde_json::to_value(&dto).unwrap();
assert_eq!(v["agentId"], agent.to_string());
assert_eq!(v["nodeId"], node.to_string());
assert_eq!(v["sessionId"], session.to_string());
assert_eq!(v["kind"], "pty");
// No snake_case leak.
assert!(v.get("agent_id").is_none());
assert!(v.get("session_id").is_none());
}
#[test]
fn stop_live_agent_request_deserialises_camelcase() {
use app_tauri_lib::dto::StopLiveAgentRequestDto;
let raw = json!({
"projectId": Uuid::from_u128(1).to_string(),
"agentId": Uuid::from_u128(2).to_string()
});
let dto: StopLiveAgentRequestDto = serde_json::from_value(raw).unwrap();
assert_eq!(dto.project_id, Uuid::from_u128(1).to_string());
assert_eq!(dto.agent_id, Uuid::from_u128(2).to_string());
}
#[test]
fn stop_live_agent_response_serialises_camelcase_with_kind() {
use app_tauri_lib::dto::StopLiveAgentResponseDto;
use application::{LiveSessionKind, StopLiveAgentOutput};
let agent = AgentId::from_uuid(Uuid::from_u128(11));
let session = SessionId::from_uuid(Uuid::from_u128(13));
let dto = StopLiveAgentResponseDto::from(StopLiveAgentOutput {
agent_id: agent,
session_id: session,
kind: LiveSessionKind::Structured,
});
let v = serde_json::to_value(&dto).unwrap();
assert_eq!(v["agentId"], agent.to_string());
assert_eq!(v["sessionId"], session.to_string());
assert_eq!(v["kind"], "structured");
// Stop response carries no node id (the session is gone).
assert!(v.get("nodeId").is_none());
assert!(v.get("session_id").is_none());
}

View File

@ -119,8 +119,9 @@ pub use terminal::{
}; };
pub use window::{MoveTabToNewWindow, MoveTabToNewWindowInput, MoveTabToNewWindowOutput}; pub use window::{MoveTabToNewWindow, MoveTabToNewWindowInput, MoveTabToNewWindowOutput};
pub use workstate::{ pub use workstate::{
AgentTicketState, AgentWorkState, ConversationLogProvider, ConversationPreviewStatus, AgentTicketState, AgentWorkState, AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput,
ConversationTurnWorkPreview, ConversationWorkSummary, GetProjectWorkState, ConversationLogProvider, ConversationPreviewStatus, ConversationTurnWorkPreview,
GetProjectWorkStateInput, LiveWorkSession, ProjectWorkState, TicketWorkSource, ConversationWorkSummary, GetProjectWorkState, GetProjectWorkStateInput, LiveWorkSession,
ProjectWorkState, StopLiveAgent, StopLiveAgentInput, StopLiveAgentOutput, TicketWorkSource,
TicketWorkStatus, TicketWorkStatus,
}; };

View File

@ -0,0 +1,177 @@
//! Agent-level controlled actions over live sessions (Lot D).
//!
//! Companion to the read-only work-state model: these use cases let the UI drive
//! an **already-running** agent's live session by **agent id**, never by spawning a
//! new process. [`AttachLiveAgent`] rebinds the hosting cell ("a cell is a view");
//! [`StopLiveAgent`] tears the live session down polymorphically (PTY kill vs
//! structured shutdown). Neither touches the agent entity, its tickets, the
//! conversation summaries, the handoff or the provider sessions.
use std::sync::Arc;
use domain::{AgentId, NodeId, Project, SessionId};
use crate::error::AppError;
use crate::terminal::{CloseTerminal, CloseTerminalInput, LiveSessionKind, LiveSessions};
/// Input for [`AttachLiveAgent::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachLiveAgentInput {
/// The owning project (boundary/symmetry; the registries are global by agent).
pub project: Project,
/// The already-running agent whose live session is rebound.
pub agent_id: AgentId,
/// The layout leaf that should host the live session view.
pub node_id: NodeId,
}
/// Output of [`AttachLiveAgent::execute`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AttachLiveAgentOutput {
/// The rebound agent.
pub agent_id: AgentId,
/// The node now hosting the session view.
pub node_id: NodeId,
/// The unchanged live session id.
pub session_id: SessionId,
/// Runtime family that owns the session.
pub kind: LiveSessionKind,
}
/// Rebinds an already-running agent session to a visible layout cell, never
/// spawning a process ("a cell is a view").
///
/// Resolves the live session by agent in the PTY registry first, then the
/// structured one, and updates only the hosting `node_id` (the PTY handle / agent
/// session, its id and scrollback stay intact). Idempotent when the agent is
/// already attached to the same node (the rebind is a no-op that returns the same
/// session). No log/handoff/provider-session is touched.
pub struct AttachLiveAgent {
live: Arc<LiveSessions>,
}
impl AttachLiveAgent {
/// Builds the use case from the aggregated live-session registry.
#[must_use]
pub fn new(live: Arc<LiveSessions>) -> Self {
Self { live }
}
/// Rebinds the agent's live session onto `node_id`.
///
/// # Errors
/// [`AppError::NotFound`] when the agent has no live session in either registry.
pub fn execute(&self, input: AttachLiveAgentInput) -> Result<AttachLiveAgentOutput, AppError> {
// PTY first, then structured (one-live-session-per-agent ⇒ at most one match).
if let Some(session) = self
.live
.pty
.rebind_agent_node(&input.agent_id, input.node_id)
{
return Ok(AttachLiveAgentOutput {
agent_id: input.agent_id,
node_id: session.node_id,
session_id: session.id,
kind: LiveSessionKind::Pty,
});
}
if let Some(session) = self
.live
.structured
.rebind_agent_node(&input.agent_id, input.node_id)
{
return Ok(AttachLiveAgentOutput {
agent_id: input.agent_id,
node_id: input.node_id,
session_id: session.id(),
kind: LiveSessionKind::Structured,
});
}
Err(AppError::NotFound(format!(
"running session for agent {}",
input.agent_id
)))
}
}
/// Input for [`StopLiveAgent::execute`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StopLiveAgentInput {
/// The owning project (boundary/symmetry; the registries are global by agent).
pub project: Project,
/// The agent whose live session is stopped.
pub agent_id: AgentId,
}
/// Output of [`StopLiveAgent::execute`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StopLiveAgentOutput {
/// The stopped agent.
pub agent_id: AgentId,
/// The id of the session that was torn down.
pub session_id: SessionId,
/// Runtime family that owned the session.
pub kind: LiveSessionKind,
}
/// Stops an already-running agent's live session, polymorphically.
///
/// Resolves the session by agent (PTY first, then structured). A PTY session is
/// torn down through the existing [`CloseTerminal`] primitive (registry removal +
/// process kill); a structured session is removed then `shutdown()`. The agent
/// entity, its tickets, conversation summaries and handoff are **not** removed. Any
/// exit event is left to the existing infrastructure (the PTY pump / session
/// backend) — no bus is invented here.
pub struct StopLiveAgent {
live: Arc<LiveSessions>,
close: Arc<CloseTerminal>,
}
impl StopLiveAgent {
/// Builds the use case from the live-session registry and the close primitive.
#[must_use]
pub fn new(live: Arc<LiveSessions>, close: Arc<CloseTerminal>) -> Self {
Self { live, close }
}
/// Tears down the agent's live session.
///
/// # Errors
/// - [`AppError::NotFound`] when the agent has no live session,
/// - [`AppError::Process`] when the PTY kill or structured shutdown fails.
pub async fn execute(
&self,
input: StopLiveAgentInput,
) -> Result<StopLiveAgentOutput, AppError> {
// PTY first: delegate to the existing close primitive (removes + kills).
if let Some(session_id) = self.live.pty.session_for_agent(&input.agent_id) {
self.close
.execute(CloseTerminalInput { session_id })
.await?;
return Ok(StopLiveAgentOutput {
agent_id: input.agent_id,
session_id,
kind: LiveSessionKind::Pty,
});
}
// Structured: remove from the registry first (so the uniqueness guard no
// longer sees a live session), then shut the session down out of the lock.
if let Some(session_id) = self.live.structured.session_id_for_agent(&input.agent_id) {
if let Some(session) = self.live.structured.remove(&session_id) {
session
.shutdown()
.await
.map_err(|e| AppError::Process(e.to_string()))?;
}
return Ok(StopLiveAgentOutput {
agent_id: input.agent_id,
session_id,
kind: LiveSessionKind::Structured,
});
}
Err(AppError::NotFound(format!(
"running session for agent {}",
input.agent_id
)))
}
}

View File

@ -5,6 +5,13 @@
//! beyond loading the manifest through the existing context store and creates no //! beyond loading the manifest through the existing context store and creates no
//! durable projection. //! durable projection.
mod actions;
pub use actions::{
AttachLiveAgent, AttachLiveAgentInput, AttachLiveAgentOutput, StopLiveAgent,
StopLiveAgentInput, StopLiveAgentOutput,
};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::sync::Arc; use std::sync::Arc;

View File

@ -0,0 +1,351 @@
//! Tests for the Lot D agent-level controlled actions (`AttachLiveAgent`,
//! `StopLiveAgent`) over the live-session registries.
//!
//! Every port is faked in-memory so the use cases run without a real PTY or
//! agent-session backend: [`FakePty`] records `kill`s, [`FakeSession`] records
//! `shutdown`s.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use application::{
AttachLiveAgent, AttachLiveAgentInput, CloseTerminal, LiveSessionKind, LiveSessions,
StopLiveAgent, StopLiveAgentInput, StructuredSessions, TerminalSessions,
};
use domain::ports::{
AgentSession, AgentSessionError, ExitStatus, OutputStream, PtyError, PtyHandle, PtyPort,
ReplyStream, SpawnSpec,
};
use domain::Project;
use domain::{
AgentId, NodeId, ProjectId, ProjectPath, PtySize, RemoteRef, SessionId, SessionKind,
TerminalSession,
};
use uuid::Uuid;
// ---------------------------------------------------------------------------
// ids / fixtures
// ---------------------------------------------------------------------------
fn aid(n: u128) -> AgentId {
AgentId::from_uuid(Uuid::from_u128(n))
}
fn sid(n: u128) -> SessionId {
SessionId::from_uuid(Uuid::from_u128(n))
}
fn nid(n: u128) -> NodeId {
NodeId::from_uuid(Uuid::from_u128(n))
}
fn project() -> Project {
Project::new(
ProjectId::from_uuid(Uuid::from_u128(1)),
"demo",
ProjectPath::new("/tmp/idea-workstate-actions").unwrap(),
RemoteRef::local(),
1_700_000_000_000,
)
.unwrap()
}
// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------
/// A recording [`PtyPort`] whose `kill` records the killed session id.
#[derive(Default)]
struct FakePty {
kills: Mutex<Vec<SessionId>>,
}
impl FakePty {
fn kills(&self) -> Vec<SessionId> {
self.kills.lock().unwrap().clone()
}
}
#[async_trait]
impl PtyPort for FakePty {
async fn spawn(&self, _spec: SpawnSpec, _size: PtySize) -> Result<PtyHandle, PtyError> {
unreachable!("Lot D never spawns")
}
fn write(&self, _handle: &PtyHandle, _data: &[u8]) -> Result<(), PtyError> {
Ok(())
}
fn resize(&self, _handle: &PtyHandle, _size: PtySize) -> Result<(), PtyError> {
Ok(())
}
fn subscribe_output(&self, _handle: &PtyHandle) -> Result<OutputStream, PtyError> {
Ok(Box::new(std::iter::empty()))
}
fn scrollback(&self, _handle: &PtyHandle) -> Result<Vec<u8>, PtyError> {
Ok(Vec::new())
}
async fn kill(&self, handle: &PtyHandle) -> Result<ExitStatus, PtyError> {
self.kills.lock().unwrap().push(handle.session_id);
Ok(ExitStatus { code: Some(0) })
}
}
/// A fake structured [`AgentSession`] recording whether `shutdown` was called.
struct FakeSession {
id: SessionId,
shutdown_called: Arc<AtomicBool>,
}
#[async_trait]
impl AgentSession for FakeSession {
fn id(&self) -> SessionId {
self.id
}
fn conversation_id(&self) -> Option<String> {
None
}
async fn send(&self, _prompt: &str) -> Result<ReplyStream, AgentSessionError> {
Ok(Box::new(std::iter::empty()))
}
async fn shutdown(&self) -> Result<(), AgentSessionError> {
self.shutdown_called.store(true, Ordering::SeqCst);
Ok(())
}
}
// ---------------------------------------------------------------------------
// wiring helpers
// ---------------------------------------------------------------------------
struct Fixture {
attach: AttachLiveAgent,
stop: StopLiveAgent,
pty: Arc<TerminalSessions>,
structured: Arc<StructuredSessions>,
pty_port: Arc<FakePty>,
}
fn fixture() -> Fixture {
let pty = Arc::new(TerminalSessions::new());
let structured = Arc::new(StructuredSessions::new());
let live = Arc::new(LiveSessions::new(Arc::clone(&pty), Arc::clone(&structured)));
let pty_port = Arc::new(FakePty::default());
let close = Arc::new(CloseTerminal::new(
Arc::clone(&pty_port) as Arc<dyn PtyPort>,
Arc::clone(&pty),
));
Fixture {
attach: AttachLiveAgent::new(Arc::clone(&live)),
stop: StopLiveAgent::new(Arc::clone(&live), close),
pty,
structured,
pty_port,
}
}
fn insert_pty(
sessions: &TerminalSessions,
session_id: SessionId,
agent_id: AgentId,
node_id: NodeId,
) {
sessions.insert(
PtyHandle { session_id },
TerminalSession::starting(
session_id,
node_id,
ProjectPath::new("/tmp/idea-workstate-actions").unwrap(),
SessionKind::Agent { agent_id },
PtySize { rows: 24, cols: 80 },
),
);
}
fn insert_structured(
sessions: &StructuredSessions,
session_id: SessionId,
agent_id: AgentId,
node_id: NodeId,
) -> Arc<AtomicBool> {
let flag = Arc::new(AtomicBool::new(false));
sessions.insert(
Arc::new(FakeSession {
id: session_id,
shutdown_called: Arc::clone(&flag),
}),
agent_id,
node_id,
);
flag
}
// ---------------------------------------------------------------------------
// AttachLiveAgent
// ---------------------------------------------------------------------------
#[test]
fn attach_pty_rebinds_node_without_changing_session() {
let f = fixture();
let a = aid(10);
insert_pty(&f.pty, sid(1), a, nid(100));
let out = f
.attach
.execute(AttachLiveAgentInput {
project: project(),
agent_id: a,
node_id: nid(200),
})
.unwrap();
assert_eq!(out.agent_id, a);
assert_eq!(out.session_id, sid(1), "session id is preserved on rebind");
assert_eq!(out.node_id, nid(200), "view rebound to the new node");
assert_eq!(out.kind, LiveSessionKind::Pty);
// The registry reflects the new host node, same session.
assert_eq!(f.pty.node_for_agent(&a), Some(nid(200)));
assert_eq!(f.pty.session_for_agent(&a), Some(sid(1)));
}
#[test]
fn attach_structured_rebinds_node() {
let f = fixture();
let a = aid(10);
let _flag = insert_structured(&f.structured, sid(2), a, nid(100));
let out = f
.attach
.execute(AttachLiveAgentInput {
project: project(),
agent_id: a,
node_id: nid(300),
})
.unwrap();
assert_eq!(out.session_id, sid(2));
assert_eq!(out.node_id, nid(300));
assert_eq!(out.kind, LiveSessionKind::Structured);
assert_eq!(f.structured.node_for_agent(&a), Some(nid(300)));
}
#[test]
fn attach_unknown_agent_is_not_found() {
let f = fixture();
let err = f
.attach
.execute(AttachLiveAgentInput {
project: project(),
agent_id: aid(999),
node_id: nid(1),
})
.expect_err("absent agent ⇒ NOT_FOUND");
assert!(
matches!(err, application::AppError::NotFound(_)),
"got {err:?}"
);
}
#[test]
fn attach_same_node_is_idempotent() {
let f = fixture();
let a = aid(10);
insert_pty(&f.pty, sid(1), a, nid(100));
let first = f
.attach
.execute(AttachLiveAgentInput {
project: project(),
agent_id: a,
node_id: nid(100),
})
.unwrap();
let second = f
.attach
.execute(AttachLiveAgentInput {
project: project(),
agent_id: a,
node_id: nid(100),
})
.unwrap();
// Re-attaching to the same node is a no-op: same session, same node, no spawn.
assert_eq!(first.session_id, second.session_id);
assert_eq!(first.node_id, nid(100));
assert_eq!(second.node_id, nid(100));
assert_eq!(f.pty.len(), 1, "no extra session created");
}
// ---------------------------------------------------------------------------
// StopLiveAgent
// ---------------------------------------------------------------------------
#[tokio::test]
async fn stop_pty_kills_and_removes_session() {
let f = fixture();
let a = aid(10);
insert_pty(&f.pty, sid(1), a, nid(100));
let out = f
.stop
.execute(StopLiveAgentInput {
project: project(),
agent_id: a,
})
.await
.unwrap();
assert_eq!(out.agent_id, a);
assert_eq!(out.session_id, sid(1));
assert_eq!(out.kind, LiveSessionKind::Pty);
// Delegated to the close primitive: process killed and registry emptied.
assert_eq!(f.pty_port.kills(), vec![sid(1)]);
assert!(f.pty.is_empty(), "live session removed from the registry");
assert_eq!(f.pty.session_for_agent(&a), None);
}
#[tokio::test]
async fn stop_structured_shuts_down_and_removes_session() {
let f = fixture();
let a = aid(10);
let flag = insert_structured(&f.structured, sid(2), a, nid(100));
let out = f
.stop
.execute(StopLiveAgentInput {
project: project(),
agent_id: a,
})
.await
.unwrap();
assert_eq!(out.session_id, sid(2));
assert_eq!(out.kind, LiveSessionKind::Structured);
assert!(flag.load(Ordering::SeqCst), "session.shutdown() was called");
assert!(f.structured.is_empty(), "live session removed");
assert_eq!(f.structured.session_id_for_agent(&a), None);
// No PTY was touched.
assert!(f.pty_port.kills().is_empty());
}
#[tokio::test]
async fn stop_unknown_agent_is_not_found() {
let f = fixture();
let err = f
.stop
.execute(StopLiveAgentInput {
project: project(),
agent_id: aid(999),
})
.await
.expect_err("absent agent ⇒ NOT_FOUND");
assert!(
matches!(err, application::AppError::NotFound(_)),
"got {err:?}"
);
assert!(f.pty_port.kills().is_empty(), "nothing killed");
}

View File

@ -61,13 +61,34 @@ describe("TauriAgentGateway invoke payloads", () => {
}); });
it("attach_live_agent wraps project, agent and target node in the request DTO", async () => { it("attach_live_agent wraps project, agent and target node in the request DTO", async () => {
invoke.mockResolvedValueOnce([ invoke.mockResolvedValueOnce({
{ agentId: "agent-2", nodeId: "node-3", sessionId: "session-4" }, agentId: "agent-2",
]); nodeId: "node-3",
await new TauriAgentGateway().attachLiveAgent("proj-1", "agent-2", "node-3"); sessionId: "session-4",
kind: "pty",
});
const out = await new TauriAgentGateway().attachLiveAgent(
"proj-1",
"agent-2",
"node-3",
);
expect(invoke).toHaveBeenCalledWith("attach_live_agent", { expect(invoke).toHaveBeenCalledWith("attach_live_agent", {
request: { projectId: "proj-1", agentId: "agent-2", nodeId: "node-3" }, request: { projectId: "proj-1", agentId: "agent-2", nodeId: "node-3" },
}); });
expect(out.sessionId).toBe("session-4");
});
it("stop_live_agent wraps project and agent in the request DTO", async () => {
invoke.mockResolvedValueOnce({
agentId: "agent-2",
sessionId: "session-4",
kind: "pty",
});
const out = await new TauriAgentGateway().stopLiveAgent("proj-1", "agent-2");
expect(invoke).toHaveBeenCalledWith("stop_live_agent", {
request: { projectId: "proj-1", agentId: "agent-2" },
});
expect(out.sessionId).toBe("session-4");
}); });
it("change_agent_profile wraps all five fields in the request DTO (camelCase)", async () => { it("change_agent_profile wraps all five fields in the request DTO (camelCase)", async () => {

View File

@ -26,6 +26,7 @@ import type {
LiveAgent, LiveAgent,
OpenTerminalOptions, OpenTerminalOptions,
ReattachResult, ReattachResult,
StoppedLiveAgent,
TerminalHandle, TerminalHandle,
} from "@/ports"; } from "@/ports";
import { makeTerminalHandle } from "./terminal"; import { makeTerminalHandle } from "./terminal";
@ -63,14 +64,14 @@ export class TauriAgentGateway implements AgentGateway {
agentId: string, agentId: string,
nodeId: string, nodeId: string,
): Promise<LiveAgent> { ): Promise<LiveAgent> {
return invoke<LiveAgent[]>("attach_live_agent", { return invoke<LiveAgent>("attach_live_agent", {
request: { projectId, agentId, nodeId }, request: { projectId, agentId, nodeId },
}).then((list) => { });
const attached = list[0]; }
if (!attached) {
throw new Error(`running session for agent ${agentId} was not returned`); stopLiveAgent(projectId: string, agentId: string): Promise<StoppedLiveAgent> {
} return invoke<StoppedLiveAgent>("stop_live_agent", {
return attached; request: { projectId, agentId },
}); });
} }

View File

@ -61,6 +61,7 @@ import type {
ReattachResult, ReattachResult,
RemoteGateway, RemoteGateway,
SkillGateway, SkillGateway,
StoppedLiveAgent,
SystemGateway, SystemGateway,
TemplateGateway, TemplateGateway,
TerminalGateway, TerminalGateway,
@ -215,7 +216,8 @@ export class MockAgentGateway implements AgentGateway {
.map(([agentId, nodeId]) => ({ .map(([agentId, nodeId]) => ({
agentId, agentId,
nodeId, nodeId,
sessionId: this.liveSessionByAgent.get(agentId), sessionId: this.liveSessionByAgent.get(agentId)!,
kind: "pty" as const,
})); }));
} }
@ -256,7 +258,32 @@ export class MockAgentGateway implements AgentGateway {
throw err; throw err;
} }
this.liveByAgent.set(agentId, nodeId); this.liveByAgent.set(agentId, nodeId);
return { agentId, nodeId, sessionId }; return { agentId, nodeId, sessionId, kind: "pty" };
}
async stopLiveAgent(projectId: string, agentId: string): Promise<StoppedLiveAgent> {
const list = this.getAgents(projectId);
if (!list.some((a) => a.id === agentId)) {
const err: GatewayError = {
code: "NOT_FOUND",
message: `agent ${agentId} not found in project ${projectId}`,
};
throw err;
}
const sessionId = this.liveSessionByAgent.get(agentId);
if (!sessionId) {
const err: GatewayError = {
code: "NOT_FOUND",
message: `agent ${agentId} has no live session`,
};
throw err;
}
const session = this.sessions.get(sessionId);
if (session) session.closed = true;
this.sessions.delete(sessionId);
this.liveSessionByAgent.delete(agentId);
this.liveByAgent.delete(agentId);
return { agentId, sessionId, kind: "pty" };
} }
async createAgent(projectId: string, input: CreateAgentInput): Promise<Agent> { async createAgent(projectId: string, input: CreateAgentInput): Promise<Agent> {

View File

@ -103,7 +103,7 @@ describe("R0d — launch refused with AGENT_ALREADY_RUNNING", () => {
// The live set reports the agent already hosted in cell B (the host). // The live set reports the agent already hosted in cell B (the host).
vi.spyOn(agentGateway, "listLiveAgents").mockResolvedValue([ vi.spyOn(agentGateway, "listLiveAgents").mockResolvedValue([
{ agentId: agent.id, nodeId: bId, sessionId: "s-1" }, { agentId: agent.id, nodeId: bId, sessionId: "s-1", kind: "pty" },
]); ]);
// The launch from cell A is refused by the backend (singleton invariant). // The launch from cell A is refused by the backend (singleton invariant).
vi.spyOn(agentGateway, "launchAgent").mockRejectedValue({ vi.spyOn(agentGateway, "launchAgent").mockRejectedValue({

View File

@ -70,6 +70,7 @@ describe("singleton agent — mock gateway guard (T5)", () => {
agentId: a.id, agentId: a.id,
nodeId: "node-A", nodeId: "node-A",
sessionId: "mock-agent-session-1", sessionId: "mock-agent-session-1",
kind: "pty",
}, },
]); ]);
}); });
@ -146,6 +147,7 @@ describe("singleton agent — dropdown guard (T6)", () => {
agentId: a.id, agentId: a.id,
nodeId: leafId, nodeId: leafId,
sessionId: "mock-agent-session-1", sessionId: "mock-agent-session-1",
kind: "pty",
}, },
]); ]);
}); });
@ -156,7 +158,7 @@ describe("singleton agent — dropdown guard (T6)", () => {
const a = await agent.createAgent("p1", { name: "Busy", profileId: "p" }); const a = await agent.createAgent("p1", { name: "Busy", profileId: "p" });
vi.spyOn(agent, "listLiveAgents").mockResolvedValue([ vi.spyOn(agent, "listLiveAgents").mockResolvedValue([
{ agentId: a.id, nodeId: "some-other-node" }, { agentId: a.id, nodeId: "some-other-node" } as LiveAgent,
]); ]);
renderGrid(layout, agent); renderGrid(layout, agent);
@ -190,7 +192,7 @@ describe("singleton agent — dropdown guard (T6)", () => {
// The agent is live in THIS very cell (same node id as the leaf). // The agent is live in THIS very cell (same node id as the leaf).
vi.spyOn(agent, "listLiveAgents").mockResolvedValue([ vi.spyOn(agent, "listLiveAgents").mockResolvedValue([
{ agentId: a.id, nodeId: leafId }, { agentId: a.id, nodeId: leafId, sessionId: "s-own", kind: "pty" },
]); ]);
renderGrid(layout, agent); renderGrid(layout, agent);
@ -239,7 +241,7 @@ describe("R0d — dropdown disables agents live elsewhere + go-to-cell", () => {
// The agent is live in cell B (a currently-visible leaf). // The agent is live in cell B (a currently-visible leaf).
vi.spyOn(agent, "listLiveAgents").mockResolvedValue([ vi.spyOn(agent, "listLiveAgents").mockResolvedValue([
{ agentId: ag.id, nodeId: b, sessionId: "s-1" }, { agentId: ag.id, nodeId: b, sessionId: "s-1", kind: "pty" },
]); ]);
renderGrid(layout, agent); renderGrid(layout, agent);

View File

@ -3,12 +3,19 @@
* and idle/busy state from the backend read-model, plus the current input queue. * and idle/busy state from the backend read-model, plus the current input queue.
*/ */
import { useState } from "react";
import type { import type {
AgentTicketState, AgentTicketState,
AgentWorkState, AgentWorkState,
ConversationPreviewStatus, ConversationPreviewStatus,
ConversationWorkSummary, ConversationWorkSummary,
LeafCell,
} from "@/domain"; } from "@/domain";
import { useGateways } from "@/app/di";
import { leaves } from "@/features/layout/layout";
import { useLayout } from "@/features/layout/useLayout";
import type { LayoutViewModel } from "@/features/layout/useLayout";
import { Button, Panel, Spinner, cn } from "@/shared"; import { Button, Panel, Spinner, cn } from "@/shared";
import { useProjectWorkState } from "./useProjectWorkState"; import { useProjectWorkState } from "./useProjectWorkState";
@ -52,26 +59,99 @@ function summaryText(summary: ConversationWorkSummary): string | null {
return lastTurn ? `Last: ${lastTurn.textPreview}` : null; return lastTurn ? `Last: ${lastTurn.textPreview}` : null;
} }
function goToCell(nodeId: string): void {
if (typeof document === "undefined") return;
const el = document.querySelector<HTMLElement>(`[data-node-id="${nodeId}"]`);
if (!el) return;
el.scrollIntoView?.({ block: "nearest", inline: "nearest" });
const previous = el.style.outline;
el.style.outline = "2px solid var(--color-primary, #5b9bd5)";
window.setTimeout(() => {
el.style.outline = previous;
}, 1200);
}
async function copyToClipboard(text: string): Promise<void> {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return;
}
throw new Error("Clipboard unavailable");
}
function ConversationSummaryLine({ function ConversationSummaryLine({
summary, summary,
}: { }: {
summary: ConversationWorkSummary; summary: ConversationWorkSummary;
}) { }) {
const text = summaryText(summary); const text = summaryText(summary);
const [expanded, setExpanded] = useState(false);
const [copied, setCopied] = useState(false);
if (!text) return null; if (!text) return null;
return ( return (
<div className="mt-1 flex min-w-0 items-start gap-2 pl-1 text-xs text-muted"> <div className="mt-1 min-w-0 pl-1 text-xs text-muted">
<span <div className="flex min-w-0 items-start gap-2">
className={cn( <span
"mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium", className={cn(
summary.status === "ready" "mt-0.5 shrink-0 rounded-full px-1.5 py-0.5 font-medium",
? "bg-success/10 text-success" summary.status === "ready"
: "bg-raised text-muted", ? "bg-success/10 text-success"
)} : "bg-raised text-muted",
> )}
{summaryLabel(summary.status)} >
</span> {summaryLabel(summary.status)}
<span className="min-w-0 break-words">{text}</span> </span>
<span className="min-w-0 flex-1 break-words">{text}</span>
<button
type="button"
className="shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content"
onClick={() => setExpanded((v) => !v)}
>
{expanded ? "Hide" : "View"}
</button>
<button
type="button"
className="shrink-0 rounded px-1 py-0.5 text-[11px] text-muted hover:bg-raised hover:text-content disabled:opacity-50"
disabled={!text}
onClick={() => {
void copyToClipboard(text).then(() => {
setCopied(true);
window.setTimeout(() => setCopied(false), 1000);
});
}}
>
{copied ? "Copied" : "Copy"}
</button>
</div>
{expanded && (
<div
aria-label={`conversation ${summary.conversationId} details`}
className="mt-1 space-y-1 border-l border-border pl-2"
>
{summary.objectivePreview && (
<p>
<span className="font-medium text-content">Goal:</span>{" "}
{summary.objectivePreview}
</p>
)}
{summary.summaryPreview && (
<p>
<span className="font-medium text-content">Summary:</span>{" "}
{summary.summaryPreview}
</p>
)}
{summary.recentTurns.length > 0 && (
<ul className="space-y-0.5">
{summary.recentTurns.map((turn) => (
<li key={`${turn.atMs}-${turn.role}-${turn.textPreview}`}>
<span className="font-medium text-content">{turn.role}:</span>{" "}
{turn.textPreview}
</li>
))}
</ul>
)}
</div>
)}
</div> </div>
); );
} }
@ -127,13 +207,82 @@ function TicketRow({
function AgentRow({ function AgentRow({
agent, agent,
conversations, conversations,
visibleLeaves,
layout,
projectId,
onRefresh,
}: { }: {
agent: AgentWorkState; agent: AgentWorkState;
conversations: Map<string, ConversationWorkSummary>; conversations: Map<string, ConversationWorkSummary>;
visibleLeaves: LeafCell[];
layout: LayoutViewModel;
projectId: string;
onRefresh: () => Promise<void>;
}) { }) {
const { agent: agentGateway } = useGateways();
const [message, setMessage] = useState<string | null>(null);
const [actionBusy, setActionBusy] = useState(false);
const live = agent.live !== undefined; const live = agent.live !== undefined;
const busy = agent.busy.state === "busy"; const busy = agent.busy.state === "busy";
const tickets = [...agent.tickets].sort((a, b) => a.position - b.position); const tickets = [...agent.tickets].sort((a, b) => a.position - b.position);
const visibleNodeIds = new Set(visibleLeaves.map((leaf) => leaf.id));
const liveVisible = live && visibleNodeIds.has(agent.live!.nodeId);
const attachTarget = visibleLeaves.find((leaf) => !leaf.session && !leaf.agent);
const currentTurn =
busy || tickets.some((ticket) => ticket.status === "inProgress");
async function refreshAfterAction(): Promise<void> {
await onRefresh();
}
async function attach(): Promise<void> {
if (!agent.live || !attachTarget || !agentGateway?.attachLiveAgent) return;
setActionBusy(true);
setMessage(null);
try {
const attached = await agentGateway.attachLiveAgent(
projectId,
agent.agentId,
attachTarget.id,
);
await layout.attachLiveAgentToCell(
attachTarget.id,
agent.agentId,
attached.sessionId,
);
await refreshAfterAction();
goToCell(attachTarget.id);
} catch (e) {
setMessage(e instanceof Error ? e.message : String(e));
} finally {
setActionBusy(false);
}
}
async function stop(): Promise<void> {
if (!agent.live || !agentGateway?.stopLiveAgent) return;
const warning = currentTurn
? " The current turn will be interrupted."
: "";
if (!window.confirm(`Stop ${agent.name}?${warning}`)) return;
setActionBusy(true);
setMessage(null);
try {
const stopped = await agentGateway.stopLiveAgent(projectId, agent.agentId);
if (visibleNodeIds.has(agent.live.nodeId)) {
const leaf = visibleLeaves.find((candidate) => candidate.id === agent.live?.nodeId);
if (!leaf?.session || leaf.session === stopped.sessionId) {
await layout.setSession(agent.live.nodeId, null);
}
}
await refreshAfterAction();
} catch (e) {
setMessage(e instanceof Error ? e.message : String(e));
} finally {
setActionBusy(false);
}
}
return ( return (
<li className="py-2 first:pt-0 last:pb-0"> <li className="py-2 first:pt-0 last:pb-0">
<div className="flex items-center justify-between gap-3"> <div className="flex items-center justify-between gap-3">
@ -173,8 +322,52 @@ function AgentRow({
{shortTicket(agent.busy.ticket)} {shortTicket(agent.busy.ticket)}
</code> </code>
)} )}
{agent.live && liveVisible && (
<Button
size="sm"
variant="ghost"
onClick={() => goToCell(agent.live!.nodeId)}
>
Open
</Button>
)}
{agent.live && !liveVisible && (
<Button
size="sm"
variant="ghost"
disabled={!attachTarget || !agentGateway?.attachLiveAgent}
loading={actionBusy}
title={
attachTarget
? undefined
: "No empty visible cell available"
}
onClick={() => void attach()}
>
Attach
</Button>
)}
{agent.live && (
<Button
size="sm"
variant="danger"
loading={actionBusy}
disabled={!agentGateway?.stopLiveAgent}
onClick={() => void stop()}
>
Stop
</Button>
)}
</span> </span>
</div> </div>
{agent.live && !liveVisible && !attachTarget && (
<p className="mt-1 text-xs text-muted">No empty visible cell.</p>
)}
{message && (
<p role="alert" className="mt-1 text-xs text-danger">
{message}
</p>
)}
{tickets.length > 0 && ( {tickets.length > 0 && (
<ul <ul
aria-label={`${agent.name} tickets`} aria-label={`${agent.name} tickets`}
@ -195,7 +388,9 @@ function AgentRow({
export function ProjectWorkStatePanel({ projectId }: ProjectWorkStatePanelProps) { export function ProjectWorkStatePanel({ projectId }: ProjectWorkStatePanelProps) {
const vm = useProjectWorkState(projectId); const vm = useProjectWorkState(projectId);
const layoutVm = useLayout(projectId);
const agents = vm.state?.agents ?? []; const agents = vm.state?.agents ?? [];
const visibleLeaves = layoutVm.layout ? leaves(layoutVm.layout) : [];
const conversations = new Map( const conversations = new Map(
(vm.state?.conversations ?? []).map((summary) => [ (vm.state?.conversations ?? []).map((summary) => [
summary.conversationId, summary.conversationId,
@ -239,6 +434,10 @@ export function ProjectWorkStatePanel({ projectId }: ProjectWorkStatePanelProps)
key={agent.agentId} key={agent.agentId}
agent={agent} agent={agent}
conversations={conversations} conversations={conversations}
visibleLeaves={visibleLeaves}
layout={layoutVm}
projectId={projectId}
onRefresh={vm.refresh}
/> />
))} ))}
</ul> </ul>

View File

@ -1,8 +1,14 @@
import { describe, it, expect, vi } from "vitest"; import { describe, it, expect, vi } from "vitest";
import { render, screen, waitFor, within } from "@testing-library/react"; import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { DIProvider } from "@/app/di"; import { DIProvider } from "@/app/di";
import { MockSystemGateway, MockWorkStateGateway } from "@/adapters/mock"; import {
MockAgentGateway,
MockLayoutGateway,
MockSystemGateway,
MockWorkStateGateway,
} from "@/adapters/mock";
import { leaves } from "@/features/layout/layout";
import type { Gateways } from "@/ports"; import type { Gateways } from "@/ports";
import { ProjectWorkStatePanel } from "./ProjectWorkStatePanel"; import { ProjectWorkStatePanel } from "./ProjectWorkStatePanel";
@ -11,8 +17,9 @@ const PROJECT_ID = "project-work-state-test";
function renderPanel( function renderPanel(
workState: MockWorkStateGateway = new MockWorkStateGateway(), workState: MockWorkStateGateway = new MockWorkStateGateway(),
system: MockSystemGateway = new MockSystemGateway(), system: MockSystemGateway = new MockSystemGateway(),
overrides: Partial<Gateways> = {},
) { ) {
const gateways = { workState, system } as unknown as Gateways; const gateways = { workState, system, ...overrides } as unknown as Gateways;
return { return {
workState, workState,
system, system,
@ -411,4 +418,311 @@ describe("ProjectWorkStatePanel", () => {
expect(screen.getByText("#1 In progress")).toBeTruthy(); expect(screen.getByText("#1 In progress")).toBeTruthy();
await waitFor(() => expect(spy).toHaveBeenCalled()); await waitFor(() => expect(spy).toHaveBeenCalled());
}); });
it("Open focuses a visible live cell and does not launch", async () => {
const workState = new MockWorkStateGateway();
const layout = new MockLayoutGateway();
const agent = new MockAgentGateway();
const leafId = leaves(await layout.loadLayout(PROJECT_ID))[0].id;
const host = document.createElement("div");
host.dataset.nodeId = leafId;
document.body.appendChild(host);
const launchSpy = vi.spyOn(agent, "launchAgent");
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: "agent-open",
name: "Visible",
profileId: "codex",
live: { nodeId: leafId, sessionId: "session-open", kind: "pty" },
busy: { state: "idle" },
tickets: [],
},
],
conversations: [],
});
renderPanel(workState, new MockSystemGateway(), { layout, agent });
fireEvent.click(await screen.findByRole("button", { name: "Open" }));
expect(host.style.outline).toContain("2px solid");
expect(launchSpy).not.toHaveBeenCalled();
host.remove();
});
it("Attach rebinds a hidden live agent to the deterministic empty cell", async () => {
const workState = new MockWorkStateGateway();
const layout = new MockLayoutGateway();
const agent = new MockAgentGateway();
const created = await agent.createAgent(PROJECT_ID, {
name: "Hidden",
profileId: "codex",
});
await agent.launchAgent(
PROJECT_ID,
created.id,
{ cwd: "/x", rows: 24, cols: 80, nodeId: "hidden-node" },
() => {},
);
const attachSpy = vi.spyOn(agent, "attachLiveAgent");
const launchSpy = vi.spyOn(agent, "launchAgent");
const target = leaves(await layout.loadLayout(PROJECT_ID))[0].id;
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: created.id,
name: "Hidden",
profileId: "codex",
live: { nodeId: "hidden-node", sessionId: "mock-agent-session-1", kind: "pty" },
busy: { state: "idle" },
tickets: [],
},
],
conversations: [],
});
renderPanel(workState, new MockSystemGateway(), { layout, agent });
const attach = await screen.findByRole("button", { name: "Attach" });
await waitFor(() => expect((attach as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(attach);
await waitFor(() =>
expect(attachSpy).toHaveBeenCalledWith(PROJECT_ID, created.id, target),
);
await waitFor(async () => {
const leaf = leaves(await layout.loadLayout(PROJECT_ID))[0];
expect(leaf.agent).toBe(created.id);
expect(leaf.session).toBe("mock-agent-session-1");
});
expect(launchSpy).not.toHaveBeenCalled();
});
it("disables Attach when no visible target cell exists", async () => {
const workState = new MockWorkStateGateway();
const layout = new MockLayoutGateway();
const leafId = leaves(await layout.loadLayout(PROJECT_ID))[0].id;
await layout.mutateLayout(PROJECT_ID, {
type: "setCellAgent",
target: leafId,
agent: "other-agent",
});
await layout.mutateLayout(PROJECT_ID, {
type: "setSession",
target: leafId,
session: "occupied-session",
});
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: "agent-hidden",
name: "Hidden",
profileId: "codex",
live: { nodeId: "hidden-node", sessionId: "session-hidden", kind: "pty" },
busy: { state: "idle" },
tickets: [],
},
],
conversations: [],
});
renderPanel(workState, new MockSystemGateway(), {
layout,
agent: new MockAgentGateway(),
});
const attach = await screen.findByRole("button", { name: "Attach" });
await waitFor(() => expect((attach as HTMLButtonElement).disabled).toBe(true));
expect(await screen.findByText("No empty visible cell.")).toBeTruthy();
});
it("Stop confirms with a busy warning, stops the live agent, and refreshes Work", async () => {
const workState = new MockWorkStateGateway();
const layout = new MockLayoutGateway();
const agent = new MockAgentGateway();
const created = await agent.createAgent(PROJECT_ID, {
name: "Runner",
profileId: "codex",
});
const leafId = leaves(await layout.loadLayout(PROJECT_ID))[0].id;
await agent.launchAgent(
PROJECT_ID,
created.id,
{ cwd: "/x", rows: 24, cols: 80, nodeId: leafId },
() => {},
);
await layout.mutateLayout(PROJECT_ID, {
type: "setCellAgent",
target: leafId,
agent: created.id,
});
await layout.mutateLayout(PROJECT_ID, {
type: "setSession",
target: leafId,
session: "mock-agent-session-1",
});
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: created.id,
name: "Runner",
profileId: "codex",
live: { nodeId: leafId, sessionId: "mock-agent-session-1", kind: "pty" },
busy: { state: "busy", ticket: "ticket-stop", sinceMs: 1 },
tickets: [
{
ticketId: "ticket-stop",
conversationId: "conv-stop",
position: 0,
status: "inProgress",
source: { kind: "human" },
requesterLabel: "Human",
taskPreview: "Do work",
taskLen: 7,
},
],
},
],
conversations: [],
});
const stopSpy = vi.spyOn(agent, "stopLiveAgent");
const refreshSpy = vi.spyOn(workState, "getProjectWorkState");
const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);
renderPanel(workState, new MockSystemGateway(), { layout, agent });
fireEvent.click(await screen.findByRole("button", { name: "Stop" }));
await waitFor(() =>
expect(confirmSpy).toHaveBeenCalledWith(
"Stop Runner? The current turn will be interrupted.",
),
);
await waitFor(() => expect(stopSpy).toHaveBeenCalledWith(PROJECT_ID, created.id));
await waitFor(() => expect(refreshSpy).toHaveBeenCalled());
await waitFor(async () => {
const leaf = leaves(await layout.loadLayout(PROJECT_ID))[0];
expect(leaf.session).toBeNull();
});
confirmSpy.mockRestore();
});
it("View conversation exposes only Lot C preview fields", async () => {
const workState = new MockWorkStateGateway();
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: "agent-view",
name: "Viewer",
profileId: "codex",
busy: { state: "idle" },
tickets: [
{
ticketId: "ticket-view",
conversationId: "conversation-view",
position: 0,
status: "queued",
source: { kind: "human" },
requesterLabel: "Human",
taskPreview: "Inspect preview",
taskLen: 15,
},
],
},
],
conversations: [
{
conversationId: "conversation-view",
status: "ready",
objectivePreview: "Keep it compact",
summaryPreview: "Only the exposed summary preview.",
summaryLen: 33,
upTo: "internal-turn-id",
recentTurns: [
{
role: "response",
source: { kind: "agent", agentId: "agent-view" },
atMs: 42,
textPreview: "Recent exposed turn.",
textLen: 20,
},
],
},
],
});
renderPanel(workState);
const list = await screen.findByLabelText("Viewer tickets");
fireEvent.click(within(list).getByRole("button", { name: "View" }));
expect(within(list).getByText("Goal:")).toBeTruthy();
expect(within(list).getByText("Keep it compact")).toBeTruthy();
expect(within(list).getByText("Summary:")).toBeTruthy();
expect(
within(list).getByText("Only the exposed summary preview."),
).toBeTruthy();
expect(within(list).getByText("response:")).toBeTruthy();
expect(within(list).getByText("Recent exposed turn.")).toBeTruthy();
expect(list.textContent).not.toContain("internal-turn-id");
});
it("Copy summary copies only the exposed preview text", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", { clipboard: { writeText } });
const workState = new MockWorkStateGateway();
workState._setProjectWorkState(PROJECT_ID, {
agents: [
{
agentId: "agent-copy",
name: "Copier",
profileId: "codex",
busy: { state: "idle" },
tickets: [
{
ticketId: "ticket-copy",
conversationId: "conversation-copy",
position: 0,
status: "queued",
source: { kind: "human" },
requesterLabel: "Human",
taskPreview: "Copy preview",
taskLen: 12,
},
],
},
],
conversations: [
{
conversationId: "conversation-copy",
status: "ready",
objectivePreview: null,
summaryPreview: "Copy this summary preview only.",
summaryLen: 31,
upTo: null,
recentTurns: [
{
role: "prompt",
source: { kind: "human" },
atMs: 1,
textPreview: "Do not copy this turn.",
textLen: 22,
},
],
},
],
});
renderPanel(workState);
const list = await screen.findByLabelText("Copier tickets");
fireEvent.click(within(list).getByRole("button", { name: "Copy" }));
await waitFor(() =>
expect(writeText).toHaveBeenCalledWith("Copy this summary preview only."),
);
expect(await within(list).findByRole("button", { name: "Copied" })).toBeTruthy();
vi.unstubAllGlobals();
});
}); });

View File

@ -108,6 +108,11 @@ export interface AgentGateway {
agentId: string, agentId: string,
nodeId: string, nodeId: string,
): Promise<LiveAgent>; ): Promise<LiveAgent>;
/**
* Stops an already-live agent session without going through terminal teardown
* commands from the Work panel. The backend owns the live-agent lifecycle.
*/
stopLiveAgent?(projectId: string, agentId: string): Promise<StoppedLiveAgent>;
/** Creates a new agent from scratch; returns the created agent. */ /** Creates a new agent from scratch; returns the created agent. */
createAgent(projectId: string, input: CreateAgentInput): Promise<Agent>; createAgent(projectId: string, input: CreateAgentInput): Promise<Agent>;
/** /**
@ -205,7 +210,16 @@ export interface LiveAgent {
* The live PTY session id, when the backend exposes it. Required for opening * The live PTY session id, when the backend exposes it. Required for opening
* a background/running agent in a new visible cell without respawning it. * a background/running agent in a new visible cell without respawning it.
*/ */
sessionId?: string; sessionId: string;
/** Runtime kind backing the live agent. */
kind: "pty" | "structured";
}
/** Result returned when the backend stops a live agent. */
export interface StoppedLiveAgent {
agentId: string;
sessionId: string;
kind: "pty" | "structured";
} }
/** /**