From 583c12d5a89bc696888873582b7382afeaff57a2 Mon Sep 17 00:00:00 2001 From: thierryvm <46031203+thierryvm@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:22:27 +0100 Subject: [PATCH 1/5] fix(ai-tutor): move the Gemini default off gemini-2.0-flash, shut down by Google Google shut down `gemini-2.0-flash` on 1 June 2026 (Gemini API deprecations page, read on 9 November 2026). Unless VITE_AI_TUTOR_GEMINI_MODEL overrides it, the tutor's Gemini option now gets a 404 (`model_unavailable`) on every question. - Default model: `gemini-3.6-flash`, the replacement Google recommends for gemini-2.0-flash; stable, no shutdown date announced. `gemini-2.5-flash` was not taken: it is deprecated too and reroutes on 1 December 2026. - Same behaviour as before: Gemini 3 models think by default (medium) and thinking tokens count against maxOutputTokens, so with our 1024-token cap answers could come back cut or empty. The request now sets `thinkingConfig.thinkingLevel: MINIMAL`, only for Gemini 3 and later: older models reject the field, and a deploy may still point the env override at a 2.5 model. - Label "Gemini 3.6 Flash" added so the drawer shows the model by name. Tests: default model, thinkingConfig sent to Gemini 3+, absent for 2.5, model-id detection. No live call (BYOK, no Gemini key on this machine). --- src/lib/ai/providers/gemini.ts | 27 ++++++++++- src/lib/ai/providers/index.ts | 1 + src/test/ai/providers/gemini.test.ts | 54 +++++++++++++++++++++- src/test/ai/providers/resolveModel.test.ts | 1 + 4 files changed, 80 insertions(+), 3 deletions(-) diff --git a/src/lib/ai/providers/gemini.ts b/src/lib/ai/providers/gemini.ts index 13561a17..53517b8c 100644 --- a/src/lib/ai/providers/gemini.ts +++ b/src/lib/ai/providers/gemini.ts @@ -21,9 +21,27 @@ import { ChatError, type ChatErrorCode, type ChatParams, type ChatStream } from import { streamSseEvents } from './_sse'; const GEMINI_BASE = 'https://generativelanguage.googleapis.com/v1beta/models'; -export const GEMINI_DEFAULT_MODEL = 'gemini-2.0-flash'; +// `gemini-2.0-flash` was shut down by Google on 1 June 2026; its official +// replacement is `gemini-3.6-flash` (stable, no shutdown date announced on +// 9 November 2026). Source: Gemini API deprecations page. +export const GEMINI_DEFAULT_MODEL = 'gemini-3.6-flash'; export const GEMINI_MAX_TOKENS = 1024; +/** + * Gemini 3+ models think by default (`gemini-3.6-flash`: medium), and + * thinking tokens count against `maxOutputTokens`: with our 1024 cap the + * answer could come back truncated or empty. `MINIMAL` keeps the tutor's + * previous behaviour (gemini-2.0-flash did not think). Earlier models reject + * `thinkingLevel` with an error, so it is only sent to Gemini 3 and later + * (a deploy may still point `VITE_AI_TUTOR_GEMINI_MODEL` at a 2.5 model). + */ +export const GEMINI_THINKING_LEVEL = 'MINIMAL'; + +export function supportsThinkingLevel(model: string): boolean { + const match = /^gemini-(\d+)/.exec(model.toLowerCase()); + return match !== null && Number(match[1]) >= 3; +} + interface GeminiFrame { candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>; } @@ -69,7 +87,12 @@ export async function chat(params: ChatParams): Promise { const body = JSON.stringify({ contents, systemInstruction: { parts: [{ text: params.systemPrompt }] }, - generationConfig: { maxOutputTokens: GEMINI_MAX_TOKENS }, + generationConfig: { + maxOutputTokens: GEMINI_MAX_TOKENS, + ...(supportsThinkingLevel(params.model) + ? { thinkingConfig: { thinkingLevel: GEMINI_THINKING_LEVEL } } + : {}), + }, }); let res: Response; diff --git a/src/lib/ai/providers/index.ts b/src/lib/ai/providers/index.ts index 3bff18c5..fd2b39b7 100644 --- a/src/lib/ai/providers/index.ts +++ b/src/lib/ai/providers/index.ts @@ -89,6 +89,7 @@ const MODEL_LABELS: ReadonlyArray = [ ['gpt-5-nano', 'GPT-5 nano'], ['gpt-5', 'GPT-5'], // Gemini frontier 2025-2026 (more specific first) + ['gemini-3.6-flash', 'Gemini 3.6 Flash'], ['gemini-3.5-flash', 'Gemini 3.5 Flash'], ['gemini-2.5-flash-lite', 'Gemini 2.5 Flash Lite'], ['gemini-2.5-flash', 'Gemini 2.5 Flash'], diff --git a/src/test/ai/providers/gemini.test.ts b/src/test/ai/providers/gemini.test.ts index 483fdc65..09acc378 100644 --- a/src/test/ai/providers/gemini.test.ts +++ b/src/test/ai/providers/gemini.test.ts @@ -6,7 +6,13 @@ * with `contents` + `systemInstruction`, no [DONE] sentinel. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { chat, geminiUrl, GEMINI_DEFAULT_MODEL } from '@/lib/ai/providers/gemini'; +import { + chat, + geminiUrl, + GEMINI_DEFAULT_MODEL, + GEMINI_MAX_TOKENS, + supportsThinkingLevel, +} from '@/lib/ai/providers/gemini'; const FAKE_KEY = 'AIzaFAKE_TEST_KEY_DO_NOT_USE_0123'; @@ -183,3 +189,49 @@ describe('Gemini chat — streaming + errors', () => { ).rejects.toMatchObject({ name: 'ChatError', code: 'rate_limited', status: 429 }); }); }); + +describe('Gemini chat — default model and thinking level', () => { + type Body = { generationConfig: { maxOutputTokens: number; thinkingConfig?: unknown } }; + async function sentBody(model: string): Promise { + fetchSpy.mockResolvedValue(makeStreamResponse([geminiFrame('ok')])); + await collect( + await chat({ + apiKey: FAKE_KEY, + model, + systemPrompt: 'sys', + messages: [{ role: 'user', content: 'hi' }], + }), + ); + const init = fetchSpy.mock.calls[0]![1] as RequestInit; + return JSON.parse(init.body as string) as Body; + } + + it('defaults to gemini-3.6-flash (gemini-2.0-flash was shut down on 1 June 2026)', () => { + expect(GEMINI_DEFAULT_MODEL).toBe('gemini-3.6-flash'); + }); + + it('asks Gemini 3+ for minimal thinking so the 1024-token cap stays for the answer', async () => { + const body = await sentBody(GEMINI_DEFAULT_MODEL); + expect(body.generationConfig).toEqual({ + maxOutputTokens: GEMINI_MAX_TOKENS, + thinkingConfig: { thinkingLevel: 'MINIMAL' }, + }); + }); + + it('sends no thinkingConfig to models before Gemini 3, which would reject it', async () => { + const body = await sentBody('gemini-2.5-flash-lite'); + expect(body.generationConfig).toEqual({ maxOutputTokens: GEMINI_MAX_TOKENS }); + }); + + it('detects Gemini 3 and later from the model id', () => { + expect(supportsThinkingLevel('gemini-3.6-flash')).toBe(true); + expect(supportsThinkingLevel('gemini-3.8-flash')).toBe(true); + expect(supportsThinkingLevel('gemini-4-argon')).toBe(true); + expect(supportsThinkingLevel('Gemini-3.5-Flash-Lite')).toBe(true); + expect(supportsThinkingLevel('gemini-2.5-pro')).toBe(false); + expect(supportsThinkingLevel('gemini-2.0-flash')).toBe(false); + expect(supportsThinkingLevel('gemini-1.5-flash')).toBe(false); + expect(supportsThinkingLevel('models/gemini-3.6-flash')).toBe(false); + expect(supportsThinkingLevel('')).toBe(false); + }); +}); diff --git a/src/test/ai/providers/resolveModel.test.ts b/src/test/ai/providers/resolveModel.test.ts index 95389f1c..8c6d15a9 100644 --- a/src/test/ai/providers/resolveModel.test.ts +++ b/src/test/ai/providers/resolveModel.test.ts @@ -91,6 +91,7 @@ describe('getModelLabel — short human-friendly labels', () => { }); it('normalises Gemini frontier (2.5 Flash Lite + 3.5 Flash + 2.5 Pro)', () => { + expect(getModelLabel('gemini-3.6-flash')).toBe('Gemini 3.6 Flash'); expect(getModelLabel('google/gemini-3.5-flash')).toBe('Gemini 3.5 Flash'); expect(getModelLabel('google/gemini-2.5-flash-lite')).toBe('Gemini 2.5 Flash Lite'); expect(getModelLabel('google/gemini-2.5-flash')).toBe('Gemini 2.5 Flash'); From bde5dde941b89472e6663bd7e64d28cd6cd86806 Mon Sep 17 00:00:00 2001 From: thierryvm <46031203+thierryvm@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:27:57 +0100 Subject: [PATCH 2/5] feat(ai-tutor): let learners pick their model; Sonnet 5.5 and Gemini 3.5 Flash-Lite by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New `modelChoices.ts` extends `resolveModel`: learner choice (localStorage `ai_tutor_model_`, flushed at signout) > env override if offered > code default. Stale stored values or overrides (gemini-2.0-flash, gemini-2.5-*, claude-sonnet-4-6) fall back to the default. - Paramètres IA: radio group per provider (OpenRouter, Anthropic, Gemini) with name + French cost hint; OpenAI keeps the read-only model line. - Defaults: OpenRouter anthropic/claude-sonnet-5.5 (Opus 5.5 offered), Anthropic claude-sonnet-5-5 (claude-opus-5-5 offered), Gemini gemini-3.5-flash-lite (gemini-3.6-flash offered). - Gemini: thinkingLevel MINIMAL only for models documented with `minimal`. Anthropic: thinking between_tools on Sonnet 5.5; Opus 5.5 (always on) gets a 4096 output cap. Sources checked 2026-11-09: ai.google.dev/gemini-api/docs/{models,pricing,thinking}, platform.claude.com/docs/en/about-claude/models/overview, .../build-with-claude/effort, GET openrouter.ai/api/v1/models. --- .env.example | 10 +- CHANGELOG.md | 12 ++ docs/processes/feature-flags.md | 8 +- src/app/components/AiSettings.tsx | 84 +++++++++++-- src/app/components/ai/AiTutorPanel.tsx | 11 +- src/lib/ai/keyManager.ts | 10 +- src/lib/ai/providers/anthropic.ts | 43 ++++++- src/lib/ai/providers/gemini.ts | 42 ++++--- src/lib/ai/providers/index.ts | 42 +++++-- src/lib/ai/providers/modelChoices.ts | 130 +++++++++++++++++++++ src/lib/ai/providers/openrouter.ts | 12 +- src/test/ai/AiTutorPanel.test.tsx | 28 +++-- src/test/ai/providers/anthropic.test.ts | 53 +++++++++ src/test/ai/providers/gemini.test.ts | 60 ++++++---- src/test/ai/providers/resolveModel.test.ts | 109 ++++++++++++++--- src/test/app/AiSettings.test.tsx | 92 +++++++++++++-- src/test/authContextSignoutAiKeys.test.ts | 11 ++ 17 files changed, 646 insertions(+), 111 deletions(-) create mode 100644 src/lib/ai/providers/modelChoices.ts diff --git a/.env.example b/.env.example index 9b4de3f7..80942ac0 100644 --- a/.env.example +++ b/.env.example @@ -37,10 +37,12 @@ SENTRY_VERCEL_LOG_DRAIN_URL=https://your-log-drain-url # via the in-app modal — never set OPENROUTER_API_KEY in any env file). VITE_AI_TUTOR_ENABLED=false -# Default model for first-time users (they can override per-message in UI). -# Production uses Anthropic Claude Sonnet 4.6 via OpenRouter (cf. ADR-005, -# PR #279 model upgrade decision 21 mai 2026). -VITE_AI_TUTOR_OPENROUTER_MODEL=anthropic/claude-sonnet-4-6 +# Default model for first-time users. Learners can pick another offered model +# in Paramètres IA; this override is only used when it is one of the offered +# models (`src/lib/ai/providers/modelChoices.ts`), otherwise the code default +# applies. OpenRouter ids use a dot: `anthropic/claude-sonnet-5.5`. +# Sonnet 5.5 is the default since 9 November 2026 (Opus 5.5 offered as option). +VITE_AI_TUTOR_OPENROUTER_MODEL=anthropic/claude-sonnet-5.5 # ─── Resend (Phase 9 Sprint 2.C — Support emails) ───────────────────────────── # Server-side only, **NEVER** in client bundle. Production scope only by diff --git a/CHANGELOG.md b/CHANGELOG.md index 9692efa4..ed141cf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ --- +## 🤖 9 novembre 2026 — Tuteur IA : choisir son modèle, Claude Sonnet 5.5 par défaut + +*Tuteur IA (clé personnelle) · identifiants et tarifs vérifiés le 9 novembre 2026 sur les pages officielles de Google, d'Anthropic et l'API d'OpenRouter* + +- **Gemini fonctionne de nouveau.** Google a arrêté `gemini-2.0-flash` le 1er juin 2026 : chaque question renvoyait une erreur. Le tuteur utilise maintenant **Gemini 3.5 Flash-Lite**, le modèle le moins cher (0,30 $ / 2,50 $ par million de jetons), puisque c'est l'élève qui paie avec sa propre clé. +- **Choisir son modèle dans Paramètres IA.** Pour Gemini : 3.5 Flash-Lite (par défaut) ou 3.6 Flash (meilleures réponses, plus cher). Pour OpenRouter et Anthropic : **Claude Sonnet 5.5** (par défaut, 2 $ / 10 $) ou **Claude Opus 5.5** (environ deux fois plus cher). Le choix reste enregistré dans le navigateur et s'efface à la déconnexion, comme le fournisseur choisi. +- Un ancien choix qui pointe vers un modèle arrêté est ignoré : le tuteur reprend le modèle par défaut. +- Les modèles récents réfléchissent avant de répondre, et cette réflexion compte dans la limite de longueur de la réponse. Le tuteur règle donc la réflexion au minimum là où le fournisseur le permet (Gemini 3.5 Flash-Lite et 3.6 Flash, Claude Sonnet 5.5), et laisse plus de place à Claude Opus 5.5, dont la réflexion ne se coupe pas, pour éviter des réponses coupées. +- OpenAI ne change pas : son modèle reste fixé par le déploiement. + +--- + ## ✳️ 2 octobre 2026 — Les jokers `*`, `?` et `[...]` fonctionnent *Terminal Linux et macOS · comportement vérifié sur bash 5.2 (Ubuntu 24.04)* diff --git a/docs/processes/feature-flags.md b/docs/processes/feature-flags.md index dfe1743b..7e3e281a 100644 --- a/docs/processes/feature-flags.md +++ b/docs/processes/feature-flags.md @@ -12,10 +12,10 @@ Les feature flags Terminal Learning sont des **booléens read-once à l'init**, | Flag | Default | Owner | Lieu | Usage | |---|---|---|---|---| | `VITE_AI_TUTOR_ENABLED` | `false` | THI-111 | `src/app/components/ai/AiTutorPanel.tsx` | Panel Tuteur IA — kill-switch ADR-005 V1 | -| `VITE_AI_TUTOR_OPENROUTER_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Override le modèle OpenRouter sans modifier le code (utile pour échapper au rate limit `:free` partagé). Ex: `meta-llama/llama-3.3-70b-instruct` (payant, ~0.001 €/question, pas de rate limit). | -| `VITE_AI_TUTOR_ANTHROPIC_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Override modèle Anthropic. Ex: `claude-sonnet-4-6`. | -| `VITE_AI_TUTOR_OPENAI_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Override modèle OpenAI (utile une fois le proxy V2 en place). | -| `VITE_AI_TUTOR_GEMINI_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Override modèle Gemini. Ex: `gemini-2.5-pro`. | +| `VITE_AI_TUTOR_OPENROUTER_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Modèle OpenRouter par défaut du déploiement. Depuis le 9/11/2026, pris en compte seulement s'il fait partie des modèles proposés dans Paramètres IA (`modelChoices.ts` : `anthropic/claude-sonnet-5.5`, `anthropic/claude-opus-5.5`) ; sinon le défaut du code s'applique. Le choix de l'élève passe avant. | +| `VITE_AI_TUTOR_ANTHROPIC_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Idem pour Anthropic direct : `claude-sonnet-5-5` ou `claude-opus-5-5`. | +| `VITE_AI_TUTOR_OPENAI_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Override modèle OpenAI (utile une fois le proxy V2 en place). Pas de choix proposé à l'élève : la valeur est utilisée telle quelle. | +| `VITE_AI_TUTOR_GEMINI_MODEL` | (DEFAULT_MODELS) | THI-111 | idem | Idem pour Gemini : `gemini-3.5-flash-lite` (défaut) ou `gemini-3.6-flash`. Une valeur arrêtée (`gemini-2.0-flash`, `gemini-2.5-*`) est ignorée. | --- diff --git a/src/app/components/AiSettings.tsx b/src/app/components/AiSettings.tsx index 02a39007..a451e013 100644 --- a/src/app/components/AiSettings.tsx +++ b/src/app/components/AiSettings.tsx @@ -7,6 +7,8 @@ * key body itself is never rendered, masked or otherwise, to keep * zero-disclosure on a casual screen-share or screenshot * - consent record (accepted? when? expires when? remaining days) + * - model choice for OpenRouter, Anthropic and Gemini (`modelChoices.ts`), + * stored locally; OpenAI shows the model in use without a picker * - actions: edit a key (mounts AiKeySetup inline), forget a key, * revoke consent * @@ -34,7 +36,7 @@ import { isEncrypted as kmIsEncrypted, type Provider, } from '@/lib/ai/keyManager'; -import { resolveModel } from '@/lib/ai/providers'; +import { getModelChoices, resolveModel, saveModelChoice } from '@/lib/ai/providers'; import { PROVIDER_LABELS } from '@/lib/ai/providers/meta'; import { CONSENT_KEY, @@ -50,6 +52,8 @@ interface ProviderStatus { provider: Provider; configured: boolean; encrypted: boolean; + /** Model actually used (`resolveModel`), shown and selectable below. */ + model: string; } const ONE_DAY_MS = 24 * 60 * 60 * 1000; @@ -110,6 +114,7 @@ export function AiSettings() { provider: p, configured: await kmHasKey(p), encrypted: await kmIsEncrypted(p), + model: resolveModel(p), })), ); setStatuses(next); @@ -151,6 +156,15 @@ export function AiSettings() { await refresh(); }, [refresh]); + // Model choice is a plain local preference (not a secret). Update the row + // right away, from what `resolveModel` now returns, so the UI only shows a + // choice that was actually stored. + const onModelChange = useCallback((p: Provider, model: string) => { + saveModelChoice(p, model); + const effective = resolveModel(p); + setStatuses((cur) => cur.map((s) => (s.provider === p ? { ...s, model: effective } : s))); + }, []); + return (

{PROVIDER_LABELS[s.provider]}

-

- Modèle utilisé :{' '} - - {resolveModel(s.provider)} - -

+ {getModelChoices(s.provider).length === 0 && ( +

+ Modèle utilisé :{' '} + + {s.model} + +

+ )}

Statut :{' '} {s.configured ? ( @@ -243,6 +259,60 @@ export function AiSettings() { )}

+ {getModelChoices(s.provider).length > 0 && ( +
+ + Modèle utilisé{' '} + avec {PROVIDER_LABELS[s.provider]} + +
+ {getModelChoices(s.provider).map((c) => { + const inputId = `ai-settings-model-${s.provider}-${c.id.replace(/[^a-z0-9]+/gi, '-')}`; + const checked = s.model === c.id; + return ( + // The whole card is clickable; the radio's accessible + // name is the model name, the hint is its description. + + ); + })} +
+

+ Tu paies les questions avec ta propre clé, au tarif du + fournisseur. +

+
+ )} {editingProvider === s.provider && (
(null); // Single source of truth for "which model is actually used" — `resolveModel` - // reads the Vercel env override `VITE_AI_TUTOR__MODEL` first and - // falls back to `DEFAULT_MODELS` only when the var is unset. Same helper is - // used by `AiSettings` so the two surfaces never disagree. - const model = useMemo(() => resolveModel(provider), [provider]); + // reads the learner's choice (Settings page), then the Vercel env override + // `VITE_AI_TUTOR__MODEL`, then `DEFAULT_MODELS`. Same helper as + // `AiSettings`, so the two surfaces never disagree. Not memoised on purpose: + // the choice can change on the Settings page while this panel stays + // mounted, and opening the panel re-renders it, which re-reads the choice + // (one localStorage read). + const model = resolveModel(provider); // THI-148 V1.0.1 — static, public-only platform overview injected as // . Same trust class as lessonContext (curriculum data, diff --git a/src/lib/ai/keyManager.ts b/src/lib/ai/keyManager.ts index 66cc4d0d..968ce31b 100644 --- a/src/lib/ai/keyManager.ts +++ b/src/lib/ai/keyManager.ts @@ -30,6 +30,8 @@ export const PROVIDER_KEY = 'ai_tutor_provider'; export const CONSENT_KEY = 'ai_consent_v1'; export const RATE_KEY = 'ai_rate_v1'; export const MODE_KEY = 'ai_tutor_mode'; +/** Prefix for the learner's model choice per provider (`providers/modelChoices.ts`). Not a secret. */ +export const MODEL_KEY_PREFIX = 'ai_tutor_model_'; const DB_NAME = 'ai_keys_encrypted'; const DB_VERSION = 1; const STORE_NAME = 'keys'; @@ -283,7 +285,8 @@ export async function forgetKey(provider: Provider): Promise { * * RGPD critical: `ai_consent_v1` survives signout in localStorage by default * — next user on the same device inherits consent without seeing the modal. - * Plain API keys, the last selected provider, the rate counter and the tutor + * Plain API keys, the last selected provider, the model choices, the rate + * counter and the tutor * mode are also flushed so a sequential user does not inherit a previous * user's state. * @@ -297,7 +300,10 @@ export async function clearAiSessionData(opts?: { includeEncrypted?: boolean }): const ls = getLocalStorage(); const ss = (globalThis as { sessionStorage?: Storage }).sessionStorage; - for (const p of PROVIDERS) ls.removeItem(LS_PREFIX + p); + for (const p of PROVIDERS) { + ls.removeItem(LS_PREFIX + p); + ls.removeItem(MODEL_KEY_PREFIX + p); + } ls.removeItem(PROVIDER_KEY); ls.removeItem(CONSENT_KEY); diff --git a/src/lib/ai/providers/anthropic.ts b/src/lib/ai/providers/anthropic.ts index bd9012af..dfed39b5 100644 --- a/src/lib/ai/providers/anthropic.ts +++ b/src/lib/ai/providers/anthropic.ts @@ -20,8 +20,47 @@ import { safeCancel, streamSseEvents } from './_sse'; export const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages'; export const ANTHROPIC_VERSION = '2023-06-01'; -export const ANTHROPIC_DEFAULT_MODEL = 'claude-sonnet-4-6'; +// Claude Sonnet 5.5 (`claude-sonnet-5-5`, $2 / $10 per million tokens); +// Claude Opus 5.5 (`claude-opus-5-5`) is offered as the stronger option in +// `modelChoices.ts`. Previous default `claude-sonnet-4-6` is still active but +// older. Source (9 November 2026): +// https://platform.claude.com/docs/en/about-claude/models/overview +export const ANTHROPIC_DEFAULT_MODEL = 'claude-sonnet-5-5'; export const ANTHROPIC_MAX_TOKENS = 1024; +/** + * Output cap for models whose thinking cannot be turned off. Thinking counts + * toward `max_tokens` (Effort guide), so 1024 could leave a cut or empty + * answer. This is a ceiling, not a spend: short answers stay short. + */ +export const ANTHROPIC_THINKING_MAX_TOKENS = 4096; + +/** + * Thinking settings per model, from the Anthropic docs read on 9 November + * 2026 (https://platform.claude.com/docs/en/build-with-claude/effort and + * https://platform.claude.com/docs/en/models/sonnet-5-5/overview): + * - Sonnet 5.5 thinks by default; `thinking: {type: "between_tools"}` turns + * off up-front thinking (`"disabled"` returns 400). It works at `high` + * effort or below, and `high` is the default we keep. With no tools in + * the tutor, the answer gets the whole 1024-token budget, as before. + * - Opus 5.5 thinking is always on and cannot be turned off (`disabled` + * returns 400 at every effort level): we only raise the output cap. + * - Other models (env override, older ids) get the request unchanged. + */ +const BETWEEN_TOOLS_MODELS: ReadonlySet = new Set(['claude-sonnet-5-5']); +const ALWAYS_THINKING_MODELS: ReadonlySet = new Set(['claude-opus-5-5']); + +export function anthropicThinkingOptions(model: string): { + max_tokens: number; + thinking?: { type: 'between_tools' }; +} { + if (BETWEEN_TOOLS_MODELS.has(model)) { + return { max_tokens: ANTHROPIC_MAX_TOKENS, thinking: { type: 'between_tools' } }; + } + if (ALWAYS_THINKING_MODELS.has(model)) { + return { max_tokens: ANTHROPIC_THINKING_MAX_TOKENS }; + } + return { max_tokens: ANTHROPIC_MAX_TOKENS }; +} interface ContentBlockDelta { type?: 'content_block_delta'; @@ -63,7 +102,7 @@ async function* parseStream( export async function chat(params: ChatParams): Promise { const body = JSON.stringify({ model: params.model, - max_tokens: ANTHROPIC_MAX_TOKENS, + ...anthropicThinkingOptions(params.model), stream: true, system: params.systemPrompt, messages: params.messages, // already user/assistant alternating diff --git a/src/lib/ai/providers/gemini.ts b/src/lib/ai/providers/gemini.ts index 53517b8c..10d504f3 100644 --- a/src/lib/ai/providers/gemini.ts +++ b/src/lib/ai/providers/gemini.ts @@ -21,25 +21,39 @@ import { ChatError, type ChatErrorCode, type ChatParams, type ChatStream } from import { streamSseEvents } from './_sse'; const GEMINI_BASE = 'https://generativelanguage.googleapis.com/v1beta/models'; -// `gemini-2.0-flash` was shut down by Google on 1 June 2026; its official -// replacement is `gemini-3.6-flash` (stable, no shutdown date announced on -// 9 November 2026). Source: Gemini API deprecations page. -export const GEMINI_DEFAULT_MODEL = 'gemini-3.6-flash'; +// `gemini-2.0-flash` was shut down by Google on 1 June 2026. Default is now +// the cheapest current model, `gemini-3.5-flash-lite` ($0.30 / $2.50 per +// million tokens): the learner pays with their own key. `gemini-3.6-flash` +// is offered as the better-quality option (see `modelChoices.ts`). +// Sources (9 November 2026): https://ai.google.dev/gemini-api/docs/models, +// https://ai.google.dev/gemini-api/docs/pricing +export const GEMINI_DEFAULT_MODEL = 'gemini-3.5-flash-lite'; export const GEMINI_MAX_TOKENS = 1024; /** - * Gemini 3+ models think by default (`gemini-3.6-flash`: medium), and - * thinking tokens count against `maxOutputTokens`: with our 1024 cap the - * answer could come back truncated or empty. `MINIMAL` keeps the tutor's - * previous behaviour (gemini-2.0-flash did not think). Earlier models reject - * `thinkingLevel` with an error, so it is only sent to Gemini 3 and later - * (a deploy may still point `VITE_AI_TUTOR_GEMINI_MODEL` at a 2.5 model). + * Thinking tokens count against `maxOutputTokens`: with our 1024 cap a model + * that thinks at `medium` (the `gemini-3.6-flash` default) could return a cut + * or empty answer. `MINIMAL` keeps the tutor's previous behaviour + * (gemini-2.0-flash did not think). + * + * `thinkingLevel` is only sent to the models whose documented levels include + * `minimal` (Gemini thinking guide, table "Controlling thinking", read on + * 9 November 2026: https://ai.google.dev/gemini-api/docs/thinking). + * Models before Gemini 3 reject the field with an error, and some Gemini 3+ + * models (3.8 Flash, 3.1 Pro, 4 Argon) do not accept `minimal`. + * `gemini-3.5-flash-lite` already defaults to minimal; sending it explicitly + * is harmless and keeps the request deterministic. */ export const GEMINI_THINKING_LEVEL = 'MINIMAL'; -export function supportsThinkingLevel(model: string): boolean { - const match = /^gemini-(\d+)/.exec(model.toLowerCase()); - return match !== null && Number(match[1]) >= 3; +const MINIMAL_THINKING_MODELS: ReadonlySet = new Set([ + 'gemini-3.5-flash-lite', + 'gemini-3.6-flash', + 'gemini-3-flash-preview', +]); + +export function acceptsMinimalThinking(model: string): boolean { + return MINIMAL_THINKING_MODELS.has(model.toLowerCase()); } interface GeminiFrame { @@ -89,7 +103,7 @@ export async function chat(params: ChatParams): Promise { systemInstruction: { parts: [{ text: params.systemPrompt }] }, generationConfig: { maxOutputTokens: GEMINI_MAX_TOKENS, - ...(supportsThinkingLevel(params.model) + ...(acceptsMinimalThinking(params.model) ? { thinkingConfig: { thinkingLevel: GEMINI_THINKING_LEVEL } } : {}), }, diff --git a/src/lib/ai/providers/index.ts b/src/lib/ai/providers/index.ts index fd2b39b7..c22aae1c 100644 --- a/src/lib/ai/providers/index.ts +++ b/src/lib/ai/providers/index.ts @@ -12,7 +12,16 @@ import { chat as openrouterChat } from './openrouter'; import { chat as anthropicChat } from './anthropic'; import { chat as openaiChat } from './openai'; import { chat as geminiChat } from './gemini'; +import { getModelChoices, isOfferedModel, readStoredModel } from './modelChoices'; +export { + MODEL_CHOICES, + getModelChoices, + isOfferedModel, + readStoredModel, + saveModelChoice, + type ModelChoice, +} from './modelChoices'; export { OPENROUTER_DEFAULT_MODEL, OPENROUTER_URL } from './openrouter'; export { ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_URL } from './anthropic'; export { OPENAI_DEFAULT_MODEL, OPENAI_URL } from './openai'; @@ -38,13 +47,19 @@ export const DEFAULT_MODELS: Readonly> = { }; /** - * Single source of truth for "which model is actually used" — reads the - * deploy-time Vercel env override `VITE_AI_TUTOR__MODEL` first, - * falls back to `DEFAULT_MODELS` only when the env var is unset/empty. + * Single source of truth for "which model is actually used". Settings page + * and Drawer panel must both use this helper so they never disagree (bug + * fixed in PR #280: Settings showed the fallback while the Drawer used the + * env override). * - * Settings page and Drawer panel must use this helper to avoid the bug - * where Settings showed the hardcoded fallback (e.g. Llama 3.3 70B free) - * while the Drawer used the env override (e.g. Sonnet 4.6 paid). + * Order, for providers that offer a model picker (`modelChoices.ts`: + * OpenRouter, Anthropic, Gemini): + * 1. the learner's stored choice (validated; a stale value is dropped); + * 2. the deploy-time env override `VITE_AI_TUTOR__MODEL`, only if + * it is one of the offered models (an override pointing at a model the + * provider has shut down, e.g. `gemini-2.0-flash`, is ignored); + * 3. `DEFAULT_MODELS`. + * Providers without a picker (OpenAI) keep env override > default. */ export function resolveModel(provider: Provider): string { const envKeys: Readonly> = { @@ -53,8 +68,16 @@ export function resolveModel(provider: Provider): string { openai: 'VITE_AI_TUTOR_OPENAI_MODEL', gemini: 'VITE_AI_TUTOR_GEMINI_MODEL', }; - const override = import.meta.env[envKeys[provider]] as string | undefined; - return override && override.length > 0 ? override : DEFAULT_MODELS[provider]; + const raw = import.meta.env[envKeys[provider]] as string | undefined; + const override = raw && raw.length > 0 ? raw : null; + + if (getModelChoices(provider).length === 0) { + return override ?? DEFAULT_MODELS[provider]; + } + const stored = readStoredModel(provider); + if (stored) return stored; + if (override && isOfferedModel(provider, override)) return override; + return DEFAULT_MODELS[provider]; } /** @@ -79,6 +102,8 @@ export function resolveModel(provider: Provider): string { */ const MODEL_LABELS: ReadonlyArray = [ // Claude family + ['opus-5.5', 'Opus 5.5'], + ['sonnet-5.5', 'Sonnet 5.5'], ['opus-4.7', 'Opus 4.7'], ['sonnet-4.6', 'Sonnet 4.6'], ['sonnet-4.5', 'Sonnet 4.5'], @@ -90,6 +115,7 @@ const MODEL_LABELS: ReadonlyArray = [ ['gpt-5', 'GPT-5'], // Gemini frontier 2025-2026 (more specific first) ['gemini-3.6-flash', 'Gemini 3.6 Flash'], + ['gemini-3.5-flash-lite', 'Gemini 3.5 Flash-Lite'], ['gemini-3.5-flash', 'Gemini 3.5 Flash'], ['gemini-2.5-flash-lite', 'Gemini 2.5 Flash Lite'], ['gemini-2.5-flash', 'Gemini 2.5 Flash'], diff --git a/src/lib/ai/providers/modelChoices.ts b/src/lib/ai/providers/modelChoices.ts new file mode 100644 index 00000000..f46634c3 --- /dev/null +++ b/src/lib/ai/providers/modelChoices.ts @@ -0,0 +1,130 @@ +/** + * Models the learner can pick per provider, and the stored choice. + * + * Extends the existing `resolveModel` mechanism (see `./index.ts`) instead of + * adding a second one: `resolveModel(provider)` reads the stored choice first, + * then the deploy-time env override, then the provider default. + * + * Rules: + * - The FIRST entry of each list is the provider default (asserted by tests + * against the provider's `*_DEFAULT_MODEL` constant). + * - Only ids listed here can be stored. A stored value that is not in the + * list (a model Google or Anthropic has shut down since, a hand-edited + * value) is removed and the default applies again. + * - Providers without a list (OpenAI) keep the env override / default only. + * + * The choice is not a secret: it lives in plain localStorage under + * `MODEL_KEY_PREFIX + provider`, and `clearAiSessionData()` removes it at + * signout like the selected provider. + * + * Model ids and prices were checked on 9 November 2026: + * - Gemini: https://ai.google.dev/gemini-api/docs/models and + * https://ai.google.dev/gemini-api/docs/pricing + * - Anthropic: https://platform.claude.com/docs/en/about-claude/models/overview + * - OpenRouter: GET https://openrouter.ai/api/v1/models + */ +import { MODEL_KEY_PREFIX, type Provider } from '../keyManager'; +import { ANTHROPIC_DEFAULT_MODEL } from './anthropic'; +import { GEMINI_DEFAULT_MODEL } from './gemini'; +import { OPENROUTER_DEFAULT_MODEL } from './openrouter'; + +export interface ModelChoice { + /** Exact provider model id sent in the request. */ + readonly id: string; + /** Name shown to the learner. */ + readonly label: string; + /** Short French hint: quality and relative cost. */ + readonly hint: string; +} + +export const MODEL_CHOICES: Readonly>> = { + // Sonnet 5.5: $2 / $10 per million tokens; Opus 5.5: $4 / $20. + openrouter: [ + { + id: OPENROUTER_DEFAULT_MODEL, + label: 'Claude Sonnet 5.5', + hint: 'Rapide et précis · choix par défaut', + }, + { + id: 'anthropic/claude-opus-5.5', + label: 'Claude Opus 5.5', + hint: 'Réponses plus poussées · environ 2 fois plus cher', + }, + ], + anthropic: [ + { + id: ANTHROPIC_DEFAULT_MODEL, + label: 'Claude Sonnet 5.5', + hint: 'Rapide et précis · choix par défaut', + }, + { + id: 'claude-opus-5-5', + label: 'Claude Opus 5.5', + hint: 'Réponses plus poussées · environ 2 fois plus cher', + }, + ], + // Flash-Lite: $0.30 / $2.50 per million tokens. 3.6 Flash: $0.75 / $3.75 + // until 31 December 2026, then $1.50 / $7.50 (Google pricing page). + gemini: [ + { + id: GEMINI_DEFAULT_MODEL, + label: 'Gemini 3.5 Flash-Lite', + hint: 'Le moins cher · choix par défaut', + }, + { + id: 'gemini-3.6-flash', + label: 'Gemini 3.6 Flash', + hint: 'Meilleures réponses · plusieurs fois plus cher', + }, + ], +}; + +/** Models offered for this provider; empty when the provider has no picker. */ +export function getModelChoices(provider: Provider): readonly ModelChoice[] { + return MODEL_CHOICES[provider] ?? []; +} + +export function isOfferedModel(provider: Provider, model: string): boolean { + return getModelChoices(provider).some((c) => c.id === model); +} + +function storage(): Storage | null { + try { + return (globalThis as { localStorage?: Storage }).localStorage ?? null; + } catch { + return null; + } +} + +/** + * The learner's stored model for this provider, or `null` when none is + * stored. An invalid stored value (e.g. `gemini-2.0-flash`, shut down by + * Google) is removed so the default applies. + */ +export function readStoredModel(provider: Provider): string | null { + const ls = storage(); + if (!ls) return null; + const key = MODEL_KEY_PREFIX + provider; + try { + const value = ls.getItem(key); + if (value === null) return null; + if (isOfferedModel(provider, value)) return value; + ls.removeItem(key); + } catch { + /* storage disabled — fall back to the default */ + } + return null; +} + +/** Stores the learner's choice. Returns false for a model that is not offered. */ +export function saveModelChoice(provider: Provider, model: string): boolean { + if (!isOfferedModel(provider, model)) return false; + const ls = storage(); + if (!ls) return false; + try { + ls.setItem(MODEL_KEY_PREFIX + provider, model); + return true; + } catch { + return false; + } +} diff --git a/src/lib/ai/providers/openrouter.ts b/src/lib/ai/providers/openrouter.ts index fbfb1025..9f710de0 100644 --- a/src/lib/ai/providers/openrouter.ts +++ b/src/lib/ai/providers/openrouter.ts @@ -21,10 +21,12 @@ import { safeCancel, streamSseEvents } from './_sse'; export const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'; /** - * Default OpenRouter model when `VITE_AI_TUTOR_OPENROUTER_MODEL` env override - * is unset (local dev, CI, preview without env). Bumped 2026-05-24 to align - * with prod Vercel env (Sonnet 4.6, sync via API REST PR #279) and the Stage - * B1 eval matrix verdict (THI-260 — `docs/audits/eval-tutor-matrix-2026-05-24.md`). + * Default OpenRouter model when no learner choice is stored and the + * `VITE_AI_TUTOR_OPENROUTER_MODEL` env override is unset or not one of the + * offered models (`modelChoices.ts`). Moved to Claude Sonnet 5.5 on + * 9 November 2026 (decision @thierry); id checked on + * GET https://openrouter.ai/api/v1/models the same day ($2 / $10 per million + * tokens). Previously Sonnet 4.6 (THI-260, 2026-05-24). * * Previous default `meta-llama/llama-3.3-70b-instruct:free` is legacy 2024, * hallucinatoire FR (cf. `feedback_llm_hallucinations_inter_phrase.md`), rate- @@ -32,7 +34,7 @@ export const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'; * Sonnet 4.6 (default prod, 7/8 PASS, $0.054/run, stable) as VERIFIED finding * H2-AI of `llm-security-auditor` 2026-05-24 audit. */ -export const OPENROUTER_DEFAULT_MODEL = 'anthropic/claude-sonnet-4.6'; +export const OPENROUTER_DEFAULT_MODEL = 'anthropic/claude-sonnet-5.5'; const APP_TITLE = 'Terminal Learning Tutor'; const APP_REFERER = 'https://terminallearning.dev'; diff --git a/src/test/ai/AiTutorPanel.test.tsx b/src/test/ai/AiTutorPanel.test.tsx index 6e1c3a5b..3b666725 100644 --- a/src/test/ai/AiTutorPanel.test.tsx +++ b/src/test/ai/AiTutorPanel.test.tsx @@ -239,7 +239,7 @@ describe('AiTutorPanel — conversation', () => { describe('AiTutorPanel — header displays the active model (transparency)', () => { it('header includes the model label when an env override is set', async () => { vi.stubEnv('VITE_AI_TUTOR_ENABLED', 'true'); - vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-sonnet-4-6'); + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-opus-5.5'); const user = userEvent.setup(); render(); @@ -247,7 +247,7 @@ describe('AiTutorPanel — header displays the active model (transparency)', () const heading = await screen.findByRole('heading', { level: 2 }); expect(heading.textContent).toContain('OpenRouter'); - expect(heading.textContent).toContain('Sonnet 4.6'); + expect(heading.textContent).toContain('Opus 5.5'); }); it('header falls back to the default model label when no env override is set', async () => { @@ -259,15 +259,14 @@ describe('AiTutorPanel — header displays the active model (transparency)', () const heading = await screen.findByRole('heading', { level: 2 }); expect(heading.textContent).toContain('OpenRouter'); - // The OpenRouter default was bumped to Sonnet 4.6 on 2026-05-24 (THI-260, - // H2-AI finding) — previously Llama 3.3 70B free (legacy 2024, hallucinatoire - // FR + rate-limited Venice provider). - expect(heading.textContent).toContain('Sonnet 4.6'); + // The OpenRouter default moved to Sonnet 5.5 on 2026-11-09 (decision @thierry); + // before: Sonnet 4.6 (THI-260, 2026-05-24), Llama 3.3 70B free before that. + expect(heading.textContent).toContain('Sonnet 5.5'); }); it('header `title` attribute exposes the full string for truncated viewports', async () => { vi.stubEnv('VITE_AI_TUTOR_ENABLED', 'true'); - vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-sonnet-4-6'); + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-opus-5.5'); const user = userEvent.setup(); render(); @@ -277,9 +276,22 @@ describe('AiTutorPanel — header displays the active model (transparency)', () // Tooltip mirrors the visible text so hover/long-press reveals the full // model name when the title is clipped by `truncate`. expect(heading.getAttribute('title')).toBe( - 'Tuteur IA — OpenRouter • Sonnet 4.6', + 'Tuteur IA — OpenRouter • Opus 5.5', ); }); + + it('header shows the model the learner picked in Paramètres IA, re-read when the panel opens', async () => { + vi.stubEnv('VITE_AI_TUTOR_ENABLED', 'true'); + + const user = userEvent.setup(); + render(); + // Picked while the panel is already mounted (Settings page in the same tab). + localStorage.setItem('ai_tutor_model_openrouter', 'anthropic/claude-opus-5.5'); + await user.click(screen.getByLabelText(/Ouvrir le tuteur IA/)); + + const heading = await screen.findByRole('heading', { level: 2 }); + expect(heading.textContent).toContain('Opus 5.5'); + }); }); // THI-263 fix (A1 from llm-security-auditor 23/05/2026 audit) — encrypted diff --git a/src/test/ai/providers/anthropic.test.ts b/src/test/ai/providers/anthropic.test.ts index 9f7a23c1..7606aafe 100644 --- a/src/test/ai/providers/anthropic.test.ts +++ b/src/test/ai/providers/anthropic.test.ts @@ -9,9 +9,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { chat, + anthropicThinkingOptions, + ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_URL, ANTHROPIC_VERSION, ANTHROPIC_MAX_TOKENS, + ANTHROPIC_THINKING_MAX_TOKENS, } from '@/lib/ai/providers/anthropic'; const FAKE_KEY = 'sk-ant-FAKE_TEST_KEY_DO_NOT_USE_0123'; @@ -203,3 +206,53 @@ describe('Anthropic chat — streaming + errors', () => { ).rejects.toMatchObject({ name: 'ChatError', code: 'rate_limited', status: 429 }); }); }); + +describe('Anthropic chat — default model and thinking settings', () => { + type Body = { model: string; max_tokens: number; thinking?: unknown }; + async function sentBody(model: string): Promise { + fetchSpy.mockResolvedValue(makeStreamResponse(['event: message_stop\ndata: {}\n\n'])); + await collect( + await chat({ + apiKey: FAKE_KEY, + model, + systemPrompt: 'SYS', + messages: [{ role: 'user', content: 'q' }], + }), + ); + const init = fetchSpy.mock.calls[0]![1] as RequestInit; + return JSON.parse(init.body as string) as Body; + } + + it('defaults to Claude Sonnet 5.5 (`claude-sonnet-5-5`, Anthropic models overview)', () => { + expect(ANTHROPIC_DEFAULT_MODEL).toBe('claude-sonnet-5-5'); + }); + + it('turns off up-front thinking on Sonnet 5.5 so the 1024-token cap stays for the answer', async () => { + const body = await sentBody('claude-sonnet-5-5'); + expect(body.max_tokens).toBe(ANTHROPIC_MAX_TOKENS); + expect(body.thinking).toEqual({ type: 'between_tools' }); + }); + + it('gives Opus 5.5 (thinking always on) a larger output cap and no thinking field', async () => { + const body = await sentBody('claude-opus-5-5'); + expect(body.max_tokens).toBe(ANTHROPIC_THINKING_MAX_TOKENS); + expect(body).not.toHaveProperty('thinking'); + }); + + it('leaves other models unchanged (no thinking field, 1024 cap)', async () => { + const body = await sentBody('claude-sonnet-4-6'); + expect(body.max_tokens).toBe(ANTHROPIC_MAX_TOKENS); + expect(body).not.toHaveProperty('thinking'); + }); + + it('maps each model to its documented options', () => { + expect(anthropicThinkingOptions('claude-sonnet-5-5')).toEqual({ + max_tokens: ANTHROPIC_MAX_TOKENS, + thinking: { type: 'between_tools' }, + }); + expect(anthropicThinkingOptions('claude-opus-5-5')).toEqual({ + max_tokens: ANTHROPIC_THINKING_MAX_TOKENS, + }); + expect(anthropicThinkingOptions('claude-haiku-4-5')).toEqual({ max_tokens: ANTHROPIC_MAX_TOKENS }); + }); +}); diff --git a/src/test/ai/providers/gemini.test.ts b/src/test/ai/providers/gemini.test.ts index 09acc378..36131883 100644 --- a/src/test/ai/providers/gemini.test.ts +++ b/src/test/ai/providers/gemini.test.ts @@ -11,7 +11,7 @@ import { geminiUrl, GEMINI_DEFAULT_MODEL, GEMINI_MAX_TOKENS, - supportsThinkingLevel, + acceptsMinimalThinking, } from '@/lib/ai/providers/gemini'; const FAKE_KEY = 'AIzaFAKE_TEST_KEY_DO_NOT_USE_0123'; @@ -206,32 +206,42 @@ describe('Gemini chat — default model and thinking level', () => { return JSON.parse(init.body as string) as Body; } - it('defaults to gemini-3.6-flash (gemini-2.0-flash was shut down on 1 June 2026)', () => { - expect(GEMINI_DEFAULT_MODEL).toBe('gemini-3.6-flash'); + it('defaults to gemini-3.5-flash-lite, the cheapest current model (gemini-2.0-flash was shut down on 1 June 2026)', () => { + expect(GEMINI_DEFAULT_MODEL).toBe('gemini-3.5-flash-lite'); }); - it('asks Gemini 3+ for minimal thinking so the 1024-token cap stays for the answer', async () => { - const body = await sentBody(GEMINI_DEFAULT_MODEL); - expect(body.generationConfig).toEqual({ - maxOutputTokens: GEMINI_MAX_TOKENS, - thinkingConfig: { thinkingLevel: 'MINIMAL' }, - }); - }); - - it('sends no thinkingConfig to models before Gemini 3, which would reject it', async () => { - const body = await sentBody('gemini-2.5-flash-lite'); - expect(body.generationConfig).toEqual({ maxOutputTokens: GEMINI_MAX_TOKENS }); - }); + it.each(['gemini-3.5-flash-lite', 'gemini-3.6-flash'])( + 'asks %s for minimal thinking so the 1024-token cap stays for the answer', + async (model) => { + const body = await sentBody(model); + expect(body.generationConfig).toEqual({ + maxOutputTokens: GEMINI_MAX_TOKENS, + thinkingConfig: { thinkingLevel: 'MINIMAL' }, + }); + }, + ); - it('detects Gemini 3 and later from the model id', () => { - expect(supportsThinkingLevel('gemini-3.6-flash')).toBe(true); - expect(supportsThinkingLevel('gemini-3.8-flash')).toBe(true); - expect(supportsThinkingLevel('gemini-4-argon')).toBe(true); - expect(supportsThinkingLevel('Gemini-3.5-Flash-Lite')).toBe(true); - expect(supportsThinkingLevel('gemini-2.5-pro')).toBe(false); - expect(supportsThinkingLevel('gemini-2.0-flash')).toBe(false); - expect(supportsThinkingLevel('gemini-1.5-flash')).toBe(false); - expect(supportsThinkingLevel('models/gemini-3.6-flash')).toBe(false); - expect(supportsThinkingLevel('')).toBe(false); + it.each(['gemini-2.5-flash-lite', 'gemini-3.8-flash', 'gemini-4-argon'])( + 'sends no thinkingConfig to %s, which does not accept the minimal level', + async (model) => { + const body = await sentBody(model); + expect(body.generationConfig).toEqual({ maxOutputTokens: GEMINI_MAX_TOKENS }); + }, + ); + + it('accepts minimal thinking only for the documented models', () => { + expect(acceptsMinimalThinking('gemini-3.5-flash-lite')).toBe(true); + expect(acceptsMinimalThinking('gemini-3.6-flash')).toBe(true); + expect(acceptsMinimalThinking('Gemini-3.6-Flash')).toBe(true); + expect(acceptsMinimalThinking('gemini-3-flash-preview')).toBe(true); + // Gemini 3+ models whose levels start at `low` (thinking guide table). + expect(acceptsMinimalThinking('gemini-3.8-flash')).toBe(false); + expect(acceptsMinimalThinking('gemini-3.1-pro-preview')).toBe(false); + expect(acceptsMinimalThinking('gemini-4-argon')).toBe(false); + // Before Gemini 3: `thinkingLevel` is an error. + expect(acceptsMinimalThinking('gemini-2.5-pro')).toBe(false); + expect(acceptsMinimalThinking('gemini-2.0-flash')).toBe(false); + expect(acceptsMinimalThinking('models/gemini-3.6-flash')).toBe(false); + expect(acceptsMinimalThinking('')).toBe(false); }); }); diff --git a/src/test/ai/providers/resolveModel.test.ts b/src/test/ai/providers/resolveModel.test.ts index 8c6d15a9..e26d71fb 100644 --- a/src/test/ai/providers/resolveModel.test.ts +++ b/src/test/ai/providers/resolveModel.test.ts @@ -1,50 +1,115 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; +import { MODEL_KEY_PREFIX } from '@/lib/ai/keyManager'; import { ANTHROPIC_DEFAULT_MODEL, DEFAULT_MODELS, GEMINI_DEFAULT_MODEL, + MODEL_CHOICES, OPENAI_DEFAULT_MODEL, OPENROUTER_DEFAULT_MODEL, + getModelChoices, getModelLabel, + readStoredModel, resolveModel, + saveModelChoice, } from '@/lib/ai/providers'; afterEach(() => { vi.unstubAllEnvs(); + localStorage.clear(); }); -describe('resolveModel — env override > fallback', () => { - it('returns the OpenRouter env override when set', () => { - vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-sonnet-4-6'); - expect(resolveModel('openrouter')).toBe('anthropic/claude-sonnet-4-6'); - }); - - it('returns the Anthropic env override when set', () => { - vi.stubEnv('VITE_AI_TUTOR_ANTHROPIC_MODEL', 'claude-opus-4-7'); - expect(resolveModel('anthropic')).toBe('claude-opus-4-7'); - }); - +describe('resolveModel — providers without a picker (OpenAI): env override > fallback', () => { it('returns the OpenAI env override when set', () => { vi.stubEnv('VITE_AI_TUTOR_OPENAI_MODEL', 'gpt-4o'); expect(resolveModel('openai')).toBe('gpt-4o'); }); - it('returns the Gemini env override when set', () => { - vi.stubEnv('VITE_AI_TUTOR_GEMINI_MODEL', 'gemini-1.5-pro'); - expect(resolveModel('gemini')).toBe('gemini-1.5-pro'); - }); - it('falls back to DEFAULT_MODELS when env override is empty string', () => { - vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', ''); - expect(resolveModel('openrouter')).toBe(OPENROUTER_DEFAULT_MODEL); + vi.stubEnv('VITE_AI_TUTOR_OPENAI_MODEL', ''); + expect(resolveModel('openai')).toBe(OPENAI_DEFAULT_MODEL); }); it('falls back to DEFAULT_MODELS when env override is unset', () => { // No stubEnv call — the var is undefined in the test environment. + expect(resolveModel('openai')).toBe(OPENAI_DEFAULT_MODEL); + }); +}); + +describe('resolveModel — providers with a picker (OpenRouter, Anthropic, Gemini)', () => { + it('uses the cheapest Gemini model by default', () => { + expect(resolveModel('gemini')).toBe('gemini-3.5-flash-lite'); + }); + + it('uses Sonnet 5.5 by default on OpenRouter and Anthropic', () => { + expect(resolveModel('openrouter')).toBe('anthropic/claude-sonnet-5.5'); + expect(resolveModel('anthropic')).toBe('claude-sonnet-5-5'); + }); + + it('honours an env override that is one of the offered models', () => { + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-opus-5.5'); + vi.stubEnv('VITE_AI_TUTOR_ANTHROPIC_MODEL', 'claude-opus-5-5'); + vi.stubEnv('VITE_AI_TUTOR_GEMINI_MODEL', 'gemini-3.6-flash'); + expect(resolveModel('openrouter')).toBe('anthropic/claude-opus-5.5'); + expect(resolveModel('anthropic')).toBe('claude-opus-5-5'); + expect(resolveModel('gemini')).toBe('gemini-3.6-flash'); + }); + + it('ignores an env override pointing at a model that is not offered (shut down or old)', () => { + vi.stubEnv('VITE_AI_TUTOR_GEMINI_MODEL', 'gemini-2.0-flash'); + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-sonnet-4-6'); + vi.stubEnv('VITE_AI_TUTOR_ANTHROPIC_MODEL', 'claude-sonnet-4-6'); + expect(resolveModel('gemini')).toBe(GEMINI_DEFAULT_MODEL); + expect(resolveModel('openrouter')).toBe(OPENROUTER_DEFAULT_MODEL); expect(resolveModel('anthropic')).toBe(ANTHROPIC_DEFAULT_MODEL); }); + it('keeps the learner choice across reads (persisted in localStorage)', () => { + expect(saveModelChoice('gemini', 'gemini-3.6-flash')).toBe(true); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'gemini')).toBe('gemini-3.6-flash'); + expect(resolveModel('gemini')).toBe('gemini-3.6-flash'); + expect(resolveModel('gemini')).toBe('gemini-3.6-flash'); + // Other providers are not affected. + expect(resolveModel('openrouter')).toBe(OPENROUTER_DEFAULT_MODEL); + }); + + it('lets the learner choice win over the env override', () => { + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-opus-5.5'); + saveModelChoice('openrouter', 'anthropic/claude-sonnet-5.5'); + expect(resolveModel('openrouter')).toBe('anthropic/claude-sonnet-5.5'); + }); + + it.each(['gemini-2.0-flash', 'gemini-2.5-flash', 'gemini-2.5-pro', 'nonsense'])( + 'drops a stale stored Gemini value (%s) and falls back to the default', + (stale) => { + localStorage.setItem(MODEL_KEY_PREFIX + 'gemini', stale); + expect(resolveModel('gemini')).toBe(GEMINI_DEFAULT_MODEL); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'gemini')).toBeNull(); + }, + ); + + it('refuses to store a model that is not offered', () => { + expect(saveModelChoice('gemini', 'gemini-2.0-flash')).toBe(false); + expect(saveModelChoice('openai', 'gpt-4o')).toBe(false); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'gemini')).toBeNull(); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'openai')).toBeNull(); + }); + + it('readStoredModel returns null when nothing is stored', () => { + expect(readStoredModel('anthropic')).toBeNull(); + }); + + it('lists the default first for every provider with a picker', () => { + for (const [provider, choices] of Object.entries(MODEL_CHOICES)) { + expect(choices?.[0]?.id).toBe(DEFAULT_MODELS[provider as keyof typeof DEFAULT_MODELS]); + expect(choices?.length).toBe(2); + } + expect(getModelChoices('openai')).toEqual([]); + }); +}); + +describe('DEFAULT_MODELS', () => { it('DEFAULT_MODELS map matches the per-provider constants', () => { expect(DEFAULT_MODELS.openrouter).toBe(OPENROUTER_DEFAULT_MODEL); expect(DEFAULT_MODELS.anthropic).toBe(ANTHROPIC_DEFAULT_MODEL); @@ -68,6 +133,13 @@ describe('getModelLabel — short human-friendly labels', () => { expect(getModelLabel('claude-opus-4-7')).toBe('Opus 4.7'); }); + it('normalises Claude Sonnet 5.5 and Opus 5.5 (both naming conventions)', () => { + expect(getModelLabel('anthropic/claude-sonnet-5.5')).toBe('Sonnet 5.5'); + expect(getModelLabel('claude-sonnet-5-5')).toBe('Sonnet 5.5'); + expect(getModelLabel('anthropic/claude-opus-5.5')).toBe('Opus 5.5'); + expect(getModelLabel('claude-opus-5-5')).toBe('Opus 5.5'); + }); + it('normalises GPT-4o and GPT-4o mini (mini before generic gpt-4o)', () => { expect(getModelLabel('gpt-4o-mini')).toBe('GPT-4o mini'); expect(getModelLabel('openai/gpt-4o')).toBe('GPT-4o'); @@ -92,6 +164,7 @@ describe('getModelLabel — short human-friendly labels', () => { it('normalises Gemini frontier (2.5 Flash Lite + 3.5 Flash + 2.5 Pro)', () => { expect(getModelLabel('gemini-3.6-flash')).toBe('Gemini 3.6 Flash'); + expect(getModelLabel('gemini-3.5-flash-lite')).toBe('Gemini 3.5 Flash-Lite'); expect(getModelLabel('google/gemini-3.5-flash')).toBe('Gemini 3.5 Flash'); expect(getModelLabel('google/gemini-2.5-flash-lite')).toBe('Gemini 2.5 Flash Lite'); expect(getModelLabel('google/gemini-2.5-flash')).toBe('Gemini 2.5 Flash'); diff --git a/src/test/app/AiSettings.test.tsx b/src/test/app/AiSettings.test.tsx index 6d060e33..3c4105bd 100644 --- a/src/test/app/AiSettings.test.tsx +++ b/src/test/app/AiSettings.test.tsx @@ -16,9 +16,10 @@ import { MemoryRouter } from 'react-router'; import { AiSettings } from '@/app/components/AiSettings'; import { forgetKey as kmForgetKey, + MODEL_KEY_PREFIX, saveKey as kmSaveKey, } from '@/lib/ai/keyManager'; -import { OPENROUTER_DEFAULT_MODEL } from '@/lib/ai/providers'; +import { OPENAI_DEFAULT_MODEL, OPENROUTER_DEFAULT_MODEL } from '@/lib/ai/providers'; import { CONSENT_KEY, CONSENT_TTL_MS, CONSENT_VERSION } from '@/lib/ai/useAiTutor'; const FAKE_OPENROUTER = 'sk-or-v1-FAKE_TEST_KEY_DO_NOT_USE_0123456789'; @@ -194,15 +195,24 @@ describe('AiSettings — accessibility landmarks', () => { // billed for the paid model the Drawer was actually calling. // Post-fix: both surfaces resolve the same model via `resolveModel()`. describe('AiSettings — Settings/Drawer model consistency (regression)', () => { - it('displays the env override value when set (not the hardcoded fallback)', async () => { - vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-sonnet-4-6'); + it('checks the env override when it is one of the offered models (not the hardcoded fallback)', async () => { + vi.stubEnv('VITE_AI_TUTOR_OPENROUTER_MODEL', 'anthropic/claude-opus-5.5'); try { renderSettings(); - await screen.findByText('OpenRouter'); - // The env override must be visible inside the OpenRouter row. - expect(await screen.findByText('anthropic/claude-sonnet-4-6')).toBeInTheDocument(); - // The hardcoded fallback must NOT be visible when override is set. - expect(screen.queryByText(OPENROUTER_DEFAULT_MODEL)).not.toBeInTheDocument(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec OpenRouter/ }); + expect(within(group).getByRole('radio', { name: /Claude Opus 5\.5/ })).toBeChecked(); + expect(within(group).getByRole('radio', { name: /Claude Sonnet 5\.5/ })).not.toBeChecked(); + } finally { + vi.unstubAllEnvs(); + } + }); + + it('displays the OpenAI env override as text (OpenAI has no picker)', async () => { + vi.stubEnv('VITE_AI_TUTOR_OPENAI_MODEL', 'gpt-4o'); + try { + renderSettings(); + expect(await screen.findByText('gpt-4o')).toBeInTheDocument(); + expect(screen.queryByText(OPENAI_DEFAULT_MODEL)).not.toBeInTheDocument(); } finally { vi.unstubAllEnvs(); } @@ -210,8 +220,11 @@ describe('AiSettings — Settings/Drawer model consistency (regression)', () => it('falls back to the hardcoded default when no env override is set', async () => { renderSettings(); - await screen.findByText('OpenRouter'); - expect(await screen.findByText(OPENROUTER_DEFAULT_MODEL)).toBeInTheDocument(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec OpenRouter/ }); + const sonnet = within(group).getByRole('radio', { name: /Claude Sonnet 5\.5/ }); + expect(sonnet).toBeChecked(); + expect(sonnet).toHaveAttribute('value', OPENROUTER_DEFAULT_MODEL); + expect(await screen.findByText(OPENAI_DEFAULT_MODEL)).toBeInTheDocument(); }); it('uses the "Modèle utilisé" label (transparency wording, not "défaut")', async () => { @@ -222,3 +235,62 @@ describe('AiSettings — Settings/Drawer model consistency (regression)', () => expect(screen.queryByText(/Modèle par défaut/i)).not.toBeInTheDocument(); }); }); + +describe('AiSettings — model choice', () => { + it('offers Gemini 3.5 Flash-Lite (default, cheapest) and Gemini 3.6 Flash, with a cost hint', async () => { + renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + const radios = within(group).getAllByRole('radio'); + expect(radios).toHaveLength(2); + const lite = within(group).getByRole('radio', { name: /Gemini 3\.5 Flash-Lite/ }); + expect(lite).toBeChecked(); + expect(lite).toHaveAttribute('value', 'gemini-3.5-flash-lite'); + expect(within(group).getByText(/Le moins cher/)).toBeInTheDocument(); + expect(within(group).getByRole('radio', { name: /Gemini 3\.6 Flash/ })).not.toBeChecked(); + }); + + it('stores the choice and keeps it after a new render', async () => { + const user = userEvent.setup(); + const { unmount } = renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + await user.click(within(group).getByRole('radio', { name: /Gemini 3\.6 Flash/ })); + + expect(within(group).getByRole('radio', { name: /Gemini 3\.6 Flash/ })).toBeChecked(); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'gemini')).toBe('gemini-3.6-flash'); + + unmount(); + renderSettings(); + const again = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + await waitFor(() => + expect(within(again).getByRole('radio', { name: /Gemini 3\.6 Flash/ })).toBeChecked(), + ); + }); + + it('falls back to the default when the stored value is a shut-down model', async () => { + localStorage.setItem(MODEL_KEY_PREFIX + 'gemini', 'gemini-2.0-flash'); + renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + await waitFor(() => + expect(within(group).getByRole('radio', { name: /Gemini 3\.5 Flash-Lite/ })).toBeChecked(), + ); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'gemini')).toBeNull(); + }); + + it('can be changed with the keyboard (arrow keys inside the radio group)', async () => { + const user = userEvent.setup(); + renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Anthropic/ }); + const sonnet = within(group).getByRole('radio', { name: /Claude Sonnet 5\.5/ }); + sonnet.focus(); + await user.keyboard('{ArrowDown}'); + expect(within(group).getByRole('radio', { name: /Claude Opus 5\.5/ })).toBeChecked(); + expect(localStorage.getItem(MODEL_KEY_PREFIX + 'anthropic')).toBe('claude-opus-5-5'); + }); + + it('shows no picker for OpenAI', async () => { + renderSettings(); + await screen.findByText('OpenAI'); + expect(screen.queryByRole('group', { name: /Modèle utilisé avec OpenAI/ })).not.toBeInTheDocument(); + expect(screen.getAllByRole('group', { name: /Modèle utilisé avec/ })).toHaveLength(3); + }); +}); diff --git a/src/test/authContextSignoutAiKeys.test.ts b/src/test/authContextSignoutAiKeys.test.ts index 63420b0a..a12f8a95 100644 --- a/src/test/authContextSignoutAiKeys.test.ts +++ b/src/test/authContextSignoutAiKeys.test.ts @@ -20,6 +20,7 @@ import { getKey, LS_PREFIX, MODE_KEY, + MODEL_KEY_PREFIX, PROVIDER_KEY, PROVIDERS, RATE_KEY, @@ -82,6 +83,16 @@ describe('THI-207 clearAiSessionData — 5 items + IDB preserved by default', () expect(localStorage.getItem(CONSENT_KEY)).toBeNull(); }); + it('flushes the per-provider model choice from localStorage', async () => { + for (const p of PROVIDERS) localStorage.setItem(`${MODEL_KEY_PREFIX}${p}`, `model-${p}`); + + await clearAiSessionData(); + + for (const p of PROVIDERS) { + expect(localStorage.getItem(`${MODEL_KEY_PREFIX}${p}`)).toBeNull(); + } + }); + it('flushes the rate counter and the tutor mode from sessionStorage', async () => { seedPrefs(); expect(sessionStorage.getItem(RATE_KEY)).not.toBeNull(); From b8668dfdffe4d1bb412c9a3b85acf3b5f8b2e563 Mon Sep 17 00:00:00 2001 From: thierryvm <46031203+thierryvm@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:30:29 +0100 Subject: [PATCH 3/5] fix(auth): clear AI session data on every SIGNED_OUT event A logout from another tab, or a revoked or expired session, reached the auth listener without running the client teardown, so the next learner on a shared computer inherited the previous learner's AI data (model choice included). Sourcery review on #420. --- src/app/context/AuthContext.tsx | 8 +++- src/test/authSignedOutEvent.test.tsx | 64 ++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 src/test/authSignedOutEvent.test.tsx diff --git a/src/app/context/AuthContext.tsx b/src/app/context/AuthContext.tsx index 7a59f2d3..02294a77 100644 --- a/src/app/context/AuthContext.tsx +++ b/src/app/context/AuthContext.tsx @@ -74,8 +74,14 @@ export function AuthProvider({ children }: { children: ReactNode }) { if (!cancelled) setLoading(false); }); - const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, s) => { + const { data: { subscription } } = supabase.auth.onAuthStateChange((event, s) => { setSession(s); + // A SIGNED_OUT can reach this tab without going through `signOut` + // below: logout from another tab, session revoked or expired. Run the + // same teardown so the next learner on a shared school computer does + // not inherit the previous one's AI data (plain keys, consent, model + // choice). Idempotent, so the extra run after `signOut` is harmless. + if (event === 'SIGNED_OUT') void teardownClientState(); }); unsubscribe = () => subscription.unsubscribe(); }).catch(() => { diff --git a/src/test/authSignedOutEvent.test.tsx b/src/test/authSignedOutEvent.test.tsx new file mode 100644 index 00000000..810f7b58 --- /dev/null +++ b/src/test/authSignedOutEvent.test.tsx @@ -0,0 +1,64 @@ +/** + * PR #420 (Sourcery) — a SIGNED_OUT event that does not come from this tab's + * `signOut` (logout in another tab, revoked or expired session) must run the + * same client teardown, so the next learner on a shared computer does not + * inherit the previous learner's AI data (model choice included). + */ +import { render, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { clearAi, clearRole, listeners } = vi.hoisted(() => ({ + clearAi: vi.fn(() => Promise.resolve()), + clearRole: vi.fn(), + listeners: [] as Array<(event: string, session: unknown) => void>, +})); +vi.mock('../lib/ai/keyManager', () => ({ clearAiSessionData: clearAi })); +vi.mock('../lib/hooks/useUserRole', () => ({ clearUserRoleCache: clearRole })); +vi.mock('../lib/supabase', () => ({ + supabase: { + auth: { + getSession: vi.fn(() => Promise.resolve({ data: { session: null } })), + onAuthStateChange: vi.fn((cb: (event: string, session: unknown) => void) => { + listeners.push(cb); + return { data: { subscription: { unsubscribe: vi.fn() } } }; + }), + signOut: vi.fn(() => Promise.resolve({ error: null })), + }, + }, +})); + +import { AuthProvider } from '../app/context/AuthContext'; + +beforeEach(() => { + clearAi.mockClear(); + clearRole.mockClear(); + listeners.length = 0; +}); + +async function mountAndGetListener() { + render( + + + , + ); + await waitFor(() => expect(listeners).toHaveLength(1)); + return listeners[0]; +} + +describe('AuthContext — SIGNED_OUT from the auth listener', () => { + it('runs the client teardown (AI data + role cache)', async () => { + const listener = await mountAndGetListener(); + listener('SIGNED_OUT', null); + await waitFor(() => expect(clearAi).toHaveBeenCalledOnce()); + expect(clearRole).toHaveBeenCalledOnce(); + }); + + it('leaves the AI data alone on other events', async () => { + const listener = await mountAndGetListener(); + listener('TOKEN_REFRESHED', { user: { id: 'u1' } }); + listener('SIGNED_IN', { user: { id: 'u1' } }); + await Promise.resolve(); + expect(clearAi).not.toHaveBeenCalled(); + expect(clearRole).not.toHaveBeenCalled(); + }); +}); From 5561f362f1dc1b926aad4b8c1bbd763cfe82d1bc Mon Sep 17 00:00:00 2001 From: thierryvm <46031203+thierryvm@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:30:33 +0100 Subject: [PATCH 4/5] fix(ai-tutor): keep the model choice in sync and explain failed saves - Tutor panel and Settings follow a choice made in another tab (storage event). - Settings resolves the model after the IndexedDB awaits, so a refresh no longer restores an older choice. - Settings shows a French alert when the browser refuses to store the choice. - OpenRouter: 4096-token output ceiling for Opus 5.5, as on the Anthropic route. - Opus cost hint no longer understates the cost (thinking is billed too). - Tests neutralise VITE_AI_TUTOR_*_MODEL before checking code defaults. Sourcery review on #420. --- src/app/components/AiSettings.tsx | 28 ++++++++++-- src/app/components/ai/AiTutorPanel.tsx | 9 ++-- src/lib/ai/providers/modelChoices.ts | 4 +- src/lib/ai/providers/openrouter.ts | 17 ++++++++ src/lib/hooks/useResolvedModel.ts | 33 ++++++++++++++ src/test/ai/AiTutorPanel.test.tsx | 23 ++++++++++ src/test/ai/providers/openrouter.test.ts | 13 ++++++ src/test/ai/providers/resolveModel.test.ts | 18 +++++++- src/test/app/AiSettings.test.tsx | 50 +++++++++++++++++++++- 9 files changed, 183 insertions(+), 12 deletions(-) create mode 100644 src/lib/hooks/useResolvedModel.ts diff --git a/src/app/components/AiSettings.tsx b/src/app/components/AiSettings.tsx index a451e013..aea878d5 100644 --- a/src/app/components/AiSettings.tsx +++ b/src/app/components/AiSettings.tsx @@ -38,6 +38,7 @@ import { } from '@/lib/ai/keyManager'; import { getModelChoices, resolveModel, saveModelChoice } from '@/lib/ai/providers'; import { PROVIDER_LABELS } from '@/lib/ai/providers/meta'; +import { subscribeToModelChoice } from '@/lib/hooks/useResolvedModel'; import { CONSENT_KEY, readConsentRecord, @@ -104,6 +105,8 @@ export function AiSettings() { const [statuses, setStatuses] = useState([]); const [consent, setConsent] = useState(null); const [editingProvider, setEditingProvider] = useState(null); + /** Provider whose last model choice could not be stored (storage blocked). */ + const [modelSaveError, setModelSaveError] = useState(null); // Refresh local-storage / IndexedDB-backed state. Called on mount and // whenever a save / forget / revoke action mutates that state so the UI @@ -114,10 +117,12 @@ export function AiSettings() { provider: p, configured: await kmHasKey(p), encrypted: await kmIsEncrypted(p), - model: resolveModel(p), })), ); - setStatuses(next); + // Resolve the model only after the IndexedDB awaits: a choice made while + // they were pending is already in localStorage and must not be replaced + // by an older snapshot. + setStatuses(next.map((s) => ({ ...s, model: resolveModel(s.provider) }))); setConsent(readConsentRecord()); }, []); @@ -160,11 +165,21 @@ export function AiSettings() { // right away, from what `resolveModel` now returns, so the UI only shows a // choice that was actually stored. const onModelChange = useCallback((p: Provider, model: string) => { - saveModelChoice(p, model); + const saved = saveModelChoice(p, model); + setModelSaveError(saved ? null : p); const effective = resolveModel(p); setStatuses((cur) => cur.map((s) => (s.provider === p ? { ...s, model: effective } : s))); }, []); + // A choice changed in another tab: show what the tutor now uses. + useEffect( + () => + subscribeToModelChoice(() => { + setStatuses((cur) => cur.map((s) => ({ ...s, model: resolveModel(s.provider) }))); + }), + [], + ); + return (
+ {modelSaveError === s.provider && ( +

+ Ton choix n’a pas pu être enregistré : ce navigateur + bloque le stockage local. Le modèle coché reste celui + qui est utilisé. +

+ )}

Tu paies les questions avec ta propre clé, au tarif du fournisseur. diff --git a/src/app/components/ai/AiTutorPanel.tsx b/src/app/components/ai/AiTutorPanel.tsx index 9390d37c..7b71e8f2 100644 --- a/src/app/components/ai/AiTutorPanel.tsx +++ b/src/app/components/ai/AiTutorPanel.tsx @@ -27,10 +27,11 @@ import { PROVIDER_KEY, type Provider, } from '@/lib/ai/keyManager'; -import { getModelLabel, resolveModel } from '@/lib/ai/providers'; +import { getModelLabel } from '@/lib/ai/providers'; import { PROVIDER_LABELS } from '@/lib/ai/providers/meta'; import type { TutorLang } from '@/lib/ai/systemPrompt'; import { useAiTutor } from '@/lib/ai/useAiTutor'; +import { useResolvedModel } from '@/lib/hooks/useResolvedModel'; import type { UserRole } from '@/app/types/database'; import { AiConsentModal } from './AiConsentModal'; @@ -107,9 +108,9 @@ export function AiTutorPanel({ lang = 'fr', lessonContext, role, liftAboveMobile // `VITE_AI_TUTOR__MODEL`, then `DEFAULT_MODELS`. Same helper as // `AiSettings`, so the two surfaces never disagree. Not memoised on purpose: // the choice can change on the Settings page while this panel stays - // mounted, and opening the panel re-renders it, which re-reads the choice - // (one localStorage read). - const model = resolveModel(provider); + // mounted: `useResolvedModel` re-reads it on every render and listens to + // the `storage` event, so a change made in another tab applies at once. + const model = useResolvedModel(provider); // THI-148 V1.0.1 — static, public-only platform overview injected as // . Same trust class as lessonContext (curriculum data, diff --git a/src/lib/ai/providers/modelChoices.ts b/src/lib/ai/providers/modelChoices.ts index f46634c3..758a6509 100644 --- a/src/lib/ai/providers/modelChoices.ts +++ b/src/lib/ai/providers/modelChoices.ts @@ -48,7 +48,7 @@ export const MODEL_CHOICES: Readonly = new Set(['anthropic/claude-opus-5.5']); + +export function openRouterOutputOptions(model: string): { max_tokens?: number } { + return ALWAYS_THINKING_MODELS.has(model) ? { max_tokens: ANTHROPIC_THINKING_MAX_TOKENS } : {}; +} + const APP_TITLE = 'Terminal Learning Tutor'; const APP_REFERER = 'https://terminallearning.dev'; @@ -83,6 +99,7 @@ export async function chat(params: ChatParams): Promise { const body = JSON.stringify({ model: params.model, stream: true, + ...openRouterOutputOptions(params.model), messages: [ { role: 'system', content: params.systemPrompt }, ...params.messages, diff --git a/src/lib/hooks/useResolvedModel.ts b/src/lib/hooks/useResolvedModel.ts new file mode 100644 index 00000000..1968f9e5 --- /dev/null +++ b/src/lib/hooks/useResolvedModel.ts @@ -0,0 +1,33 @@ +/** + * Model actually used for a provider (`resolveModel`), kept in sync with the + * learner's stored choice. + * + * `resolveModel` is re-read on every render (one localStorage read), and the + * `storage` event re-renders the component when the choice changes in + * another tab (the event never fires in the tab that wrote the value; that + * tab re-renders on its own). + */ +import { useCallback, useSyncExternalStore } from 'react'; +import { MODEL_KEY_PREFIX, type Provider } from '@/lib/ai/keyManager'; +import { resolveModel } from '@/lib/ai/providers'; + +/** True for a `storage` event that can change a stored model choice. */ +export function isModelChoiceStorageEvent(e: StorageEvent): boolean { + // `key === null` means `localStorage.clear()` in another tab. + return e.key === null || e.key.startsWith(MODEL_KEY_PREFIX); +} + +/** Calls `onChange` when another tab changes a stored model choice. */ +export function subscribeToModelChoice(onChange: () => void): () => void { + if (typeof window === 'undefined') return () => {}; + const handler = (e: StorageEvent) => { + if (isModelChoiceStorageEvent(e)) onChange(); + }; + window.addEventListener('storage', handler); + return () => window.removeEventListener('storage', handler); +} + +export function useResolvedModel(provider: Provider): string { + const getSnapshot = useCallback(() => resolveModel(provider), [provider]); + return useSyncExternalStore(subscribeToModelChoice, getSnapshot, getSnapshot); +} diff --git a/src/test/ai/AiTutorPanel.test.tsx b/src/test/ai/AiTutorPanel.test.tsx index 3b666725..b661c441 100644 --- a/src/test/ai/AiTutorPanel.test.tsx +++ b/src/test/ai/AiTutorPanel.test.tsx @@ -10,6 +10,7 @@ import 'fake-indexeddb/auto'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { + act, render as rtlRender, screen, waitFor, @@ -56,6 +57,10 @@ let fetchSpy: ReturnType; beforeEach(() => { localStorage.clear(); sessionStorage.clear(); + // Default-model checks must not depend on the runner's env (Sourcery #420). + for (const p of ['OPENROUTER', 'ANTHROPIC', 'OPENAI', 'GEMINI']) { + vi.stubEnv(`VITE_AI_TUTOR_${p}_MODEL`, ''); + } fetchSpy = vi.spyOn(globalThis, 'fetch') as ReturnType; }); @@ -292,6 +297,24 @@ describe('AiTutorPanel — header displays the active model (transparency)', () const heading = await screen.findByRole('heading', { level: 2 }); expect(heading.textContent).toContain('Opus 5.5'); }); + + it('header follows a model picked in another tab while the panel stays open', async () => { + vi.stubEnv('VITE_AI_TUTOR_ENABLED', 'true'); + + const user = userEvent.setup(); + render(); + await user.click(screen.getByLabelText(/Ouvrir le tuteur IA/)); + const heading = await screen.findByRole('heading', { level: 2 }); + expect(heading.textContent).toContain('Sonnet 5.5'); + + // Another tab writes the choice; this tab only receives a `storage` event. + localStorage.setItem('ai_tutor_model_openrouter', 'anthropic/claude-opus-5.5'); + act(() => { + window.dispatchEvent(new StorageEvent('storage', { key: 'ai_tutor_model_openrouter' })); + }); + + await waitFor(() => expect(heading.textContent).toContain('Opus 5.5')); + }); }); // THI-263 fix (A1 from llm-security-auditor 23/05/2026 audit) — encrypted diff --git a/src/test/ai/providers/openrouter.test.ts b/src/test/ai/providers/openrouter.test.ts index e92800a7..a28c4dfa 100644 --- a/src/test/ai/providers/openrouter.test.ts +++ b/src/test/ai/providers/openrouter.test.ts @@ -129,6 +129,19 @@ describe('chat — request shape', () => { ]); }); + it('caps the output of Opus 5.5 (thinking always on) and leaves other models unchanged', async () => { + const send = async (model: string) => { + fetchSpy.mockResolvedValue(makeStreamResponse(['data: [DONE]\n\n'])); + await collect(await chat({ apiKey: FAKE_KEY, model, systemPrompt: 'S', messages: [] })); + const init = fetchSpy.mock.calls.at(-1)![1] as RequestInit; + return JSON.parse(init.body as string) as { max_tokens?: number }; + }; + + expect((await send('anthropic/claude-opus-5.5')).max_tokens).toBe(4096); + expect(await send(OPENROUTER_DEFAULT_MODEL)).not.toHaveProperty('max_tokens'); + expect(await send('some/other-model')).not.toHaveProperty('max_tokens'); + }); + it('never leaks the API key into the request URL or body', async () => { fetchSpy.mockResolvedValue(makeStreamResponse(['data: [DONE]\n\n'])); diff --git a/src/test/ai/providers/resolveModel.test.ts b/src/test/ai/providers/resolveModel.test.ts index e26d71fb..78f426e8 100644 --- a/src/test/ai/providers/resolveModel.test.ts +++ b/src/test/ai/providers/resolveModel.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { MODEL_KEY_PREFIX } from '@/lib/ai/keyManager'; import { @@ -15,6 +15,20 @@ import { saveModelChoice, } from '@/lib/ai/providers'; +// Neutralise the deploy-time overrides so the default checks below test the +// code, whatever the runner's environment holds (Sourcery on #420). An empty +// value counts as unset; tests that need an override stub it again. +beforeEach(() => { + for (const name of [ + 'VITE_AI_TUTOR_OPENROUTER_MODEL', + 'VITE_AI_TUTOR_ANTHROPIC_MODEL', + 'VITE_AI_TUTOR_OPENAI_MODEL', + 'VITE_AI_TUTOR_GEMINI_MODEL', + ]) { + vi.stubEnv(name, ''); + } +}); + afterEach(() => { vi.unstubAllEnvs(); localStorage.clear(); @@ -32,7 +46,7 @@ describe('resolveModel — providers without a picker (OpenAI): env override > f }); it('falls back to DEFAULT_MODELS when env override is unset', () => { - // No stubEnv call — the var is undefined in the test environment. + // Reset to unset in `beforeEach` (empty string, same as unset). expect(resolveModel('openai')).toBe(OPENAI_DEFAULT_MODEL); }); }); diff --git a/src/test/app/AiSettings.test.tsx b/src/test/app/AiSettings.test.tsx index 3c4105bd..59ef7c60 100644 --- a/src/test/app/AiSettings.test.tsx +++ b/src/test/app/AiSettings.test.tsx @@ -9,7 +9,7 @@ */ import 'fake-indexeddb/auto'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { render, screen, waitFor, within } from '@testing-library/react'; +import { act, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter } from 'react-router'; @@ -33,11 +33,25 @@ function renderSettings() { ); } +// The deploy-time overrides would change which model is "the default": +// neutralise them so these tests check the code's defaults whatever the +// runner's environment says (Sourcery on #420). Empty = unset for +// `resolveModel`. +const MODEL_ENV_VARS = [ + 'VITE_AI_TUTOR_OPENROUTER_MODEL', + 'VITE_AI_TUTOR_ANTHROPIC_MODEL', + 'VITE_AI_TUTOR_OPENAI_MODEL', + 'VITE_AI_TUTOR_GEMINI_MODEL', +] as const; + beforeEach(() => { localStorage.clear(); + for (const name of MODEL_ENV_VARS) vi.stubEnv(name, ''); }); afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); await Promise.all([ kmForgetKey('openrouter'), kmForgetKey('anthropic'), @@ -293,4 +307,38 @@ describe('AiSettings — model choice', () => { expect(screen.queryByRole('group', { name: /Modèle utilisé avec OpenAI/ })).not.toBeInTheDocument(); expect(screen.getAllByRole('group', { name: /Modèle utilisé avec/ })).toHaveLength(3); }); + + it('explains in French when the browser refuses to store the choice', async () => { + const user = userEvent.setup(); + renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + const realSetItem = localStorage.setItem.bind(localStorage); + vi.spyOn(localStorage, 'setItem').mockImplementation((k: string, v: string) => { + if (k.startsWith(MODEL_KEY_PREFIX)) throw new DOMException('blocked', 'SecurityError'); + realSetItem(k, v); + }); + + await user.click(within(group).getByRole('radio', { name: /Gemini 3\.6 Flash/ })); + + expect(within(group).getByRole('alert')).toHaveTextContent(/n’a pas pu être enregistré/); + expect(within(group).getByRole('radio', { name: /Gemini 3\.5 Flash-Lite/ })).toBeChecked(); + expect(screen.getAllByRole('alert')).toHaveLength(1); + }); + + it('follows a choice made in another tab', async () => { + renderSettings(); + const group = await screen.findByRole('group', { name: /Modèle utilisé avec Gemini/ }); + await waitFor(() => + expect(within(group).getByRole('radio', { name: /Gemini 3\.5 Flash-Lite/ })).toBeChecked(), + ); + + localStorage.setItem(MODEL_KEY_PREFIX + 'gemini', 'gemini-3.6-flash'); + act(() => { + window.dispatchEvent(new StorageEvent('storage', { key: MODEL_KEY_PREFIX + 'gemini' })); + }); + + await waitFor(() => + expect(within(group).getByRole('radio', { name: /Gemini 3\.6 Flash/ })).toBeChecked(), + ); + }); }); From d4752b7dd0f811207f1220a9abf02532081efe0c Mon Sep 17 00:00:00 2001 From: thierryvm <46031203+thierryvm@users.noreply.github.com> Date: Mon, 9 Nov 2026 21:30:36 +0100 Subject: [PATCH 5/5] docs(ai-tutor): story chapter, banners and ADR-009 amendment for the model picker ADR-009 amendment: one model list per provider for every role; isolation comes from the per-role prompt, not the model. Sourcery review on #420. --- CHANGELOG.md | 4 ++-- STORY.md | 10 +++++++++- docs/ROADMAP.md | 2 +- .../ADR-009-ai-tutor-cross-role-prompt-isolation.md | 11 +++++++++++ docs/plan.md | 2 +- 5 files changed, 24 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed141cf0..fd519d2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,9 +10,9 @@ *Tuteur IA (clé personnelle) · identifiants et tarifs vérifiés le 9 novembre 2026 sur les pages officielles de Google, d'Anthropic et l'API d'OpenRouter* - **Gemini fonctionne de nouveau.** Google a arrêté `gemini-2.0-flash` le 1er juin 2026 : chaque question renvoyait une erreur. Le tuteur utilise maintenant **Gemini 3.5 Flash-Lite**, le modèle le moins cher (0,30 $ / 2,50 $ par million de jetons), puisque c'est l'élève qui paie avec sa propre clé. -- **Choisir son modèle dans Paramètres IA.** Pour Gemini : 3.5 Flash-Lite (par défaut) ou 3.6 Flash (meilleures réponses, plus cher). Pour OpenRouter et Anthropic : **Claude Sonnet 5.5** (par défaut, 2 $ / 10 $) ou **Claude Opus 5.5** (environ deux fois plus cher). Le choix reste enregistré dans le navigateur et s'efface à la déconnexion, comme le fournisseur choisi. +- **Choisir son modèle dans Paramètres IA.** Pour Gemini : 3.5 Flash-Lite (par défaut) ou 3.6 Flash (meilleures réponses, plus cher). Pour OpenRouter et Anthropic : **Claude Sonnet 5.5** (par défaut, 2 $ / 10 $) ou **Claude Opus 5.5** (nettement plus cher : tarif doublé, et sa réflexion avant chaque réponse est facturée aussi). Le choix reste enregistré dans le navigateur et s'efface à chaque fin de session (déconnexion, session fermée dans un autre onglet ou expirée), comme le fournisseur choisi. Un choix fait dans un autre onglet s'applique tout de suite au tuteur ouvert ; si le navigateur refuse d'enregistrer le choix, un message l'explique. - Un ancien choix qui pointe vers un modèle arrêté est ignoré : le tuteur reprend le modèle par défaut. -- Les modèles récents réfléchissent avant de répondre, et cette réflexion compte dans la limite de longueur de la réponse. Le tuteur règle donc la réflexion au minimum là où le fournisseur le permet (Gemini 3.5 Flash-Lite et 3.6 Flash, Claude Sonnet 5.5), et laisse plus de place à Claude Opus 5.5, dont la réflexion ne se coupe pas, pour éviter des réponses coupées. +- Les modèles récents réfléchissent avant de répondre, et cette réflexion compte dans la limite de longueur de la réponse. Le tuteur règle donc la réflexion au minimum là où le fournisseur le permet (Gemini 3.5 Flash-Lite et 3.6 Flash, Claude Sonnet 5.5), et laisse plus de place à Claude Opus 5.5, dont la réflexion ne se coupe pas, pour éviter des réponses coupées (4 096 jetons au plus, par Anthropic comme par OpenRouter). - OpenAI ne change pas : son modèle reste fixé par le déploiement. --- diff --git a/STORY.md b/STORY.md index e4c9405b..d5cb0f10 100644 --- a/STORY.md +++ b/STORY.md @@ -1305,6 +1305,14 @@ Les quarante captures faites sur le vrai bash ont fixé le reste : l'ordre des r L'auditeur de fidélité a ensuite rejoué 573 commandes contre le vrai bash. Le cœur des jokers tenait bon, mais l'étoile a révélé une famille entière de défauts cachés : `chmod`, `rm`, `mkdir`, `head` et `tail` ne traitaient que leur premier fichier. Personne ne l'avait vu, parce qu'avant les jokers, presque personne ne leur en donnait plusieurs. Une seule nouveauté a suffi à rendre visibles des écarts anciens : c'est pour cela que chaque PR repasse devant un vrai shell. +### Le modèle qu'on ne pouvait plus appeler (9 novembre 2026) + +Un jour, l'option Gemini du tuteur IA a cessé de répondre : chaque question renvoyait une erreur. Aucune ligne de notre code n'avait changé. Google avait simplement arrêté `gemini-2.0-flash` le 1er juin 2026, et c'était le modèle inscrit en dur dans l'application. + +La réparation tenait en une ligne. La leçon, non : un modèle d'IA a une date de fin, comme une version de logiciel. Le tuteur propose donc maintenant une courte liste de modèles vérifiés, et un ancien choix qui pointe vers un modèle arrêté est ignoré au lieu de casser le tuteur. Comme c'est l'élève qui paie avec sa propre clé, le modèle par défaut est le moins cher qui répond bien, et le plus puissant affiche clairement son coût : Claude Opus coûte le double par mot, et sa réflexion avant chaque réponse est facturée aussi. + +La revue automatique a ensuite posé une question à laquelle on n'avait pas pensé : que se passe-t-il sur un ordinateur d'école partagé ? La déconnexion effaçait bien les données du tuteur, mais seulement quand l'élève cliquait sur « Se déconnecter » dans cet onglet. Une session fermée dans un autre onglet ou expirée laissait le choix de l'élève précédent au suivant. Le nettoyage se fait maintenant à chaque fin de session, d'où qu'elle vienne. + --- ## Épilogue ouvert @@ -1320,4 +1328,4 @@ Ce journal continuera d'être écrit tant que le projet continue d'être constru --- *Terminal Learning est un projet open source, construit bénévolement en Belgique.* -*Dernière mise à jour : 2 octobre 2026.* +*Dernière mise à jour : 9 novembre 2026.* diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 6a84da5b..b89472a4 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2,7 +2,7 @@ > **Decision (1 October 2026, @thierry):** Terminal Learning becomes **the reference for learning the terminal from scratch up to an intermediate level**, within what a faithful simulation can do. Job-specific tools (offensive security, network analysis, OSINT) are not simulated; the site points to the free platforms that already teach them. Ordered plan: [Phase 5d](#phase-5d--from-the-basics-to-an-intermediate-level--planned-1-october-2026). Delivery checklist: [`docs/processes/curriculum-delivery-checklist.md`](processes/curriculum-delivery-checklist.md). > -> **Last update:** 2 October 2026 — **Phase 5d, Lot 1, PR 2b** (#419): wildcards `*`, `?`, `[...]` expand as in bash; `ls` with several operands. Before: **PR 2** (#418): `find`, `xargs`, `rmdir`, GNU `wc` widths, `grep -l`; reference now 81 commands. Next: globbing (`ls *.txt`). Before: **PR 1** (#417): `sort`, `uniq`, `cut` faithful to GNU coreutils 9.4 (captured on WSL's Ubuntu), `Sort-Object`, `Get-Unique`, `Group-Object`; reference now 79 commands. Before: **Lot 0b** (#416): `llms.txt`, `llms-full.txt` and the `index.html` metadata are checked against the curriculum by a test; 10 stale lesson titles fixed. Next: Lot 1 (`sort`, `uniq`, `cut`). +> **Last update:** 9 November 2026 — **AI tutor** (#420): Gemini answers again (`gemini-2.0-flash`, shut down by Google, replaced by Gemini 3.5 Flash-Lite); learners pick their model in AI Settings (Claude Sonnet 5.5 by default or Opus 5.5, Gemini 3.5 Flash-Lite or 3.6 Flash); tutor data is cleared at every session end. Phase 5d next step unchanged: the rest of Lot 1. Before: 2 October 2026 — **Phase 5d, Lot 1, PR 2b** (#419): wildcards `*`, `?`, `[...]` expand as in bash; `ls` with several operands. Before: **PR 2** (#418): `find`, `xargs`, `rmdir`, GNU `wc` widths, `grep -l`; reference now 81 commands. Next: globbing (`ls *.txt`). Before: **PR 1** (#417): `sort`, `uniq`, `cut` faithful to GNU coreutils 9.4 (captured on WSL's Ubuntu), `Sort-Object`, `Get-Unique`, `Group-Object`; reference now 79 commands. Before: **Lot 0b** (#416): `llms.txt`, `llms-full.txt` and the `index.html` metadata are checked against the curriculum by a test; 10 stale lesson titles fixed. Next: Lot 1 (`sort`, `uniq`, `cut`). > > **Previous update:** 1 October 2026 CEST — 🩺 **Full check-up (P1 terminal fidelity, THI-353), continued**: #396 every reference example runs · #397 tables, blank lines and mobile keys · #398 the installed app clears iOS 26's edge blur · #399 git reads real files, outputs match Git 2.56 · **#400 real git branches** (commit graph, ids identical to real git, merges and real conflicts; two fidelity audits, two code reviews) · #401 the landing page only lists commands the terminal runs and the lessons teach, and its terminal preview prints what real shells print. Planned: a **customising the terminal** module (idea from @thierry, #402). **Multi-step exercises checked on the terminal state** (the conflict lesson now resolves a real conflict end to end; no more auto-advance, a « Suivant » button instead). **Git module as steps** (init, first commit, diff, branch, merge). **Remote repositories as in real git** (`push`, `pull`, `fetch`, `clone`, `remote`, branch tracking in `status` and `branch -vv`, #406). **A remote where a colleague pushes** (`fetch`/`pull` bring real commits, a push is rejected with "fetch first", `gh` says it is not simulated; theory gaps 146 → 120). **GitHub module as steps** (remote, push & pull, fetch, pull request, merge strategies, GitHub Actions; #410, theory gaps 120 → 90). **The top of the installed iPhone app is clear at last** (#411, confirmed on @thierry's iPhone). **#413 Windows fidelity** (`ls`/`Get-ChildItem` print PowerShell 7.6's real table, `rm`/`cp`/`mv` are the cmdlets with their parameters — `rm -rf` is refused —, PowerShell's error messages, reference page updated; bash shown on Windows 34 → 32). Next: the ~20 commands taught but not simulated yet (`find`, `sort`, `diff`, `tar`, `Where-Object`…) and the remaining Windows debt (`New-Item`'s table, case-insensitive paths). > diff --git a/docs/adr/ADR-009-ai-tutor-cross-role-prompt-isolation.md b/docs/adr/ADR-009-ai-tutor-cross-role-prompt-isolation.md index f851167d..60ff1431 100644 --- a/docs/adr/ADR-009-ai-tutor-cross-role-prompt-isolation.md +++ b/docs/adr/ADR-009-ai-tutor-cross-role-prompt-isolation.md @@ -153,6 +153,17 @@ Stage B3 peut maintenant livrer un dropdown picker filtré par rôle : Sans ADR-009, ce filtrage UI aurait été cosmétique (le prompt élève ne changeait pas selon le modèle choisi). Avec ADR-009, le filtrage UI **encadre** un cloisonnement déjà réel au niveau system prompt. +### Amendement du 9 novembre 2026 — picker identique pour tous les rôles (PR #420) + +Le picker livré par la PR #420 (`src/lib/ai/providers/modelChoices.ts`) **remplace** les listes par rôle ci-dessus, qui ne sont plus appliquées : + +- **Une seule liste courte par fournisseur, la même pour tous les rôles** : Claude Sonnet 5.5 (défaut) ou Claude Opus 5.5 sur OpenRouter et Anthropic ; Gemini 3.5 Flash-Lite (défaut) ou Gemini 3.6 Flash sur Gemini. OpenAI garde son modèle unique. +- **Pourquoi pas de liste par rôle** : la sécurité ne dépend pas du modèle. Cette ADR l'établit elle-même (Option C rejetée : « le cloisonnement vient du prompt, pas du modèle »). Le prompt de chaque rôle reste appliqué quel que soit le modèle choisi. Le choix ne touche que la qualité et le coût, et c'est l'utilisateur qui paie avec sa propre clé (BYOK). +- **Modèles des listes d'origine** : ils appartiennent à des générations remplacées depuis (5.5 chez Anthropic, 3.5 et 3.6 chez Gemini). Un modèle hors liste stocké en local est effacé et le défaut s'applique. +- **Coût affiché** : le choix d'Opus indique à l'élève qu'il coûte nettement plus (tarif doublé, réflexion facturée). + +Une liste par rôle reste possible plus tard, si un besoin réel apparaît (budget d'école, par exemple). Elle demandera un nouvel amendement. + ## Refs - **PR** : [#291](https://github.com/thierryvm/TerminalLearning/pull/291) — `feat(ai-tutor): THI-275 Stage B2 — system prompts par rôle (teacher/admin/superadmin)` diff --git a/docs/plan.md b/docs/plan.md index 45c68896..fa355be9 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -2,7 +2,7 @@ > **Décision du 1er octobre 2026 (@thierry)** : Terminal Learning devient **la référence pour apprendre le terminal de zéro jusqu'au niveau intermédiaire**, dans les limites d'une simulation fidèle. Les outils de métier (sécurité offensive, analyse réseau, OSINT) ne sont pas simulés : le site oriente vers les plateformes gratuites qui les enseignent. Plan ordonné : [`docs/strategy/2026-10-01-bases-vers-intermediaire.md`](strategy/2026-10-01-bases-vers-intermediaire.md) · procédure de livraison : [`docs/processes/curriculum-delivery-checklist.md`](processes/curriculum-delivery-checklist.md). > -> Dernière mise à jour : **2 octobre 2026** — **Phase 5d, lot 1, PR 2b** (#419) : les jokers `*`, `?`, `[...]` sont développés comme dans bash ; `ls` avec plusieurs fichiers. Avant : **PR 2** (#418) : `find`, `xargs`, `rmdir`, `wc` aux largeurs GNU, `grep -l` ; Référence 81 commandes. Suite : les jokers (`ls *.txt`). Avant : **PR 1** (#417) : `sort`, `uniq`, `cut` fidèles à GNU coreutils 9.4 (capturés sur l'Ubuntu de WSL), `Sort-Object`, `Get-Unique`, `Group-Object` ; Référence 79 commandes. Avant : **lot 0b** (#416) : `llms.txt`, `llms-full.txt` et les métadonnées d'`index.html` sont comparés au curriculum par un test ; 10 titres de leçon périmés corrigés. Suite : lot 1 (`sort`, `uniq`, `cut`). +> Dernière mise à jour : **9 novembre 2026** — **Tuteur IA** (#420) : Gemini répond de nouveau (`gemini-2.0-flash`, arrêté par Google, remplacé par Gemini 3.5 Flash-Lite) ; l'élève choisit son modèle dans Paramètres IA (Claude Sonnet 5.5 par défaut ou Opus 5.5, Gemini 3.5 Flash-Lite ou 3.6 Flash) ; les données du tuteur s'effacent à chaque fin de session. Suite Phase 5d inchangée : le reste du lot 1. Avant : **2 octobre 2026** — **Phase 5d, lot 1, PR 2b** (#419) : les jokers `*`, `?`, `[...]` sont développés comme dans bash ; `ls` avec plusieurs fichiers. Avant : **PR 2** (#418) : `find`, `xargs`, `rmdir`, `wc` aux largeurs GNU, `grep -l` ; Référence 81 commandes. Suite : les jokers (`ls *.txt`). Avant : **PR 1** (#417) : `sort`, `uniq`, `cut` fidèles à GNU coreutils 9.4 (capturés sur l'Ubuntu de WSL), `Sort-Object`, `Get-Unique`, `Group-Object` ; Référence 79 commandes. Avant : **lot 0b** (#416) : `llms.txt`, `llms-full.txt` et les métadonnées d'`index.html` sont comparés au curriculum par un test ; 10 titres de leçon périmés corrigés. Suite : lot 1 (`sort`, `uniq`, `cut`). > > Précédente mise à jour : **1er octobre 2026 CEST** — **🩺 Grand Check-up, P1 « fidélité du terminal » (THI-353), suite** : #396 exemples de la Référence tous exécutables · #397 tableaux, lignes vides et touches du clavier mobile · #398 haut de l'app installée dégagé du flou d'iOS 26 · #399 git lit les vrais fichiers, sorties identiques à Git 2.56 · **#400 vraies branches Git** (graphe de commits, identifiants identiques au vrai Git, fusions et vrais conflits ; deux audits de fidélité et deux revues de code) · #401 page d'accueil : ne promet plus que des commandes simulées · #402 module « Personnaliser son terminal » annoncé · **exercices en plusieurs étapes vérifiés sur l'état du terminal** (le conflit Git se résout de A à Z, plus de saut automatique : bouton « Suivant »). · **module Git en étapes** (init, premier commit, diff, branche, fusion) · **dépôts distants identiques au vrai Git** (`push`, `pull`, `fetch`, `clone`, `remote`, suivi de branche dans `status` et `branch -vv`, #406) · **dépôt distant où un collègue pousse** (`fetch`/`pull` ramènent de vrais commits, push refusé « fetch first », `gh` dit qu'il n'est pas simulé ; écarts théorie 146 → 120) · **module GitHub en étapes** (remote, push & pull, fetch, Pull Request, stratégies de merge, GitHub Actions ; #410, écarts théorie 120 → 90) · **haut de l'app installée sur iPhone enfin net** (#411, confirmé sur l'iPhone de @thierry). **#413 fidélité Windows** (`ls`/`Get-ChildItem` affichent le vrai tableau de PowerShell 7.6, `rm`/`cp`/`mv` sont les cmdlets avec leurs paramètres — `rm -rf` refusé —, erreurs de PowerShell, page Référence à jour ; bash montré sous Windows 34 → 32). Suite : les ~20 commandes enseignées mais pas encore simulées (`find`, `sort`, `diff`, `tar`, `Where-Object`…) et la dette Windows restante (tableau de `New-Item`, chemins insensibles à la casse). > Précédent : **26 septembre 2026 CEST** — **🩺 Grand Check-up, P1 « fidélité du terminal » (THI-353)** : #389 vraie couche shell (**198/198 exercices sans ligne rouge**) · #390 sorties d'un vrai shell · #391 rejeu permanent de la théorie · #392 `cp`/`mv` vers un dossier + chemins Windows natifs (écarts théorie **174 → 162**) · #393 agents d'audit remis à jour + `terminal-fidelity-auditor` · roadmap publique corrigée. Suite : messages d'erreur PowerShell, page Référence, écarts restants.