Compare commits

...
5 Commits
Author SHA1 Message Date
Gitea Actions 9a8eb9ae85 Release 0.1.68 [auto-version-bump] 2026-10-19 13:10:07 +02:00
Ein Anderssono b0832f122d Update frontend checks for local AI feature flag
Build and publish frontend / publish (push) Successful in 50s
2026-10-19 13:09:37 +02:00
Ein Anderssono 3a9d02bc64 Pause browser local AI behind disabled feature flag
Build and publish frontend / publish (push) Failing after 2s
2026-10-19 13:08:45 +02:00
Gitea Actions 1444f202c6 Release 0.1.67 [auto-version-bump] 2026-10-19 12:45:06 +02:00
Ein Anderssono f464bd5490 Show player-facing processing feedback
Build and publish frontend / publish (push) Successful in 47s
2026-10-19 12:37:04 +02:00
9 changed files with 138 additions and 24 deletions
+1 -1
View File
@@ -10,5 +10,5 @@
- Helm charts are published to `harbor.k3s.k0.nu/ai-spel`; Argo CD uses the existing `ai-spel` project and namespace.
- Player-facing speech uses the local Piper WebAssembly adapter when the player has activated audio. The separate `ai-spel-static` Nginx service serves pinned Swedish Piper models and ONNX/Piper runtime files from same-origin `/static/piper-wasm-v1/` URLs with immutable caching. Game text is synthesized on-device and must never be sent to a TTS provider.
- This pipeline bundles only the Piper worker/client glue. Model/runtime downloads, image builds, and deployment belong to `ai-spel/ai-spel-static` and the existing `large` runner. Never build or run these assets locally.
- Browser local AI loads its client adapter, Wllama runtime, WebAssembly, Gemma model, manifest, YAML prompt, and license resources only from the same-origin `/static/wllama-gemma3-v1/` path owned by `ai-spel/ai-spel-static`. Do not add browser CDN, npm, or model-hub fallbacks. The player must be shown and accept applicable model terms before the model downloads or runs. Acceptance, model failure, or local-AI opt-out must never block play. Incompatible asset changes require a new immutable static path and a coordinated frontend release.
- Browser local AI is paused by default behind `FEATURE_FLAGS.localAI` in `index.html`. When disabled, do not load its adapter or any Wllama/WebAssembly/Gemma assets. If it is deliberately enabled in a later change, it must load the adapter, runtime, model, manifest, YAML prompt, and license resources only from the same-origin `/static/wllama-gemma3-v2/` path owned by `ai-spel/ai-spel-static`. Do not add browser CDN, npm, or model-hub fallbacks. The player must be shown and accept applicable model terms before the model downloads or runs. Acceptance, model failure, or local-AI opt-out must never block play. Incompatible asset changes require a new immutable static path and a coordinated frontend release.
- Local model output is advisory only. Preserve the original player input, send local hints only as untrusted context to Rust, and label offline replies as unsaved. Local diagnostic logging is opt-in, browser-local, exportable/deletable, and expires after 30 days.
+3
View File
@@ -39,3 +39,6 @@ CI needs repository Action secrets named `HARBOR_USERNAME` and `HARBOR_PASSWORD`
The first Argo Application is described in `deploy/argocd/application.yaml`. The backend ingress routes `/api`, `/version`, and health checks to Rust while serving the static client at `/`. Both services share the same origin so the session cookie remains same-origin.
Builds, checks, and runtime verification happen in the pipeline and Kubernetes. Do not run the app, tests, container images, or binaries locally.
# Browser-local AI status
Gemma/Wllama assistance is currently paused. `FEATURE_FLAGS.localAI` in `index.html` is `false`; while disabled, the client does not load the adapter, download model/runtime assets, run local inference, or send local hints. Re-enabling it requires an explicit code change and the normal frontend release pipeline. This does not affect the regular Rust-backed dialogue flow.
+1 -1
View File
@@ -1 +1 @@
0.1.66
0.1.68
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: ai-spel-frontend
description: Static web frontend for the Swedish life simulator
type: application
version: 0.1.66
appVersion: "0.1.66"
version: 0.1.68
appVersion: "0.1.68"
+19
View File
@@ -0,0 +1,19 @@
# ADR 0004: Pause browser-local AI by default
## Status
Accepted
## Decision
Browser-local Gemma/Wllama assistance is disabled by the `FEATURE_FLAGS.localAI` flag in `index.html`. The adapter is loaded dynamically only when the flag is true. When it is false, the browser does not load the adapter, request model/runtime assets, initialize local inference, attach local hints to dialogue requests, or produce local offline replies. The normal text dialogue remains available through the Rust API.
## Rationale
Pause model execution while the rest of the game and narrator experience is stabilized. Keep the implementation available for a deliberate future reactivation without downloading model resources or sending local inference hints in the meantime.
## Consequences
- Re-enabling local AI requires an explicit code change and frontend release.
- Tests and the static frontend check must enforce the default-off behavior and lazy loading.
- Existing Gemma asset publication and documentation may remain in place; the browser does not request those assets while the flag is off.
+77 -15
View File
@@ -116,8 +116,25 @@
<footer id="version-footer">Frontend <span id="frontend-version">__FRONTEND_VERSION__</span> · Statik <span id="static-version">hämtar version…</span> · API <span id="api-version">hämtar version…</span></footer>
<script src="/piper-runtime.js?v=__FRONTEND_VERSION__"></script>
<script src="/voice.js?v=__FRONTEND_VERSION__"></script>
<script src="/static/wllama-gemma3-v1/local-ai.js"></script>
<script>
// Local Gemma/Wllama assistance is paused until explicitly re-enabled here.
// Keep the adapter unloaded when false so it cannot download or initialize.
const FEATURE_FLAGS = Object.freeze({localAI: false});
let localAiAdapterPromise = null;
function loadLocalAiAdapter() {
if (!FEATURE_FLAGS.localAI) return Promise.resolve(null);
if (window.localGameAI) return Promise.resolve(window.localGameAI);
if (!localAiAdapterPromise) {
localAiAdapterPromise = new Promise((resolve) => {
const script = document.createElement('script');
script.src = '/static/' + 'wllama-gemma3-v2/local-ai.js';
script.onload = () => resolve(window.localGameAI || null);
script.onerror = () => resolve(null);
document.head.append(script);
});
}
return localAiAdapterPromise;
}
const auth = document.querySelector('#auth');
const play = document.querySelector('#play');
const playLayout = document.querySelector('#play-layout');
@@ -163,7 +180,7 @@
line.dataset.role = role;
line.textContent = `${options.speaker || (role === 'user' ? 'Du' : 'Berättelsen')}: ${content}`;
transcript.append(line);
if (role === 'user' || role === 'assistant') window.localGameAI?.record({type: 'dialogue', role, content});
if (FEATURE_FLAGS.localAI && (role === 'user' || role === 'assistant')) window.localGameAI?.record({type: 'dialogue', role, content});
line.scrollIntoView({block: 'end'});
if (role === 'assistant') {
latestAssistantText = content;
@@ -174,6 +191,24 @@
}
return line;
}
let activityStatusLine = null;
function setActivityStatus(message) {
if (!message) return;
if (!activityStatusLine?.isConnected) {
activityStatusLine = document.createElement('li');
activityStatusLine.dataset.role = 'system';
activityStatusLine.dataset.activityStatus = 'true';
activityStatusLine.setAttribute('role', 'status');
activityStatusLine.setAttribute('aria-live', 'polite');
transcript.append(activityStatusLine);
}
activityStatusLine.textContent = `Berättelsen: ${message}`;
activityStatusLine.scrollIntoView({block: 'end'});
}
function clearActivityStatus() {
activityStatusLine?.remove();
activityStatusLine = null;
}
function biographyContextText(context) {
if (!context || typeof context !== 'object') return '';
const details = [];
@@ -209,14 +244,18 @@
if (authVoiceStatus && !auth.hidden && message) authVoiceStatus.textContent = message;
}
window.addEventListener('local-ai-status', event => {
if (!currentAccount || currentAccount.is_admin || play.hidden) return;
let statusLine = transcript.querySelector('li[data-local-ai-status]');
if (!statusLine) {
const detail = typeof event.detail === 'string' ? {text: event.detail} : event.detail;
statusLine = appendLine(detail.type === 'terms-required' ? 'assistant' : 'system', detail.text || '', {speaker: 'Lokal AI', speak: detail.type === 'terms-required'});
statusLine.dataset.localAiStatus = 'true';
}
if (!FEATURE_FLAGS.localAI || !currentAccount || currentAccount.is_admin || play.hidden) return;
const detail = typeof event.detail === 'string' ? {text: event.detail} : event.detail;
const statusAttribute = detail.type === 'activity' ? 'data-local-ai-activity' : 'data-local-ai-status';
let statusLine = transcript.querySelector(`li[${statusAttribute}]`);
if (!statusLine) {
statusLine = appendLine(detail.type === 'terms-required' ? 'assistant' : 'system', detail.text || '', {
speaker: 'Lokal AI', speak: detail.type === 'terms-required',
});
statusLine.setAttribute(statusAttribute, 'true');
statusLine.setAttribute('role', 'status');
statusLine.setAttribute('aria-live', 'polite');
}
statusLine.replaceChildren(document.createTextNode(`Lokal AI: ${detail.text || ''}`));
if (detail.type === 'terms-required') {
statusLine.append(document.createTextNode(' Läs dokumenten: '));
@@ -670,15 +709,17 @@
stage = 'world-start';
messageField.disabled = true;
appendLine('user', message);
appendLine('assistant', 'Jag tar fram ett förslag på startplats och startläge…');
setActivityStatus('Berättaren ber AI ta fram ett förslag på startvärld och en plats som passar din biografi.');
try {
const proposal = await request('/api/world/draft', {
method: 'POST', headers: {'content-type': 'application/json'},
body: JSON.stringify({input: message, current_draft: worldDraft}),
});
worldDraft = proposal.draft;
clearActivityStatus();
appendLine('assistant', `${proposal.message}\n\nVärld: ${worldDraft.name}\nStartplats: ${worldDraft.location_name}. ${worldDraft.location_description}\nStartbelopp: ${worldDraft.starting_balance_sek} kronor. ${worldDraft.offer_name} kostar ${worldDraft.offer_price_sek} kronor.\n\nSkriv ändringar eller “godkänn”.`);
} catch (error) {
clearActivityStatus();
appendLine('assistant', `Förslaget kunde inte tas fram: ${error.message}. Skriv “försök igen” när du vill försöka på nytt.`);
}
setStage('world-draft');
@@ -692,6 +733,7 @@
}
appendLine('user', message);
messageField.disabled = true;
setActivityStatus('Sparar det godkända världsförslaget och skapar din startposition.');
try {
gameState = await request('/api/world/start', {
method: 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify(worldDraft),
@@ -699,8 +741,10 @@
worldDraft = null;
await loadSavedDialogue();
setStage('game');
clearActivityStatus();
appendLine('assistant', 'Du kan fråga om platsen, dina saker eller din ekonomi, vänta, handla, prata med någon som finns här eller skriva vart du vill gå.');
} catch (error) {
clearActivityStatus();
appendLine('assistant', `Världsförslaget kunde inte sparas: ${error.message}. Förslaget finns kvar så att du kan försöka igen.`);
}
messageField.disabled = false;
@@ -724,7 +768,10 @@
currentAccount = await request('/api/me');
gameState = await request('/api/world');
showPlay();
if (!currentAccount.is_admin) window.localGameAI?.start(currentAccount.id);
if (!currentAccount.is_admin && FEATURE_FLAGS.localAI) {
const localAI = await loadLocalAiAdapter();
localAI?.start(currentAccount.id);
}
if (!gameState.character) {
transcript.replaceChildren();
appendInitialPrompt();
@@ -891,7 +938,7 @@
presenceTimer = null;
playerMessagesPrimed = false;
seenPlayerMessageIds.clear();
window.localGameAI?.stop();
if (FEATURE_FLAGS.localAI) window.localGameAI?.stop();
await request('/api/logout', {method: 'POST'});
if (location.pathname !== '/admin') appendLine('assistant', 'Du har loggat ut. Logga in igen för att fortsätta spela.');
characterDraft = null;
@@ -924,6 +971,7 @@
}
appendLine('user', message);
messageField.disabled = true;
setActivityStatus('Berättaren ber AI skapa eller uppdatera ett biografiförslag utifrån det du skrev.');
try {
const proposal = await request('/api/character/draft', {
method: 'POST',
@@ -931,8 +979,10 @@
body: JSON.stringify({input: message, current_draft: characterDraft}),
});
characterDraft = proposal.draft;
clearActivityStatus();
appendLine('assistant', `${proposal.message}\n\nFörslag: ${characterDraft.name}, ${characterDraft.age} år.\n${characterDraft.biography}${biographyContextText(characterDraft.life_context)}\n\nSkriv ändringar eller “godkänn”.`);
} catch (error) {
clearActivityStatus();
appendLine('assistant', `Jag kunde inte ta fram ett biografiförslag: ${error.message}. Försök igen när tjänsten svarar.`);
}
messageField.disabled = false;
@@ -944,7 +994,7 @@
document.querySelector('#dry-run-action').disabled = !enabled;
}
async function handleGameMessage(message, actionMode = 'normal') {
if (actionMode === 'normal' && /^lokal ai(?:\s|$)/i.test(message.trim())) {
if (FEATURE_FLAGS.localAI && actionMode === 'normal' && /^lokal ai(?:\s|$)/i.test(message.trim())) {
const response = await window.localGameAI?.settings(message);
appendLine('user', message);
appendLine('assistant', response || 'Kommandon: “lokal ai villkor”, “lokal ai godkänn villkor”, “lokal ai avvisa villkor”, “lokal ai på/av”, “lokal ai loggar på/av”, “lokal ai exportera loggar” och “lokal ai radera loggar”.');
@@ -977,9 +1027,14 @@
if (actionMode === 'normal') pendingDialogue = {message, idempotencyKey};
appendLine('user', message, actionMode === 'dry_run' ? {speaker: 'Torrkörning'} : actionMode === 'redo' ? {speaker: 'Gör om'} : {});
messageField.disabled = true;
setActivityStatus(actionMode === 'dry_run'
? 'Torrkör handlingen utan att spara eller göra framsteg.'
: actionMode === 'redo'
? 'Gör om den senaste handlingen med aktuella regler.'
: 'Berättaren arbetar med din avsikt. Den avgör om en plats, scen eller person behöver etableras och fortsätter sedan berättelsen.');
try {
let clientAssistance = null;
if (actionMode === 'normal' && currentAccount && !currentAccount.is_admin && window.localGameAI) {
if (FEATURE_FLAGS.localAI && actionMode === 'normal' && currentAccount && !currentAccount.is_admin && window.localGameAI) {
try {
const history = [...transcript.querySelectorAll('li')].map(line => line.textContent).filter(Boolean);
const assisted = await window.localGameAI.assist(message, history, gameState?.world || {});
@@ -1017,7 +1072,11 @@
if (refreshed.world) gameState = refreshed;
} catch (_) { /* The committed dialogue stays successful if this optional view refresh fails. */ }
}
clearActivityStatus();
const speakingNpc = result.status !== 'dry_run' && ['speak', 'meet'].includes(result.intent) ? gameState.world.npc : null;
for (const change of result.world_changes || []) {
appendLine('system', change, {speaker: 'Världsändring', speak: false});
}
for (const ruleName of result.debug_rules_created || []) {
appendLine('assistant', ruleName, {speaker: 'Nya regler', speak: false});
}
@@ -1031,10 +1090,13 @@
}
refreshActionTools();
} catch (error) {
clearActivityStatus();
messageField.value = message;
try {
const history = [...transcript.querySelectorAll('li')].map(line => line.textContent).filter(Boolean);
const localReply = await window.localGameAI?.offline(message, history, gameState?.world || {});
const localReply = FEATURE_FLAGS.localAI
? await window.localGameAI?.offline(message, history, gameState?.world || {})
: null;
if (localReply) appendLine('assistant', `Lokalt, osparat förslag: ${localReply}`, {speaker: 'Lokal hjälp'});
else appendLine('assistant', `${explainDialogueError(error)} Ditt meddelande ligger kvar i inmatningen.`);
} catch (_) { appendLine('assistant', `${explainDialogueError(error)} Ditt meddelande ligger kvar i inmatningen.`); }
+6 -2
View File
@@ -5,7 +5,10 @@ test -s index.html
grep -q '<html lang="sv">' index.html
grep -q 'id="frontend-version">__FRONTEND_VERSION__' index.html
grep -q '<script src="/voice.js?v=__FRONTEND_VERSION__"></script>' index.html
grep -q '<script src="/static/wllama-gemma3-v1/local-ai.js"></script>' index.html
grep -q 'const FEATURE_FLAGS = Object.freeze({localAI: false})' index.html
grep -q 'if (!FEATURE_FLAGS.localAI) return Promise.resolve(null)' index.html
grep -q "script.src = '/static/' + 'wllama-gemma3-v2/local-ai.js'" index.html
! grep -q '<script src="/static/wllama-gemma3-v2/local-ai.js"></script>' index.html
grep -q '<script src="/piper-runtime.js?v=__FRONTEND_VERSION__"></script>' index.html
grep -q 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0' nginx/default.conf
grep -q 'Cross-Origin-Embedder-Policy "require-corp"' nginx/default.conf
@@ -47,7 +50,8 @@ grep -q 'WebKit versions before Safari 27' voice.js
grep -q "voiceIdentity: speakingNpc.voice_identity" index.html
grep -q "role: 'narrator', voiceIdentity: 'neutral'" index.html
grep -q 'COPY voice.js /usr/share/nginx/html/voice.js' Dockerfile
grep -Fq 'localGameAI?.start(currentAccount.id)' index.html
grep -Fq 'if (!currentAccount.is_admin && FEATURE_FLAGS.localAI)' index.html
grep -Fq 'localAI?.start(currentAccount.id)' index.html
grep -q "type === 'terms-required'" index.html
grep -q 'Gemma-villkor' index.html
grep -q 'lokal ai godkänn villkor' index.html
+23
View File
@@ -0,0 +1,23 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const source = fs.readFileSync(path.join(__dirname, '..', 'index.html'), 'utf8');
test('player sees an accessible live activity line during world and character proposals', () => {
assert.match(source, /function setActivityStatus\(message\)/);
assert.match(source, /setAttribute\('aria-live', 'polite'\)/);
assert.match(source, /AI ta fram ett förslag på startvärld och en plats/);
assert.match(source, /AI skapa eller uppdatera ett biografiförslag/);
});
test('dialogue processing explains that scene, place, or person establishment is being considered', () => {
assert.match(source, /Berättaren arbetar med din avsikt\. Den avgör om en plats, scen eller person behöver etableras/);
});
test('local AI activity is shown separately from general narrator processing', () => {
assert.match(source, /detail\.type === 'activity' \? 'data-local-ai-activity'/);
assert.match(source, /Lokal AI: \$\{detail\.text \|\| ''\}/);
assert.match(source, /clearActivityStatus\(\);/);
});
+6 -3
View File
@@ -5,9 +5,12 @@ const test = require('node:test');
const page = fs.readFileSync(path.join(__dirname, '..', 'index.html'), 'utf8');
test('local AI adapter comes from the static service and starts after authenticated game entry', () => {
assert.match(page, /<script src="\/static\/wllama-gemma3-v1\/local-ai\.js"><\/script>/);
assert.match(page, /showPlay\(\);\s*if \(!currentAccount\.is_admin\) window\.localGameAI\?\.start\(currentAccount\.id\)/);
test('local AI is paused by default and adapter loading is gated by its feature flag', () => {
assert.match(page, /const FEATURE_FLAGS = Object\.freeze\(\{localAI: false\}\)/);
assert.match(page, /if \(!FEATURE_FLAGS\.localAI\) return Promise\.resolve\(null\)/);
assert.match(page, /script\.src = '\/static\/' \+ 'wllama-gemma3-v2\/local-ai\.js'/);
assert.doesNotMatch(page, /<script src="\/static\/wllama-gemma3-v2\/local-ai\.js"><\/script>/);
assert.match(page, /if \(!currentAccount\.is_admin && FEATURE_FLAGS\.localAI\)[\s\S]*?loadLocalAiAdapter\(\)/);
});
test('Gemma license links are shown in the accessible game dialogue and consent can be withdrawn', () => {