Compare commits

..
11 Commits
Author SHA1 Message Date
Gitea Actions 5354132489 Release 0.1.31 [auto-version-bump] 2026-10-15 10:46:29 +02:00
Ein Anderssono 0005bb1c83 Support NPC-led conversation flow
Build and publish frontend / publish (push) Successful in 38s
2026-10-15 10:45:33 +02:00
Gitea Actions b3a0e0ca5a Release 0.1.30 [auto-version-bump] 2026-10-15 10:25:53 +02:00
Ein Anderssono de915b4aa6 Migrate players to automatic voice replies
Build and publish frontend / publish (push) Successful in 38s
2026-10-15 10:25:35 +02:00
Gitea Actions 421b14c398 Release 0.1.29 [auto-version-bump] 2026-10-15 10:21:53 +02:00
Ein Anderssono 9efb602653 Keep screen reader voice mode test explicit
Build and publish frontend / publish (push) Successful in 38s
2026-10-15 10:21:29 +02:00
Ein Anderssono 222dcb9054 Enable automatic speech for game replies
Build and publish frontend / publish (push) Failing after 3s
2026-10-15 10:21:00 +02:00
Gitea Actions 0876538e58 Release 0.1.28 [auto-version-bump] 2026-10-15 10:06:31 +02:00
Ein Anderssono f2a2a3b30a Speak dialogue with persistent character voices
Build and publish frontend / publish (push) Successful in 50s
2026-10-15 10:06:04 +02:00
Gitea Actions c9e31d23ba Release 0.1.27 [auto-version-bump] 2026-10-15 09:57:23 +02:00
Ein Anderssono 1f9fc464d4 Disclose browser speech processing before microphone use
Build and publish frontend / publish (push) Successful in 43s
2026-10-15 09:56:46 +02:00
7 changed files with 141 additions and 33 deletions
+5 -1
View File
@@ -6,11 +6,15 @@ After login, character creation and play use one dialogue history and one text i
During play the UI has no persistent location, task, inventory, economy, status, or purchase panels. The player asks for information or writes an action in the same input. Rust validates state changes; the AI can only propose a typed intent. A direct request to travel may establish a new place and an encounter when Rust commits that movement.
If the player asks to find or approach someone and no NPC is present, the direct dialogue scene may propose one person and an opening line. Rust creates that NPC only for the explicit request and commits the first exchange idempotently; a later turn continues the saved conversation. Clear requests about the current location are answered from its saved facts without asking the player to restate what they want to inspect.
The separate `/admin` route provides an authenticated, read-only operations view for player search/profile/trace, YAML prompt assets, generated Luau rules with validation results, and the append-only audit log. All privileged data comes from the Rust `/api/admin/...` API; the browser never connects directly to PostgreSQL. Backend endpoints require `accounts.is_admin=true`.
The game is text- and dialogue-based and uses no images. Place descriptions include sound, smell, air/temperature, touch/surface, and spatial-orientation cues. Visible details may also be described in words, but are never required to understand the scene or play. The transcript is screen-reader announced, and Enter submits the input while Shift+Enter inserts a newline; no separate send button is required.
Voice input and output are optional browser features. The microphone button beside the text field uses Web Speech API when available and sends only its final Swedish transcript through the same submission path as typed text. Writing `röstinställningar` or saying `röstkommando alternativ` opens the temporary controls in the dialogue. The player can choose `Spelets röst`, `Skärmläsare`, or `Endast text`, select available Swedish speech voices and rate, and enable auto-read and short audio cues. The default mode is `Skärmläsare`; auto-read is off. These preferences are stored in browser `localStorage`. If speech APIs are unavailable or permission is denied, text play remains available. No audio is uploaded or stored by this feature.
Voice input and output are browser features. Every new game reply is read automatically with the browser's Swedish speech synthesis by default, including character creation and gameplay; the transcript remains available as text. The microphone button beside the text field uses Web Speech API when available and sends only its final Swedish transcript through the same submission path as typed text. Before its first use, the client explains that the browser may process audio through a provider-selected service; the game itself does not receive or store recordings, while the final transcript is saved as ordinary dialogue. Writing `röstinställningar` or saying `röstkommando alternativ` opens the temporary controls in the dialogue. The player can choose `Spelets röst`, `Skärmläsare`, or `Endast text`, select available Swedish speech voices and rate, and enable or disable auto-read and short audio cues. The default mode is `Spelets röst` with auto-read on. Screen-reader and text-only modes remain explicit alternatives. These preferences are stored in browser `localStorage`. If speech APIs are unavailable, text play remains available.
When a character or NPC is created, its saved voice identity is masculine, feminine, or neutral. The biography prompt only assigns masculine/feminine when the character is explicitly described that way; otherwise it uses neutral. Speech synthesis applies a stable, subtly varied pitch/rate profile per character, so a character keeps the same sound across visits. Narration always uses neutral pitch. The browser's selected Swedish voice still determines the underlying voice, so the exact sound depends on installed system voices.
System voice commands require the prefix `röstkommando`: `upprepa`, `avbryt`, `hjälp`, `alternativ`, or `paus`. Without the prefix, the same words remain ordinary dialogue. Speech recognition and synthesis are browser-dependent; release acceptance must record which real iPhone/Safari/VoiceOver and Android/Chrome/TalkBack combinations were actually checked.
+1 -1
View File
@@ -1 +1 @@
0.1.26
0.1.31
+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.26
appVersion: "0.1.26"
version: 0.1.31
appVersion: "0.1.31"
+44 -9
View File
@@ -84,10 +84,12 @@
let submitBusy = false;
let pendingDialogue = null;
let latestAssistantText = '';
const voiceSettingsKey = 'ai-spel.voice-settings.v1';
let voiceSettings = window.GameVoice.loadSettings(localStorage, voiceSettingsKey);
let latestAssistantVoice = {role: 'narrator', voiceIdentity: 'neutral'};
const voiceSettingsKey = 'ai-spel.voice-settings.v2';
let voiceSettings = window.GameVoice.loadSettings(localStorage, voiceSettingsKey, 'ai-spel.voice-settings.v1');
let voiceController;
let audioContext;
let voiceDisclosureAcknowledged = false;
let adminOffset = 0;
const adminPageSize = 50;
@@ -105,13 +107,25 @@
line.scrollIntoView({block: 'end'});
if (role === 'assistant') {
latestAssistantText = content;
latestAssistantVoice = options.voice || {role: 'narrator', voiceIdentity: 'neutral'};
if (options.speak !== false && !content.trim().endsWith('…') && !content.trim().endsWith('...')
&& voiceSettings.mode === 'game-voice' && voiceSettings.autoSpeak && !play.hidden) {
voiceController?.speak(content, options.voice || {});
voiceController?.speak(content, latestAssistantVoice);
}
}
return line;
}
function explainDialogueError(error) {
const code = String(error?.message || '');
const known = {
dialogue_temporarily_unavailable: 'Berättartjänsten svarar inte just nu. Vänta en stund och försök igen.',
world_version_conflict: 'Världen hann ändras medan du skrev. Jag har uppdaterat läget; skicka meddelandet igen.',
world_not_available: 'Världen är inte tillgänglig just nu. Försök igen om en liten stund.',
};
return known[code] || (/^[a-z0-9_]+$/.test(code)
? 'Jag kunde inte behandla det just nu. Försök igen om en liten stund.'
: code || 'Ett tillfälligt fel uppstod. Försök igen om en liten stund.');
}
function setVoiceStatus(message = '') { document.querySelector('#voice-status').textContent = message; }
function refreshMicrophone() {
const button = document.querySelector('#microphone');
@@ -198,7 +212,7 @@
signalLabel.append(signals, document.createTextNode(' Ljudsignal vid röstinmatning')); fieldset.append(signalLabel);
item.append(fieldset);
const speakLatest = () => {
if (!voiceController.speak(latestAssistantText)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
if (!voiceController.speak(latestAssistantText, latestAssistantVoice)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
};
addVoiceButton(item, 'Läs senaste repliken', speakLatest);
addVoiceButton(item, 'Upprepa', speakLatest);
@@ -211,12 +225,26 @@
addVoiceButton(item, 'Stäng röstinställningar', () => item.remove());
transcript.append(item); item.scrollIntoView({block: 'end'}); mode.focus();
}
function requestVoiceDisclosure() {
const item = document.createElement('li'); item.dataset.role = 'voice-controls';
item.setAttribute('aria-label', 'Information om mikrofonen');
const message = document.createElement('p');
message.textContent = 'Innan du startar: webbläsarens taligenkänning kan behandla ljud genom en tjänst som webbläsaren väljer. Spelet tar inte emot eller sparar ljudinspelningen. Den färdiga transkriberingen skickas och sparas som din vanliga dialog. Fortsätt bara om du godkänner webbläsarens hantering av tal.';
item.append(message);
addVoiceButton(item, 'Jag förstår – starta mikrofonen', () => {
voiceDisclosureAcknowledged = true;
item.remove();
voiceController.startListening();
});
transcript.append(item); item.scrollIntoView({block: 'end'});
item.querySelector('button').focus();
}
function handleVoiceCommand(message, source) {
const parsed = window.GameVoice.parseVoiceCommand(message, {requirePrefix: source === 'voice'});
if (!parsed) return false;
if (parsed.command === 'settings') appendVoiceSettings();
else if (parsed.command === 'repeat') {
if (!voiceController.speak(latestAssistantText)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
if (!voiceController.speak(latestAssistantText, latestAssistantVoice)) setVoiceStatus('Talsyntes stöds inte här eller är avstängd. Dialogen finns kvar som text.');
} else if (parsed.command === 'stop') {
voiceController.cancelSpeech(); voiceController.stopListening(); setVoiceStatus('Röstinteraktionen är avbruten.');
} else if (parsed.command === 'help') {
@@ -226,6 +254,7 @@
}
document.querySelector('#microphone').addEventListener('click', () => {
if (voiceController.getState() === 'LISTENING') voiceController.stopListening();
else if (!voiceDisclosureAcknowledged && voiceController.supportsRecognition()) requestVoiceDisclosure();
else voiceController.startListening();
});
document.addEventListener('visibilitychange', () => { if (document.hidden) voiceController.stopAll(); });
@@ -516,13 +545,19 @@
gameState.world.version = result.world_version;
gameState.world.world_time = result.world_time;
pendingDialogue = null;
const speakingNpc = result.intent === 'speak' ? gameState.world.npc : null;
if (result.intent === 'move' || result.intent === 'meet') {
try {
const refreshed = await request('/api/world');
if (refreshed.world) gameState = refreshed;
} catch (_) { /* The committed dialogue stays successful if this optional view refresh fails. */ }
}
const speakingNpc = ['speak', 'meet'].includes(result.intent) ? gameState.world.npc : null;
appendLine('assistant', result.reply, speakingNpc
? {speaker: speakingNpc.name, voice: {characterId: speakingNpc.id}}
: {speaker: 'Berättelsen'});
? {speaker: speakingNpc.name, voice: {characterId: speakingNpc.id, voiceIdentity: speakingNpc.voice_identity}}
: {speaker: 'Berättelsen', voice: {role: 'narrator', voiceIdentity: 'neutral'}});
} catch (error) {
messageField.value = message;
appendLine('assistant', `Meddelandet kunde inte behandlas: ${error.message}. Texten ligger kvar i inmatningen; skicka igen för att försöka på nytt.`);
appendLine('assistant', `${explainDialogueError(error)} Ditt meddelande ligger kvar i inmatningen.`);
}
messageField.disabled = false;
messageField.focus();
+7
View File
@@ -11,6 +11,11 @@ grep -q 'id="message" name="message"' index.html
grep -q 'id="microphone" aria-pressed="false"' index.html
grep -q 'id="voice-status" role="status" aria-live="polite"' index.html
grep -q "window.GameVoice.createVoiceController" index.html
grep -q 'Jag förstår – starta mikrofonen' index.html
grep -q 'supportsRecognition' voice.js
grep -q 'characterVoiceProfile' 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 -q "SpeechRecognition || win.webkitSpeechRecognition" voice.js
grep -q "submitMessage(text, 'voice')" index.html
@@ -21,6 +26,8 @@ grep -q "event.key === 'Enter' && !event.shiftKey" index.html
grep -q "request('/api/character/draft'" index.html
grep -q "request('/api/world/draft'" index.html
grep -q "request('/api/dialogue'" index.html
grep -q "result.intent === 'move' || result.intent === 'meet'" index.html
grep -q 'dialogue_temporarily_unavailable:' index.html
grep -q 'id="admin-view"' index.html
grep -q '/api/admin/players?' index.html
grep -q "request('/api/admin/prompts'" index.html
+47 -12
View File
@@ -5,6 +5,9 @@ const test = require('node:test');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '..', 'voice.js'), 'utf8');
const apiWindow = {};
vm.runInNewContext(source, {window: apiWindow, globalThis: apiWindow, Promise, String, Math, Object});
const GameVoice = apiWindow.GameVoice;
function makeHarness({supported = true, tts = true, onTranscript = () => Promise.resolve()} = {}) {
const recognitions = [];
@@ -119,6 +122,26 @@ test('TTS selects Swedish fallback, applies rate, and cancellation invalidates c
assert.equal(h.controller.getState(), 'IDLE');
});
test('character voice identity gives stable distinct masculine, feminine, and neutral timbres', () => {
const profile = GameVoice.characterVoiceProfile;
const masculine = profile('masculine', 'character-1');
const feminine = profile('feminine', 'character-1');
const neutral = profile('neutral', 'character-1');
assert.equal(profile('masculine', 'character-1').pitch, masculine.pitch);
assert.ok(masculine.pitch < neutral.pitch);
assert.ok(neutral.pitch < feminine.pitch);
assert.notEqual(profile('masculine', 'character-2').pitch, masculine.pitch);
});
test('narrator uses neutral pitch while character replies use their saved voice identity', () => {
const h = makeHarness();
h.controller.update({mode: 'game-voice'});
h.controller.speak('Berättarröst', {role: 'narrator', voiceIdentity: 'feminine', characterId: 'narrator'});
h.controller.speak('NPC-replik', {voiceIdentity: 'masculine', characterId: 'npc-1'});
assert.equal(h.utterances[0].pitch, 1);
assert.ok(h.utterances[1].pitch < 1);
});
test('TTS and microphone are mutually exclusive', () => {
const h = makeHarness();
h.controller.update({mode: 'game-voice'});
@@ -130,6 +153,7 @@ test('TTS and microphone are mutually exclusive', () => {
test('speech is disabled in screen-reader mode and gracefully degrades without synthesis', () => {
const screenReader = makeHarness();
screenReader.controller.update({mode: 'screen-reader'});
assert.equal(screenReader.controller.speak('dialog'), false);
const noTts = makeHarness({tts: false});
noTts.controller.update({mode: 'game-voice'});
@@ -139,13 +163,13 @@ test('speech is disabled in screen-reader mode and gracefully degrades without s
test('system commands require an explicit prefix; ordinary dialogue words are untouched', () => {
const global = {};
vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object});
assert.equal(global.GameVoice.parseVoiceCommand('upprepa'), null);
assert.equal(global.GameVoice.parseVoiceCommand('hjälp'), null);
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando upprepa.' ).command, 'repeat');
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando alternativ').command, 'settings');
assert.equal(global.GameVoice.parseVoiceCommand('röstinställningar').command, 'settings');
assert.equal(global.GameVoice.parseVoiceCommand('röstinställningar', {requirePrefix: true}), null);
assert.equal(global.GameVoice.parseVoiceCommand('röstkommando alternativ', {requirePrefix: true}).command, 'settings');
assert.equal(GameVoice.parseVoiceCommand('upprepa'), null);
assert.equal(GameVoice.parseVoiceCommand('hjälp'), null);
assert.equal(GameVoice.parseVoiceCommand('röstkommando upprepa.' ).command, 'repeat');
assert.equal(GameVoice.parseVoiceCommand('röstkommando alternativ').command, 'settings');
assert.equal(GameVoice.parseVoiceCommand('röstinställningar').command, 'settings');
assert.equal(GameVoice.parseVoiceCommand('röstinställningar', {requirePrefix: true}), null);
assert.equal(GameVoice.parseVoiceCommand('röstkommando alternativ', {requirePrefix: true}).command, 'settings');
});
test('settings survive reload and invalid storage falls back to accessible defaults', () => {
@@ -153,14 +177,25 @@ test('settings survive reload and invalid storage falls back to accessible defau
vm.runInNewContext(source, {window: global, globalThis: global, Promise, String, Math, Object});
const values = new Map();
const storage = {getItem: key => values.get(key) || null, setItem: (key, value) => values.set(key, value)};
const requested = {...global.GameVoice.DEFAULT_SETTINGS, mode: 'game-voice', autoSpeak: true, rate: 1.5, voiceName: 'Svensk'};
assert.equal(global.GameVoice.saveSettings(storage, 'voice', requested), true);
const loaded = global.GameVoice.loadSettings(storage, 'voice');
const defaults = GameVoice.loadSettings(storage, 'new-player');
assert.equal(defaults.mode, 'game-voice');
assert.equal(defaults.autoSpeak, true);
values.set('voice-v1', JSON.stringify({mode: 'screen-reader', autoSpeak: false, rate: 1.4, voiceName: 'Svensk', soundSignals: false}));
const migrated = GameVoice.loadSettings(storage, 'voice-v2', 'voice-v1');
assert.equal(migrated.mode, 'game-voice');
assert.equal(migrated.autoSpeak, true);
assert.equal(migrated.rate, 1.4);
assert.equal(migrated.voiceName, 'Svensk');
assert.equal(migrated.soundSignals, false);
const requested = {...GameVoice.DEFAULT_SETTINGS, mode: 'game-voice', autoSpeak: true, rate: 1.5, voiceName: 'Svensk'};
assert.equal(GameVoice.saveSettings(storage, 'voice', requested), true);
const loaded = GameVoice.loadSettings(storage, 'voice');
assert.equal(loaded.mode, 'game-voice');
assert.equal(loaded.autoSpeak, true);
assert.equal(loaded.rate, 1.5);
assert.equal(loaded.voiceName, 'Svensk');
values.set('voice', '{trasig');
assert.equal(global.GameVoice.loadSettings(storage, 'voice').mode, 'screen-reader');
assert.equal(global.GameVoice.saveSettings({setItem() { throw new Error('blocked'); }}, 'voice', requested), false);
assert.equal(GameVoice.loadSettings(storage, 'voice').mode, 'game-voice');
assert.equal(GameVoice.loadSettings(storage, 'voice').autoSpeak, true);
assert.equal(GameVoice.saveSettings({setItem() { throw new Error('blocked'); }}, 'voice', requested), false);
});
+35 -8
View File
@@ -1,8 +1,8 @@
/* Browser voice adapters. Kept independent of the game submission and API layer. */
(function exposeVoice(root) {
const DEFAULT_SETTINGS = Object.freeze({
mode: 'screen-reader',
autoSpeak: false,
mode: 'game-voice',
autoSpeak: true,
language: 'sv-SE',
rate: 1,
voiceName: '',
@@ -25,9 +25,22 @@
return {command: aliases[command] || 'unknown'};
}
function loadSettings(storage, key) {
function loadSettings(storage, key, legacyKey) {
try {
const stored = JSON.parse(storage.getItem(key) || '{}');
const current = storage.getItem(key);
if (!current && legacyKey) {
const legacy = JSON.parse(storage.getItem(legacyKey) || '{}');
const migrated = {
...DEFAULT_SETTINGS,
rate: legacy.rate,
voiceName: legacy.voiceName,
speakerProfiles: legacy.speakerProfiles,
soundSignals: legacy.soundSignals,
};
saveSettings(storage, key, migrated);
return migrated;
}
const stored = JSON.parse(current || '{}');
const settings = {...DEFAULT_SETTINGS, ...stored};
if (!['screen-reader', 'game-voice', 'text-only'].includes(settings.mode)) settings.mode = DEFAULT_SETTINGS.mode;
settings.rate = Math.min(2, Math.max(0.5, Number(settings.rate) || 1));
@@ -44,6 +57,16 @@
catch (_) { return false; }
}
function characterVoiceProfile(voiceIdentity, characterId = '') {
const identity = ['masculine', 'feminine', 'neutral'].includes(voiceIdentity) ? voiceIdentity : 'neutral';
let hash = 2166136261;
for (const char of String(characterId)) hash = Math.imul(hash ^ char.charCodeAt(0), 16777619) >>> 0;
const variation = (hash % 1000) / 1000;
if (identity === 'masculine') return {pitch: 0.88 + variation * 0.08, rate: 0.96 + variation * 0.04};
if (identity === 'feminine') return {pitch: 1.06 + variation * 0.08, rate: 0.98 + variation * 0.04};
return {pitch: 0.98 + variation * 0.04, rate: 1};
}
function createVoiceController(options = {}) {
const win = options.window || root;
const onState = options.onState || (() => {});
@@ -163,8 +186,11 @@
catch (_) { setState('IDLE', 'Talsyntesen kunde inte startas. Dialogen finns kvar som text.'); return false; }
utterance.lang = settings.language || 'sv-SE';
const profile = voiceOptions.characterId ? settings.speakerProfiles?.[voiceOptions.characterId] || {} : {};
utterance.rate = Math.min(2, Math.max(0.5, Number(voiceOptions.rate ?? profile.rate ?? settings.rate) || 1));
utterance.pitch = Math.min(2, Math.max(0, Number(voiceOptions.pitch ?? profile.pitch ?? 1) || 1));
const identityProfile = characterVoiceProfile(voiceOptions.voiceIdentity, voiceOptions.characterId);
const isNarrator = voiceOptions.role === 'narrator';
const configuredRate = Number(voiceOptions.rate ?? profile.rate ?? settings.rate) || 1;
utterance.rate = Math.min(2, Math.max(0.5, configuredRate * (isNarrator || voiceOptions.rate != null || profile.rate != null ? 1 : identityProfile.rate)));
utterance.pitch = isNarrator ? 1 : Math.min(2, Math.max(0, Number(voiceOptions.pitch ?? profile.pitch ?? identityProfile.pitch) || 1));
const requestedName = voiceOptions.voiceName || profile.voiceName || settings.voiceName;
const voices = availableVoices();
utterance.voice = voices.find(voice => voice.name === requestedName)
@@ -201,8 +227,9 @@
function getState() { return state; }
function getSettings() { return {...settings}; }
function getVoices() { return availableVoices(); }
return {startListening, stopListening, speak, cancelSpeech, stopAll, update, getState, getSettings, getVoices};
function supportsRecognition() { return Boolean(win.SpeechRecognition || win.webkitSpeechRecognition); }
return {startListening, stopListening, speak, cancelSpeech, stopAll, update, getState, getSettings, getVoices, supportsRecognition};
}
root.GameVoice = {createVoiceController, DEFAULT_SETTINGS, parseVoiceCommand, loadSettings, saveSettings};
root.GameVoice = {createVoiceController, DEFAULT_SETTINGS, parseVoiceCommand, loadSettings, saveSettings, characterVoiceProfile};
})(typeof window !== 'undefined' ? window : globalThis);