From dedddb60e1386365f56c00846bfe0d447377767c Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 16:49:45 +0200 Subject: [PATCH 01/19] feat(ai): wire OpenAI provider to the new server-orchestrated agent loop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AIService.ts gains chatAgentTurn/resumeAgentTurn, talking to the new POST /api/orgs/:orgId/ai/chat (+ /tool-result) SSE endpoints — separate from the existing chatOpenAICompatible/chatGemini regex-based paths, which keep working unchanged for mistral/gemini/custom/local until Phase 3 migrates them too. OrgAI.vue: sendMessage branches to sendMessageViaAgent() when the org's provider is 'openai'. consumeAgentStream() turns the new SSE event vocabulary (text/tool_call_result/tool_call_pending/ tool_call_client_required/done/error) into message bubbles; handleAgentToolDecision() answers a paused tool call — for a server-mutating tool it just posts {accepted}, for a 'client' tool (search_messages/create_thread/read_documentation/request_image_upload, extracted into executeClientTool()) it actually runs the existing client-side logic first and posts the real result. Session persistence for this path lives entirely server-side now; syncSession is only reached by the untouched legacy path. Co-Authored-By: Claude Sonnet 5 --- src/services/AIService.ts | 66 +++++++++ src/views/OrgSpace/views/OrgAI.vue | 218 ++++++++++++++++++++++++++++- 2 files changed, 280 insertions(+), 4 deletions(-) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index f9a9c5a2..70a7accd 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -44,6 +44,72 @@ export class AIService { return this.chatOpenAICompatible(messages); } + /** + * Nouvelle boucle d'agent serveur (provider OpenAI, cf. refonte Synco AI) : le backend possède + * la conversation et exécute lui-même les tools 'server' — contrairement à chat()/chatOpenAICompatible + * ci-dessous qui restent l'ancien parseur regex côté client pour les autres providers. + */ + public async *chatAgentTurn(orgId: string, sessionId: string | null, message: string): AsyncGenerator { + this.abortController = new AbortController(); + + const response = await sfetch(`/api/orgs/${orgId}/ai/chat`, { + method: 'POST', + body: JSON.stringify({ sessionId: sessionId || undefined, message }), + signal: this.abortController.signal, + }); + + if (!response.ok) { + const err = await response.text().catch(() => ''); + throw new Error(`Erreur agent IA (${response.status}): ${err}`); + } + + yield* this.parseAgentEventStream(response.body); + } + + public async *resumeAgentTurn(orgId: string, sessionId: string, decision: { accepted?: boolean; clientResult?: any }): AsyncGenerator { + this.abortController = new AbortController(); + + const response = await sfetch(`/api/orgs/${orgId}/ai/chat/${sessionId}/tool-result`, { + method: 'POST', + body: JSON.stringify(decision), + signal: this.abortController.signal, + }); + + if (!response.ok) { + const err = await response.text().catch(() => ''); + throw new Error(`Erreur agent IA (${response.status}): ${err}`); + } + + yield* this.parseAgentEventStream(response.body); + } + + private async *parseAgentEventStream(body: ReadableStream | null): AsyncGenerator { + if (!body) throw new Error('Réponse vide du serveur.'); + + const reader = body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() || ''; + + for (const chunk of chunks) { + const line = chunk.split('\n').find((l) => l.startsWith('data:')); + if (!line) continue; + try { + yield JSON.parse(line.slice(5).trim()); + } catch { + // ignore malformed lines + } + } + } + } + public interrupt() { if (this.isLocal) { localLLM.interrupt(); diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index 380a48d3..032f4c62 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -84,13 +84,18 @@
- -
@@ -101,8 +106,12 @@
Action acceptée et exécutée.
+
Action exécutée.
Action refusée.
+
Erreur lors de l'exécution.
{ interface ChatMessage { role: 'user' | 'assistant' | 'system' | 'tool'; content: string; - tool_call?: { name: string; arguments: string; status: 'pending' | 'accepted' | 'rejected' | 'executing' }; + tool_call?: { + toolCallId?: string; + name: string; + arguments: string; + status: 'pending' | 'accepted' | 'rejected' | 'executing' | 'done' | 'error'; + category?: 'server' | 'client'; + mutating?: boolean; + interactive?: boolean; + result?: any; + }; tool_data?: any; + /** true si ce message vient de la nouvelle boucle d'agent serveur (provider OpenAI) plutôt que + * de l'ancien parseur regex — détermine quel gestionnaire de tool utiliser. */ + viaAgentLoop?: boolean; } const recommendedModelId = ref(''); @@ -745,6 +766,187 @@ const handleToolCall = async (toolCall: NonNullable, a } }; +/** + * Consomme le flux SSE de la nouvelle boucle d'agent serveur (aiChatTurn/resumeAgentTurn) et + * met à jour les bulles de messages en conséquence. getIndex/setIndex permettent d'ouvrir une + * nouvelle bulle après un tool auto-exécuté, tout en gardant le rendu du tool sur la bulle d'origine. + */ +const consumeAgentStream = async ( + generator: AsyncGenerator, + getIndex: () => number, + setIndex: (i: number) => void +) => { + for await (const ev of generator) { + if (!isGenerating.value) break; + const idx = getIndex(); + if (!messages.value[idx]) break; + + if (ev.type === 'session') { + if (activeSessionId.value !== ev.sessionId) { + activeSessionId.value = ev.sessionId; + fetchSessions(); + } + } else if (ev.type === 'text') { + messages.value[idx]!.content += ev.delta; + } else if (ev.type === 'tool_call_result') { + messages.value[idx]!.tool_call = { + toolCallId: ev.toolCallId, name: ev.name, arguments: '', status: 'done', + category: 'server', mutating: false, result: ev.result + }; + const newIdx = messages.value.length; + messages.value.push({ role: 'assistant', content: '', viaAgentLoop: true }); + setIndex(newIdx); + } else if (ev.type === 'tool_call_pending') { + messages.value[idx]!.tool_call = { + toolCallId: ev.toolCallId, name: ev.name, arguments: JSON.stringify(ev.args), + status: 'pending', category: 'server', mutating: true + }; + } else if (ev.type === 'tool_call_client_required') { + const toolCall: ChatMessage['tool_call'] = { + toolCallId: ev.toolCallId, name: ev.name, arguments: JSON.stringify(ev.args), + status: (ev.mutating || ev.interactive) ? 'pending' : 'executing', + category: 'client', mutating: ev.mutating, interactive: ev.interactive + }; + messages.value[idx]!.tool_call = toolCall; + if (!ev.mutating && !ev.interactive) { + // Tool client non-mutant (ex: search_messages) : exécution immédiate, sans confirmation. + await handleAgentToolDecision(toolCall!, true, idx); + return; + } + } else if (ev.type === 'done') { + isGenerating.value = false; + } else if (ev.type === 'error') { + messages.value[idx]!.content += `\n\n**Erreur:** ${ev.error}`; + isGenerating.value = false; + } + + await scrollToBottom(); + } +}; + +/** Exécute côté client les tools de catégorie 'client' (contenu E2EE réel ou cérémonie de clé). */ +const executeClientTool = async (name: string, args: any, imageId?: string): Promise => { + const orgId = route.params.orgId as string; + + if (name === 'search_messages') { + const org = openedOrg.value; + if (org && org.spaces && privateKey.value) { + for (const space of org.spaces) { + await SearchSyncService.restoreWorkspaceIndexes(space.id, toRaw(privateKey.value)); + } + } + const query = args.query; + const workerId = Date.now().toString(); + const vector = await new Promise((resolve, reject) => { + const handler = (e: MessageEvent) => { + if (e.data.id === workerId && e.data.status === 'complete') { + globalVectorWorker.removeEventListener('message', handler); + resolve(e.data.vector); + } else if (e.data.id === workerId && e.data.status === 'error') { + globalVectorWorker.removeEventListener('message', handler); + reject(new Error(e.data.error)); + } + }; + globalVectorWorker.addEventListener('message', handler); + globalVectorWorker.postMessage({ id: workerId, text: query, type: 'SEARCH' }); + }); + const searchResults = await localSearchDB.searchByVector(vector, query, undefined, 5); + return { query, results: searchResults }; + } + + if (name === 'create_thread') { + const threads = args.threads || []; + if (threads.length === 0) throw new Error('Aucun salon spécifié.'); + const created = []; + for (const t of threads) { + created.push(await createThreadHelper(orgId, t.spaceId, t.name, t.type)); + } + return { threads: created }; + } + + if (name === 'read_documentation') { + const docFiles = import.meta.glob('../../../../../doc/*.md', { query: '?raw', import: 'default', eager: true }); + let fullDoc = '# Documentation de Synco\n\n'; + for (const [path, content] of Object.entries(docFiles)) { + const fileName = path.split('/').pop()?.replace('.md', '') || path; + fullDoc += `## Chapitre : ${fileName}\n\n${content}\n\n---\n\n`; + } + return { content: fullDoc }; + } + + if (name === 'request_image_upload') { + return { id: imageId, note: `Utilise EXACTEMENT '${imageId}' pour le paramètre 'logo' de create_space.` }; + } + + throw new Error(`Outil client inconnu: ${name}`); +}; + +/** Accepte/refuse un tool_call posé par la nouvelle boucle d'agent serveur, puis reprend le flux. */ +const handleAgentToolDecision = async ( + toolCall: NonNullable, + accept: boolean, + assistantMsgIndex: number, + imageId?: string +) => { + const orgId = route.params.orgId as string; + const sessionId = activeSessionId.value; + if (!sessionId || !toolCall.toolCallId) return; + + toolCall.status = 'executing'; + + let decision: { accepted?: boolean; clientResult?: any }; + + if (toolCall.category === 'client') { + if (!accept) { + decision = { clientResult: { error: "Action refusée par l'utilisateur." } }; + } else { + try { + const args = typeof toolCall.arguments === 'string' ? JSON.parse(toolCall.arguments || '{}') : toolCall.arguments; + decision = { clientResult: await executeClientTool(toolCall.name, args, imageId) }; + } catch (e: any) { + decision = { clientResult: { error: e.message || 'Erreur technique.' } }; + } + } + } else { + decision = { accepted: accept }; + } + + isGenerating.value = true; + await scrollToBottom(); + try { + let idx = assistantMsgIndex; + const generator = aiService.resumeAgentTurn(orgId, sessionId, decision); + await consumeAgentStream(generator, () => idx, (i) => { idx = i; }); + } catch (e: any) { + if (messages.value[assistantMsgIndex]) messages.value[assistantMsgIndex]!.content += `\n\n**Erreur:** ${e.message}`; + } finally { + isGenerating.value = false; + } +}; + +/** Provider OpenAI : la conversation passe entièrement par la boucle d'agent serveur. */ +const sendMessageViaAgent = async (text: string) => { + const orgId = route.params.orgId as string; + messages.value.push({ role: 'user', content: text }); + const assistantMsgIndex = messages.value.length; + messages.value.push({ role: 'assistant', content: '', viaAgentLoop: true }); + + isGenerating.value = true; + await scrollToBottom(); + + try { + let idx = assistantMsgIndex; + const generator = aiService.chatAgentTurn(orgId, activeSessionId.value, text); + await consumeAgentStream(generator, () => idx, (i) => { idx = i; }); + } catch (error: any) { + if (error.message !== 'USER_STOPPED' && !String(error).includes('USER_STOPPED')) { + messages.value[assistantMsgIndex]!.content += `\n\n**Erreur:** ${error.message}`; + } + } finally { + isGenerating.value = false; + } +}; + const sendMessage = async (hiddenPrompt?: string) => { if (isGenerating.value) { stopGeneration(); @@ -756,6 +958,14 @@ const sendMessage = async (hiddenPrompt?: string) => { if (!hiddenPrompt) { inputMsg.value = ''; + } + + if (!hiddenPrompt && aiService.config.provider === 'openai') { + await sendMessageViaAgent(text); + return; + } + + if (!hiddenPrompt) { messages.value.push({ role: 'user', content: text }); } From bf33e726c3196632ecfde94896a333544cd0557c Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 17:06:21 +0200 Subject: [PATCH 02/19] feat(ai): Claude-like turn UI with a connected tool-step timeline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the one-tool-call-per-bubble hack from the earlier agent loop integration with a proper structured-turn model: each assistant turn (OpenAI/Mistral/Gemini path) is a single message holding interleaved text/tool parts in arrival order, exactly like a real Claude turn — text, then a tool step, then more text, all in one continuous block instead of spawning a new bubble per tool call. New components (src/views/OrgSpace/components/ai/): - AgentTurn.vue: renders a turn's parts, markdown text via the shared MarkdownRender.vue, tool parts via ToolStepItem. - ToolStepItem.vue: the connected-dot/line timeline look (grey outline pending, pulsing primary while executing, filled primary when done, red on error/reject), collapsed by default, accept/refuse inline for mutating tools, dedicated slot for the interactive image-upload tool. - ToolResultBody.vue: per-tool result rendering — search_messages reuses ThreadMessage.vue so results look and behave like real messages, with a teleport-to-thread button; create_task/create_space/ create_thread get clickable cards; list_* tools get a plain list; everything else falls back to a readable JSON dump. OrgAI.vue: user bubbles stay bubbles, but assistant turns are now full-width (no boxed/mono chat-bubble look) for both the new structured path and the legacy per-provider-migration path (local/ custom), which keeps its existing single tool_call widget untouched functionally, just visually aligned with the new full-width style. Co-Authored-By: Claude Sonnet 5 --- .../OrgSpace/components/ai/AgentTurn.vue | 52 +++++++ .../OrgSpace/components/ai/ToolResultBody.vue | 141 +++++++++++++++++ .../OrgSpace/components/ai/ToolStepItem.vue | 88 +++++++++++ .../OrgSpace/components/ai/agentTypes.ts | 39 +++++ src/views/OrgSpace/views/OrgAI.vue | 142 +++++++++++------- 5 files changed, 405 insertions(+), 57 deletions(-) create mode 100644 src/views/OrgSpace/components/ai/AgentTurn.vue create mode 100644 src/views/OrgSpace/components/ai/ToolResultBody.vue create mode 100644 src/views/OrgSpace/components/ai/ToolStepItem.vue create mode 100644 src/views/OrgSpace/components/ai/agentTypes.ts diff --git a/src/views/OrgSpace/components/ai/AgentTurn.vue b/src/views/OrgSpace/components/ai/AgentTurn.vue new file mode 100644 index 00000000..cbcbb707 --- /dev/null +++ b/src/views/OrgSpace/components/ai/AgentTurn.vue @@ -0,0 +1,52 @@ + + + diff --git a/src/views/OrgSpace/components/ai/ToolResultBody.vue b/src/views/OrgSpace/components/ai/ToolResultBody.vue new file mode 100644 index 00000000..cf9137a3 --- /dev/null +++ b/src/views/OrgSpace/components/ai/ToolResultBody.vue @@ -0,0 +1,141 @@ + + + diff --git a/src/views/OrgSpace/components/ai/ToolStepItem.vue b/src/views/OrgSpace/components/ai/ToolStepItem.vue new file mode 100644 index 00000000..8af69aac --- /dev/null +++ b/src/views/OrgSpace/components/ai/ToolStepItem.vue @@ -0,0 +1,88 @@ + + + diff --git a/src/views/OrgSpace/components/ai/agentTypes.ts b/src/views/OrgSpace/components/ai/agentTypes.ts new file mode 100644 index 00000000..6f260bdb --- /dev/null +++ b/src/views/OrgSpace/components/ai/agentTypes.ts @@ -0,0 +1,39 @@ +export type ToolStepStatus = 'pending' | 'executing' | 'done' | 'rejected' | 'error'; + +export interface ToolStep { + toolCallId: string; + name: string; + args?: any; + status: ToolStepStatus; + category?: 'server' | 'client'; + mutating?: boolean; + interactive?: boolean; + result?: any; +} + +export type TurnPart = + | { type: 'text'; text: string } + | { type: 'tool'; tool: ToolStep }; + +/** Libellés/icônes français par tool — utilisés par ToolStepItem pour l'affichage replié. */ +export const TOOL_LABELS: Record = { + create_space: { label: 'Création d\'un espace', icon: 'bi-folder-plus' }, + create_task: { label: "Création d'une tâche", icon: 'bi-check2-square' }, + update_task: { label: "Modification d'une tâche", icon: 'bi-pencil-square' }, + complete_task: { label: 'Tâche marquée terminée', icon: 'bi-check2-circle' }, + delete_task: { label: "Suppression d'une tâche", icon: 'bi-trash' }, + update_space: { label: "Modification d'un espace", icon: 'bi-pencil-square' }, + create_thread: { label: 'Création de salon(s)', icon: 'bi-hash' }, + search_messages: { label: 'Recherche dans les messages', icon: 'bi-search' }, + read_documentation: { label: 'Consultation de la documentation', icon: 'bi-book' }, + read_tasks: { label: 'Lecture des tâches', icon: 'bi-list-check' }, + get_task: { label: "Lecture d'une tâche", icon: 'bi-card-checklist' }, + list_spaces: { label: 'Liste des espaces', icon: 'bi-grid-3x3-gap' }, + list_threads: { label: 'Liste des salons', icon: 'bi-collection' }, + list_members: { label: "Liste des membres", icon: 'bi-people' }, + request_image_upload: { label: "Sélection d'une image", icon: 'bi-image' }, +}; + +export function toolLabel(name: string) { + return TOOL_LABELS[name] || { label: name, icon: 'bi-wrench-adjustable-circle' }; +} diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index 032f4c62..d7f3ef66 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -36,22 +36,40 @@
-
-
- - {{ msg.role === 'user' ? 'Vous' : 'Synco AI' }} -
+ + +
+
+
+ + +
+ +
+ + +
-
-
-
-
+
+
+
+
- -
+ +
@@ -84,18 +102,15 @@
@@ -106,12 +121,8 @@
Action acceptée et exécutée.
-
Action exécutée.
Action refusée.
-
Erreur lors de l'exécution.
- - -
@@ -358,6 +366,8 @@ import ThreadMessage from '../components/common/ThreadMessage.vue'; import TaskDetailsModal from '../components/popup/TaskDetailsModal.vue'; import MobileBackBtn from '@/components/common/MobileBackBtn.vue'; import IconSelector from '@/components/common/IconSelector.vue'; +import AgentTurn from '../components/ai/AgentTurn.vue'; +import type { TurnPart, ToolStep } from '../components/ai/agentTypes'; import { useUsersBar } from '@/composables/useUsersBar'; import useSettingsItem from '@/composables/useSettingsItem'; import { useRoute, useRouter } from 'vue-router'; @@ -431,9 +441,14 @@ interface ChatMessage { result?: any; }; tool_data?: any; - /** true si ce message vient de la nouvelle boucle d'agent serveur (provider OpenAI) plutôt que - * de l'ancien parseur regex — détermine quel gestionnaire de tool utiliser. */ + /** + * true si ce message vient de la nouvelle boucle d'agent serveur (providers OpenAI/Mistral/ + * Gemini) plutôt que de l'ancien parseur regex — détermine quel gestionnaire de tool utiliser + * ET quel rendu appliquer (parts structurées vs. widget tool_call unique historique). + */ viaAgentLoop?: boolean; + /** Uniquement pour viaAgentLoop : texte et tools entrelacés dans l'ordre d'arrivée. */ + parts?: TurnPart[]; } const recommendedModelId = ref(''); @@ -766,10 +781,31 @@ const handleToolCall = async (toolCall: NonNullable, a } }; +/** Ajoute du texte au dernier segment 'text' de la turn, ou en ouvre un nouveau si le dernier segment est un tool. */ +const appendTextPart = (idx: number, delta: string) => { + const parts = messages.value[idx]!.parts!; + const last = parts[parts.length - 1]; + if (last && last.type === 'text') last.text += delta; + else parts.push({ type: 'text', text: delta }); +}; + +/** Met à jour le tool_call déjà présent dans la turn (par id), ou en ajoute un nouveau segment. */ +const upsertToolPart = (idx: number, toolCallId: string, patch: Partial & { name: string }) => { + const parts = messages.value[idx]!.parts!; + const existing = parts.find((p) => p.type === 'tool' && p.tool.toolCallId === toolCallId) as { type: 'tool'; tool: ToolStep } | undefined; + if (existing) { + Object.assign(existing.tool, patch); + } else { + parts.push({ type: 'tool', tool: { toolCallId, status: 'pending', ...patch } }); + } +}; + /** - * Consomme le flux SSE de la nouvelle boucle d'agent serveur (aiChatTurn/resumeAgentTurn) et - * met à jour les bulles de messages en conséquence. getIndex/setIndex permettent d'ouvrir une - * nouvelle bulle après un tool auto-exécuté, tout en gardant le rendu du tool sur la bulle d'origine. + * Consomme le flux SSE de la nouvelle boucle d'agent serveur (chatAgentTurn/resumeAgentTurn) et + * alimente les parts (texte + tools entrelacés) de la turn en cours. getIndex/setIndex existent + * pour compatibilité mais pointent désormais toujours vers LA MÊME turn : contrairement à l'ancien + * modèle une bulle par tool, tout le tour (texte + tools + texte...) reste dans un seul message, + * comme le fait réellement Claude. */ const consumeAgentStream = async ( generator: AsyncGenerator, @@ -787,36 +823,28 @@ const consumeAgentStream = async ( fetchSessions(); } } else if (ev.type === 'text') { - messages.value[idx]!.content += ev.delta; + appendTextPart(idx, ev.delta); } else if (ev.type === 'tool_call_result') { - messages.value[idx]!.tool_call = { - toolCallId: ev.toolCallId, name: ev.name, arguments: '', status: 'done', - category: 'server', mutating: false, result: ev.result - }; - const newIdx = messages.value.length; - messages.value.push({ role: 'assistant', content: '', viaAgentLoop: true }); - setIndex(newIdx); + upsertToolPart(idx, ev.toolCallId, { name: ev.name, status: 'done', category: 'server', mutating: false, result: ev.result }); } else if (ev.type === 'tool_call_pending') { - messages.value[idx]!.tool_call = { - toolCallId: ev.toolCallId, name: ev.name, arguments: JSON.stringify(ev.args), - status: 'pending', category: 'server', mutating: true - }; + upsertToolPart(idx, ev.toolCallId, { name: ev.name, args: ev.args, status: 'pending', category: 'server', mutating: true }); } else if (ev.type === 'tool_call_client_required') { - const toolCall: ChatMessage['tool_call'] = { - toolCallId: ev.toolCallId, name: ev.name, arguments: JSON.stringify(ev.args), + upsertToolPart(idx, ev.toolCallId, { + name: ev.name, args: ev.args, status: (ev.mutating || ev.interactive) ? 'pending' : 'executing', - category: 'client', mutating: ev.mutating, interactive: ev.interactive - }; - messages.value[idx]!.tool_call = toolCall; + category: 'client', mutating: ev.mutating, interactive: ev.interactive, + }); if (!ev.mutating && !ev.interactive) { // Tool client non-mutant (ex: search_messages) : exécution immédiate, sans confirmation. - await handleAgentToolDecision(toolCall!, true, idx); + const parts = messages.value[idx]!.parts!; + const tool = (parts.find((p) => p.type === 'tool' && p.tool.toolCallId === ev.toolCallId) as { type: 'tool'; tool: ToolStep }).tool; + await handleAgentToolDecision(tool, true, idx); return; } } else if (ev.type === 'done') { isGenerating.value = false; } else if (ev.type === 'error') { - messages.value[idx]!.content += `\n\n**Erreur:** ${ev.error}`; + appendTextPart(idx, `\n\n**Erreur:** ${ev.error}`); isGenerating.value = false; } @@ -881,9 +909,9 @@ const executeClientTool = async (name: string, args: any, imageId?: string): Pro throw new Error(`Outil client inconnu: ${name}`); }; -/** Accepte/refuse un tool_call posé par la nouvelle boucle d'agent serveur, puis reprend le flux. */ +/** Accepte/refuse un tool posé par la nouvelle boucle d'agent serveur, puis reprend le flux. */ const handleAgentToolDecision = async ( - toolCall: NonNullable, + toolCall: ToolStep, accept: boolean, assistantMsgIndex: number, imageId?: string @@ -901,7 +929,7 @@ const handleAgentToolDecision = async ( decision = { clientResult: { error: "Action refusée par l'utilisateur." } }; } else { try { - const args = typeof toolCall.arguments === 'string' ? JSON.parse(toolCall.arguments || '{}') : toolCall.arguments; + const args = typeof toolCall.args === 'string' ? JSON.parse(toolCall.args || '{}') : toolCall.args; decision = { clientResult: await executeClientTool(toolCall.name, args, imageId) }; } catch (e: any) { decision = { clientResult: { error: e.message || 'Erreur technique.' } }; @@ -918,18 +946,18 @@ const handleAgentToolDecision = async ( const generator = aiService.resumeAgentTurn(orgId, sessionId, decision); await consumeAgentStream(generator, () => idx, (i) => { idx = i; }); } catch (e: any) { - if (messages.value[assistantMsgIndex]) messages.value[assistantMsgIndex]!.content += `\n\n**Erreur:** ${e.message}`; + if (messages.value[assistantMsgIndex]) appendTextPart(assistantMsgIndex, `\n\n**Erreur:** ${e.message}`); } finally { isGenerating.value = false; } }; -/** Provider OpenAI : la conversation passe entièrement par la boucle d'agent serveur. */ +/** Providers OpenAI/Mistral/Gemini : la conversation passe entièrement par la boucle d'agent serveur. */ const sendMessageViaAgent = async (text: string) => { const orgId = route.params.orgId as string; messages.value.push({ role: 'user', content: text }); const assistantMsgIndex = messages.value.length; - messages.value.push({ role: 'assistant', content: '', viaAgentLoop: true }); + messages.value.push({ role: 'assistant', content: '', viaAgentLoop: true, parts: [] }); isGenerating.value = true; await scrollToBottom(); @@ -940,7 +968,7 @@ const sendMessageViaAgent = async (text: string) => { await consumeAgentStream(generator, () => idx, (i) => { idx = i; }); } catch (error: any) { if (error.message !== 'USER_STOPPED' && !String(error).includes('USER_STOPPED')) { - messages.value[assistantMsgIndex]!.content += `\n\n**Erreur:** ${error.message}`; + appendTextPart(assistantMsgIndex, `\n\n**Erreur:** ${error.message}`); } } finally { isGenerating.value = false; @@ -960,7 +988,7 @@ const sendMessage = async (hiddenPrompt?: string) => { inputMsg.value = ''; } - if (!hiddenPrompt && aiService.config.provider === 'openai') { + if (!hiddenPrompt && ['openai', 'mistral', 'gemini'].includes(aiService.config.provider)) { await sendMessageViaAgent(text); return; } From 4b8a38592ddc939e253ea6773d1dabe88026c0ba Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 17:18:35 +0200 Subject: [PATCH 03/19] feat(ai): clickable card components for every list-shaped tool result MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds EntityRow.vue (icon/logo-or-avatar + title + subtitle, hover chevron) as the shared building block for anything the agent lists: - list_spaces: grid of space cards (logo or icon), click navigates into the workspace. - list_threads / create_thread: salon cards (hash or vocal icon), click opens the thread. - list_members: member cards (avatar), click opens a DM with them. - read_tasks (flattened across lists + unlisted) / get_task / create_task: task cards, click opens TaskDetailsModal. - create_space: same card, click navigates into the new space. Read-only tool results (list_*, search_messages, read_tasks, get_task) now expand by default instead of staying collapsed behind a click — that's the actual payload the user asked for, not an implementation detail to hide. Mutating tools stay collapsed by default since their text confirmation already says what happened. Co-Authored-By: Claude Sonnet 5 --- .../OrgSpace/components/ai/EntityRow.vue | 40 +++++ .../OrgSpace/components/ai/ToolResultBody.vue | 141 ++++++++++++------ .../OrgSpace/components/ai/ToolStepItem.vue | 4 +- 3 files changed, 141 insertions(+), 44 deletions(-) create mode 100644 src/views/OrgSpace/components/ai/EntityRow.vue diff --git a/src/views/OrgSpace/components/ai/EntityRow.vue b/src/views/OrgSpace/components/ai/EntityRow.vue new file mode 100644 index 00000000..19626b6f --- /dev/null +++ b/src/views/OrgSpace/components/ai/EntityRow.vue @@ -0,0 +1,40 @@ + + + diff --git a/src/views/OrgSpace/components/ai/ToolResultBody.vue b/src/views/OrgSpace/components/ai/ToolResultBody.vue index cf9137a3..70811ae5 100644 --- a/src/views/OrgSpace/components/ai/ToolResultBody.vue +++ b/src/views/OrgSpace/components/ai/ToolResultBody.vue @@ -34,58 +34,92 @@

Aucun résultat trouvé.

- -
+ -
- -
-

{{ createdTask.title }}

-

{{ createdTask.description }}

-
-
- -
+ /> - -
+ -
- -

{{ createdSpace.name }}

-
- -
+ />
-
-
- -

{{ th.name }}

-
- -
+ /> +
+ + +
+ +

Aucun espace de travail.

- -
    -
  • - - {{ item.name }} -
  • -
  • Aucun résultat.
  • -
+ +
+ +

Aucun salon.

+
+ + +
+ +

Aucun membre.

+
+ + + + + +
+ +

Aucune tâche.

+

@@ -103,6 +137,7 @@ import { computed } from 'vue'; import { useRoute, useRouter } from 'vue-router'; import type { ToolStep } from './agentTypes'; import ThreadMessage from '../common/ThreadMessage.vue'; +import EntityRow from './EntityRow.vue'; import { openedOrg } from '@/assets/var'; const props = defineProps<{ tool: ToolStep }>(); @@ -116,9 +151,19 @@ const searchResults = computed(() => props.tool.result?.results || []); const createdTask = computed(() => (props.tool.name === 'create_task' ? props.tool.result : null)); const createdSpace = computed(() => (props.tool.name === 'create_space' ? props.tool.result : null)); const createdThreads = computed(() => (props.tool.name === 'create_thread' ? (props.tool.result?.threads || []) : [])); - -const isNamedList = computed(() => ['list_spaces', 'list_threads', 'list_members'].includes(props.tool.name)); -const namedListItems = computed(() => Array.isArray(props.tool.result) ? props.tool.result : []); +const singleTask = computed(() => (props.tool.name === 'get_task' ? props.tool.result : null)); + +const namedListItems = computed(() => + ['list_spaces', 'list_threads', 'list_members'].includes(props.tool.name) && Array.isArray(props.tool.result) + ? props.tool.result + : [] +); + +const flattenedTasks = computed(() => { + if (props.tool.name !== 'read_tasks' || !props.tool.result) return []; + const { lists = [], unlistedTasks = [] } = props.tool.result; + return [...unlistedTasks, ...lists.flatMap((l: any) => l.tasks || [])]; +}); const prettyResult = computed(() => { try { @@ -128,6 +173,16 @@ const prettyResult = computed(() => { } }); +function isImageLogo(logo?: string) { + return !!logo && logo.startsWith('data:image'); +} + +function statusIcon(status?: string) { + if (status === 'DONE') return 'bi-check-circle-fill'; + if (status === 'IN_PROGRESS') return 'bi-arrow-repeat'; + return 'bi-circle'; +} + function spaceAndThreadName(workspaceId: string, threadId: string) { const space = openedOrg.value?.spaces?.find((s) => s.id === workspaceId); const thread = space?.threads?.find((t) => t.id === threadId) || openedOrg.value?.home?.threads?.find((t) => t.id === threadId); diff --git a/src/views/OrgSpace/components/ai/ToolStepItem.vue b/src/views/OrgSpace/components/ai/ToolStepItem.vue index 8af69aac..5296af9c 100644 --- a/src/views/OrgSpace/components/ai/ToolStepItem.vue +++ b/src/views/OrgSpace/components/ai/ToolStepItem.vue @@ -60,7 +60,9 @@ import IconSelector from '@/components/common/IconSelector.vue'; const props = defineProps<{ tool: ToolStep; isLast?: boolean }>(); defineEmits(['accept', 'reject', 'open-task', 'provide-image']); -const expanded = ref(false); +// Les tools de lecture (non mutants) affichent directement leur résultat — c'est ce que +// l'utilisateur a demandé. Les tools mutants restent repliés : leur confirmation textuelle suffit. +const expanded = ref(!props.tool.mutating); const { label, icon } = toolLabel(props.tool.name); From dd66432cc1db21d9dbc0ed5ea0d7af34b9324248 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 17:24:22 +0200 Subject: [PATCH 04/19] fix(ai): restore tool steps when reloading a saved agent conversation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit loadSession() was assigning the backend's structured StoredMessage[] (role 'user'/'assistant'/'tool', toolCalls arrays, toolCallId/ toolResult) straight into aiSessionMessages — a completely different shape from the parts-based turns OrgAI.vue renders live, so every reopened conversation silently lost its tool steps and results, showing only... whatever happened to survive the shape mismatch. convertStoredMessagesToChatMessages() rebuilds the same {viaAgentLoop, parts: [...]} turns the live SSE consumer builds: one turn per 'user'-delimited run of assistant/tool messages, tool results matched back to their call by toolCallId. A cheap heuristic (isStructuredAgentTranscript) only applies this when the loaded messages are actually in the new format, so old-format sessions (local/custom's flat syncSession() writes) keep loading as before. Co-Authored-By: Claude Sonnet 5 --- src/services/AIService.ts | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 70a7accd..434f4bb3 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -354,6 +354,63 @@ export const fetchSessions = async () => { } }; +/** + * Reconstruit les turns "parts" (texte + tools entrelacés) affichés par OrgAI.vue à partir des + * StoredMessage[] structurés persistés par la nouvelle boucle d'agent serveur (rôles 'user' / + * 'assistant' avec toolCalls / 'tool' avec le résultat) — sans quoi une session rechargée perd + * tout l'affichage des tools (ils n'existent que sous forme de turns "parts" côté client). + * Une seule "turn" regroupe tout ce qui suit un message 'user', jusqu'au 'user' suivant : + * une réponse peut en effet être composée de plusieurs StoredMessage successifs (texte, tool, + * texte, tool...) qui forment visuellement un seul tour assistant continu. + */ +function convertStoredMessagesToChatMessages(stored: any[]): any[] { + const result: any[] = []; + let currentTurn: any = null; + + for (const m of stored) { + if (m.role === 'user') { + currentTurn = null; + result.push({ role: 'user', content: m.content || '' }); + continue; + } + + if (!currentTurn) { + currentTurn = { role: 'assistant', content: '', viaAgentLoop: true, parts: [] }; + result.push(currentTurn); + } + + if (m.role === 'assistant') { + if (m.content) currentTurn.parts.push({ type: 'text', text: m.content }); + for (const tc of m.toolCalls || []) { + currentTurn.parts.push({ + type: 'tool', + tool: { + toolCallId: tc.id, + name: tc.name, + args: tc.arguments, + status: tc.status === 'error' ? 'error' : 'pending', + category: tc.category, + mutating: tc.mutating, + }, + }); + } + } else if (m.role === 'tool') { + const part = currentTurn.parts.find((p: any) => p.type === 'tool' && p.tool.toolCallId === m.toolCallId); + if (part) { + part.tool.status = m.toolResult?.error ? 'error' : 'done'; + part.tool.result = m.toolResult; + } + } + } + + return result; +} + +/** true si ces messages viennent de la nouvelle boucle d'agent serveur (présence d'un rôle 'tool' ou de toolCalls structurés). */ +function isStructuredAgentTranscript(messages: any[]): boolean { + return messages.some((m) => m.role === 'tool' || (Array.isArray(m.toolCalls) && m.toolCalls.length > 0)); +} + export const loadSession = async (id: string) => { if (!openedOrg.value) return; try { @@ -382,6 +439,10 @@ export const loadSession = async (id: string) => { } } + if (Array.isArray(loadedMessages) && isStructuredAgentTranscript(loadedMessages)) { + loadedMessages = convertStoredMessagesToChatMessages(loadedMessages); + } + aiSessionMessages.value = loadedMessages; } } catch (e) { From 166bbdba57e6b0353ff159a91699810f1f980bda Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 17:32:19 +0200 Subject: [PATCH 05/19] feat(ai): scroll-to-bottom button and textarea autofocus in OrgAI - Floating button appears once the user scrolls more than ~200px away from the bottom of the conversation, click jumps back down (mirrors the existing scrollToBottom()). - The composer textarea now grabs focus on mount too, not just on session switch (that watcher already existed). Co-Authored-By: Claude Sonnet 5 --- src/views/OrgSpace/views/OrgAI.vue | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index d7f3ef66..97dd3e02 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -20,7 +20,8 @@

-
+
+ + + + +
@@ -474,6 +487,16 @@ const scrollToBottom = async () => { if (chatContainer.value) { chatContainer.value.scrollTop = chatContainer.value.scrollHeight; } + showScrollToBottom.value = false; +}; + +const showScrollToBottom = ref(false); + +const onChatScroll = () => { + const el = chatContainer.value; + if (!el) return; + const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight; + showScrollToBottom.value = distanceFromBottom > 200; }; const initError = ref(''); @@ -1047,6 +1070,9 @@ const sendMessage = async (hiddenPrompt?: string) => { onMounted(async () => { const recommended = await localLLM.getRecommendedModel(); recommendedModelId.value = recommended.id; + + await nextTick(); + chatInputRef.value?.textarea?.focus(); }); watch(() => openedOrg.value, async (newVal) => { From 4fcda2a60374f7492af94b355f39bfbcf01902cc Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 17:37:39 +0200 Subject: [PATCH 06/19] fix(ai): read_documentation glob path had one extra ../, always empty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit '../../../../../doc/*.md' from OrgAI.vue (src/views/OrgSpace/views/) resolves to the GitHub/ parent directory, not synco_app/doc/ where the 8 real .md files live — so import.meta.glob matched nothing and the tool always returned just the header, no chapters. Pre-existing bug (present in the old handleToolCall before this rework), carried over verbatim into executeClientTool. Fixed both occurrences to '../../../../doc/*.md' (4 levels up reaches synco_app/). Co-Authored-By: Claude Sonnet 5 --- src/views/OrgSpace/views/OrgAI.vue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index 97dd3e02..a52fc2a2 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -757,7 +757,7 @@ const handleToolCall = async (toolCall: NonNullable, a result = `${created.length} salon(s) créé(s) avec succès. Les clés E2EE ont été générées et distribuées.`; } else if (toolCall.name === 'read_documentation') { - const docFiles = import.meta.glob('../../../../../doc/*.md', { query: '?raw', import: 'default', eager: true }); + const docFiles = import.meta.glob('../../../../doc/*.md', { query: '?raw', import: 'default', eager: true }); let fullDoc = "# Documentation de Synco\n\n"; for (const [path, content] of Object.entries(docFiles)) { @@ -916,7 +916,7 @@ const executeClientTool = async (name: string, args: any, imageId?: string): Pro } if (name === 'read_documentation') { - const docFiles = import.meta.glob('../../../../../doc/*.md', { query: '?raw', import: 'default', eager: true }); + const docFiles = import.meta.glob('../../../../doc/*.md', { query: '?raw', import: 'default', eager: true }); let fullDoc = '# Documentation de Synco\n\n'; for (const [path, content] of Object.entries(docFiles)) { const fileName = path.split('/').pop()?.replace('.md', '') || path; From f89ffaaeac3cc8160eda1922deded0bdcde01292 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 18:16:45 +0200 Subject: [PATCH 07/19] feat(ai): wire the 'gateway' provider (self-hosted Synco AI Gateway) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AISettings.vue: new provider tile "Passerelle Synco AI (auto-hébergée)" with two fields (gateway URL, Ollama URL — reusing endpointUrl) instead of an API key, since auth is the user's own Synco/Keycloak token, not a stored secret. Skips the cloud-data-transfer warning, same as 'custom' and 'local'. AIService.ts: chatAgentTurn/resumeAgentTurn branch on provider==='gateway' to call the gateway's own URL directly (plain fetch with the Keycloak token attached by hand, since sfetch always targets VITE_API_URL) instead of synco_api's /ai/chat — sending {orgId, syncoApiUrl, ollamaUrl, modelId} alongside the usual payload so the gateway can reach back to synco_api and Ollama with no per-deployment config of its own. OrgAI.vue: sendMessage's provider gate now includes 'gateway' — nothing else changes, consumeAgentStream/AgentTurn already render whichever backend drives the loop identically. Co-Authored-By: Claude Sonnet 5 --- src/services/AIService.ts | 77 +++++++++++++++---- src/views/OrgSpace/views/OrgAI.vue | 2 +- .../views/settings/views/AISettings.vue | 63 ++++++++++++--- 3 files changed, 119 insertions(+), 23 deletions(-) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 434f4bb3..b449cd6a 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -2,12 +2,15 @@ import { openedOrg, user } from '@/assets/var'; import { localLLM } from './LocalLLMService'; import { computed, ref } from 'vue'; import sfetch from '@/assets/utils/sfetch'; +import { keycloak } from '@/assets/keycloak'; import { encryptForPeer, decryptFromPeer, privateKey } from '@/assets/utils/crypto'; export interface AIProviderConfig { - provider: 'local' | 'openai' | 'gemini' | 'mistral' | 'custom'; + provider: 'local' | 'openai' | 'gemini' | 'mistral' | 'custom' | 'gateway'; apiKey?: string; endpointUrl?: string; + /** URL de la Synco AI Gateway auto-hébergée (provider 'gateway' uniquement). */ + gatewayUrl?: string; modelId?: string; } @@ -45,18 +48,53 @@ export class AIService { } /** - * Nouvelle boucle d'agent serveur (provider OpenAI, cf. refonte Synco AI) : le backend possède - * la conversation et exécute lui-même les tools 'server' — contrairement à chat()/chatOpenAICompatible + * Appel direct navigateur → passerelle, sans passer par sfetch (qui cible toujours + * VITE_API_URL) : on attache le même token Keycloak à la main, exactement comme sfetch le + * ferait, mais vers une origine arbitraire (l'URL de la Synco AI Gateway auto-hébergée). + */ + private async gatewayFetch(url: string, body: any, signal: AbortSignal): Promise { + if (keycloak.authenticated) { + await keycloak.updateToken(60).catch(() => {}); + } + return fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}), + }, + body: JSON.stringify(body), + signal, + }); + } + + /** + * Nouvelle boucle d'agent serveur (providers OpenAI/Mistral/Gemini via synco_api, ou une + * Synco AI Gateway auto-hébergée pour Ollama) : le backend qui répond possède la conversation + * et exécute lui-même les tools 'server' — contrairement à chat()/chatOpenAICompatible * ci-dessous qui restent l'ancien parseur regex côté client pour les autres providers. */ public async *chatAgentTurn(orgId: string, sessionId: string | null, message: string): AsyncGenerator { this.abortController = new AbortController(); - const response = await sfetch(`/api/orgs/${orgId}/ai/chat`, { - method: 'POST', - body: JSON.stringify({ sessionId: sessionId || undefined, message }), - signal: this.abortController.signal, - }); + let response: Response; + + if (this.config.provider === 'gateway') { + const gatewayUrl = (this.config.gatewayUrl || '').replace(/\/$/, ''); + response = await this.gatewayFetch(`${gatewayUrl}/chat`, { + orgId, + sessionId: sessionId || undefined, + message, + syncoApiUrl: import.meta.env.VITE_API_URL, + ollamaUrl: this.config.endpointUrl, + modelId: this.config.modelId, + }, this.abortController.signal); + } else { + response = await sfetch(`/api/orgs/${orgId}/ai/chat`, { + method: 'POST', + body: JSON.stringify({ sessionId: sessionId || undefined, message }), + signal: this.abortController.signal, + }); + } if (!response.ok) { const err = await response.text().catch(() => ''); @@ -69,11 +107,24 @@ export class AIService { public async *resumeAgentTurn(orgId: string, sessionId: string, decision: { accepted?: boolean; clientResult?: any }): AsyncGenerator { this.abortController = new AbortController(); - const response = await sfetch(`/api/orgs/${orgId}/ai/chat/${sessionId}/tool-result`, { - method: 'POST', - body: JSON.stringify(decision), - signal: this.abortController.signal, - }); + let response: Response; + + if (this.config.provider === 'gateway') { + const gatewayUrl = (this.config.gatewayUrl || '').replace(/\/$/, ''); + response = await this.gatewayFetch(`${gatewayUrl}/chat/${sessionId}/tool-result`, { + orgId, + syncoApiUrl: import.meta.env.VITE_API_URL, + ollamaUrl: this.config.endpointUrl, + modelId: this.config.modelId, + ...decision, + }, this.abortController.signal); + } else { + response = await sfetch(`/api/orgs/${orgId}/ai/chat/${sessionId}/tool-result`, { + method: 'POST', + body: JSON.stringify(decision), + signal: this.abortController.signal, + }); + } if (!response.ok) { const err = await response.text().catch(() => ''); diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index a52fc2a2..e20306e8 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -1011,7 +1011,7 @@ const sendMessage = async (hiddenPrompt?: string) => { inputMsg.value = ''; } - if (!hiddenPrompt && ['openai', 'mistral', 'gemini'].includes(aiService.config.provider)) { + if (!hiddenPrompt && ['openai', 'mistral', 'gemini', 'gateway'].includes(aiService.config.provider)) { await sendMessageViaAgent(text); return; } diff --git a/src/views/OrgSpace/views/settings/views/AISettings.vue b/src/views/OrgSpace/views/settings/views/AISettings.vue index efbe6373..02e0a2e8 100644 --- a/src/views/OrgSpace/views/settings/views/AISettings.vue +++ b/src/views/OrgSpace/views/settings/views/AISettings.vue @@ -52,8 +52,8 @@
- -
+ +
@@ -78,7 +78,7 @@
-
+ + +
@@ -115,7 +149,7 @@
-
+
@@ -155,9 +189,9 @@ class="primary px-6 py-2.5 rounded-xl text-sm font-medium" :class="[ saving ? 'loader' : '', - orgData.provider !== 'local' && orgData.provider !== 'custom' && !acceptCloudWarning ? 'opacity-50 grayscale-100 pointer-events-none' : '' + orgData.provider !== 'local' && orgData.provider !== 'custom' && orgData.provider !== 'gateway' && !acceptCloudWarning ? 'opacity-50 grayscale-100 pointer-events-none' : '' ]" - :disabled="orgData.provider !== 'local' && orgData.provider !== 'custom' && !acceptCloudWarning" + :disabled="orgData.provider !== 'local' && orgData.provider !== 'custom' && orgData.provider !== 'gateway' && !acceptCloudWarning" > Enregistrer les modifications @@ -206,6 +240,7 @@ const showLearnMorePopup = ref(false); const providers = [ { id: 'local', name: 'WebGPU (Local Browser)', desc: 'Exécuté sur la carte graphique de l\'utilisateur. Gratuit, 100% privé, mais dépend des performances de chaque machine.' }, { id: 'custom', name: 'Serveur Client (Custom API)', desc: 'Votre propre serveur local ou distant avec une API compatible OpenAI (Ollama, vLLM, etc.).' }, + { id: 'gateway', name: 'Passerelle Synco AI (auto-hébergée)', desc: 'Votre propre Synco AI Gateway devant un Ollama que vous contrôlez : vrais outils IA, authentification via votre compte Synco, aucune clé à distribuer.' }, { id: 'openai', name: 'OpenAI', desc: 'Modèles Cloud de pointe (GPT-4o, GPT-4o-mini).' }, { id: 'gemini', name: 'Google Gemini', desc: 'Modèles très rapides et puissants (1.5 Pro, Flash).' }, { id: 'mistral', name: 'Mistral AI', desc: 'Modèles souverains européens (Mistral Large, Pixtral).' }, @@ -218,6 +253,7 @@ const getAiConfig = () => { apiKey: '', // API key is never populated from backend hasApiKey: config.hasApiKey || false, endpointUrl: config.endpointUrl || '', + gatewayUrl: config.gatewayUrl || '', modelId: config.modelId || '' }; }; @@ -230,6 +266,7 @@ const hasChanges = computed(() => { orgData.value.provider !== initial.provider || (orgData.value.apiKey || '') !== '' || orgData.value.endpointUrl !== initial.endpointUrl || + orgData.value.gatewayUrl !== initial.gatewayUrl || orgData.value.modelId !== initial.modelId ); }); @@ -259,16 +296,22 @@ const saveSettings = async () => { // Validation if (orgData.value.provider !== 'local') { - if (!orgData.value.apiKey && !orgData.value.hasApiKey && orgData.value.provider !== 'custom') { + if (!orgData.value.apiKey && !orgData.value.hasApiKey && orgData.value.provider !== 'custom' && orgData.value.provider !== 'gateway') { return toast.show('Veuillez entrer une clé API pour ce fournisseur.', 'error'); } if (orgData.value.provider === 'custom' && !orgData.value.endpointUrl) { return toast.show('Veuillez entrer l\'URL de l\'endpoint pour le serveur custom.', 'error'); } + if (orgData.value.provider === 'gateway' && !orgData.value.gatewayUrl) { + return toast.show('Veuillez entrer l\'URL de votre Synco AI Gateway.', 'error'); + } + if (orgData.value.provider === 'gateway' && !orgData.value.endpointUrl) { + return toast.show('Veuillez entrer l\'URL du serveur Ollama utilisé par la passerelle.', 'error'); + } if (!orgData.value.modelId) { return toast.show('Veuillez indiquer l\'ID du modèle à utiliser.', 'error'); } - if (orgData.value.provider !== 'custom' && !acceptCloudWarning.value) { + if (orgData.value.provider !== 'custom' && orgData.value.provider !== 'gateway' && !acceptCloudWarning.value) { return toast.show('Vous devez accepter les conditions d\'utilisation des services cloud externes.', 'error'); } } @@ -280,6 +323,7 @@ const saveSettings = async () => { const aiConfigPayload: any = { provider: orgData.value.provider, endpointUrl: orgData.value.endpointUrl, + gatewayUrl: orgData.value.gatewayUrl, modelId: orgData.value.modelId }; @@ -330,7 +374,8 @@ watch(() => orgData.value.provider, (newProv, oldProv) => { else if (newProv === 'gemini' && (!orgData.value.modelId || !orgData.value.modelId.includes('gemini'))) orgData.value.modelId = 'gemini-1.5-flash'; else if (newProv === 'mistral' && (!orgData.value.modelId || !orgData.value.modelId.includes('istral'))) orgData.value.modelId = 'pixtral-12b-2409'; - if (newProv !== 'custom') orgData.value.endpointUrl = ''; + if (newProv !== 'custom' && newProv !== 'gateway') orgData.value.endpointUrl = ''; + if (newProv !== 'gateway') orgData.value.gatewayUrl = ''; } }); From bf2db0cfa9c6d5ae0bdd5e3c1104e0705bf88638 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 18:47:34 +0200 Subject: [PATCH 08/19] =?UTF-8?q?feat(ai):=20model=20selectors=20in=20AISe?= =?UTF-8?q?ttings=20=E2=80=94=20live=20for=20gateway,=20curated=20for=20cl?= =?UTF-8?q?oud=20providers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit listGatewayModels() (AIService.ts) calls the gateway's new GET /models?ollamaUrl=... to list what's already pulled on the org's Ollama, with the Keycloak token attached the same way chatAgentTurn does for that provider. AISettings.vue: entering the gateway/Ollama URL (debounced 500ms) auto-fetches that list and replaces the free-text model field with a treatment using the existing curated recommendedModels list (expanded a bit) instead of the old suggestion-chip buttons. Every selector keeps an "Autre (saisie manuelle)" escape hatch so an already-configured model outside the list, or one Ollama doesn't expose via /v1/models, is never silently lost. Co-Authored-By: Claude Sonnet 5 --- src/services/AIService.ts | 25 ++++ .../views/settings/views/AISettings.vue | 115 +++++++++++++++--- 2 files changed, 124 insertions(+), 16 deletions(-) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index b449cd6a..121433b2 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -377,6 +377,31 @@ export class AIService { } } +/** + * Liste les modèles déjà présents sur le serveur Ollama d'une organisation, via sa Synco AI + * Gateway (pas d'appel direct navigateur → Ollama, pour éviter une config CORS séparée sur + * Ollama). Utilisé par AISettings.vue pour peupler le sélecteur de modèle du provider 'gateway'. + */ +export async function listGatewayModels(gatewayUrl: string, ollamaUrl: string): Promise { + if (keycloak.authenticated) { + await keycloak.updateToken(60).catch(() => {}); + } + const base = gatewayUrl.replace(/\/$/, ''); + const url = `${base}/models?ollamaUrl=${encodeURIComponent(ollamaUrl)}`; + + const res = await fetch(url, { + headers: keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}, + }); + + if (!res.ok) { + const body = await res.json().catch(() => ({} as any)); + throw new Error(body.error || `Erreur ${res.status} lors de la récupération des modèles.`); + } + + const data = await res.json(); + return Array.isArray(data.models) ? data.models : []; +} + export const aiService = new AIService(); // Vue Reactive Bindings for OrgAI.vue compatibility diff --git a/src/views/OrgSpace/views/settings/views/AISettings.vue b/src/views/OrgSpace/views/settings/views/AISettings.vue index 02e0a2e8..ac2b112f 100644 --- a/src/views/OrgSpace/views/settings/views/AISettings.vue +++ b/src/views/OrgSpace/views/settings/views/AISettings.vue @@ -124,28 +124,51 @@
-
+ +
+
+
+ +
+ +
+ +
+ +
-
-
- -
+ +

+ Récupération des modèles disponibles sur Ollama... +

+

+ {{ modelsError }} +

+

+ Renseignez l'URL du serveur Ollama ci-dessus pour lister les modèles déjà téléchargés. +

@@ -228,6 +251,7 @@ import Popup from '@/components/Popup.vue'; import { openedOrg, organizations } from '@/assets/var'; import { useToast } from '@/composables/useToast'; import sfetch from '@/assets/utils/sfetch'; +import { listGatewayModels } from '@/services/AIService'; const toast = useToast(); @@ -279,12 +303,71 @@ const defaultModelPlaceholder = computed(() => { }); const recommendedModels = computed(() => { - if (orgData.value.provider === 'openai') return ['gpt-4o-mini', 'gpt-4o']; - if (orgData.value.provider === 'gemini') return ['gemini-1.5-flash', 'gemini-1.5-pro']; - if (orgData.value.provider === 'mistral') return ['pixtral-12b-2409', 'mistral-large-latest']; + if (orgData.value.provider === 'openai') return ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-4.1', 'o3-mini']; + if (orgData.value.provider === 'gemini') return ['gemini-1.5-flash', 'gemini-1.5-pro', 'gemini-2.0-flash']; + if (orgData.value.provider === 'mistral') return ['pixtral-12b-2409', 'mistral-large-latest', 'mistral-small-latest']; return []; }); +// Modèles réellement disponibles sur l'Ollama de l'org (provider 'gateway'), récupérés en +// direct via la passerelle dès que son URL et celle d'Ollama sont renseignées. +const ollamaModels = ref([]); +const loadingModels = ref(false); +const modelsError = ref(''); +let modelsFetchTimeout: ReturnType | null = null; + +const fetchOllamaModels = async () => { + if (orgData.value.provider !== 'gateway' || !orgData.value.gatewayUrl || !orgData.value.endpointUrl) { + ollamaModels.value = []; + return; + } + loadingModels.value = true; + modelsError.value = ''; + try { + ollamaModels.value = await listGatewayModels(orgData.value.gatewayUrl, orgData.value.endpointUrl); + if (ollamaModels.value.length === 0) { + modelsError.value = "Aucun modèle trouvé sur cet Ollama — pensez à en télécharger un (ollama pull)."; + } + } catch (e: any) { + ollamaModels.value = []; + modelsError.value = e.message || 'Impossible de récupérer la liste des modèles.'; + } finally { + loadingModels.value = false; + } +}; + +watch([() => orgData.value.provider, () => orgData.value.gatewayUrl, () => orgData.value.endpointUrl], () => { + if (modelsFetchTimeout) clearTimeout(modelsFetchTimeout); + modelsFetchTimeout = setTimeout(fetchOllamaModels, 500); +}, { immediate: true }); + +const availableModelOptions = computed(() => { + if (orgData.value.provider === 'gateway') return ollamaModels.value; + if (['openai', 'gemini', 'mistral'].includes(orgData.value.provider)) return recommendedModels.value; + return []; +}); + +const showModelSelect = computed(() => availableModelOptions.value.length > 0 || (orgData.value.provider === 'gateway' && loadingModels.value)); + +// Select lié à orgData.modelId : reflète l'option en cours si elle fait partie de la liste, +// bascule sur "saisie manuelle" sinon (garde une valeur déjà configurée qui ne serait plus +// dans la liste, ex. un modèle retiré d'Ollama ou un ancien choix hors liste curatée). +const modelSelection = computed({ + get() { + if (orgData.value.modelId && availableModelOptions.value.includes(orgData.value.modelId)) { + return orgData.value.modelId; + } + return orgData.value.modelId ? '__manual__' : ''; + }, + set(value: string) { + if (value !== '__manual__') { + orgData.value.modelId = value; + } else if (availableModelOptions.value.includes(orgData.value.modelId)) { + orgData.value.modelId = ''; + } + } +}); + const resetChanges = () => { orgData.value = { ...getAiConfig() }; showApiKey.value = false; From 132dac9fec24f503e25bcafea7b25ba90137f937 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Wed, 9 Sep 2026 19:06:07 +0200 Subject: [PATCH 09/19] =?UTF-8?q?feat(ai):=20drop=20the=20Ollama=20URL=20f?= =?UTF-8?q?ield=20=E2=80=94=20the=20gateway=20knows=20on=20its=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Matches the backend change: OLLAMA_URL is now the gateway's own deployment config (defaults to 127.0.0.1:11434, always correct for the all-in-one image), not something a Synco admin should ever need to know or type. AISettings.vue's "gateway" provider now shows a single field (the gateway's own URL); listGatewayModels() and chatAgentTurn/resumeAgentTurn no longer send an ollamaUrl the gateway never asked for. Co-Authored-By: Claude Sonnet 5 --- src/services/AIService.ts | 13 ++-- .../views/settings/views/AISettings.vue | 63 +++++++------------ 2 files changed, 28 insertions(+), 48 deletions(-) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 121433b2..6aedeadc 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -85,7 +85,6 @@ export class AIService { sessionId: sessionId || undefined, message, syncoApiUrl: import.meta.env.VITE_API_URL, - ollamaUrl: this.config.endpointUrl, modelId: this.config.modelId, }, this.abortController.signal); } else { @@ -114,7 +113,6 @@ export class AIService { response = await this.gatewayFetch(`${gatewayUrl}/chat/${sessionId}/tool-result`, { orgId, syncoApiUrl: import.meta.env.VITE_API_URL, - ollamaUrl: this.config.endpointUrl, modelId: this.config.modelId, ...decision, }, this.abortController.signal); @@ -378,16 +376,17 @@ export class AIService { } /** - * Liste les modèles déjà présents sur le serveur Ollama d'une organisation, via sa Synco AI - * Gateway (pas d'appel direct navigateur → Ollama, pour éviter une config CORS séparée sur - * Ollama). Utilisé par AISettings.vue pour peupler le sélecteur de modèle du provider 'gateway'. + * Liste les modèles déjà présents sur l'Ollama d'une organisation, via sa Synco AI Gateway (pas + * d'appel direct navigateur → Ollama, pour éviter une config CORS séparée sur Ollama). La + * passerelle sait elle-même où joindre Ollama (OLLAMA_URL, config de déploiement) — on ne le lui + * dit pas ici. Utilisé par AISettings.vue pour peupler le sélecteur de modèle du provider 'gateway'. */ -export async function listGatewayModels(gatewayUrl: string, ollamaUrl: string): Promise { +export async function listGatewayModels(gatewayUrl: string): Promise { if (keycloak.authenticated) { await keycloak.updateToken(60).catch(() => {}); } const base = gatewayUrl.replace(/\/$/, ''); - const url = `${base}/models?ollamaUrl=${encodeURIComponent(ollamaUrl)}`; + const url = `${base}/models`; const res = await fetch(url, { headers: keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}, diff --git a/src/views/OrgSpace/views/settings/views/AISettings.vue b/src/views/OrgSpace/views/settings/views/AISettings.vue index ac2b112f..c297d48f 100644 --- a/src/views/OrgSpace/views/settings/views/AISettings.vue +++ b/src/views/OrgSpace/views/settings/views/AISettings.vue @@ -87,39 +87,22 @@
- - +

Le navigateur appelle cette passerelle directement (pas notre serveur), avec votre compte Synco pour vous authentifier. Ollama vit à côté (ou dans le même conteneur) de cette passerelle — elle sait déjà où le trouver.

+
@@ -166,8 +149,8 @@

{{ modelsError }}

-

- Renseignez l'URL du serveur Ollama ci-dessus pour lister les modèles déjà téléchargés. +

+ Renseignez l'URL de votre passerelle ci-dessus pour lister les modèles déjà téléchargés sur Ollama.

@@ -310,21 +293,22 @@ const recommendedModels = computed(() => { }); // Modèles réellement disponibles sur l'Ollama de l'org (provider 'gateway'), récupérés en -// direct via la passerelle dès que son URL et celle d'Ollama sont renseignées. +// direct via la passerelle dès que son URL est renseignée — c'est elle qui sait où trouver +// Ollama (OLLAMA_URL, une config de déploiement de la passerelle, pas des paramètres Synco). const ollamaModels = ref([]); const loadingModels = ref(false); const modelsError = ref(''); let modelsFetchTimeout: ReturnType | null = null; const fetchOllamaModels = async () => { - if (orgData.value.provider !== 'gateway' || !orgData.value.gatewayUrl || !orgData.value.endpointUrl) { + if (orgData.value.provider !== 'gateway' || !orgData.value.gatewayUrl) { ollamaModels.value = []; return; } loadingModels.value = true; modelsError.value = ''; try { - ollamaModels.value = await listGatewayModels(orgData.value.gatewayUrl, orgData.value.endpointUrl); + ollamaModels.value = await listGatewayModels(orgData.value.gatewayUrl); if (ollamaModels.value.length === 0) { modelsError.value = "Aucun modèle trouvé sur cet Ollama — pensez à en télécharger un (ollama pull)."; } @@ -336,7 +320,7 @@ const fetchOllamaModels = async () => { } }; -watch([() => orgData.value.provider, () => orgData.value.gatewayUrl, () => orgData.value.endpointUrl], () => { +watch([() => orgData.value.provider, () => orgData.value.gatewayUrl], () => { if (modelsFetchTimeout) clearTimeout(modelsFetchTimeout); modelsFetchTimeout = setTimeout(fetchOllamaModels, 500); }, { immediate: true }); @@ -388,9 +372,6 @@ const saveSettings = async () => { if (orgData.value.provider === 'gateway' && !orgData.value.gatewayUrl) { return toast.show('Veuillez entrer l\'URL de votre Synco AI Gateway.', 'error'); } - if (orgData.value.provider === 'gateway' && !orgData.value.endpointUrl) { - return toast.show('Veuillez entrer l\'URL du serveur Ollama utilisé par la passerelle.', 'error'); - } if (!orgData.value.modelId) { return toast.show('Veuillez indiquer l\'ID du modèle à utiliser.', 'error'); } @@ -457,7 +438,7 @@ watch(() => orgData.value.provider, (newProv, oldProv) => { else if (newProv === 'gemini' && (!orgData.value.modelId || !orgData.value.modelId.includes('gemini'))) orgData.value.modelId = 'gemini-1.5-flash'; else if (newProv === 'mistral' && (!orgData.value.modelId || !orgData.value.modelId.includes('istral'))) orgData.value.modelId = 'pixtral-12b-2409'; - if (newProv !== 'custom' && newProv !== 'gateway') orgData.value.endpointUrl = ''; + if (newProv !== 'custom') orgData.value.endpointUrl = ''; if (newProv !== 'gateway') orgData.value.gatewayUrl = ''; } }); From b122e1d455e6f734b6ab262e4b1c6b06748e9b05 Mon Sep 17 00:00:00 2001 From: Antigravity Bot Date: Thu, 10 Sep 2026 09:12:39 +0200 Subject: [PATCH 10/19] docs: plan de chiffrement des sessions IA (provider gateway) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Génération/distribution de la clé de session IA par org (réutilise le pattern ThreadKey/WorkspaceKey déjà en place), déchiffrement client des sessions gateway. Plan jumeau avec Synco_AI_Gateway/E2EE_PLAN.md et synco_api/E2EE_PLAN.md (même format wire, vecteur de test partagé). Co-Authored-By: Claude Sonnet 5 --- E2EE_PLAN.md | 232 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 E2EE_PLAN.md diff --git a/E2EE_PLAN.md b/E2EE_PLAN.md new file mode 100644 index 00000000..50adf304 --- /dev/null +++ b/E2EE_PLAN.md @@ -0,0 +1,232 @@ +# Plan — Chiffrement des sessions IA (synco_app) + +> Ce document est un des 3 plans jumeaux (`Synco_AI_Gateway`, `synco_api`, `synco_app`) écrits pour être +> donnés chacun à une session Claude dédiée, travaillant dans un seul repo à la fois, sans accès aux deux +> autres. Le **format binaire/wire (section 2)** est identique dans les 3 fichiers — ne pas le modifier sans +> répercuter le changement dans les deux autres plans. + +## 1. Contexte et objectif + +Objectif : pour les sessions IA utilisant le provider `gateway` (*"Passerelle Synco AI (auto-hébergée)"*), +`synco_api` ne doit jamais voir le contenu en clair. Ce repo (`synco_app`, le frontend Vue) est responsable +de : (a) générer et distribuer une clé symétrique partagée par organisation, (b) la transmettre directement à +`Synco_AI_Gateway` à chaque appel (jamais via `synco_api`), (c) déchiffrer côté client tout ce qu'il relit +depuis `synco_api` (historique, titres de sidebar). + +**Bonne nouvelle** : ce repo a déjà toute l'infrastructure crypto nécessaire. `src/assets/utils/crypto.ts` +implémente déjà un système E2EE complet (RSA-OAEP 4096 par utilisateur, clé privée déverrouillée par PIN et +jamais persistée en clair, enveloppe RSA+AES-GCM via `encryptForPeer`/`decryptFromPeer`, distribution de clé +partagée pour les threads/spaces via `generateThreadKey`/`encryptThreadKeyForMember`/ +`decryptThreadKeyWithRsa`). Ce plan consiste essentiellement à **répliquer le pattern `ThreadKey` existant** +pour une nouvelle ressource "clé de session IA par org", pas à inventer un nouveau système crypto. + +**Incohérence actuelle à corriger** : `AIService.ts` a DÉJÀ un chiffrement E2EE pour les sessions IA — mais +seulement sur l'ancien flux client-driven (`syncSession()`/`loadSession()`, providers `local`/`custom`, via +`encryptForPeer`/`decryptFromPeer` en auto-chiffrement pour l'utilisateur lui-même). Le nouveau flux agent +serveur (provider `gateway`, `chatAgentTurn`/`resumeAgentTurn`) ne passe PAS par ce chiffrement — c'est +précisément le trou que ce plan comble, avec un schéma de clé *partagée par org* (pas juste auto-chiffrée +pour soi-même) puisque plusieurs membres de l'org doivent pouvoir relire le même historique. + +**Hors périmètre** : les providers `openai`/`mistral`/`gemini` (flux `sfetch('/api/orgs/${orgId}/ai/chat', ...)`) +restent inchangés — ne touche pas à ce chemin. + +## 2. Format binaire (wire format) — identique aux 2 autres plans, ne pas diverger + +- **Algorithme** : AES-256-GCM, clé 256 bits. +- **Nonce** : 12 octets aléatoires par opération. +- **Tag** : 16 octets, standard GCM. +- **Valeur sur le fil** : `"gcm1:" + base64_standard(nonce(12) || ciphertext || tag(16))`. + - En Web Crypto : `crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData, tagLength: 128 }, key, plaintextBytes)` + retourne **déjà** `ciphertext || tag` concaténés (comportement natif du navigateur) — il suffit de + préfixer avec le `nonce` généré, puis encoder en base64 standard (`btoa`/`Buffer`, PAS url-safe). + - `base64_standard` = RFC 4648 §4 avec padding. +- **AAD** : chaîne UTF-8 `"{session_id}:{message_id}:{field_name}"`, encodée en `Uint8Array` via + `TextEncoder`. `field_name` : `"content"`, `"tool_result"`, `"tool_call_arguments:{call_id}"`, `"title"` + (avec `message_id = "__session_title__"`), `"pending_tool_call_args"` (avec `message_id = "__pending__"`). +- **Valeurs JSON** (`toolResult`, `toolCalls[].arguments`) : `JSON.stringify(...)` avant chiffrement, + `JSON.parse(...)` après déchiffrement. +- **`null`/absent** : ne jamais chiffrer, laisser tel quel. + +### Vecteur de test (identique au plan `Synco_AI_Gateway` — sert à vérifier l'interopérabilité TS↔Rust sans +jamais faire tourner les deux implémentations ensemble ; régénère toi-même les octets bruts depuis les hex +ci-dessous plutôt que de faire confiance à un éventuel problème de copier-coller) : + +``` +key (hex, 32 octets) : d82f2646d1113270f58fa3daf64de7e9f64253123a0ec7fdbaa24e34081d791 +key (base64) : 2C8mRtERMnD1j6Pa9k3n6fZCUxI6Dsf9uqJONAgdeRE= +nonce (hex, 12 octets) : 1024c8c26840d416f50b5072 +session_id : sess_test0000000000000000000001 +message_id : msg_test00000000000000000000001 +field_name : content +AAD (utf8) : sess_test0000000000000000000001:msg_test00000000000000000000001:content +plaintext (utf8) : Bonjour, ceci est un message de test pour Synco AI. +wire_value : gcm1:ECTIwmhA1Bb1C1ByL8IECZj8SkBl2TYmk9665e/jnrCQNjYdR+CMirRU75qIq5pxnrallgkaWQtrQreT8eCSCf6JAzUrY5mTb/Ez42WxSw== +``` +Écris un test qui importe `key` brute via `crypto.subtle.importKey('raw', ...)`, déchiffre `wire_value` avec +l'AAD ci-dessus, et vérifie que le résultat === `plaintext`. Si ça échoue, le bug est dans l'implémentation +TS (mauvais split nonce/ciphertext, mauvais AAD, mauvais `tagLength`), pas dans le vecteur. + +## 3. Nouvelle brique : clé de session IA par organisation + +### 3.1 Génération/enveloppe — mirror exact de `generateThreadKey`/`encryptThreadKeyForMember` + +Dans `src/assets/utils/crypto.ts`, regarde d'abord précisément comment `generateThreadKey`, +`encryptThreadKeyForMember(rawKey, recipientPublicKey)` et `decryptThreadKeyWithRsa(encryptedKey, iv, +privateKey)` sont implémentées (signatures exactes, format retourné). Ajoute des fonctions analogues +(ou réutilise-les directement si elles sont déjà génériques et non spécifiques aux threads — vérifie) : +- `generateAiSessionKey(): Promise` — `crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])`. + Doit être `extractable: true` (contrairement à la clé privée RSA de l'utilisateur) puisqu'elle doit être + exportée en bytes bruts pour (a) être enveloppée RSA pour chaque membre, (b) être envoyée en clair (base64) + au gateway via TLS. +- `wrapAiSessionKeyForMember(rawKeyBytes: ArrayBuffer, recipientPublicKey: CryptoKey): Promise<{ encryptedKey: string, iv?: string }>` + — même schéma d'enveloppe que `encryptThreadKeyForMember`. +- `unwrapAiSessionKey(encryptedKey: string, iv: string | undefined, privateKey: CryptoKey): Promise` + — inverse, utilise `privateKey.value` (la ref globale déjà déverrouillée par PIN, cf. `crypto.ts` existant). + +### 3.2 Nouveau service : `src/services/AiSessionKeyService.ts` (ou étendre `AIService.ts` — à toi de juger +selon la taille, mais garder ça séparé de la logique HTTP de chat est probablement plus propre) + +- Un `ref` en mémoire (jamais persisté en `localStorage`, cohérent avec la convention + existante pour `privateKey`), un par org actuellement ouverte (`Map` ou juste re-fetch à + chaque changement d'org — vérifie le pattern déjà utilisé pour `openedOrg` dans `var.ts`). +- `async function ensureAiSessionKey(orgId: string): Promise` : + 1. `GET /api/orgs/:orgId/ai/key` (nouvel endpoint, cf. plan `synco_api` §4.3). + 2. Si trouvé : déchiffrer avec `unwrapAiSessionKey` + `privateKey.value`, importer en `CryptoKey` via + `crypto.subtle.importKey('raw', bytes, 'AES-GCM', false, ['encrypt','decrypt'])`, cacher, retourner. + Si `privateKey.value` est `null` (PIN pas encore déverrouillé) : lever une erreur typée que l'appelant + (UI) doit traduire en message "déverrouillez votre sécurité pour accéder à l'IA", même pattern que le + `[🔒 Conversation chiffrée. Clé privée manquante.]` déjà affiché ailleurs dans `AIService.ts`. + 3. Si absent (404) : c'est la première fois que quelqu'un active le provider `gateway` pour cette org — + générer une nouvelle clé (`generateAiSessionKey`), l'envelopper pour soi-même + (`wrapAiSessionKeyForMember` avec sa propre clé publique), `POST /api/orgs/:orgId/ai/key`. **Décision à + prendre** : qui a le droit de faire ce bootstrap ? Probablement restreint aux mêmes permissions que + `AISettings.vue`/`saveSettings()` (admin d'org) — vérifie quelle vérification de permission encadre déjà + l'écriture de `activeModules.aiConfig` côté frontend/route, et applique la même règle ici pour cohérence + (même si l'endpoint `synco_api` fera de toute façon sa propre vérification serveur). +- `async function getAiSessionKeyRawBase64(orgId: string): Promise` — retourne la clé en base64 + standard (`crypto.subtle.exportKey('raw', key)` → base64), prête à poser dans le header `X-Session-Key`. +- Partage avec les autres membres de l'org (pour qu'ils puissent, eux aussi, lire l'historique) : nécessite + un flux où un membre qui a DÉJÀ la clé en enveloppe pour un NOUVEAU membre (qui vient de rejoindre l'org, ou + qui n'avait pas encore de ligne `AiSessionKey`). Regarde comment ce cas est géré aujourd'hui pour + `ThreadKey`/`WorkspaceKey` (probablement déclenché à l'ouverture d'un écran, ou par un admin) et réplique + exactement le même déclencheur pour rester cohérent avec le reste de l'app plutôt que d'introduire un + nouveau pattern UX. + +## 4. Changements dans `src/services/AIService.ts` + +### 4.1 `gatewayFetch` (méthode privée, lignes ~55-68) +Ajouter le header `X-Session-Key` : +```ts +const sessionKeyB64 = await getAiSessionKeyRawBase64(orgId); // nouveau +return fetch(url, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}), + 'X-Session-Key': sessionKeyB64, + }, + body: JSON.stringify(body), + signal, +}); +``` +Nécessite de faire passer `orgId` jusqu'à `gatewayFetch` (vérifie s'il l'a déjà — `chatAgentTurn`/ +`resumeAgentTurn` l'ont sûrement déjà dans leur propre scope). `listGatewayModels` (lignes ~384-402) n'a PAS +besoin de ce header — elle ne touche à aucun contenu de session, laisse-la inchangée. + +### 4.2 `fetchSessions()` (lignes ~420-430) — sidebar +Après réception de la liste, pour chaque session avec `encryptionScheme` non-null (nouveau champ renvoyé par +`synco_api`, cf. plan `synco_api` §4.1), déchiffrer `title` avec la clé de session AES (AAD : +`"{session.id}:__session_title__:title"`) avant de l'assigner à `chatSessions`. Si la clé n'est pas +disponible (PIN verrouillé), afficher un placeholder (`"🔒 Titre chiffré"`) plutôt que planter. + +### 4.3 `loadSession(id)` (lignes ~489-526) — trois formats à distinguer maintenant +1. **Legacy le plus ancien** : `messages` est directement un `StoredMessage[]` en clair (pré-existant, avant + tout chiffrement) — comportement actuel, inchangé. +2. **Legacy E2EE client-driven** : `messages` a la forme `{ isE2EE: true, ciphertext, encryptedAesKey, iv }` + (enveloppe RSA+AES-GCM auto-chiffrée, ancien flux `local`/`custom`) — comportement actuel + (`decryptFromPeer` + `privateKey.value`), inchangé. +3. **Nouveau — gateway-aes-gcm-v1** : `session.encryptionScheme === "gateway-aes-gcm-v1"` → `messages` est un + `StoredMessage[]` en clair au niveau structure JSON, mais avec `content`/`toolResult`/ + `toolCalls[].arguments` valant des chaînes opaques `"gcm1:..."`. Récupérer la clé via + `ensureAiSessionKey(orgId)`, puis déchiffrer chaque champ concerné (AAD par champ, cf. §2) avant de passer + le résultat à `convertStoredMessagesToChatMessages` (comportement inchangé à partir de là). + `pendingToolCall.args` (si présent au niveau session, pas par message) suit le même traitement (AAD + `"{session.id}:__pending__:pending_tool_call_args"`). + +Distingue les 3 cas AVANT de toucher au contenu : `session.encryptionScheme === 'gateway-aes-gcm-v1'` → cas 3 ; +sinon `typeof session.messages === 'object' && session.messages.isE2EE` → cas 2 ; sinon → cas 1 +(`isStructuredAgentTranscript` existant peut rester tel quel, appliqué APRÈS déchiffrement pour le cas 3). + +### 4.4 `syncSession()` (lignes ~552-603) — écriture du titre pour le nouveau flux +Ce chemin reste tel quel pour les providers `local`/`custom` (cas 2 ci-dessus). Pour le provider `gateway`, +ce n'est PAS `syncSession()` qui écrit les messages (c'est `Synco_AI_Gateway` qui le fait directement côté +serveur, cf. plan gateway) — mais le TITRE doit être posé côté client, puisque `synco_api` ne peut plus le +dériver lui-même (cf. plan `synco_api` §4.2). Ajoute une fonction dédiée : +```ts +async function setEncryptedSessionTitle(orgId: string, sessionId: string, plainTitle: string) { + const key = await ensureAiSessionKey(orgId); + const encryptedTitle = await encryptField(key, sessionId, '__session_title__', 'title', plainTitle.slice(0, 60)); + await sfetch(`/api/orgs/${orgId}/ai/sessions/${sessionId}`, { + method: 'PATCH', + body: JSON.stringify({ title: encryptedTitle }), + }); +} +``` +À appeler juste après l'envoi du tout premier message d'une nouvelle session gateway (dans `OrgAI.vue`, +`sendMessageViaAgent`, cf. §5) — le titre est calculé à partir du texte que l'utilisateur vient de taper, +donc disponible en clair côté client à ce moment précis, avant même que le gateway ne réponde. + +### 4.5 `deleteSession()` (lignes ~528-544) — aucun changement, opère sur l'id, pas le contenu. + +## 5. Changements dans `src/views/OrgSpace/views/OrgAI.vue` + +- `sendMessageViaAgent` (lignes ~979-999) : si c'est le tout premier message d'une session gateway + (`sessionId` encore vide/juste créé, ou `messages.value.length === 0` avant envoi), appeler + `setEncryptedSessionTitle(orgId, sessionId, userText)` (fire-and-forget, ne pas bloquer l'envoi du message + sur ça). +- `consumeAgentStream` (lignes ~833-876) : **aucun changement** — le flux SSE en direct depuis le gateway + reste en clair (canal direct navigateur↔gateway déjà de confiance), donc l'affichage live n'est pas + affecté par ce plan. Seul le rechargement d'historique (`loadSession`) est concerné. +- Watcher `fetchSessions()` au montage (lignes ~1078-1082) : aucun changement structurel, bénéficie + automatiquement du déchiffrement ajouté dans `fetchSessions()` (§4.2). + +## 6. Changements dans `src/views/OrgSpace/views/settings/views/AISettings.vue` + +- Dans `saveSettings()` (lignes ~360-428), quand l'admin sélectionne/confirme le provider `gateway` pour la + première fois (transition depuis un autre provider, ou premier réglage IA de l'org) : déclencher + `ensureAiSessionKey(orgId)` pour provisionner la clé AVANT ou juste après l'écriture de `activeModules.aiConfig` + — si ça échoue (pas de permission, RSA verrouillé), bloquer la sauvegarde avec un message clair plutôt que + de laisser l'org dans un état "provider=gateway mais pas de clé" qui ferait échouer silencieusement le + premier chat de n'importe quel membre. + +## 7. Changements dans `src/views/OrgSpace/components/layouts/ThreadsBar.vue` + +- Aucun changement structurel attendu — elle consomme `chatSessions` déjà déchiffré par `fetchSessions()` + (§4.2). Vérifie juste que l'état "titre non déchiffrable" (clé absente/PIN verrouillé) s'affiche proprement + dans la boucle `v-for` existante (lignes ~206-226) sans casser le layout. + +## 8. Ce qui NE change PAS + +- `src/assets/utils/workspaceCrypto.ts`, `webhookCrypto.ts`, `useSecurePeer.ts`, `SearchSyncService.ts` : hors + périmètre, ne pas toucher. +- Le flux `local`/`custom` (LLM local WebGPU, `LocalLLMService.ts`) : hors périmètre, déjà purement client-side + (jamais de contenu envoyé à un serveur), rien à changer. +- Providers `openai`/`mistral`/`gemini` (`sfetch('/api/orgs/${orgId}/ai/chat', ...)`) : hors périmètre, cf. §1. + +## 9. Perte d'accès / UX de récupération + +Si la clé privée RSA de l'utilisateur est perdue (PIN oublié, pas de sauvegarde), il perd l'accès à +l'historique IA chiffré — exactement le même compromis que pour les threads/espaces déjà E2EE dans ce repo. +Ne pas inventer un mécanisme de récupération spécifique à l'IA ; si un mécanisme de récupération existe déjà +pour la clé privée RSA générale (sauvegarde, réinitialisation admin, etc.), il couvre automatiquement ce cas +aussi. Vérifier qu'aucun message d'erreur nouveau introduit par ce plan ne laisse l'utilisateur bloqué sans +indication (réutiliser le message `[🔒 Conversation chiffrée. Clé privée manquante.]` existant comme modèle). + +## 10. Tests à écrire + +- Vecteur de test cryptographique du §2 (round-trip + comparaison avec la valeur `wire_value` fixe). +- `loadSession()` : un test par branche (legacy plain, legacy E2EE enveloppe, nouveau gateway-aes-gcm-v1), + avec des fixtures représentant chaque forme de `session.messages`. +- `ensureAiSessionKey()` : test du chemin bootstrap (404 → génération → POST) et du chemin normal (trouvé → + déchiffrement → cache). +- `AISettings.vue` : test que la sauvegarde est bloquée si le provisionnement de clé échoue. From c1e307711ab01c61cd2224c3378a05dce144315b Mon Sep 17 00:00:00 2001 From: Antigravity Bot Date: Thu, 10 Sep 2026 14:00:54 +0200 Subject: [PATCH 11/19] =?UTF-8?q?fix(tasks):=20include=20unassigned=20pers?= =?UTF-8?q?onal=20tasks=20in=20"Mes=20T=C3=A2ches"=20view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tasks created without a space and without an assignee (e.g. by the Synco AI agent's create_task tool, which never sets assigneeIds) were silently hidden: the frontend filter only checked assignees, ignoring the backend's listMyTasks() rule that a self-created, space-less task is also yours even if unassigned. Co-Authored-By: Claude Sonnet 5 --- src/views/OrgSpace/views/TasksGlobal.vue | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/views/OrgSpace/views/TasksGlobal.vue b/src/views/OrgSpace/views/TasksGlobal.vue index b56de31d..ba5d965a 100644 --- a/src/views/OrgSpace/views/TasksGlobal.vue +++ b/src/views/OrgSpace/views/TasksGlobal.vue @@ -347,8 +347,12 @@ const spacesGroups = computed(() => { rawTasks.value.forEach(task => { - // Only show tasks assigned to me - if (!task.assignees?.some(a => a.id === user.value?.id)) return; + // Une tâche m'appartient si elle m'est assignée, ou si je l'ai créée sans espace + // (tâche personnelle non assignée, ex: créée par l'agent IA) — même règle que + // listMyTasks() côté backend (tasksService.ts). + const isAssignedToMe = task.assignees?.some(a => a.id === user.value?.id); + const isMyPersonalTask = !task.spaceId && task.creatorId === user.value?.id; + if (!isAssignedToMe && !isMyPersonalTask) return; if (!task.spaceId) { groups['personal']!.tasks.push(task); From dd80740fd582b33a95380f524626a73d70420a05 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:32:59 +0200 Subject: [PATCH 12/19] feat(crypto): AI session key wrapping + gcm1 field encryption primitives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds generateAiSessionKey/wrapAiSessionKeyForMember/unwrapAiSessionKey (RSA-OAEP envelope for the per-org AES session key, mirroring the existing ThreadKey pattern) and encryptAiField/decryptAiField (the "gcm1:" AES-256-GCM wire format shared with Synco_AI_Gateway/synco_api, AAD-bound to session/message/field) per E2EE_PLAN.md §2-3. Test vector round-trips against the fixed wire_value from the plan. Note: the plan's "key (hex)" line is missing a trailing nibble (63 hex chars); the test derives the key from the accompanying base64 value instead, which does produce the documented wire_value. Test files are excluded from the app tsconfig (bun:test runs without type-checking; no test infra existed in this repo before). --- src/assets/utils/crypto.aiSession.test.ts | 80 ++++++++++++++++ src/assets/utils/crypto.ts | 112 ++++++++++++++++++++++ tsconfig.app.json | 3 +- 3 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 src/assets/utils/crypto.aiSession.test.ts diff --git a/src/assets/utils/crypto.aiSession.test.ts b/src/assets/utils/crypto.aiSession.test.ts new file mode 100644 index 00000000..53b95c00 --- /dev/null +++ b/src/assets/utils/crypto.aiSession.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, test } from "bun:test"; +import { decryptAiField, encryptAiField } from "./crypto"; + +/** + * Vecteur de test partagé avec `Synco_AI_Gateway`/E2EE_PLAN.md et `synco_api`/E2EE_PLAN.md §2 — + * vérifie l'interopérabilité du wire format sans faire tourner les 2 autres implémentations. + * + * NB: la ligne `key (hex, 32 octets)` du document E2EE_PLAN.md est tronquée d'un nibble + * ("...4081d791" au lieu de "...4081d7911", 63 caractères hex au lieu de 64) — on part donc de la + * valeur `key (base64)` du même document, qui elle décode bien en 32 octets et produit le + * `wire_value` attendu. + */ +const KEY_BASE64 = "2C8mRtERMnD1j6Pa9k3n6fZCUxI6Dsf9uqJONAgdeRE="; +const NONCE_HEX = "1024c8c26840d416f50b5072"; +const SESSION_ID = "sess_test0000000000000000000001"; +const MESSAGE_ID = "msg_test00000000000000000000001"; +const FIELD_NAME = "content"; +const PLAINTEXT = "Bonjour, ceci est un message de test pour Synco AI."; +const EXPECTED_WIRE = "gcm1:ECTIwmhA1Bb1C1ByL8IECZj8SkBl2TYmk9665e/jnrCQNjYdR+CMirRU75qIq5pxnrallgkaWQtrQreT8eCSCf6JAzUrY5mTb/Ez42WxSw=="; + +function hexToBytes(hex: string): Uint8Array { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16); + return bytes; +} + +async function importTestKey(): Promise { + const rawKey = Uint8Array.from(atob(KEY_BASE64), c => c.charCodeAt(0)); + return crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]); +} + +describe("AI session field wire format (gcm1)", () => { + + test("decrypts the fixed wire_value from the plan into the expected plaintext", async () => { + const key = await importTestKey(); + const decrypted = await decryptAiField(key, SESSION_ID, MESSAGE_ID, FIELD_NAME, EXPECTED_WIRE); + expect(decrypted).toBe(PLAINTEXT); + }); + + test("encrypting with the vector's nonce reproduces the exact fixed wire_value", async () => { + const key = await importTestKey(); + + // encryptAiField génère son propre nonce aléatoire ; on reproduit ici le format à la main + // avec le nonce fixe du vecteur pour vérifier l'égalité byte-à-byte avec `wire_value`. + const iv = hexToBytes(NONCE_HEX); + const aad = new TextEncoder().encode(`${SESSION_ID}:${MESSAGE_ID}:${FIELD_NAME}`); + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv: iv as BufferSource, additionalData: aad as BufferSource, tagLength: 128 }, + key, + new TextEncoder().encode(PLAINTEXT) + ); + const combined = new Uint8Array(iv.length + ciphertext.byteLength); + combined.set(iv, 0); + combined.set(new Uint8Array(ciphertext), iv.length); + const wire = "gcm1:" + btoa(String.fromCharCode(...combined)); + + expect(wire).toBe(EXPECTED_WIRE); + }); + + test("round-trips arbitrary plaintext through encryptAiField/decryptAiField", async () => { + const key = await importTestKey(); + const text = "Un message plus long, avec des caractères accentués éàç et un peu de JSON: {\"a\":1}"; + const wire = await encryptAiField(key, SESSION_ID, MESSAGE_ID, "tool_result", text); + + expect(wire.startsWith("gcm1:")).toBe(true); + + const decrypted = await decryptAiField(key, SESSION_ID, MESSAGE_ID, "tool_result", wire); + expect(decrypted).toBe(text); + }); + + test("fails to decrypt when the AAD (field_name) doesn't match — binds ciphertext to its field", async () => { + const key = await importTestKey(); + const wire = await encryptAiField(key, SESSION_ID, MESSAGE_ID, "content", "secret"); + + await expect( + decryptAiField(key, SESSION_ID, MESSAGE_ID, "title", wire) + ).rejects.toThrow(); + }); + +}); diff --git a/src/assets/utils/crypto.ts b/src/assets/utils/crypto.ts index 59cd157e..5910c098 100644 --- a/src/assets/utils/crypto.ts +++ b/src/assets/utils/crypto.ts @@ -470,6 +470,118 @@ export function lockSecurity() } +// For AI session E2EE (provider 'gateway' — clé de session partagée par organisation) + +export async function generateAiSessionKey(): Promise +{ + return await crypto.subtle.generateKey( + { name: "AES-GCM", length: 256 }, + true, + ["encrypt", "decrypt"] + ); +} + +export async function wrapAiSessionKeyForMember( + rawKeyBytes: ArrayBuffer, + recipientPublicKeyJWK: string | object +): Promise +{ + + const pubKey = await crypto.subtle.importKey( + "jwk", + typeof recipientPublicKeyJWK === 'string' ? JSON.parse(recipientPublicKeyJWK) : recipientPublicKeyJWK, + { name: "RSA-OAEP", hash: "SHA-256" }, + false, + ["encrypt"] + ); + + const encryptedBuffer = await crypto.subtle.encrypt( + { name: "RSA-OAEP" }, + pubKey, + rawKeyBytes + ); + + return btoa(String.fromCharCode(...new Uint8Array(encryptedBuffer))); + +} + +export async function unwrapAiSessionKey( + encryptedKeyBase64: string, + myPrivateKey: CryptoKey +): Promise +{ + + const encryptedKeyBuffer = Uint8Array.from(atob(encryptedKeyBase64), c => c.charCodeAt(0)); + + return await crypto.subtle.decrypt( + { name: "RSA-OAEP" }, + myPrivateKey, + encryptedKeyBuffer + ); + +} + +/** + * Wire format partagé avec `Synco_AI_Gateway` et `synco_api` (cf. E2EE_PLAN.md §2) : + * "gcm1:" + base64standard(nonce(12) || ciphertext||tag(16)), AAD = "{sessionId}:{messageId}:{fieldName}". + */ +export async function encryptAiField( + key: CryptoKey, + sessionId: string, + messageId: string, + fieldName: string, + plaintext: string +): Promise +{ + + const encoder = new TextEncoder(); + const iv = crypto.getRandomValues(new Uint8Array(12)); + const aad = encoder.encode(`${sessionId}:${messageId}:${fieldName}`); + + const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv, additionalData: aad, tagLength: 128 }, + key, + encoder.encode(plaintext) + ); + + const combined = new Uint8Array(iv.length + ciphertext.byteLength); + combined.set(iv, 0); + combined.set(new Uint8Array(ciphertext), iv.length); + + return "gcm1:" + btoa(String.fromCharCode(...combined)); + +} + +export async function decryptAiField( + key: CryptoKey, + sessionId: string, + messageId: string, + fieldName: string, + wireValue: string +): Promise +{ + + if (!wireValue.startsWith("gcm1:")) { + throw new Error("Format de champ IA chiffré inconnu."); + } + + const encoder = new TextEncoder(); + const raw = Uint8Array.from(atob(wireValue.slice(5)), c => c.charCodeAt(0)); + const iv = raw.slice(0, 12); + const ciphertext = raw.slice(12); + const aad = encoder.encode(`${sessionId}:${messageId}:${fieldName}`); + + const decrypted = await crypto.subtle.decrypt( + { name: "AES-GCM", iv, additionalData: aad, tagLength: 128 }, + key, + ciphertext + ); + + return new TextDecoder().decode(decrypted); + +} + + export const generateSalt = (): string => { const array = new Uint8Array(16); diff --git a/tsconfig.app.json b/tsconfig.app.json index 80955ce3..4ffc38a5 100644 --- a/tsconfig.app.json +++ b/tsconfig.app.json @@ -16,5 +16,6 @@ "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, - "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"], + "exclude": ["src/**/*.test.ts"] } \ No newline at end of file From a2e86a9d081dcf072cfe1d618e0030e980f9dcdd Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:35:29 +0200 Subject: [PATCH 13/19] =?UTF-8?q?feat(ai):=20AiSessionKeyService=20?= =?UTF-8?q?=E2=80=94=20per-org=20AI=20session=20key=20fetch/bootstrap/cach?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ensureAiSessionKey(orgId) fetches the caller's wrapped AiSessionKey (GET /api/orgs/:orgId/ai/key per synco_api's E2EE_PLAN.md §4.3), unwraps it with the user's RSA private key, and caches the imported CryptoKey + raw base64 in memory only (never localStorage, same convention as `privateKey` in crypto.ts). On 404 (no key provisioned yet for this org) it bootstraps: generates a new key, wraps it for self, and POSTs it — no separate admin check client-side, matching AISettings.vue/saveSettings() which also leaves that to the server. getAiSessionKeyRawBase64 exposes the raw key for the gateway's X-Session-Key header. shareAiSessionKeyWithMember re-wraps the already-cached key for another member's public key (used when onboarding a member who doesn't have a key yet). Tests cover the bootstrap path, the normal fetch+unwrap path, the locked-PIN error, and request de-duplication for concurrent callers — the concurrency test caught a real unhandled-rejection bug in the `pending` map's cleanup (`.finally()` returns an unawaited promise that must itself be caught). --- src/services/AiSessionKeyService.test.ts | 119 +++++++++++++++++ src/services/AiSessionKeyService.ts | 160 +++++++++++++++++++++++ 2 files changed, 279 insertions(+) create mode 100644 src/services/AiSessionKeyService.test.ts create mode 100644 src/services/AiSessionKeyService.ts diff --git a/src/services/AiSessionKeyService.test.ts b/src/services/AiSessionKeyService.test.ts new file mode 100644 index 00000000..11b0beaf --- /dev/null +++ b/src/services/AiSessionKeyService.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, mock, test } from "bun:test"; + +// `@/assets/utils/sfetch` transitively imports keycloak.ts (Keycloak client, Capacitor/Tauri +// plugins) which has browser-only import-time side effects — mock it out before anything else +// imports it, and dynamically import the modules under test afterwards so they pick up the mock. +let sfetchImpl: (url: string, init?: any) => Promise = async () => new Response(null, { status: 500 }); + +mock.module("@/assets/utils/sfetch", () => ({ + default: (url: string, init?: any) => sfetchImpl(url, init), +})); + +const { ensureAiSessionKey, getAiSessionKeyRawBase64, AiSessionKeyUnavailableError } = await import("./AiSessionKeyService"); +const { user } = await import("@/assets/var"); +const { privateKey, wrapAiSessionKeyForMember } = await import("@/assets/utils/crypto"); + +async function generateTestIdentity() { + const keyPair = await crypto.subtle.generateKey( + { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + true, + ["encrypt", "decrypt"] + ); + const publicKeyJWK = JSON.stringify(await crypto.subtle.exportKey("jwk", keyPair.publicKey)); + return { publicKeyJWK, privateKey: keyPair.privateKey }; +} + +describe("ensureAiSessionKey", () => { + + test("bootstrap (404): generates a new key, wraps it for self, and POSTs it", async () => { + const identity = await generateTestIdentity(); + user.value = { id: "u1", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + let getCalls = 0; + let postBody: any = null; + sfetchImpl = async (_url, init) => { + if (!init?.method) { + getCalls++; + return new Response(null, { status: 404 }); + } + if (init.method === "POST") { + postBody = JSON.parse(init.body); + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + } + throw new Error(`unexpected method: ${init.method}`); + }; + + const orgId = "org-bootstrap"; + const key = await ensureAiSessionKey(orgId); + + expect(key).toBeDefined(); + expect(typeof postBody.encryptedKey).toBe("string"); + expect(postBody.encryptedKey.length).toBeGreaterThan(0); + + // Cache hit: a second call must not re-fetch. + getCalls = 0; + await ensureAiSessionKey(orgId); + expect(getCalls).toBe(0); + }); + + test("normal path (found): fetches, unwraps with the private key, and caches the raw key", async () => { + const identity = await generateTestIdentity(); + user.value = { id: "u2", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + const rawKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); + const rawBytes = await crypto.subtle.exportKey("raw", rawKey); + const encryptedKey = await wrapAiSessionKeyForMember(rawBytes, identity.publicKeyJWK); + const expectedB64 = btoa(String.fromCharCode(...new Uint8Array(rawBytes))); + + sfetchImpl = async (_url, init) => { + if (!init?.method) { + return new Response(JSON.stringify({ encryptedKey }), { status: 200 }); + } + throw new Error(`unexpected method: ${init.method}`); + }; + + const orgId = "org-normal"; + await ensureAiSessionKey(orgId); + const rawB64 = await getAiSessionKeyRawBase64(orgId); + + expect(rawB64).toBe(expectedB64); + }); + + test("throws AiSessionKeyUnavailableError when the private key is locked (PIN not entered)", async () => { + privateKey.value = null; + sfetchImpl = async () => new Response(null, { status: 404 }); + + let caught: unknown = null; + try { + await ensureAiSessionKey("org-locked"); + } catch (e) { + caught = e; + } + + expect(caught).toBeInstanceOf(AiSessionKeyUnavailableError); + }); + + test("concurrent calls for the same org only trigger a single GET", async () => { + const identity = await generateTestIdentity(); + user.value = { id: "u3", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + let getCalls = 0; + sfetchImpl = async (_url, init) => { + if (!init?.method) { + getCalls++; + await new Promise((r) => setTimeout(r, 10)); + return new Response(null, { status: 404 }); + } + return new Response(JSON.stringify({ ok: true }), { status: 200 }); + }; + + const orgId = "org-concurrent"; + await Promise.all([ensureAiSessionKey(orgId), ensureAiSessionKey(orgId), ensureAiSessionKey(orgId)]); + + expect(getCalls).toBe(1); + }); + +}); diff --git a/src/services/AiSessionKeyService.ts b/src/services/AiSessionKeyService.ts new file mode 100644 index 00000000..2ff74f41 --- /dev/null +++ b/src/services/AiSessionKeyService.ts @@ -0,0 +1,160 @@ +import sfetch from '@/assets/utils/sfetch'; +import { user } from '@/assets/var'; +import { + privateKey, + generateAiSessionKey, + wrapAiSessionKeyForMember, + unwrapAiSessionKey, +} from '@/assets/utils/crypto'; + +/** + * Erreur typée levée par `ensureAiSessionKey`/`getAiSessionKeyRawBase64` — l'appelant (UI) doit la + * traduire en message utilisateur, sur le même principe que le placeholder + * "[🔒 Conversation chiffrée. Clé privée manquante.]" déjà utilisé dans AIService.ts. + */ +export class AiSessionKeyUnavailableError extends Error {} + +interface CachedAiSessionKey { + cryptoKey: CryptoKey; + rawBase64: string; +} + +// Clé de session IA par organisation, en mémoire uniquement — jamais persistée en localStorage, +// cohérent avec la convention existante pour `privateKey` dans crypto.ts. +const cache = new Map(); +const pending = new Map>(); + +function bytesToBase64(bytes: ArrayBuffer): string { + return btoa(String.fromCharCode(...new Uint8Array(bytes))); +} + +function base64ToBytes(b64: string): ArrayBuffer { + return Uint8Array.from(atob(b64), c => c.charCodeAt(0)).buffer; +} + +async function toCachedKey(rawKeyBytes: ArrayBuffer): Promise { + const cryptoKey = await crypto.subtle.importKey( + 'raw', rawKeyBytes, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'] + ); + return { cryptoKey, rawBase64: bytesToBase64(rawKeyBytes) }; +} + +/** + * Première activation du provider 'gateway' pour cette org : personne n'a encore de clé de + * session IA, on en génère une et on l'enveloppe pour soi-même. L'endpoint synco_api fait sa + * propre vérification de permission (cf. plan synco_api §4.3) — comme AISettings.vue/saveSettings() + * ne fait elle-même aucun contrôle de rôle côté client pour écrire activeModules.aiConfig, on + * n'en duplique pas non plus ici. + */ +async function bootstrapAiSessionKey(orgId: string): Promise { + if (!user.value?.publicKey) { + throw new AiSessionKeyUnavailableError("Votre clé publique de chiffrement E2EE n'est pas configurée."); + } + + const sessionKey = await generateAiSessionKey(); + const rawKeyBytes = await crypto.subtle.exportKey('raw', sessionKey); + const encryptedKey = await wrapAiSessionKeyForMember(rawKeyBytes, user.value.publicKey); + + const res = await sfetch(`/api/orgs/${orgId}/ai/key`, { + method: 'POST', + body: JSON.stringify({ encryptedKey }), + }); + + if (!res.ok) { + const body = await res.text().catch(() => ''); + throw new AiSessionKeyUnavailableError(`Impossible de provisionner la clé de session IA (${res.status}): ${body}`); + } + + return toCachedKey(rawKeyBytes); +} + +/** + * Récupère (et déchiffre) la clé de session IA de l'org courante, en la mettant en cache pour les + * appels suivants. Si aucune clé n'existe encore pour l'org (404), en génère une nouvelle + * (bootstrap, cf. E2EE_PLAN.md §3.2). + */ +export async function ensureAiSessionKey(orgId: string): Promise { + const cached = cache.get(orgId); + if (cached) return cached.cryptoKey; + + let inflight = pending.get(orgId); + if (!inflight) { + inflight = (async () => { + if (!privateKey.value) { + throw new AiSessionKeyUnavailableError('🔒 Déverrouillez votre sécurité (code PIN) pour accéder à l\'IA.'); + } + const myPrivateKey = privateKey.value; + + const res = await sfetch(`/api/orgs/${orgId}/ai/key`); + + let result: CachedAiSessionKey; + if (res.status === 404) { + result = await bootstrapAiSessionKey(orgId); + } else if (res.ok) { + const { encryptedKey } = await res.json(); + const rawKeyBytes = await unwrapAiSessionKey(encryptedKey, myPrivateKey); + result = await toCachedKey(rawKeyBytes); + } else { + const body = await res.text().catch(() => ''); + throw new AiSessionKeyUnavailableError(`Erreur de récupération de la clé de session IA (${res.status}): ${body}`); + } + + cache.set(orgId, result); + return result; + })(); + pending.set(orgId, inflight); + // Le retour de `.finally()` est une promesse distincte, non attendue par ailleurs : sans ce + // `.catch`, un rejet de `inflight` la ferait aussi rejeter sans jamais être capturée + // (unhandled rejection), même si l'appelant gère bien l'erreur via `await inflight` plus bas. + inflight.finally(() => pending.delete(orgId)).catch(() => {}); + } + + const result = await inflight; + return result.cryptoKey; +} + +/** Clé brute en base64, prête à poser dans le header `X-Session-Key` envoyé à la gateway. */ +export async function getAiSessionKeyRawBase64(orgId: string): Promise { + const cached = cache.get(orgId); + if (cached) return cached.rawBase64; + await ensureAiSessionKey(orgId); + return cache.get(orgId)!.rawBase64; +} + +/** À appeler quand la sécurité E2EE est verrouillée (PIN reverrouillé, changement d'utilisateur, etc). */ +export function clearAiSessionKeyCache(orgId?: string) { + if (orgId) { + cache.delete(orgId); + pending.delete(orgId); + } else { + cache.clear(); + pending.clear(); + } +} + +/** + * Partage la clé de session IA déjà connue localement avec un autre membre de l'org (nouveau + * membre, ou membre dont la ligne AiSessionKey n'a pas encore été provisionnée). Utilise les + * octets bruts mis en cache lors du dernier `ensureAiSessionKey` — la CryptoKey elle-même est + * importée non-extractable et ne peut pas être ré-exportée. + */ +export async function shareAiSessionKeyWithMember( + orgId: string, + targetUserId: string, + targetPublicKeyJWK: string | object +): Promise { + await ensureAiSessionKey(orgId); + const cached = cache.get(orgId)!; + + const encryptedKey = await wrapAiSessionKeyForMember(base64ToBytes(cached.rawBase64), targetPublicKeyJWK); + + const res = await sfetch(`/api/orgs/${orgId}/ai/key`, { + method: 'POST', + body: JSON.stringify({ encryptedKey, targetUserId }), + }); + + if (!res.ok) { + const body = await res.text().catch(() => ''); + throw new Error(`Impossible de partager la clé de session IA (${res.status}): ${body}`); + } +} From ebc0baa1e5224f46744573264b0986cabcd27f8b Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:39:05 +0200 Subject: [PATCH 14/19] feat(ai): E2EE for gateway AI sessions in AIService.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - gatewayFetch now sends X-Session-Key (org's AI session key, raw base64) so Synco_AI_Gateway can decrypt/encrypt session fields — synco_api never sees this key or the plaintext content. Plumbed through chatAgentTurn/resumeAgentTurn, which already had orgId. - fetchSessions() decrypts each session's title (gateway-aes-gcm-v1, "gcm1:"-prefixed) for the sidebar; a still-plain default title (not yet PATCHed) is left as-is, a decrypt failure (locked PIN) falls back to a placeholder rather than showing ciphertext. - loadSession() now distinguishes 3 message-storage formats: legacy plain, legacy E2EE envelope (local/custom, unchanged), and the new gateway-aes-gcm-v1 — StoredMessage[] in clear JSON structure but with content/toolResult/toolCalls[].arguments as opaque "gcm1:" strings, decrypted per-field via decryptGatewaySessionMessages() before going through the existing turn-reconstruction path. A locked private key or any decrypt error falls back to the same "[🔒 ...]"/"[⚠️ ...]" placeholders already used for legacy E2EE, instead of crashing or leaking ciphertext. - setEncryptedSessionTitle(orgId, sessionId, plainTitle): encrypts and PATCHes the title for a gateway session (called from OrgAI.vue after the first message, next commit) — synco_api can no longer derive a title itself once content is opaque to it. - pendingToolCall.args is deliberately left encrypted in loadSession: no frontend code reads session.pendingToolCall today, so decrypting it would be dead work; noted inline for whoever wires that up. Tests cover all 3 loadSession branches plus their locked-PIN fallback paths, using fixtures built with the real crypto primitives (self grown AI session key wrapped for a test RSA identity, encrypted via encryptAiField) rather than hand-rolled ciphertext. --- src/services/AIService.loadSession.test.ts | 156 +++++++++++++++++++++ src/services/AIService.ts | 121 ++++++++++++++-- 2 files changed, 264 insertions(+), 13 deletions(-) create mode 100644 src/services/AIService.loadSession.test.ts diff --git a/src/services/AIService.loadSession.test.ts b/src/services/AIService.loadSession.test.ts new file mode 100644 index 00000000..88d90fde --- /dev/null +++ b/src/services/AIService.loadSession.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, mock, test } from "bun:test"; + +// Même stratégie que AiSessionKeyService.test.ts : mock `sfetch` avant tout import, pour éviter +// d'importer keycloak.ts (side effects navigateur) et pour contrôler les réponses HTTP des deux +// endpoints traversés par loadSession() dans ce module : /ai/sessions/:id et /ai/key (via +// ensureAiSessionKey, appelé en interne pour le cas 'gateway-aes-gcm-v1'). +let sfetchImpl: (url: string, init?: any) => Promise = async () => new Response(null, { status: 500 }); + +mock.module("@/assets/utils/sfetch", () => ({ + default: (url: string, init?: any) => sfetchImpl(url, init), +})); + +const { loadSession, aiSessionMessages } = await import("./AIService"); +const { openedOrg, user } = await import("@/assets/var"); +const { privateKey, wrapAiSessionKeyForMember, encryptAiField, encryptForPeer } = await import("@/assets/utils/crypto"); + +async function generateTestIdentity() { + const keyPair = await crypto.subtle.generateKey( + { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, + true, + ["encrypt", "decrypt"] + ); + const publicKeyJWK = JSON.stringify(await crypto.subtle.exportKey("jwk", keyPair.publicKey)); + return { publicKeyJWK, privateKey: keyPair.privateKey }; +} + +function routeByUrl(routes: Record Promise | Response>) { + return async (url: string, init?: any) => { + for (const [suffix, handler] of Object.entries(routes)) { + if (url.endsWith(suffix) && (!init?.method || init.method === 'GET')) { + return handler(); + } + } + throw new Error(`unexpected sfetch call: ${init?.method || 'GET'} ${url}`); + }; +} + +describe("loadSession — the 3 message formats it must distinguish", () => { + + test("case 1 — legacy plain: messages already in clear, passed through untouched", async () => { + openedOrg.value = { id: "org-plain" } as any; + + const fixture = [{ role: "user", content: "Bonjour" }, { role: "assistant", content: "Salut !" }]; + sfetchImpl = routeByUrl({ + "/ai/sessions/sess-plain": () => new Response(JSON.stringify({ id: "sess-plain", messages: fixture }), { status: 200 }), + }); + + await loadSession("sess-plain"); + + expect(aiSessionMessages.value).toEqual(fixture); + }); + + test("case 2 — legacy E2EE envelope (local/custom): self-encrypted via encryptForPeer, decrypted with the private key", async () => { + const identity = await generateTestIdentity(); + openedOrg.value = { id: "org-legacy-e2ee" } as any; + user.value = { id: "u1", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + const original = [{ role: "user", content: "Message confidentiel" }]; + const encrypted = await encryptForPeer(JSON.stringify(original), identity.publicKeyJWK, identity.publicKeyJWK); + + sfetchImpl = routeByUrl({ + "/ai/sessions/sess-legacy": () => new Response(JSON.stringify({ + id: "sess-legacy", + messages: { + isE2EE: true, + ciphertext: encrypted.ciphertext, + encryptedAesKey: encrypted.selfEncryptedAesKey, + iv: encrypted.iv, + }, + }), { status: 200 }), + }); + + await loadSession("sess-legacy"); + + expect(aiSessionMessages.value).toEqual(original); + }); + + test("case 2 fallback — legacy E2EE envelope but private key locked: shows the placeholder instead of crashing", async () => { + openedOrg.value = { id: "org-legacy-locked" } as any; + privateKey.value = null; + + sfetchImpl = routeByUrl({ + "/ai/sessions/sess-legacy-locked": () => new Response(JSON.stringify({ + id: "sess-legacy-locked", + messages: { isE2EE: true, ciphertext: "x", encryptedAesKey: "y", iv: "z" }, + }), { status: 200 }), + }); + + await loadSession("sess-legacy-locked"); + + expect(aiSessionMessages.value).toEqual([{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]); + }); + + test("case 3 — new gateway-aes-gcm-v1: opaque gcm1: fields decrypted with the org's AI session key", async () => { + const identity = await generateTestIdentity(); + openedOrg.value = { id: "org-gateway" } as any; + user.value = { id: "u2", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + const sessionKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); + const rawKeyBytes = await crypto.subtle.exportKey("raw", sessionKey); + const encryptedKey = await wrapAiSessionKeyForMember(rawKeyBytes, identity.publicKeyJWK); + + const sessionId = "sess-gateway"; + const encryptedContent = await encryptAiField(sessionKey, sessionId, "m1", "content", "Quel temps fait-il ?"); + const encryptedArgs = await encryptAiField(sessionKey, sessionId, "m2", "tool_call_arguments:call1", JSON.stringify({ city: "Paris" })); + const encryptedToolResult = await encryptAiField(sessionKey, sessionId, "m3", "tool_result", JSON.stringify({ ok: true, weather: "sunny" })); + + sfetchImpl = routeByUrl({ + "/ai/key": () => new Response(JSON.stringify({ encryptedKey }), { status: 200 }), + "/ai/sessions/sess-gateway": () => new Response(JSON.stringify({ + id: sessionId, + encryptionScheme: "gateway-aes-gcm-v1", + // Ordre chronologique réel : user -> assistant (propose le tool call) -> tool (résultat). + messages: [ + { id: "m1", role: "user", content: encryptedContent }, + { id: "m2", role: "assistant", content: null, toolCalls: [{ id: "call1", name: "get_weather", arguments: encryptedArgs, status: "pending" }] }, + { id: "m3", role: "tool", toolCallId: "call1", toolResult: encryptedToolResult }, + ], + }), { status: 200 }), + }); + + await loadSession("sess-gateway"); + + // isStructuredAgentTranscript() détecte le rôle 'tool'/toolCalls et reconstruit des "turns" — + // on vérifie donc le contenu déchiffré à travers la structure reconstruite par + // convertStoredMessagesToChatMessages, pas les StoredMessage bruts. + const messages = aiSessionMessages.value as any[]; + expect(messages[0]).toEqual({ role: "user", content: "Quel temps fait-il ?" }); + + const assistantTurn = messages[1]; + expect(assistantTurn.role).toBe("assistant"); + const toolPart = assistantTurn.parts.find((p: any) => p.type === "tool"); + expect(toolPart.tool.args).toEqual({ city: "Paris" }); + expect(toolPart.tool.result).toEqual({ ok: true, weather: "sunny" }); + }); + + test("case 3 fallback — gateway session but private key locked: shows the placeholder instead of crashing", async () => { + openedOrg.value = { id: "org-gateway-locked" } as any; + privateKey.value = null; + + sfetchImpl = routeByUrl({ + "/ai/sessions/sess-gateway-locked": () => new Response(JSON.stringify({ + id: "sess-gateway-locked", + encryptionScheme: "gateway-aes-gcm-v1", + messages: [{ id: "m1", role: "user", content: "gcm1:doesnotmatter" }], + }), { status: 200 }), + }); + + await loadSession("sess-gateway-locked"); + + expect(aiSessionMessages.value).toEqual([{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]); + }); + +}); diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 6aedeadc..25d7bd98 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -3,7 +3,8 @@ import { localLLM } from './LocalLLMService'; import { computed, ref } from 'vue'; import sfetch from '@/assets/utils/sfetch'; import { keycloak } from '@/assets/keycloak'; -import { encryptForPeer, decryptFromPeer, privateKey } from '@/assets/utils/crypto'; +import { encryptForPeer, decryptFromPeer, privateKey, encryptAiField, decryptAiField } from '@/assets/utils/crypto'; +import { ensureAiSessionKey, getAiSessionKeyRawBase64, AiSessionKeyUnavailableError } from './AiSessionKeyService'; export interface AIProviderConfig { provider: 'local' | 'openai' | 'gemini' | 'mistral' | 'custom' | 'gateway'; @@ -51,16 +52,21 @@ export class AIService { * Appel direct navigateur → passerelle, sans passer par sfetch (qui cible toujours * VITE_API_URL) : on attache le même token Keycloak à la main, exactement comme sfetch le * ferait, mais vers une origine arbitraire (l'URL de la Synco AI Gateway auto-hébergée). + * Porte aussi la clé de session IA de l'org (X-Session-Key) — la passerelle en a besoin pour + * déchiffrer/chiffrer les champs sensibles avant/après son propre appel à synco_api, cf. + * E2EE_PLAN.md §3-4. `synco_api` ne voit jamais cette clé (appel direct navigateur→gateway). */ - private async gatewayFetch(url: string, body: any, signal: AbortSignal): Promise { + private async gatewayFetch(orgId: string, url: string, body: any, signal: AbortSignal): Promise { if (keycloak.authenticated) { await keycloak.updateToken(60).catch(() => {}); } + const sessionKeyB64 = await getAiSessionKeyRawBase64(orgId); return fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}), + 'X-Session-Key': sessionKeyB64, }, body: JSON.stringify(body), signal, @@ -80,7 +86,7 @@ export class AIService { if (this.config.provider === 'gateway') { const gatewayUrl = (this.config.gatewayUrl || '').replace(/\/$/, ''); - response = await this.gatewayFetch(`${gatewayUrl}/chat`, { + response = await this.gatewayFetch(orgId, `${gatewayUrl}/chat`, { orgId, sessionId: sessionId || undefined, message, @@ -110,7 +116,7 @@ export class AIService { if (this.config.provider === 'gateway') { const gatewayUrl = (this.config.gatewayUrl || '').replace(/\/$/, ''); - response = await this.gatewayFetch(`${gatewayUrl}/chat/${sessionId}/tool-result`, { + response = await this.gatewayFetch(orgId, `${gatewayUrl}/chat/${sessionId}/tool-result`, { orgId, syncoApiUrl: import.meta.env.VITE_API_URL, modelId: this.config.modelId, @@ -420,9 +426,25 @@ export const activeSessionId = ref(null); export const fetchSessions = async () => { if (!openedOrg.value) return; try { - const res = await sfetch(`/api/orgs/${openedOrg.value.id}/ai/sessions`); + const orgId = openedOrg.value.id; + const res = await sfetch(`/api/orgs/${orgId}/ai/sessions`); if (res.ok) { - chatSessions.value = await res.json(); + const sessions: any[] = await res.json(); + + await Promise.all(sessions.map(async (session) => { + // Titre chiffré côté client (provider 'gateway' uniquement, cf. setEncryptedSessionTitle) — + // un titre pas encore posé (session flambant neuve) reste le défaut en clair de synco_api. + if (session.encryptionScheme === 'gateway-aes-gcm-v1' && typeof session.title === 'string' && session.title.startsWith('gcm1:')) { + try { + const key = await ensureAiSessionKey(orgId); + session.title = await decryptAiField(key, session.id, '__session_title__', 'title', session.title); + } catch (e) { + session.title = '🔒 Titre chiffré'; + } + } + })); + + chatSessions.value = sessions; } } catch (e) { console.error("Erreur chargement des sessions", e); @@ -486,22 +508,74 @@ function isStructuredAgentTranscript(messages: any[]): boolean { return messages.some((m) => m.role === 'tool' || (Array.isArray(m.toolCalls) && m.toolCalls.length > 0)); } +/** + * Déchiffre les champs opaques `"gcm1:..."` d'un StoredMessage[] issu du nouveau flux agent + * serveur (provider 'gateway', session.encryptionScheme === 'gateway-aes-gcm-v1') : `content`, + * `toolResult`, `toolCalls[].arguments`, tous liés par AAD à `session.id` + l'id du message + * (cf. E2EE_PLAN.md §2 et §4.3). `pendingToolCall.args` n'est décrypté nulle part côté frontend + * aujourd'hui (aucun composant ne lit `session.pendingToolCall`) — laissé chiffré tel quel plutôt + * que déchiffré pour rien ; utiliser decryptAiField(key, session.id, '__pending__', + * 'pending_tool_call_args', ...) le jour où une UI en a besoin. + */ +async function decryptGatewaySessionMessages(key: CryptoKey, sessionId: string, messages: any[]): Promise { + return Promise.all(messages.map(async (m) => { + const out = { ...m }; + + if (typeof out.content === 'string' && out.content.startsWith('gcm1:')) { + out.content = await decryptAiField(key, sessionId, m.id, 'content', out.content); + } + + if (typeof out.toolResult === 'string' && out.toolResult.startsWith('gcm1:')) { + out.toolResult = JSON.parse(await decryptAiField(key, sessionId, m.id, 'tool_result', out.toolResult)); + } + + if (Array.isArray(out.toolCalls)) { + out.toolCalls = await Promise.all(out.toolCalls.map(async (tc: any) => { + if (typeof tc.arguments === 'string' && tc.arguments.startsWith('gcm1:')) { + const decrypted = await decryptAiField(key, sessionId, m.id, `tool_call_arguments:${tc.id}`, tc.arguments); + return { ...tc, arguments: JSON.parse(decrypted) }; + } + return tc; + })); + } + + return out; + })); +} + export const loadSession = async (id: string) => { if (!openedOrg.value) return; try { - const res = await sfetch(`/api/orgs/${openedOrg.value.id}/ai/sessions/${id}`); + const orgId = openedOrg.value.id; + const res = await sfetch(`/api/orgs/${orgId}/ai/sessions/${id}`); if (res.ok) { const session = await res.json(); activeSessionId.value = session.id; - + let loadedMessages = session.messages || []; - if (loadedMessages.isE2EE && loadedMessages.ciphertext && loadedMessages.encryptedAesKey && loadedMessages.iv) { + + if (session.encryptionScheme === 'gateway-aes-gcm-v1') { + // Cas 3 (nouveau) : structure JSON en clair, mais content/toolResult/toolCalls[].arguments + // sont des chaînes opaques "gcm1:..." chiffrées avec la clé de session IA de l'org. + try { + const key = await ensureAiSessionKey(orgId); + loadedMessages = await decryptGatewaySessionMessages(key, session.id, Array.isArray(loadedMessages) ? loadedMessages : []); + } catch (e) { + if (e instanceof AiSessionKeyUnavailableError) { + loadedMessages = [{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]; + } else { + console.error("Erreur de déchiffrement de la session AI (gateway)", e); + loadedMessages = [{ role: 'system', content: '[⚠️ Impossible de déchiffrer cette conversation.]' }]; + } + } + } else if (loadedMessages && loadedMessages.isE2EE && loadedMessages.ciphertext && loadedMessages.encryptedAesKey && loadedMessages.iv) { + // Cas 2 (legacy E2EE client-driven, providers 'local'/'custom') : enveloppe RSA+AES-GCM auto-chiffrée. if (privateKey.value) { try { const decryptedStr = await decryptFromPeer( - loadedMessages.ciphertext, - loadedMessages.encryptedAesKey, - loadedMessages.iv, + loadedMessages.ciphertext, + loadedMessages.encryptedAesKey, + loadedMessages.iv, privateKey.value ); loadedMessages = JSON.parse(decryptedStr); @@ -513,7 +587,8 @@ export const loadSession = async (id: string) => { loadedMessages = [{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]; } } - + // Sinon cas 1 (legacy le plus ancien) : messages déjà en clair, rien à faire. + if (Array.isArray(loadedMessages) && isStructuredAgentTranscript(loadedMessages)) { loadedMessages = convertStoredMessagesToChatMessages(loadedMessages); } @@ -549,6 +624,26 @@ export const newSession = () => { activeSessionId.value = null; }; +/** + * Pose le titre chiffré d'une session gateway. `syncSession()` ne s'applique pas au provider + * 'gateway' (c'est Synco_AI_Gateway, pas ce repo, qui écrit les messages) mais le titre reste à la + * charge du navigateur puisque `synco_api` ne peut plus le dériver lui-même depuis un `content` + * désormais chiffré (cf. E2EE_PLAN.md §4.4). À appeler juste après le tout premier message d'une + * nouvelle session gateway, en fire-and-forget (ne doit jamais bloquer/faire échouer l'envoi). + */ +export const setEncryptedSessionTitle = async (orgId: string, sessionId: string, plainTitle: string) => { + try { + const key = await ensureAiSessionKey(orgId); + const encryptedTitle = await encryptAiField(key, sessionId, '__session_title__', 'title', plainTitle.slice(0, 60)); + await sfetch(`/api/orgs/${orgId}/ai/sessions/${sessionId}`, { + method: 'PATCH', + body: JSON.stringify({ title: encryptedTitle }), + }); + } catch (e) { + console.error("Erreur lors de la pose du titre chiffré de la session AI", e); + } +}; + export const syncSession = async (lastPrompt: string) => { if (!openedOrg.value) return; try { From cf1a1f302c5d2077ab5fe2651c5019e6b84ad878 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:40:27 +0200 Subject: [PATCH 15/19] feat(ai): set the encrypted title on the first message of a gateway session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit consumeAgentStream() detects the transition from no active session to a freshly-assigned one (the 'session' SSE event) and, only for the 'gateway' provider, fires setEncryptedSessionTitle(orgId, sessionId, userText) with the text the user just typed — fire-and-forget, so a PATCH failure never blocks the chat. resumeAgentTurn's stream (tool decision replies) doesn't pass a title source, so it never re-triggers this on an already-active session. consumeAgentStream lives entirely client-side (live SSE from the gateway stays in clear, per E2EE_PLAN.md §5 — only loadSession's history reload goes through decryption), so this is the only hook that has the plaintext title text available at the moment the session id becomes known. --- src/views/OrgSpace/views/OrgAI.vue | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/views/OrgSpace/views/OrgAI.vue b/src/views/OrgSpace/views/OrgAI.vue index e20306e8..87dba13c 100644 --- a/src/views/OrgSpace/views/OrgAI.vue +++ b/src/views/OrgSpace/views/OrgAI.vue @@ -373,7 +373,7 @@ import { ref, onMounted, nextTick, watch, toRaw, type Ref } from 'vue'; import * as webllm from '@mlc-ai/web-llm'; import { localLLM, availableModels } from '@/services/LocalLLMService'; -import { aiService, aiIsLocal, aiIsInitialized, aiCurrentModelName, aiHasWebGPU, aiDownloadProgress, aiDownloadText, aiSessionMessages, syncSession, fetchSessions, activeSessionId, selectedModelId } from '@/services/AIService'; +import { aiService, aiIsLocal, aiIsInitialized, aiCurrentModelName, aiHasWebGPU, aiDownloadProgress, aiDownloadText, aiSessionMessages, syncSession, fetchSessions, activeSessionId, selectedModelId, setEncryptedSessionTitle } from '@/services/AIService'; import ThreadTextarea from '../components/common/ThreadTextarea.vue'; import ThreadMessage from '../components/common/ThreadMessage.vue'; import TaskDetailsModal from '../components/popup/TaskDetailsModal.vue'; @@ -833,7 +833,8 @@ const upsertToolPart = (idx: number, toolCallId: string, patch: Partial, getIndex: () => number, - setIndex: (i: number) => void + setIndex: (i: number) => void, + newSessionTitleSource?: string ) => { for await (const ev of generator) { if (!isGenerating.value) break; @@ -842,8 +843,17 @@ const consumeAgentStream = async ( if (ev.type === 'session') { if (activeSessionId.value !== ev.sessionId) { + const isNewSession = !activeSessionId.value; activeSessionId.value = ev.sessionId; fetchSessions(); + + // Titre chiffré côté client pour le tout premier message d'une nouvelle session 'gateway' — + // synco_api ne peut plus le dériver lui-même une fois le content opaque pour lui (E2EE_PLAN.md §4.4). + // Fire-and-forget : ne doit jamais bloquer/faire échouer l'envoi du message. + if (isNewSession && newSessionTitleSource && aiService.config.provider === 'gateway') { + const orgId = route.params.orgId as string; + setEncryptedSessionTitle(orgId, ev.sessionId, newSessionTitleSource); + } } } else if (ev.type === 'text') { appendTextPart(idx, ev.delta); @@ -988,7 +998,7 @@ const sendMessageViaAgent = async (text: string) => { try { let idx = assistantMsgIndex; const generator = aiService.chatAgentTurn(orgId, activeSessionId.value, text); - await consumeAgentStream(generator, () => idx, (i) => { idx = i; }); + await consumeAgentStream(generator, () => idx, (i) => { idx = i; }, text); } catch (error: any) { if (error.message !== 'USER_STOPPED' && !String(error).includes('USER_STOPPED')) { appendTextPart(assistantMsgIndex, `\n\n**Erreur:** ${error.message}`); From 5dea67b53d5571da7d5cbb64c5afe169581e89eb Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:41:12 +0200 Subject: [PATCH 16/19] feat(ai): provision the AI session key when saving with provider 'gateway' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit saveSettings() now calls ensureAiSessionKey(orgId) before writing activeModules.aiConfig whenever the selected provider is 'gateway' — first activation bootstraps a key, a later save on an already-key'd org just primes the cache (cheap, no extra request beyond the GET). A failure (locked PIN, no public key, server rejection) blocks the save with a clear toast instead of leaving the org in a provider='gateway'-but-no-key state where every member's first chat would fail silently (E2EE_PLAN.md §6). No new client-side permission check was added around this — mirrors saveSettings() itself, which already leaves authorization on activeModules.aiConfig entirely to the server. --- .../OrgSpace/views/settings/views/AISettings.vue | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/views/OrgSpace/views/settings/views/AISettings.vue b/src/views/OrgSpace/views/settings/views/AISettings.vue index c297d48f..9cb2c98f 100644 --- a/src/views/OrgSpace/views/settings/views/AISettings.vue +++ b/src/views/OrgSpace/views/settings/views/AISettings.vue @@ -235,6 +235,7 @@ import { openedOrg, organizations } from '@/assets/var'; import { useToast } from '@/composables/useToast'; import sfetch from '@/assets/utils/sfetch'; import { listGatewayModels } from '@/services/AIService'; +import { ensureAiSessionKey } from '@/services/AiSessionKeyService'; const toast = useToast(); @@ -382,6 +383,19 @@ const saveSettings = async () => { saving.value = true; + // Provisionne (ou récupère) la clé de session IA chiffrée AVANT d'activer le provider 'gateway' — + // sans ça, un membre pourrait se retrouver avec provider='gateway' mais aucune clé, et son premier + // chat échouerait silencieusement (cf. E2EE_PLAN.md §6). Idempotent : ne fait rien de coûteux si la + // clé existe déjà pour cette org. + if (orgData.value.provider === 'gateway') { + try { + await ensureAiSessionKey(openedOrg.value!.id); + } catch (keyErr: any) { + toast.show(keyErr?.message || "Impossible de provisionner la clé de session IA chiffrée pour cette organisation.", 'error'); + saving.value = false; + return; + } + } try { const aiConfigPayload: any = { From 9f6c1c6ef409b61711f7b8892a8db708390e193c Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:49:27 +0200 Subject: [PATCH 17/19] fix(ai): reopened gateway chats showed raw gcm1: ciphertext instead of decrypting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause (cross-repo, traced through synco_api and Synco_AI_Gateway): loadSession()/fetchSessions() only attempted decryption when `session.encryptionScheme === 'gateway-aes-gcm-v1'`, but Synco_AI_Gateway's SyncoClient never sends that field on create_session/patch_session (confirmed in synco_client.rs — its own crypto.rs even flags this as a known gap: "l'idée d'un marqueur encryptionScheme... reste possible plus tard"). synco_api dutifully stores and returns whatever it's given, i.e. permanently null for every gateway session. So the condition was never true, and encrypted sessions fell through to the "legacy plain" branch — ciphertext rendered as if it were the message. Fix (synco_app-only, no change needed in synco_api or the gateway): detect encrypted content by its own "gcm1:" prefix instead of the session-level marker — hasEncryptedGatewayFields() in loadSession(), and a direct prefix check (already partially there) in fetchSessions() for titles. This matches what the gateway itself actually does (decrypt_field_if_encrypted also keys off the per-field prefix, never the session marker). Since there's no longer a reliable session-level signal that "this whole session is uniformly encrypted", decryptGatewaySessionMessages now catches failures per-field instead of per-session: one corrupted or unexpectedly-plaintext field falls back to an inline placeholder for just that field, rather than replacing the entire visible history with the single "conversation illisible" placeholder. setEncryptedSessionTitle now also sends encryptionScheme: 'gateway-aes-gcm-v1' on its title PATCH — this is always true for a gateway session (the gateway encrypts unconditionally, no flag-gated fallback), so it's a safe, truthful, idempotent way to finally give synco_api's existing downgrade-guard something real to protect, even though synco_app itself no longer depends on reading it. Tests updated to set encryptionScheme: null in gateway-session fixtures (matching the real API response) — the case-3 tests are now the actual regression coverage for this bug — plus new coverage for per-field decrypt resilience and the same fetchSessions title bug. --- src/services/AIService.loadSession.test.ts | 74 +++++++++++++++++++- src/services/AIService.ts | 81 +++++++++++++++++----- 2 files changed, 136 insertions(+), 19 deletions(-) diff --git a/src/services/AIService.loadSession.test.ts b/src/services/AIService.loadSession.test.ts index 88d90fde..10697c6f 100644 --- a/src/services/AIService.loadSession.test.ts +++ b/src/services/AIService.loadSession.test.ts @@ -10,7 +10,7 @@ mock.module("@/assets/utils/sfetch", () => ({ default: (url: string, init?: any) => sfetchImpl(url, init), })); -const { loadSession, aiSessionMessages } = await import("./AIService"); +const { loadSession, aiSessionMessages, fetchSessions, chatSessions } = await import("./AIService"); const { openedOrg, user } = await import("@/assets/var"); const { privateKey, wrapAiSessionKeyForMember, encryptAiField, encryptForPeer } = await import("@/assets/utils/crypto"); @@ -93,6 +93,10 @@ describe("loadSession — the 3 message formats it must distinguish", () => { }); test("case 3 — new gateway-aes-gcm-v1: opaque gcm1: fields decrypted with the org's AI session key", async () => { + // Régression : en prod, Synco_AI_Gateway ne pose jamais `encryptionScheme` sur la session + // (il chiffre/déchiffre chaque champ par son seul préfixe "gcm1:", sans jamais lire/écrire ce + // marqueur) — la fixture reflète donc `encryptionScheme: null`, PAS 'gateway-aes-gcm-v1', pour + // vérifier que la détection par contenu (hasEncryptedGatewayFields) fonctionne quand même. const identity = await generateTestIdentity(); openedOrg.value = { id: "org-gateway" } as any; user.value = { id: "u2", publicKey: identity.publicKeyJWK } as any; @@ -111,7 +115,7 @@ describe("loadSession — the 3 message formats it must distinguish", () => { "/ai/key": () => new Response(JSON.stringify({ encryptedKey }), { status: 200 }), "/ai/sessions/sess-gateway": () => new Response(JSON.stringify({ id: sessionId, - encryptionScheme: "gateway-aes-gcm-v1", + encryptionScheme: null, // Ordre chronologique réel : user -> assistant (propose le tool call) -> tool (résultat). messages: [ { id: "m1", role: "user", content: encryptedContent }, @@ -143,7 +147,7 @@ describe("loadSession — the 3 message formats it must distinguish", () => { sfetchImpl = routeByUrl({ "/ai/sessions/sess-gateway-locked": () => new Response(JSON.stringify({ id: "sess-gateway-locked", - encryptionScheme: "gateway-aes-gcm-v1", + encryptionScheme: null, messages: [{ id: "m1", role: "user", content: "gcm1:doesnotmatter" }], }), { status: 200 }), }); @@ -153,4 +157,68 @@ describe("loadSession — the 3 message formats it must distinguish", () => { expect(aiSessionMessages.value).toEqual([{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]); }); + test("case 3 resilience — one corrupted gcm1: field doesn't wipe the rest of the history", async () => { + const identity = await generateTestIdentity(); + openedOrg.value = { id: "org-gateway-partial" } as any; + user.value = { id: "u3", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + const sessionKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); + const rawKeyBytes = await crypto.subtle.exportKey("raw", sessionKey); + const encryptedKey = await wrapAiSessionKeyForMember(rawKeyBytes, identity.publicKeyJWK); + + const sessionId = "sess-gateway-partial"; + const goodContent = await encryptAiField(sessionKey, sessionId, "m1", "content", "Bonjour"); + + sfetchImpl = routeByUrl({ + "/ai/key": () => new Response(JSON.stringify({ encryptedKey }), { status: 200 }), + "/ai/sessions/sess-gateway-partial": () => new Response(JSON.stringify({ + id: sessionId, + encryptionScheme: null, + messages: [ + { id: "m1", role: "user", content: goodContent }, + // Authentification GCM invalide (mauvais AAD implicite car nonce/tag arbitraires) — + // simule un champ corrompu/illisible sans faire planter le reste de la session. + { id: "m2", role: "assistant", content: "gcm1:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==" }, + ], + }), { status: 200 }), + }); + + await loadSession("sess-gateway-partial"); + + const messages = aiSessionMessages.value as any[]; + expect(messages[0].content).toBe("Bonjour"); + expect(messages[1].content).toBe('[⚠️ Contenu illisible.]'); + }); + +}); + +describe("fetchSessions — sidebar title decryption (same encryptionScheme-is-never-set reality)", () => { + + test("decrypts a gcm1: title even though encryptionScheme is null on the session", async () => { + const identity = await generateTestIdentity(); + openedOrg.value = { id: "org-sidebar" } as any; + user.value = { id: "u4", publicKey: identity.publicKeyJWK } as any; + privateKey.value = identity.privateKey; + + const sessionKey = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"]); + const rawKeyBytes = await crypto.subtle.exportKey("raw", sessionKey); + const encryptedKey = await wrapAiSessionKeyForMember(rawKeyBytes, identity.publicKeyJWK); + const encryptedTitle = await encryptAiField(sessionKey, "sess-a", "__session_title__", "title", "Quel temps demain ?"); + + sfetchImpl = routeByUrl({ + "/ai/key": () => new Response(JSON.stringify({ encryptedKey }), { status: 200 }), + "/ai/sessions": () => new Response(JSON.stringify([ + { id: "sess-a", title: encryptedTitle, encryptionScheme: null }, + { id: "sess-b", title: "Nouvelle session", encryptionScheme: null }, + ]), { status: 200 }), + }); + + await fetchSessions(); + + expect(chatSessions.value.find((s: any) => s.id === "sess-a")?.title).toBe("Quel temps demain ?"); + // Titre pas encore posé (pas de préfixe gcm1:) : laissé tel quel, pas de tentative de déchiffrement. + expect(chatSessions.value.find((s: any) => s.id === "sess-b")?.title).toBe("Nouvelle session"); + }); + }); diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 25d7bd98..52b7e8e8 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -432,9 +432,14 @@ export const fetchSessions = async () => { const sessions: any[] = await res.json(); await Promise.all(sessions.map(async (session) => { - // Titre chiffré côté client (provider 'gateway' uniquement, cf. setEncryptedSessionTitle) — - // un titre pas encore posé (session flambant neuve) reste le défaut en clair de synco_api. - if (session.encryptionScheme === 'gateway-aes-gcm-v1' && typeof session.title === 'string' && session.title.startsWith('gcm1:')) { + // Titre chiffré côté client (provider 'gateway' uniquement, cf. setEncryptedSessionTitle). + // Détecté par le préfixe "gcm1:" du champ lui-même, PAS par session.encryptionScheme : la + // passerelle Synco AI Gateway ne pose jamais ce marqueur (elle chiffre/déchiffre chaque + // champ selon son propre préfixe, sans jamais lire/écrire encryptionScheme — voir + // Synco_AI_Gateway/src/crypto.rs::decrypt_field_if_encrypted), donc s'y fier laisserait + // le titre affiché en clair-ciphertext indéfiniment. Un titre pas encore posé (session + // flambant neuve) reste le défaut en clair de synco_api, sans préfixe "gcm1:". + if (typeof session.title === 'string' && session.title.startsWith('gcm1:')) { try { const key = await ensureAiSessionKey(orgId); session.title = await decryptAiField(key, session.id, '__session_title__', 'title', session.title); @@ -508,32 +513,67 @@ function isStructuredAgentTranscript(messages: any[]): boolean { return messages.some((m) => m.role === 'tool' || (Array.isArray(m.toolCalls) && m.toolCalls.length > 0)); } +/** + * true si au moins un champ de ces StoredMessage[] porte le préfixe "gcm1:" (nouveau flux agent + * serveur, provider 'gateway'). Sert de détecteur à la place de `session.encryptionScheme` : la + * passerelle Synco AI Gateway ne pose jamais ce marqueur côté synco_api (elle chiffre/déchiffre + * chaque champ selon son propre préfixe uniquement, cf. Synco_AI_Gateway/src/crypto.rs — + * `decrypt_field_if_encrypted`/`encrypt_field` ne lisent/écrivent jamais encryptionScheme), donc + * une session gateway a systématiquement encryptionScheme === null malgré un contenu chiffré. + */ +function hasEncryptedGatewayFields(messages: any[]): boolean { + return messages.some((m) => { + if (typeof m.content === 'string' && m.content.startsWith('gcm1:')) return true; + if (typeof m.toolResult === 'string' && m.toolResult.startsWith('gcm1:')) return true; + if (Array.isArray(m.toolCalls) && m.toolCalls.some((tc: any) => typeof tc.arguments === 'string' && tc.arguments.startsWith('gcm1:'))) return true; + return false; + }); +} + /** * Déchiffre les champs opaques `"gcm1:..."` d'un StoredMessage[] issu du nouveau flux agent - * serveur (provider 'gateway', session.encryptionScheme === 'gateway-aes-gcm-v1') : `content`, - * `toolResult`, `toolCalls[].arguments`, tous liés par AAD à `session.id` + l'id du message - * (cf. E2EE_PLAN.md §2 et §4.3). `pendingToolCall.args` n'est décrypté nulle part côté frontend - * aujourd'hui (aucun composant ne lit `session.pendingToolCall`) — laissé chiffré tel quel plutôt - * que déchiffré pour rien ; utiliser decryptAiField(key, session.id, '__pending__', - * 'pending_tool_call_args', ...) le jour où une UI en a besoin. + * serveur : `content`, `toolResult`, `toolCalls[].arguments`, tous liés par AAD à `session.id` + + * l'id du message (cf. E2EE_PLAN.md §2 et §4.3). Chaque champ est déchiffré indépendamment — un + * échec isolé (auth GCM invalide, JSON malformé) retombe sur un placeholder pour CE champ, sans + * effacer le reste de l'historique : sans marqueur de session fiable (cf. hasEncryptedGatewayFields + * ci-dessus), on ne peut plus présumer que TOUT le contenu d'une session est chiffré de façon + * homogène. `pendingToolCall.args` n'est décrypté nulle part côté frontend aujourd'hui (aucun + * composant ne lit `session.pendingToolCall`) — laissé chiffré tel quel plutôt que déchiffré pour + * rien ; utiliser decryptAiField(key, session.id, '__pending__', 'pending_tool_call_args', ...) le + * jour où une UI en a besoin. */ async function decryptGatewaySessionMessages(key: CryptoKey, sessionId: string, messages: any[]): Promise { return Promise.all(messages.map(async (m) => { const out = { ...m }; if (typeof out.content === 'string' && out.content.startsWith('gcm1:')) { - out.content = await decryptAiField(key, sessionId, m.id, 'content', out.content); + try { + out.content = await decryptAiField(key, sessionId, m.id, 'content', out.content); + } catch (e) { + console.error("[E2EE] Échec du déchiffrement du contenu du message", m.id, e); + out.content = '[⚠️ Contenu illisible.]'; + } } if (typeof out.toolResult === 'string' && out.toolResult.startsWith('gcm1:')) { - out.toolResult = JSON.parse(await decryptAiField(key, sessionId, m.id, 'tool_result', out.toolResult)); + try { + out.toolResult = JSON.parse(await decryptAiField(key, sessionId, m.id, 'tool_result', out.toolResult)); + } catch (e) { + console.error("[E2EE] Échec du déchiffrement du résultat d'outil", m.id, e); + out.toolResult = { error: 'Résultat illisible.' }; + } } if (Array.isArray(out.toolCalls)) { out.toolCalls = await Promise.all(out.toolCalls.map(async (tc: any) => { if (typeof tc.arguments === 'string' && tc.arguments.startsWith('gcm1:')) { - const decrypted = await decryptAiField(key, sessionId, m.id, `tool_call_arguments:${tc.id}`, tc.arguments); - return { ...tc, arguments: JSON.parse(decrypted) }; + try { + const decrypted = await decryptAiField(key, sessionId, m.id, `tool_call_arguments:${tc.id}`, tc.arguments); + return { ...tc, arguments: JSON.parse(decrypted) }; + } catch (e) { + console.error("[E2EE] Échec du déchiffrement des arguments d'outil", tc.id, e); + return { ...tc, arguments: {} }; + } } return tc; })); @@ -554,12 +594,12 @@ export const loadSession = async (id: string) => { let loadedMessages = session.messages || []; - if (session.encryptionScheme === 'gateway-aes-gcm-v1') { + if (Array.isArray(loadedMessages) && hasEncryptedGatewayFields(loadedMessages)) { // Cas 3 (nouveau) : structure JSON en clair, mais content/toolResult/toolCalls[].arguments // sont des chaînes opaques "gcm1:..." chiffrées avec la clé de session IA de l'org. try { const key = await ensureAiSessionKey(orgId); - loadedMessages = await decryptGatewaySessionMessages(key, session.id, Array.isArray(loadedMessages) ? loadedMessages : []); + loadedMessages = await decryptGatewaySessionMessages(key, session.id, loadedMessages); } catch (e) { if (e instanceof AiSessionKeyUnavailableError) { loadedMessages = [{ role: 'system', content: '[🔒 Conversation chiffrée. Clé privée manquante.]' }]; @@ -630,6 +670,15 @@ export const newSession = () => { * charge du navigateur puisque `synco_api` ne peut plus le dériver lui-même depuis un `content` * désormais chiffré (cf. E2EE_PLAN.md §4.4). À appeler juste après le tout premier message d'une * nouvelle session gateway, en fire-and-forget (ne doit jamais bloquer/faire échouer l'envoi). + * + * On en profite pour poser `encryptionScheme: 'gateway-aes-gcm-v1'` sur la session — la passerelle + * ne le fait jamais elle-même (elle chiffre/déchiffre chaque champ par son seul préfixe "gcm1:", + * sans lire/écrire ce marqueur), alors qu'un provider 'gateway' chiffre TOUJOURS son contenu sans + * condition côté passerelle : c'est donc une affirmation vraie dès qu'on sait qu'on parle à une + * session gateway. Ça active enfin le garde-fou anti-downgrade déjà présent côté synco_api + * (PATCH /:sessionId refuse de changer encryptionScheme une fois posé) — synco_app lui-même ne + * s'appuie plus sur ce marqueur pour décider quoi déchiffrer (cf. hasEncryptedGatewayFields), donc + * son absence éventuelle (session encore plus ancienne que ce premier PATCH) ne casse rien ici. */ export const setEncryptedSessionTitle = async (orgId: string, sessionId: string, plainTitle: string) => { try { @@ -637,7 +686,7 @@ export const setEncryptedSessionTitle = async (orgId: string, sessionId: string, const encryptedTitle = await encryptAiField(key, sessionId, '__session_title__', 'title', plainTitle.slice(0, 60)); await sfetch(`/api/orgs/${orgId}/ai/sessions/${sessionId}`, { method: 'PATCH', - body: JSON.stringify({ title: encryptedTitle }), + body: JSON.stringify({ title: encryptedTitle, encryptionScheme: 'gateway-aes-gcm-v1' }), }); } catch (e) { console.error("Erreur lors de la pose du titre chiffré de la session AI", e); From 23ad808ba65e431d9af4bfa7e5e654fabae50be6 Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 18:58:29 +0200 Subject: [PATCH 18/19] perf(ai): fetch Keycloak token refresh and AI session key in parallel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gatewayFetch() awaited keycloak.updateToken() then, separately, the session key lookup — two independent operations (refreshing the auth token doesn't depend on the E2EE session key, and vice versa) chained sequentially. Matters most on a cold cache (first gateway message of a session, where getAiSessionKeyRawBase64 does a real GET/POST round trip), same class of fix as the gateway's session+tools-manifest parallelization. --- src/services/AIService.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/services/AIService.ts b/src/services/AIService.ts index 52b7e8e8..521f126e 100644 --- a/src/services/AIService.ts +++ b/src/services/AIService.ts @@ -57,10 +57,13 @@ export class AIService { * E2EE_PLAN.md §3-4. `synco_api` ne voit jamais cette clé (appel direct navigateur→gateway). */ private async gatewayFetch(orgId: string, url: string, body: any, signal: AbortSignal): Promise { - if (keycloak.authenticated) { - await keycloak.updateToken(60).catch(() => {}); - } - const sessionKeyB64 = await getAiSessionKeyRawBase64(orgId); + // Indépendants l'un de l'autre (rafraîchir le token Keycloak / récupérer la clé de session + // IA) — en parallèle plutôt qu'en séquence, ça évite d'empiler deux aller-retours réseau + // quand ni l'un ni l'autre n'est déjà en cache (ex: tout premier message d'une session). + const [, sessionKeyB64] = await Promise.all([ + keycloak.authenticated ? keycloak.updateToken(60).catch(() => {}) : Promise.resolve(), + getAiSessionKeyRawBase64(orgId), + ]); return fetch(url, { method: 'POST', headers: { From 22dd52f5e76d8a8723763890311ae947a06e40ca Mon Sep 17 00:00:00 2001 From: mister_papaye Date: Thu, 10 Sep 2026 19:18:08 +0200 Subject: [PATCH 19/19] Delete E2EE_PLAN.md --- E2EE_PLAN.md | 232 --------------------------------------------------- 1 file changed, 232 deletions(-) delete mode 100644 E2EE_PLAN.md diff --git a/E2EE_PLAN.md b/E2EE_PLAN.md deleted file mode 100644 index 50adf304..00000000 --- a/E2EE_PLAN.md +++ /dev/null @@ -1,232 +0,0 @@ -# Plan — Chiffrement des sessions IA (synco_app) - -> Ce document est un des 3 plans jumeaux (`Synco_AI_Gateway`, `synco_api`, `synco_app`) écrits pour être -> donnés chacun à une session Claude dédiée, travaillant dans un seul repo à la fois, sans accès aux deux -> autres. Le **format binaire/wire (section 2)** est identique dans les 3 fichiers — ne pas le modifier sans -> répercuter le changement dans les deux autres plans. - -## 1. Contexte et objectif - -Objectif : pour les sessions IA utilisant le provider `gateway` (*"Passerelle Synco AI (auto-hébergée)"*), -`synco_api` ne doit jamais voir le contenu en clair. Ce repo (`synco_app`, le frontend Vue) est responsable -de : (a) générer et distribuer une clé symétrique partagée par organisation, (b) la transmettre directement à -`Synco_AI_Gateway` à chaque appel (jamais via `synco_api`), (c) déchiffrer côté client tout ce qu'il relit -depuis `synco_api` (historique, titres de sidebar). - -**Bonne nouvelle** : ce repo a déjà toute l'infrastructure crypto nécessaire. `src/assets/utils/crypto.ts` -implémente déjà un système E2EE complet (RSA-OAEP 4096 par utilisateur, clé privée déverrouillée par PIN et -jamais persistée en clair, enveloppe RSA+AES-GCM via `encryptForPeer`/`decryptFromPeer`, distribution de clé -partagée pour les threads/spaces via `generateThreadKey`/`encryptThreadKeyForMember`/ -`decryptThreadKeyWithRsa`). Ce plan consiste essentiellement à **répliquer le pattern `ThreadKey` existant** -pour une nouvelle ressource "clé de session IA par org", pas à inventer un nouveau système crypto. - -**Incohérence actuelle à corriger** : `AIService.ts` a DÉJÀ un chiffrement E2EE pour les sessions IA — mais -seulement sur l'ancien flux client-driven (`syncSession()`/`loadSession()`, providers `local`/`custom`, via -`encryptForPeer`/`decryptFromPeer` en auto-chiffrement pour l'utilisateur lui-même). Le nouveau flux agent -serveur (provider `gateway`, `chatAgentTurn`/`resumeAgentTurn`) ne passe PAS par ce chiffrement — c'est -précisément le trou que ce plan comble, avec un schéma de clé *partagée par org* (pas juste auto-chiffrée -pour soi-même) puisque plusieurs membres de l'org doivent pouvoir relire le même historique. - -**Hors périmètre** : les providers `openai`/`mistral`/`gemini` (flux `sfetch('/api/orgs/${orgId}/ai/chat', ...)`) -restent inchangés — ne touche pas à ce chemin. - -## 2. Format binaire (wire format) — identique aux 2 autres plans, ne pas diverger - -- **Algorithme** : AES-256-GCM, clé 256 bits. -- **Nonce** : 12 octets aléatoires par opération. -- **Tag** : 16 octets, standard GCM. -- **Valeur sur le fil** : `"gcm1:" + base64_standard(nonce(12) || ciphertext || tag(16))`. - - En Web Crypto : `crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData, tagLength: 128 }, key, plaintextBytes)` - retourne **déjà** `ciphertext || tag` concaténés (comportement natif du navigateur) — il suffit de - préfixer avec le `nonce` généré, puis encoder en base64 standard (`btoa`/`Buffer`, PAS url-safe). - - `base64_standard` = RFC 4648 §4 avec padding. -- **AAD** : chaîne UTF-8 `"{session_id}:{message_id}:{field_name}"`, encodée en `Uint8Array` via - `TextEncoder`. `field_name` : `"content"`, `"tool_result"`, `"tool_call_arguments:{call_id}"`, `"title"` - (avec `message_id = "__session_title__"`), `"pending_tool_call_args"` (avec `message_id = "__pending__"`). -- **Valeurs JSON** (`toolResult`, `toolCalls[].arguments`) : `JSON.stringify(...)` avant chiffrement, - `JSON.parse(...)` après déchiffrement. -- **`null`/absent** : ne jamais chiffrer, laisser tel quel. - -### Vecteur de test (identique au plan `Synco_AI_Gateway` — sert à vérifier l'interopérabilité TS↔Rust sans -jamais faire tourner les deux implémentations ensemble ; régénère toi-même les octets bruts depuis les hex -ci-dessous plutôt que de faire confiance à un éventuel problème de copier-coller) : - -``` -key (hex, 32 octets) : d82f2646d1113270f58fa3daf64de7e9f64253123a0ec7fdbaa24e34081d791 -key (base64) : 2C8mRtERMnD1j6Pa9k3n6fZCUxI6Dsf9uqJONAgdeRE= -nonce (hex, 12 octets) : 1024c8c26840d416f50b5072 -session_id : sess_test0000000000000000000001 -message_id : msg_test00000000000000000000001 -field_name : content -AAD (utf8) : sess_test0000000000000000000001:msg_test00000000000000000000001:content -plaintext (utf8) : Bonjour, ceci est un message de test pour Synco AI. -wire_value : gcm1:ECTIwmhA1Bb1C1ByL8IECZj8SkBl2TYmk9665e/jnrCQNjYdR+CMirRU75qIq5pxnrallgkaWQtrQreT8eCSCf6JAzUrY5mTb/Ez42WxSw== -``` -Écris un test qui importe `key` brute via `crypto.subtle.importKey('raw', ...)`, déchiffre `wire_value` avec -l'AAD ci-dessus, et vérifie que le résultat === `plaintext`. Si ça échoue, le bug est dans l'implémentation -TS (mauvais split nonce/ciphertext, mauvais AAD, mauvais `tagLength`), pas dans le vecteur. - -## 3. Nouvelle brique : clé de session IA par organisation - -### 3.1 Génération/enveloppe — mirror exact de `generateThreadKey`/`encryptThreadKeyForMember` - -Dans `src/assets/utils/crypto.ts`, regarde d'abord précisément comment `generateThreadKey`, -`encryptThreadKeyForMember(rawKey, recipientPublicKey)` et `decryptThreadKeyWithRsa(encryptedKey, iv, -privateKey)` sont implémentées (signatures exactes, format retourné). Ajoute des fonctions analogues -(ou réutilise-les directement si elles sont déjà génériques et non spécifiques aux threads — vérifie) : -- `generateAiSessionKey(): Promise` — `crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'])`. - Doit être `extractable: true` (contrairement à la clé privée RSA de l'utilisateur) puisqu'elle doit être - exportée en bytes bruts pour (a) être enveloppée RSA pour chaque membre, (b) être envoyée en clair (base64) - au gateway via TLS. -- `wrapAiSessionKeyForMember(rawKeyBytes: ArrayBuffer, recipientPublicKey: CryptoKey): Promise<{ encryptedKey: string, iv?: string }>` - — même schéma d'enveloppe que `encryptThreadKeyForMember`. -- `unwrapAiSessionKey(encryptedKey: string, iv: string | undefined, privateKey: CryptoKey): Promise` - — inverse, utilise `privateKey.value` (la ref globale déjà déverrouillée par PIN, cf. `crypto.ts` existant). - -### 3.2 Nouveau service : `src/services/AiSessionKeyService.ts` (ou étendre `AIService.ts` — à toi de juger -selon la taille, mais garder ça séparé de la logique HTTP de chat est probablement plus propre) - -- Un `ref` en mémoire (jamais persisté en `localStorage`, cohérent avec la convention - existante pour `privateKey`), un par org actuellement ouverte (`Map` ou juste re-fetch à - chaque changement d'org — vérifie le pattern déjà utilisé pour `openedOrg` dans `var.ts`). -- `async function ensureAiSessionKey(orgId: string): Promise` : - 1. `GET /api/orgs/:orgId/ai/key` (nouvel endpoint, cf. plan `synco_api` §4.3). - 2. Si trouvé : déchiffrer avec `unwrapAiSessionKey` + `privateKey.value`, importer en `CryptoKey` via - `crypto.subtle.importKey('raw', bytes, 'AES-GCM', false, ['encrypt','decrypt'])`, cacher, retourner. - Si `privateKey.value` est `null` (PIN pas encore déverrouillé) : lever une erreur typée que l'appelant - (UI) doit traduire en message "déverrouillez votre sécurité pour accéder à l'IA", même pattern que le - `[🔒 Conversation chiffrée. Clé privée manquante.]` déjà affiché ailleurs dans `AIService.ts`. - 3. Si absent (404) : c'est la première fois que quelqu'un active le provider `gateway` pour cette org — - générer une nouvelle clé (`generateAiSessionKey`), l'envelopper pour soi-même - (`wrapAiSessionKeyForMember` avec sa propre clé publique), `POST /api/orgs/:orgId/ai/key`. **Décision à - prendre** : qui a le droit de faire ce bootstrap ? Probablement restreint aux mêmes permissions que - `AISettings.vue`/`saveSettings()` (admin d'org) — vérifie quelle vérification de permission encadre déjà - l'écriture de `activeModules.aiConfig` côté frontend/route, et applique la même règle ici pour cohérence - (même si l'endpoint `synco_api` fera de toute façon sa propre vérification serveur). -- `async function getAiSessionKeyRawBase64(orgId: string): Promise` — retourne la clé en base64 - standard (`crypto.subtle.exportKey('raw', key)` → base64), prête à poser dans le header `X-Session-Key`. -- Partage avec les autres membres de l'org (pour qu'ils puissent, eux aussi, lire l'historique) : nécessite - un flux où un membre qui a DÉJÀ la clé en enveloppe pour un NOUVEAU membre (qui vient de rejoindre l'org, ou - qui n'avait pas encore de ligne `AiSessionKey`). Regarde comment ce cas est géré aujourd'hui pour - `ThreadKey`/`WorkspaceKey` (probablement déclenché à l'ouverture d'un écran, ou par un admin) et réplique - exactement le même déclencheur pour rester cohérent avec le reste de l'app plutôt que d'introduire un - nouveau pattern UX. - -## 4. Changements dans `src/services/AIService.ts` - -### 4.1 `gatewayFetch` (méthode privée, lignes ~55-68) -Ajouter le header `X-Session-Key` : -```ts -const sessionKeyB64 = await getAiSessionKeyRawBase64(orgId); // nouveau -return fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...(keycloak.token ? { Authorization: `Bearer ${keycloak.token}` } : {}), - 'X-Session-Key': sessionKeyB64, - }, - body: JSON.stringify(body), - signal, -}); -``` -Nécessite de faire passer `orgId` jusqu'à `gatewayFetch` (vérifie s'il l'a déjà — `chatAgentTurn`/ -`resumeAgentTurn` l'ont sûrement déjà dans leur propre scope). `listGatewayModels` (lignes ~384-402) n'a PAS -besoin de ce header — elle ne touche à aucun contenu de session, laisse-la inchangée. - -### 4.2 `fetchSessions()` (lignes ~420-430) — sidebar -Après réception de la liste, pour chaque session avec `encryptionScheme` non-null (nouveau champ renvoyé par -`synco_api`, cf. plan `synco_api` §4.1), déchiffrer `title` avec la clé de session AES (AAD : -`"{session.id}:__session_title__:title"`) avant de l'assigner à `chatSessions`. Si la clé n'est pas -disponible (PIN verrouillé), afficher un placeholder (`"🔒 Titre chiffré"`) plutôt que planter. - -### 4.3 `loadSession(id)` (lignes ~489-526) — trois formats à distinguer maintenant -1. **Legacy le plus ancien** : `messages` est directement un `StoredMessage[]` en clair (pré-existant, avant - tout chiffrement) — comportement actuel, inchangé. -2. **Legacy E2EE client-driven** : `messages` a la forme `{ isE2EE: true, ciphertext, encryptedAesKey, iv }` - (enveloppe RSA+AES-GCM auto-chiffrée, ancien flux `local`/`custom`) — comportement actuel - (`decryptFromPeer` + `privateKey.value`), inchangé. -3. **Nouveau — gateway-aes-gcm-v1** : `session.encryptionScheme === "gateway-aes-gcm-v1"` → `messages` est un - `StoredMessage[]` en clair au niveau structure JSON, mais avec `content`/`toolResult`/ - `toolCalls[].arguments` valant des chaînes opaques `"gcm1:..."`. Récupérer la clé via - `ensureAiSessionKey(orgId)`, puis déchiffrer chaque champ concerné (AAD par champ, cf. §2) avant de passer - le résultat à `convertStoredMessagesToChatMessages` (comportement inchangé à partir de là). - `pendingToolCall.args` (si présent au niveau session, pas par message) suit le même traitement (AAD - `"{session.id}:__pending__:pending_tool_call_args"`). - -Distingue les 3 cas AVANT de toucher au contenu : `session.encryptionScheme === 'gateway-aes-gcm-v1'` → cas 3 ; -sinon `typeof session.messages === 'object' && session.messages.isE2EE` → cas 2 ; sinon → cas 1 -(`isStructuredAgentTranscript` existant peut rester tel quel, appliqué APRÈS déchiffrement pour le cas 3). - -### 4.4 `syncSession()` (lignes ~552-603) — écriture du titre pour le nouveau flux -Ce chemin reste tel quel pour les providers `local`/`custom` (cas 2 ci-dessus). Pour le provider `gateway`, -ce n'est PAS `syncSession()` qui écrit les messages (c'est `Synco_AI_Gateway` qui le fait directement côté -serveur, cf. plan gateway) — mais le TITRE doit être posé côté client, puisque `synco_api` ne peut plus le -dériver lui-même (cf. plan `synco_api` §4.2). Ajoute une fonction dédiée : -```ts -async function setEncryptedSessionTitle(orgId: string, sessionId: string, plainTitle: string) { - const key = await ensureAiSessionKey(orgId); - const encryptedTitle = await encryptField(key, sessionId, '__session_title__', 'title', plainTitle.slice(0, 60)); - await sfetch(`/api/orgs/${orgId}/ai/sessions/${sessionId}`, { - method: 'PATCH', - body: JSON.stringify({ title: encryptedTitle }), - }); -} -``` -À appeler juste après l'envoi du tout premier message d'une nouvelle session gateway (dans `OrgAI.vue`, -`sendMessageViaAgent`, cf. §5) — le titre est calculé à partir du texte que l'utilisateur vient de taper, -donc disponible en clair côté client à ce moment précis, avant même que le gateway ne réponde. - -### 4.5 `deleteSession()` (lignes ~528-544) — aucun changement, opère sur l'id, pas le contenu. - -## 5. Changements dans `src/views/OrgSpace/views/OrgAI.vue` - -- `sendMessageViaAgent` (lignes ~979-999) : si c'est le tout premier message d'une session gateway - (`sessionId` encore vide/juste créé, ou `messages.value.length === 0` avant envoi), appeler - `setEncryptedSessionTitle(orgId, sessionId, userText)` (fire-and-forget, ne pas bloquer l'envoi du message - sur ça). -- `consumeAgentStream` (lignes ~833-876) : **aucun changement** — le flux SSE en direct depuis le gateway - reste en clair (canal direct navigateur↔gateway déjà de confiance), donc l'affichage live n'est pas - affecté par ce plan. Seul le rechargement d'historique (`loadSession`) est concerné. -- Watcher `fetchSessions()` au montage (lignes ~1078-1082) : aucun changement structurel, bénéficie - automatiquement du déchiffrement ajouté dans `fetchSessions()` (§4.2). - -## 6. Changements dans `src/views/OrgSpace/views/settings/views/AISettings.vue` - -- Dans `saveSettings()` (lignes ~360-428), quand l'admin sélectionne/confirme le provider `gateway` pour la - première fois (transition depuis un autre provider, ou premier réglage IA de l'org) : déclencher - `ensureAiSessionKey(orgId)` pour provisionner la clé AVANT ou juste après l'écriture de `activeModules.aiConfig` - — si ça échoue (pas de permission, RSA verrouillé), bloquer la sauvegarde avec un message clair plutôt que - de laisser l'org dans un état "provider=gateway mais pas de clé" qui ferait échouer silencieusement le - premier chat de n'importe quel membre. - -## 7. Changements dans `src/views/OrgSpace/components/layouts/ThreadsBar.vue` - -- Aucun changement structurel attendu — elle consomme `chatSessions` déjà déchiffré par `fetchSessions()` - (§4.2). Vérifie juste que l'état "titre non déchiffrable" (clé absente/PIN verrouillé) s'affiche proprement - dans la boucle `v-for` existante (lignes ~206-226) sans casser le layout. - -## 8. Ce qui NE change PAS - -- `src/assets/utils/workspaceCrypto.ts`, `webhookCrypto.ts`, `useSecurePeer.ts`, `SearchSyncService.ts` : hors - périmètre, ne pas toucher. -- Le flux `local`/`custom` (LLM local WebGPU, `LocalLLMService.ts`) : hors périmètre, déjà purement client-side - (jamais de contenu envoyé à un serveur), rien à changer. -- Providers `openai`/`mistral`/`gemini` (`sfetch('/api/orgs/${orgId}/ai/chat', ...)`) : hors périmètre, cf. §1. - -## 9. Perte d'accès / UX de récupération - -Si la clé privée RSA de l'utilisateur est perdue (PIN oublié, pas de sauvegarde), il perd l'accès à -l'historique IA chiffré — exactement le même compromis que pour les threads/espaces déjà E2EE dans ce repo. -Ne pas inventer un mécanisme de récupération spécifique à l'IA ; si un mécanisme de récupération existe déjà -pour la clé privée RSA générale (sauvegarde, réinitialisation admin, etc.), il couvre automatiquement ce cas -aussi. Vérifier qu'aucun message d'erreur nouveau introduit par ce plan ne laisse l'utilisateur bloqué sans -indication (réutiliser le message `[🔒 Conversation chiffrée. Clé privée manquante.]` existant comme modèle). - -## 10. Tests à écrire - -- Vecteur de test cryptographique du §2 (round-trip + comparaison avec la valeur `wire_value` fixe). -- `loadSession()` : un test par branche (legacy plain, legacy E2EE enveloppe, nouveau gateway-aes-gcm-v1), - avec des fixtures représentant chaque forme de `session.messages`. -- `ensureAiSessionKey()` : test du chemin bootstrap (404 → génération → POST) et du chemin normal (trouvé → - déchiffrement → cache). -- `AISettings.vue` : test que la sauvegarde est bloquée si le provisionnement de clé échoue.