mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-11-26 17:13:52 +01:00
fix(tavern): align speech, ambient life and default Adventurer
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const Appearance = require('../src/multiplayer/appearance');
|
||||
const Entitlements = require('../src/multiplayer/entitlements');
|
||||
|
||||
// Only DOM/canvas/Pixi primitives and atlas I/O are replaced. Catalogs, entitlement
|
||||
// resolution, normalization, customizer, and both renderer paths are production code.
|
||||
function kit() {
|
||||
const frames = [], loads = [], draws = [];
|
||||
let ready = false;
|
||||
const ctx = new Proxy({}, { get(target, key) { return target[key] || (() => {}); } });
|
||||
function element(tag) {
|
||||
const e = { tagName: tag, style: {}, children: [], className: '', textContent: '',
|
||||
appendChild(c) { this.children.push(c); c.parentNode = this; },
|
||||
removeChild(c) { this.children = this.children.filter(x => x !== c); c.parentNode = null; },
|
||||
getContext: () => ctx, setAttribute() {}, addEventListener() {} };
|
||||
e.classList = { add(c) { if (!e.className.split(' ').includes(c)) e.className += ' ' + c; },
|
||||
remove(c) { e.className = e.className.split(' ').filter(x => x !== c).join(' '); },
|
||||
contains(c) { return e.className.split(' ').includes(c); } };
|
||||
Object.defineProperty(e, 'innerHTML', { set() { e.children = []; } });
|
||||
return e;
|
||||
}
|
||||
const document = { createElement: element, head: element('head'), body: element('body'), getElementById: () => null };
|
||||
const context = { document, localStorage: { getItem: () => null, setItem() {} },
|
||||
Image: class {}, console, Date, requestAnimationFrame(fn) { frames.push(fn); }, cancelAnimationFrame() {} };
|
||||
context.window = context;
|
||||
vm.createContext(context);
|
||||
for (const file of ['charSprites', 'skins', 'assetPacks', 'charCustomize', 'avatarVisuals', 'tileRenderer', 'fancyRenderer']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '../html/js/render/' + file + '.js'), 'utf8'), context);
|
||||
}
|
||||
const RK = context.RK;
|
||||
RK.setEntitlementSnapshot(Entitlements.snapshotForUser({ credits: 0, total_credits_purchased: 0 }));
|
||||
RK.charAtlas = () => ready ? {} : null;
|
||||
RK.loadCharAtlas = fn => { if (fn) loads.push(fn); };
|
||||
RK.drawCharTileCanvas = (...args) => { draws.push(args); return true; };
|
||||
RK.drawCharCompositeCanvas = () => ready;
|
||||
return { RK, frames, loads, draws, document, ctx, element,
|
||||
ready() { ready = true; }, complete() { loads.splice(0).forEach(fn => fn()); } };
|
||||
}
|
||||
function descendants(e) { return [e, ...e.children.flatMap(descendants)]; }
|
||||
function scene(id, appearance = { avatar: 'default' }) {
|
||||
return { cols: 1, rows: 1, grid: [['floor']], legend: { floor: { color: '#654321' } },
|
||||
entities: [{ id, kind: 'avatar', x: 0, y: 0, appearance }] };
|
||||
}
|
||||
function tiled(k) {
|
||||
k.RK.themeAtlas = () => null; k.RK.tileMap = () => ({}); k.RK.roomReady = () => false;
|
||||
const r = new k.RK.TileRenderer(k.element('host'));
|
||||
for (const name of ['_collectEmitters', '_snapshot', '_ensureEmbers', '_composite', '_startLoop']) r[name] = () => {};
|
||||
return r;
|
||||
}
|
||||
function fancy(k) {
|
||||
const r = Object.create(k.RK.FancyRenderer.prototype);
|
||||
Object.assign(r, { app: {}, cell: 24, sprites: {}, entityLayer: { addChild() {}, removeChild() {} } });
|
||||
const made = [];
|
||||
for (const [method, kind] of [['_makeCharSprite', 'char'], ['_makeSkinSprite', 'skin'], ['_makeSprite', 'circle']]) {
|
||||
r[method] = e => { made.push({ kind, e }); return { destroy() {} }; };
|
||||
}
|
||||
r.show = s => { r._lastScene = s; r._syncEntities(s); };
|
||||
return { r, made };
|
||||
}
|
||||
|
||||
test('client and server normalize defaults and preserve every valid catalog identity and character fields', () => {
|
||||
const { RK } = kit();
|
||||
const inputs = [undefined, null, {}, 'default', 'unknown', { appearance: { avatar: 'default' } },
|
||||
...Appearance.avatarIds().map(avatar => ({ avatar, tint: 'moss', colors: { base: 'teal', hair: 'silver' }, equipment: { body: 'mail', weapon: 'bow' } }))];
|
||||
for (const input of inputs) expect(RK.normalizeAppearance(input)).toEqual(Appearance.normalizeAppearance(input));
|
||||
expect(RK.appearances().filter(a => a.id === 'char-villager').map(a => a.label)).toEqual(['Adventurer']);
|
||||
expect(RK.appearances().some(a => a.id === 'default')).toBe(false);
|
||||
});
|
||||
|
||||
test.each(['ascii', 'topdown', 'iso', '3d'])('Adventurer is selected and remains the same saved identity in %s picker', projection => {
|
||||
const k = kit(); k.ready();
|
||||
const saved = [];
|
||||
k.RK.openCustomize('default', ap => saved.push(ap), { projection });
|
||||
const nodes = descendants(k.document.body);
|
||||
const cards = nodes.filter(e => e.classList.contains('rk-option-card'));
|
||||
const adventurers = cards.filter(e => e.children.some(c => c.textContent === 'Adventurer'));
|
||||
expect(adventurers).toHaveLength(1);
|
||||
expect(adventurers[0].classList.contains('is-selected')).toBe(true);
|
||||
nodes.find(e => e.classList.contains('rk-save')).onclick();
|
||||
expect(saved[0]).toEqual(Appearance.normalizeAppearance('char-villager'));
|
||||
expect(k.RK.canUsePack('kenney-3d-characters')).toBe(false);
|
||||
});
|
||||
|
||||
test.each(['green', 'char-ranger'])('opening another projection preserves saved %s identity', avatar => {
|
||||
const k = kit(); k.ready(); const saved = [];
|
||||
const ap = { avatar, colors: { base: 'teal', hair: 'silver' }, equipment: { weapon: 'bow' } };
|
||||
k.RK.openCustomize(ap, value => saved.push(value), { projection: 'ascii' });
|
||||
descendants(k.document.body).find(e => e.classList.contains('rk-save')).onclick();
|
||||
expect(saved[0]).toEqual(Appearance.normalizeAppearance(ap));
|
||||
});
|
||||
|
||||
test('actual FREE catalog permits character rendering without unlocking premium environments or skins', () => {
|
||||
const { RK } = kit();
|
||||
expect(RK.canUsePack('roguelike-interior')).toBe(false);
|
||||
for (const id of ['char-villager', 'char-ranger']) {
|
||||
const visual = RK.avatarVisuals.resolve(id, { projection: 'topdown' });
|
||||
expect(visual.allowed).toBe(true); expect(visual.pack).toBeNull();
|
||||
}
|
||||
expect(RK.avatarVisuals.resolve('monero-knight', { projection: 'topdown' }).allowed).toBe(false);
|
||||
expect(RK.avatarVisuals.resolve('char-villager', { projection: '3d' }).allowed).toBe(false);
|
||||
expect(RK.avatarVisuals.resolve('green', { projection: 'topdown' }).appearance.avatar).toBe('green');
|
||||
});
|
||||
|
||||
test('actual tiled FREE path repaints a canonical default character after atlas completion', () => {
|
||||
const k = kit(), r = tiled(k);
|
||||
r.render(scene('first')); r.render(scene('latest'));
|
||||
expect(k.draws).toHaveLength(0);
|
||||
k.ready(); k.complete();
|
||||
expect(k.frames).toHaveLength(1); k.frames.shift()();
|
||||
expect(k.draws.some(args => args[1] === k.RK.CHARS['char-villager'].frame)).toBe(true);
|
||||
expect(k.frames).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('Fancy uses canonical appearance, redraws latest entities once, and keeps valid colors', () => {
|
||||
const k = kit(), { r, made } = fancy(k);
|
||||
r.show(scene('first')); r.show(scene('latest'));
|
||||
expect(made.every(x => x.kind === 'circle')).toBe(true);
|
||||
k.ready(); k.complete(); expect(k.frames).toHaveLength(1); k.frames.shift()();
|
||||
expect(made.filter(x => x.kind === 'char').map(x => [x.e.id, x.e.avatar])).toEqual([['latest', 'char-villager']]);
|
||||
const explicit = scene('saved', { avatar: 'char-ranger', colors: { base: 'teal' } });
|
||||
explicit.entities[0].avatar = 'default';
|
||||
r.show(explicit);
|
||||
expect(r.sprites.saved.e.appearance).toEqual(Appearance.normalizeAppearance(explicit.entities[0].appearance));
|
||||
r.show(scene('color', { avatar: 'green' }));
|
||||
expect(r.sprites.color.kind).toBe('circle'); expect(r.sprites.color.e.avatar).toBe('green');
|
||||
});
|
||||
|
||||
test('Fancy never spins on failed atlas completion or repaints after destruction', () => {
|
||||
const k = kit(), { r } = fancy(k);
|
||||
r.show(scene('pending')); k.complete(); expect(k.frames).toHaveLength(0);
|
||||
r.show(scene('retry')); k.ready(); k.complete(); expect(k.frames).toHaveLength(1);
|
||||
r.app = null; const before = r.sprites; k.frames.shift()(); expect(r.sprites).toBe(before);
|
||||
});
|
||||
|
||||
|
||||
test('Fancy default normalization never turns monsters, features, items, or cats into humanoid avatars', () => {
|
||||
const k = kit(), { r, made } = fancy(k); k.ready();
|
||||
const mixed = scene('adventurer');
|
||||
for (const kind of ['monster', 'feature', 'item', 'cat']) {
|
||||
mixed.entities.push({ id: kind, kind, x: 0, y: 0, color: '#f85149', char: kind === 'cat' ? 'c' : '~' });
|
||||
}
|
||||
r.show(mixed);
|
||||
expect(made.filter(x => x.kind === 'char').map(x => x.e.id)).toEqual(['adventurer']);
|
||||
for (const entity of mixed.entities.slice(1)) {
|
||||
expect(r.sprites[entity.id].kind).toBe('circle');
|
||||
expect(r.sprites[entity.id].e).toBe(entity);
|
||||
expect(entity.avatar).toBeUndefined();
|
||||
}
|
||||
});
|
||||
@@ -39,11 +39,8 @@ describe('appearance catalog normalization', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back unknown avatars to default', () => {
|
||||
expect(Appearance.normalizeAppearance('rainbow')).toEqual({
|
||||
avatar: 'default',
|
||||
tint: 'none',
|
||||
equipment: { body: 'none', head: 'none', shield: 'none', weapon: 'none' }
|
||||
});
|
||||
test.each([undefined, null, {}, 'default', 'rainbow'])('normalizes legacy and missing defaults to the free Adventurer (%p)', input => {
|
||||
expect(Appearance.normalizeAppearance(input)).toEqual(Appearance.normalizeAppearance('char-villager'));
|
||||
expect(Appearance.normalizeAppearance(input).avatar).toBe('char-villager');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -67,3 +67,28 @@ describe('SocketChatProvider', () => {
|
||||
expect(shut).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trusted local delivery boundary', () => {
|
||||
test.each(['global', 'tavern:main'])('callback follows successful local emit and is never a payload/history field: %s', async scope => {
|
||||
const io = makeFakeIo();
|
||||
const saved = [];
|
||||
const provider = new SocketChatProvider({ io, historyManager: { saveMessage: async message => { saved.push(message); }, getRecentMessages: async () => [] } });
|
||||
const delivered = jest.fn(() => {
|
||||
expect(io.emitted.some(e => e.event === 'chat_broadcast')).toBe(true);
|
||||
});
|
||||
await provider.publish({ scope, username: 'Speaker', text: 'hello', onLocalDelivery: delivered });
|
||||
expect(delivered).toHaveBeenCalledTimes(1);
|
||||
expect(io.emitted.every(e => !Object.hasOwn(e.payload, 'onLocalDelivery'))).toBe(true);
|
||||
expect(saved.every(message => !Object.hasOwn(message, 'onLocalDelivery'))).toBe(true);
|
||||
await provider.getHistory({ scope });
|
||||
expect(delivered).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('failed local emit never invokes delivery even though the publisher rejects', async () => {
|
||||
const delivered = jest.fn();
|
||||
const io = { emit() { throw new Error('disposable local emit failure'); } };
|
||||
const provider = new SocketChatProvider({ io });
|
||||
await expect(provider.publish({ scope: 'global', text: 'refused', onLocalDelivery: delivered })).rejects.toThrow();
|
||||
expect(delivered).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,8 +7,8 @@ describe('cosmetic entitlements', () => {
|
||||
|
||||
expect(Entitlements.canUsePack(entitlements, 'generated-skins')).toBe(false);
|
||||
expect(Entitlements.canUsePack(entitlements, 'kenney-3d-characters')).toBe(false);
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('default');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('char-villager');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('char-villager');
|
||||
});
|
||||
|
||||
test('graduated ladder: credit spend unlocks packs by threshold', () => {
|
||||
@@ -32,7 +32,7 @@ describe('cosmetic entitlements', () => {
|
||||
expect(entitlements.packs['generated-skins']).toBe(true);
|
||||
expect(entitlements.packs['kenney-3d-characters']).toBe(false);
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'monero-knight' }, entitlements).avatar).toBe('monero-knight');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('default');
|
||||
expect(Entitlements.normalizeAppearance({ avatar: 'kenney-survivor-male' }, entitlements).avatar).toBe('char-villager');
|
||||
});
|
||||
|
||||
test('appearance catalog reports all premium avatar ids, including 3D models', () => {
|
||||
|
||||
@@ -81,8 +81,8 @@ describe('IdentityService', () => {
|
||||
|
||||
const snapshot = await svc.saveAppearanceForSocket(makeSocket(), { avatar: 'monero-knight' });
|
||||
|
||||
expect(snapshot.appearance.avatar).toBe('default');
|
||||
expect(db.state.user.appearance.avatar).toBe('default');
|
||||
expect(snapshot.appearance.avatar).toBe('char-villager');
|
||||
expect(db.state.user.appearance.avatar).toBe('char-villager');
|
||||
});
|
||||
|
||||
test('allows an explicitly granted pack appearance', async () => {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
function fixture(width = 320, height = 300) {
|
||||
let now = 1000;
|
||||
const painted = [], bodies = [];
|
||||
const ctx = {
|
||||
clearRect() { painted.length = 0; bodies.length = 0; }, save() {}, restore() {},
|
||||
beginPath() {}, fill() {}, stroke() {}, moveTo() {}, lineTo() {}, closePath() {},
|
||||
roundRect(x, y, w, h) { bodies.push({ x, y, w, h }); },
|
||||
measureText(text) { return { width: Array.from(text).length * 7 }; },
|
||||
fillText(text, x, y) { painted.push({ text, x, y }); }
|
||||
};
|
||||
const canvas = { style: {}, width, height, getContext: () => ctx };
|
||||
ctx.canvas = canvas;
|
||||
const bounds = () => ({ left: 0, top: 0, width, height });
|
||||
const host = { style: {}, clientWidth: width, clientHeight: height,
|
||||
appendChild(c) { c.parentNode = this; }, getBoundingClientRect: bounds,
|
||||
querySelector: () => ({ width, height, getBoundingClientRect: bounds }) };
|
||||
const root = { RK: {}, CanvasRenderingContext2D: function () {}, document: { createElement: () => canvas } };
|
||||
root.CanvasRenderingContext2D.prototype.roundRect = function () {};
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/tavernLife.js'), 'utf8'), { window: root });
|
||||
const scene = { cols: 8, rows: 5, grid: Array.from({ length: 5 }, () => Array(8).fill('floor')),
|
||||
entities: [{ id: 'speaker', x: 2, y: 2 }] };
|
||||
const life = new root.RK.TavernLife(host, () => scene, () => 24, { now: () => now });
|
||||
return { life, scene, painted, bodies, ctx, root, draw: () => life.update(scene, 24, 'tiles'), advance: ms => { now += ms; } };
|
||||
}
|
||||
|
||||
describe('Tavern accepted speech layout', () => {
|
||||
test('an actor-free authored room still paints accepted speech as literal text', () => {
|
||||
const f = fixture();
|
||||
f.life.spawn();
|
||||
expect(f.life._spawned).toBe(false);
|
||||
const text = 'Cheers & <b>hello</b> 🙂';
|
||||
f.life.showPlayerBubble('speaker', text); f.draw();
|
||||
expect(f.painted.map(p => p.text).join('')).toBe(text);
|
||||
expect(f.bodies.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('long unbroken and Unicode text wraps inside a narrow viewport', () => {
|
||||
const f = fixture(160, 300), text = 'a'.repeat(90) + '🙂'.repeat(10) + ' & hello';
|
||||
f.life.showPlayerBubble('speaker', text); f.draw();
|
||||
expect(f.painted.length).toBeGreaterThan(1);
|
||||
expect(f.painted.map(p => p.text).join('')).toBe(text);
|
||||
for (const body of f.bodies) {
|
||||
expect(body.x).toBeGreaterThanOrEqual(0);
|
||||
expect(body.x + body.w).toBeLessThanOrEqual(160);
|
||||
expect(body.y).toBeGreaterThanOrEqual(0);
|
||||
expect(body.y + body.h).toBeLessThanOrEqual(300);
|
||||
}
|
||||
for (const line of f.painted) expect(line.text.includes('�')).toBe(false);
|
||||
});
|
||||
|
||||
test('character bubbles anchor above sprite heads before viewport scaling', () => {
|
||||
const f = fixture();
|
||||
f.root.RK.avatarVisuals = { resolve: () => ({ kind: 'char', allowed: true }) };
|
||||
const speaker = f.scene.entities[0];
|
||||
speaker.y = 4;
|
||||
const point = f.life._entityScreenPos(speaker, f.scene, 24, 'tiles');
|
||||
const spriteTop = (speaker.y + 1) * 24 - 1.8 * 24;
|
||||
expect(point.y).toBeLessThan(spriteTop);
|
||||
f.life._viewTransform = { left: 13, top: 17, scaleX: 2, scaleY: 0.5 };
|
||||
const scaled = f.life._entityScreenPos(speaker, f.scene, 24, 'tiles');
|
||||
expect(scaled).toEqual({ x: 13 + point.x * 2, y: 17 + point.y * 0.5 });
|
||||
f.life._viewTransform = null;
|
||||
expect(f.life._entityScreenPos(speaker, f.scene, 24, 'ascii').y).toBe(speaker.y * 24);
|
||||
f.life.showPlayerBubble('speaker', 'hello'); f.draw();
|
||||
expect(f.bodies.every(body => body.y + body.h < spriteTop)).toBe(true);
|
||||
});
|
||||
|
||||
test('actual default normalization never gives a cat a humanoid head position', () => {
|
||||
const f = fixture();
|
||||
for (const name of ['charSprites', 'charCustomize', 'avatarVisuals']) {
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/' + name + '.js'), 'utf8'), { window: f.root });
|
||||
}
|
||||
expect(f.root.RK.avatarVisuals.resolve({ avatar: null }, { projection: 'topdown' }).kind).toBe('char');
|
||||
const cat = { x: 2, y: 3, role: 'cat', avatar: null, appearance: { avatar: null } };
|
||||
const point = f.life._entityScreenPos(cat, f.scene, 24, 'tiles');
|
||||
expect(point.y).toBeCloseTo((cat.y + 0.2) * 24);
|
||||
expect(f.life._entityScreenPos({ ...cat, role: undefined, kind: 'cat' }, f.scene, 24, 'tiles')).toEqual(point);
|
||||
});
|
||||
|
||||
test('failed skins anchor at the Adventurer fallback head', () => {
|
||||
const f = fixture();
|
||||
const speaker = f.scene.entities[0];
|
||||
f.root.RK.avatarVisuals = { resolve: () => ({ kind: 'skin', allowed: true, appearance: { avatar: 'failed-skin' } }) };
|
||||
f.root.RK.SKINS = { 'failed-skin': { scale: 2.5 } };
|
||||
f.root.RK.skinSheetFailed = () => false;
|
||||
expect(f.life._entityScreenPos(speaker, f.scene, 24, 'tiles').y).toBeCloseTo((speaker.y - 1.5) * 24);
|
||||
f.root.RK.skinSheetFailed = () => true;
|
||||
expect(f.life._entityScreenPos(speaker, f.scene, 24, 'tiles').y).toBeCloseTo((speaker.y - 0.9) * 24);
|
||||
});
|
||||
|
||||
test('Iso bubbles use the selected character image height above its floor anchor', () => {
|
||||
const f = fixture();
|
||||
f.root.RK.avatarVisuals = { resolve: () => ({ allowed: true, character: { imageH: 110 } }) };
|
||||
const speaker = f.scene.entities[0];
|
||||
const point = f.life._entityScreenPos(speaker, f.scene, 24, 'iso');
|
||||
const floor = 28 + 184 + (speaker.x + speaker.y) * 42 / 2;
|
||||
expect(point.y).toBeCloseTo(floor + 42 * 0.95 - 110);
|
||||
});
|
||||
|
||||
test('departure removes old speech before the same handle can return', () => {
|
||||
const f = fixture();
|
||||
f.life.showPlayerBubble('speaker', 'old visit'); f.draw();
|
||||
f.scene.entities = []; f.draw();
|
||||
expect(Object.keys(f.life._realBubbles)).toEqual([]);
|
||||
f.scene.entities = [{ id: 'speaker', x: 2, y: 2 }]; f.draw();
|
||||
expect(f.painted).toEqual([]);
|
||||
});
|
||||
|
||||
test('offscreen speakers do not pin bubbles to a viewport edge; expiry still cleans up', () => {
|
||||
const f = fixture();
|
||||
f.life.showPlayerBubble('speaker', 'hello'); f.scene.entities[0].x = -20; f.draw();
|
||||
expect(f.painted).toEqual([]);
|
||||
f.advance(10000); f.draw();
|
||||
expect(Object.keys(f.life._realBubbles)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
|
||||
function client(wallet) {
|
||||
const html = fs.readFileSync(require.resolve('../html/tavern.html'), 'utf8');
|
||||
// Execute the page's actual chat wiring with a small DOM, without booting renderers/network.
|
||||
const script = html.slice(html.indexOf('// ---- Chat '), html.indexOf('// ---- Input '));
|
||||
const handlers = {};
|
||||
const elements = [];
|
||||
const form = {};
|
||||
const context = {
|
||||
socket: { on: (name, fn) => { handlers[name] = fn; }, emit: jest.fn() },
|
||||
window: { smirk: wallet }, state: { channel: 'tavern:main', occupants: [
|
||||
{ id: 'same-prefix-one', name: 'Same name' }, { id: 'same-prefix-two', name: 'Same name' }
|
||||
] }, tavernLife: { showPlayerBubble: jest.fn() },
|
||||
chatInput: { value: 'hello' }, chatForm: { addEventListener: (_, fn) => { form.submit = fn; } },
|
||||
chatLog: { appendChild: el => elements.push(el), childElementCount: 0 },
|
||||
document: { createElement: () => ({ firstChild: {}, insertAdjacentHTML() {} }) }
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(fs.readFileSync(require.resolve('../html/js/smirkChatSign.js'), 'utf8'), context);
|
||||
vm.runInContext(script, context);
|
||||
return { ...context, handlers, form, elements };
|
||||
}
|
||||
|
||||
test('only room speech targets an exact occupant, never global names/prefixes or history', () => {
|
||||
const c = client();
|
||||
c.handlers.chat_broadcast({ username: 'Same name', message: 'remote', publicId: 'same-prefix' });
|
||||
c.handlers.chat_history({ messages: [{ username: 'Same name', message: 'old' }] });
|
||||
expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled();
|
||||
c.handlers.tavern_speech({ occupantId: 'same-prefix', text: 'guess' });
|
||||
expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled();
|
||||
c.handlers.tavern_speech({ occupantId: 'same-prefix-two', text: '<hello> & welcome' });
|
||||
expect(c.tavernLife.showPlayerBubble).toHaveBeenCalledWith('same-prefix-two', '<hello> & welcome');
|
||||
});
|
||||
|
||||
test('a declined signature never becomes unsigned chat or an optimistic bubble', async () => {
|
||||
const c = client({ signNostrEvent: async () => { throw Object.assign(new Error('declined'), { code: 'USER_REJECTED' }); } });
|
||||
c.form.submit({ preventDefault() {} });
|
||||
await new Promise(setImmediate);
|
||||
expect(c.socket.emit).not.toHaveBeenCalled();
|
||||
expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled();
|
||||
expect(c.elements.some(el => /not sent/i.test(el.textContent))).toBe(true);
|
||||
});
|
||||
|
||||
test('without a signer ordinary chat still waits for server acceptance', () => {
|
||||
const c = client();
|
||||
c.form.submit({ preventDefault() {} });
|
||||
expect(c.socket.emit).toHaveBeenCalledWith('tavern_chat', { text: 'hello' });
|
||||
expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
test('server moderation/verification refusal is visible without speech', () => {
|
||||
const c = client();
|
||||
c.handlers.status_update({ type: 'error', message: 'Signed message could not be verified.' });
|
||||
expect(c.elements.some(el => /verified/.test(el.textContent))).toBe(true);
|
||||
expect(c.tavernLife.showPlayerBubble).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
test('actual Tavern join wires 3D bubble projection to the current renderer, with safe fallback', () => {
|
||||
const html = fs.readFileSync(require.resolve('../html/tavern.html'), 'utf8');
|
||||
const script = html.slice(html.indexOf("socket.on('tavern_joined'"), html.indexOf("socket.on('blockheight'"));
|
||||
let joined;
|
||||
let options;
|
||||
const element = { classList: { add() {}, remove() {} }, setAttribute() {} };
|
||||
const context = {
|
||||
socket: { on: (_, fn) => { joined = fn; } }, state: {}, currentScene: {}, currentMode: '3d',
|
||||
currentRenderer: { projectEntityHead: jest.fn(() => ({ x: 50, y: 70 })) },
|
||||
RK: { loadMode: () => '3d', TavernLife: function (_host, _scene, _cell, opts) {
|
||||
options = opts;
|
||||
return { setMode() {}, spawn() {}, welcomeBubbles() {} };
|
||||
} },
|
||||
clearJoinAttempt() {}, applyFull() {}, rebuildScene() {}, buildModebar() {}, setMode() {},
|
||||
mountChainAmbience() {}, startRafLoop() {}, setStatus() {},
|
||||
joinPanel: element, modebar: element, stageEl: element, chatPanel: element,
|
||||
tavernDpad: element, movementHint: element, watchGamesBtn: element
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(script, context);
|
||||
joined({ you: 'speaker', state: {} });
|
||||
expect(options.projectEntityHead({ id: 'speaker' })).toEqual({ x: 50, y: 70 });
|
||||
expect(context.currentRenderer.projectEntityHead).toHaveBeenCalledWith('speaker');
|
||||
const replacement = { projectEntityHead: jest.fn(() => null) };
|
||||
context.currentRenderer = replacement;
|
||||
expect(options.projectEntityHead({ id: 'speaker' })).toBeNull();
|
||||
expect(replacement.projectEntityHead).toHaveBeenCalledWith('speaker');
|
||||
context.currentRenderer = {};
|
||||
expect(options.projectEntityHead({ id: 'speaker' })).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const sceneApi = require('../html/js/render/sceneModel');
|
||||
const { TAVERN_LAYOUT } = require('../src/multiplayer/tavernMap');
|
||||
|
||||
function loadTavernLife() {
|
||||
function CanvasRenderingContext2D() {}
|
||||
const browser = {
|
||||
CanvasRenderingContext2D,
|
||||
requestAnimationFrame: () => 1,
|
||||
cancelAnimationFrame: () => {},
|
||||
document: { createElement: () => ({ getContext: () => null }) }
|
||||
};
|
||||
vm.runInNewContext(fs.readFileSync(require.resolve('../html/js/render/tavernLife.js'), 'utf8'), { window: browser });
|
||||
return browser.RK.TavernLife;
|
||||
}
|
||||
|
||||
function makeScene(layout = TAVERN_LAYOUT) {
|
||||
return sceneApi.sceneFromTavern({
|
||||
cols: layout[0].length,
|
||||
rows: layout.length,
|
||||
layout,
|
||||
occupants: []
|
||||
});
|
||||
}
|
||||
|
||||
function createLife(layout = TAVERN_LAYOUT, random = () => 0.5) {
|
||||
const scene = makeScene(layout);
|
||||
let now = 1;
|
||||
const host = { querySelector: () => null, style: {}, appendChild: () => {} };
|
||||
const TavernLife = loadTavernLife();
|
||||
const life = new TavernLife(host, () => scene, () => 24, { now: () => now, random });
|
||||
life.spawn();
|
||||
life.injectInto(scene);
|
||||
return {
|
||||
life,
|
||||
scene,
|
||||
advance(ms) {
|
||||
now += ms;
|
||||
life.update(scene, 24, 'tiles');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function smallDesignedRoom(blockStaffLane = false) {
|
||||
const rows = [
|
||||
'########',
|
||||
blockStaffLane ? '#.hhhh.#' : '#......#',
|
||||
'#.=====#',
|
||||
'#......#',
|
||||
'#..T...#',
|
||||
'#..c...#',
|
||||
'#......#',
|
||||
'########'
|
||||
];
|
||||
return rows;
|
||||
}
|
||||
|
||||
describe('tavern ambient life', () => {
|
||||
test('the authored bar lane is one connected walkable staff route', () => {
|
||||
const scene = makeScene();
|
||||
const barY = scene.grid.findIndex(row => row.includes('bar'));
|
||||
const laneY = barY - 1;
|
||||
const counterXs = scene.grid[barY].map((tile, x) => tile === 'bar' ? x : -1).filter(x => x >= 0);
|
||||
const firstCounter = Math.min(...counterXs);
|
||||
const lastCounter = Math.max(...counterXs);
|
||||
const lane = [];
|
||||
for (let x = 0; x < scene.cols; x++) {
|
||||
if (x > firstCounter && x < lastCounter && scene.grid[laneY][x] === 'floor') lane.push({ x, y: laneY });
|
||||
}
|
||||
expect(lane.length).toBeGreaterThan(1);
|
||||
const seen = new Set();
|
||||
const queue = [lane[0]];
|
||||
while (queue.length) {
|
||||
const point = queue.shift();
|
||||
const key = `${point.x},${point.y}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
for (const next of [
|
||||
{ x: point.x - 1, y: point.y }, { x: point.x + 1, y: point.y },
|
||||
{ x: point.x, y: point.y - 1 }, { x: point.x, y: point.y + 1 }
|
||||
]) {
|
||||
if (next.x >= 0 && next.x < scene.cols && next.y >= 0 && next.y < scene.rows &&
|
||||
!seen.has(`${next.x},${next.y}`) && scene.legend[scene.grid[next.y][next.x]]?.solid === false) {
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(lane.every(point => seen.has(`${point.x},${point.y}`))).toBe(true);
|
||||
expect(scene.grid[barY].filter(tile => tile === 'bar').length).toBeGreaterThan(lane.length);
|
||||
});
|
||||
|
||||
test('starts patrons on real chairs, keeps the barkeep in the staff lane, and routes the waitress between tables', () => {
|
||||
const { life, scene, advance } = createLife();
|
||||
const patrons = life.npcs.filter(npc => npc.role === 'patron');
|
||||
const bartender = life.npcs.find(npc => npc.role === 'bartender');
|
||||
const waitress = life.npcs.find(npc => npc.role === 'waitress');
|
||||
const tableCells = [];
|
||||
for (let y = 0; y < scene.rows; y++) {
|
||||
for (let x = 0; x < scene.cols; x++) {
|
||||
if (scene.grid[y][x] === 'table') tableCells.push({ x, y });
|
||||
}
|
||||
}
|
||||
expect(patrons).toHaveLength(4);
|
||||
expect(new Set(patrons.map(npc => `${npc.x},${npc.y}`)).size).toBe(patrons.length);
|
||||
for (const patron of patrons) {
|
||||
expect(scene.grid[patron.y][patron.x]).toBe('chair');
|
||||
expect(tableCells.some(table => table.x === patron.homeX && table.y + 1 === patron.homeY)).toBe(true);
|
||||
expect(patron.phase).toBe('seated');
|
||||
}
|
||||
expect(bartender).toBeDefined();
|
||||
expect(life._isRoleCell(bartender, scene, bartender.x, bartender.y)).toBe(true);
|
||||
expect(waitress).toBeDefined();
|
||||
|
||||
const barY = scene.grid.findIndex(row => row.includes('bar'));
|
||||
const laneY = barY - 1;
|
||||
const lane = scene.grid[laneY].map((tile, x) => tile === 'floor' ? x : -1).filter(x => x >= 0);
|
||||
const bartenderVisited = new Set();
|
||||
const waitressVisited = new Set();
|
||||
const patronMoved = new Map(patrons.map(npc => [npc.id, false]));
|
||||
const patronSeatedTicks = new Map(patrons.map(npc => [npc.id, 0]));
|
||||
const outingStarts = [];
|
||||
const outingReturns = [];
|
||||
let activeExcursionTicks = 0;
|
||||
let previous = new Map(life.npcs.map(npc => [npc.id, { x: npc.x, y: npc.y }]));
|
||||
|
||||
for (let i = 0; i < 360; i++) {
|
||||
advance(1000);
|
||||
const activePatrons = patrons.filter(npc => npc.phase !== 'seated');
|
||||
expect(activePatrons.length).toBeLessThanOrEqual(1);
|
||||
if (activePatrons.length) activeExcursionTicks++;
|
||||
for (const npc of life.npcs) {
|
||||
const old = previous.get(npc.id);
|
||||
const distance = Math.abs(npc.x - old.x) + Math.abs(npc.y - old.y);
|
||||
expect(distance).toBeLessThanOrEqual(1);
|
||||
if (distance) expect(distance).toBe(1);
|
||||
if (npc.role === 'bartender') {
|
||||
expect(npc.y).toBe(laneY);
|
||||
expect(lane).toContain(npc.x);
|
||||
bartenderVisited.add(`${npc.x},${npc.y}`);
|
||||
} else if (npc.role === 'patron') {
|
||||
expect(Math.abs(npc.x - npc.homeX) + Math.abs(npc.y - npc.homeY)).toBeLessThanOrEqual(3);
|
||||
expect(['chair', 'floor']).toContain(scene.grid[npc.y][npc.x]);
|
||||
if (distance) patronMoved.set(npc.id, true);
|
||||
if (npc.phase === 'seated') {
|
||||
expect(npc.x).toBe(npc.homeX);
|
||||
expect(npc.y).toBe(npc.homeY);
|
||||
patronSeatedTicks.set(npc.id, patronSeatedTicks.get(npc.id) + 1);
|
||||
}
|
||||
if (npc.phase === 'outbound' && !previous.get(`${npc.id}:outing`)) {
|
||||
outingStarts.push((i + 1) * 1000);
|
||||
}
|
||||
const wasReturning = previous.get(`${npc.id}:returning`) === true;
|
||||
if (wasReturning && npc.phase === 'seated') outingReturns.push((i + 1) * 1000);
|
||||
previous.set(`${npc.id}:outing`, npc.phase === 'outbound' || npc.phase === 'pausing' || npc.phase === 'returning');
|
||||
previous.set(`${npc.id}:returning`, npc.phase === 'returning');
|
||||
} else if (npc.role === 'waitress') {
|
||||
expect(scene.grid[npc.y][npc.x]).toBe('floor');
|
||||
expect(npc.y).toBeGreaterThanOrEqual(3);
|
||||
waitressVisited.add(`${npc.x},${npc.y}`);
|
||||
}
|
||||
previous.set(npc.id, { x: npc.x, y: npc.y });
|
||||
}
|
||||
}
|
||||
|
||||
expect(bartenderVisited.size).toBeGreaterThan(1);
|
||||
expect(waitressVisited.size).toBeGreaterThan(2);
|
||||
expect([...patronMoved.values()].some(Boolean)).toBe(true);
|
||||
expect(outingReturns.length).toBeGreaterThanOrEqual(1);
|
||||
expect(outingStarts.length).toBeGreaterThanOrEqual(outingReturns.length);
|
||||
for (let i = 1; i < outingStarts.length; i++) {
|
||||
const previousReturn = outingReturns.filter(time => time < outingStarts[i]).at(-1);
|
||||
expect(previousReturn).toBeDefined();
|
||||
expect(outingStarts[i] - previousReturn).toBeGreaterThanOrEqual(45000);
|
||||
}
|
||||
expect(activeExcursionTicks).toBeLessThan(360 * 0.2);
|
||||
for (const patron of patrons) {
|
||||
expect(patronSeatedTicks.get(patron.id)).toBeGreaterThan(360 * 0.75);
|
||||
}
|
||||
expect(patrons.some(npc => npc.phase === 'seated' && npc.x === npc.homeX && npc.y === npc.homeY)).toBe(true);
|
||||
});
|
||||
|
||||
test('leaves designed rooms without semantic tables and chairs actor-free', () => {
|
||||
const layout = TAVERN_LAYOUT.map(row => row.replace(/T|c/g, '.'));
|
||||
const { life } = createLife(layout);
|
||||
expect(life.npcs).toEqual([]);
|
||||
expect(life._spawned).toBe(false);
|
||||
});
|
||||
|
||||
test('uses semantic seats and bar space in a compact designed room', () => {
|
||||
const { life, scene } = createLife(smallDesignedRoom());
|
||||
expect(life.npcs.map(npc => npc.role)).toEqual(['bartender', 'patron', 'waitress', 'cat']);
|
||||
const bartender = life.npcs[0];
|
||||
const patron = life.npcs.find(npc => npc.role === 'patron');
|
||||
const waitress = life.npcs.find(npc => npc.role === 'waitress');
|
||||
expect(scene.grid[bartender.y][bartender.x]).toBe('floor');
|
||||
expect(bartender.roleArea.minX).toBeLessThanOrEqual(bartender.x);
|
||||
expect(bartender.roleArea.maxX).toBeGreaterThanOrEqual(bartender.x);
|
||||
expect(scene.grid[patron.y][patron.x]).toBe('chair');
|
||||
expect(scene.grid[waitress.y][waitress.x]).toBe('floor');
|
||||
});
|
||||
|
||||
test('does not invent actors when a semantic bar has no walkable staff lane', () => {
|
||||
const { life } = createLife(smallDesignedRoom(true));
|
||||
expect(life.npcs).toEqual([]);
|
||||
expect(life._spawned).toBe(false);
|
||||
});
|
||||
|
||||
test('does not spawn a barkeep on walkable non-floor staff tiles', () => {
|
||||
const layout = smallDesignedRoom().slice();
|
||||
layout[1] = '#.rrrr.#';
|
||||
const { life } = createLife(layout);
|
||||
expect(life.npcs).toEqual([]);
|
||||
expect(life._spawned).toBe(false);
|
||||
});
|
||||
|
||||
test('preserves player-bubble identity and uses an optional viewport-relative 3D head projection', () => {
|
||||
const scene = makeScene();
|
||||
let now = 500;
|
||||
const TavernLife = loadTavernLife();
|
||||
const life = new TavernLife({}, () => scene, null, {
|
||||
now: () => now,
|
||||
projectEntityHead: entity => ({ x: entity.x + 7, y: entity.y + 11 })
|
||||
});
|
||||
life.showPlayerBubble('socket-1', 'hello');
|
||||
expect(life._realBubbles['socket-1']).toEqual({ text: 'hello', until: 4700 });
|
||||
expect(life._entityScreenPos({ x: 3, y: 4 }, scene, 24, '3d')).toEqual({ x: 10, y: 15 });
|
||||
now = 1000;
|
||||
life.showPlayerBubble('socket-1', 'again');
|
||||
expect(life._realBubbles['socket-1'].until).toBe(5200);
|
||||
});
|
||||
});
|
||||
@@ -123,7 +123,8 @@ describe('TavernManager', () => {
|
||||
const mgr = new TavernManager({ io });
|
||||
const s = makeFakeSocket('a', io);
|
||||
await mgr.join(s, { appearance: { avatar: 'monero-knight' } });
|
||||
expect(mgr.room.getOccupant('a').avatar).toBe('default');
|
||||
expect(mgr.room.getOccupant('a').avatar).not.toBe('monero-knight');
|
||||
expect(TavernManager.AVATARS).toContain(mgr.room.getOccupant('a').avatar);
|
||||
|
||||
const paid = new TavernManager({
|
||||
io,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
const TavernManager = require('../src/network/tavernManager');
|
||||
const ChatHandler = require('../src/network/chatHandler');
|
||||
const ChatHistoryManager = require('../src/network/chatHistoryManager');
|
||||
const SocketChatProvider = require('../src/network/chat/SocketChatProvider');
|
||||
const { loadNostrTools } = require('../src/utils/nostrLoader');
|
||||
const { finalizeEvent } = loadNostrTools();
|
||||
|
||||
function deferred() { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; }
|
||||
function fixture({ db = null, moderation = null, provider = null } = {}) {
|
||||
const io = { emitted: [], emit(event, payload) { this.emitted.push({ event, payload, channel: null }); },
|
||||
to(channel) { return { emit: (event, payload) => this.emitted.push({ event, payload, channel }) }; } };
|
||||
const socket = { id: 'shared-prefix-speaker', emit: jest.fn(), join() {}, leave() {} };
|
||||
const sessions = new Map([[socket.id, { id: 7 }]]);
|
||||
const gameModeManager = { db, sessionManager: { sessions }, getOrCreateUser: jest.fn(async () => ({ id: 7 })) };
|
||||
const history = new ChatHistoryManager({ db });
|
||||
const local = provider || new SocketChatProvider({ io });
|
||||
const manager = new TavernManager({ io, globalChatProvider: local, chatModeration: moderation || {
|
||||
sessionManager: gameModeManager.sessionManager, chatHistory: history, getOrCreateUser: gameModeManager.getOrCreateUser
|
||||
} });
|
||||
manager.enabled = true;
|
||||
const handler = new ChatHandler({ io, db, gameModeManager, debugManager: {}, rateLimiter: { checkLimit: async () => ({ allowed: true }), recordAttempt: async () => {} }, broadcastManager: { sendStatusUpdate: jest.fn() } });
|
||||
handler.chatProvider = local;
|
||||
return { io, socket, manager, handler, sessions, speech: () => io.emitted.filter(e => e.event === 'tavern_speech') };
|
||||
}
|
||||
const secret = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
|
||||
function signed(text = 'Signed <hello> & welcome') {
|
||||
return finalizeEvent({ kind: 1, created_at: Math.floor(Date.now() / 1000), content: text, tags: [['t', 'wowngeon-global']] }, secret);
|
||||
}
|
||||
function database({ banned = false, banFailure = false } = {}) {
|
||||
return { query: jest.fn(async sql => {
|
||||
if (sql.includes('SELECT chat_banned')) {
|
||||
if (banFailure) throw new Error('fixture moderation unavailable');
|
||||
return { rows: [{ chat_banned: banned }] };
|
||||
}
|
||||
return { rows: [{ smirk_public_key: signed().pubkey, display_name: 'Same name' }] };
|
||||
}) };
|
||||
}
|
||||
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
test('accepted ordinary speech is room-scoped, exact occupant, plain text; global delivery has no raw ID', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Same name' });
|
||||
await f.manager.join({ ...f.socket, id: 'shared-prefix-other' }, { name: 'Same name' });
|
||||
await f.manager.chat(f.socket, { text: '<hello> & welcome' });
|
||||
expect(f.speech()).toEqual([{ channel: f.manager.channel, event: 'tavern_speech', payload: {
|
||||
occupantId: f.socket.id, text: '<hello> & welcome'
|
||||
} }]);
|
||||
const global = f.io.emitted.find(e => e.event === 'chat_broadcast');
|
||||
expect(global.channel).toBeNull();
|
||||
expect(global.payload.message).toBe('<hello> & welcome');
|
||||
expect(JSON.stringify(global.payload)).not.toContain(f.socket.id);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('publish acceptance is awaited; leave/rejoin while publishing cannot speak for the replacement', async () => {
|
||||
const pending = deferred();
|
||||
let deliver;
|
||||
const f = fixture({ db: database(), provider: { publish: jest.fn(message => { deliver = message.onLocalDelivery; return pending.promise; }) } });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Same name' });
|
||||
const sending = f.manager.chat(f.socket, { text: 'stale' });
|
||||
await new Promise(setImmediate);
|
||||
expect(f.speech()).toEqual([]);
|
||||
f.manager.leave(f.socket);
|
||||
await f.manager.join(f.socket, { name: 'Same name' });
|
||||
deliver();
|
||||
pending.resolve();
|
||||
await sending;
|
||||
expect(f.speech()).toEqual([]);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test.each(['banned', 'ban database failure', 'user lookup failure', 'publish failure', 'rate limited', 'rate lookup failure'])(
|
||||
'ordinary rejected message has no speech: %s', async reason => {
|
||||
const f = fixture({ db: database({ banned: reason === 'banned', banFailure: reason === 'ban database failure' }) });
|
||||
jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
if (reason === 'user lookup failure') f.manager.chatModeration.getOrCreateUser = async () => { throw new Error('lookup unavailable'); };
|
||||
if (reason === 'publish failure') f.manager.globalChatProvider.publish = async () => { throw new Error('publish unavailable'); };
|
||||
if (reason === 'rate lookup failure') f.manager.chatModeration.rateLimiter = { checkLimit: async () => { throw new Error('limiter unavailable'); } };
|
||||
if (reason === 'rate limited') f.manager.chatModeration.rateLimiter = { checkLimit: async () => ({ allowed: false }) };
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
await f.manager.chat(f.socket, { text: 'not accepted' }).catch(() => {});
|
||||
expect(f.speech()).toEqual([]);
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('valid signed speech uses authenticated content and the current room occupant', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Different avatar label' });
|
||||
await f.handler.handleSignedChatMessage(f.socket, { event: signed() }, f.manager.captureSpeech(f.socket));
|
||||
expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id, text: signed().content } });
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test.each(['bad signature', 'banned', 'ban database failure', 'session changed', 'left room', 'publish failure', 'rate limited'])(
|
||||
'signed rejection/stale acceptance has no bubble: %s', async reason => {
|
||||
const f = fixture({ db: database({ banned: reason === 'banned', banFailure: reason === 'ban database failure' }) });
|
||||
jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
if (reason === 'rate limited') f.handler.rateLimiter = { checkLimit: async () => ({ allowed: false }) };
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const accept = f.manager.captureSpeech(f.socket);
|
||||
if (reason === 'session changed' || reason === 'left room' || reason === 'publish failure') {
|
||||
f.handler.chatProvider.relaySignedEvent = async (message) => {
|
||||
if (reason === 'session changed') f.sessions.set(f.socket.id, { id: 9 });
|
||||
if (reason === 'left room') { f.manager.leave(f.socket); await f.manager.join(f.socket, { name: 'Speaker' }); }
|
||||
if (reason === 'publish failure') throw new Error('publish unavailable');
|
||||
message.onLocalDelivery();
|
||||
};
|
||||
}
|
||||
const event = signed();
|
||||
if (reason === 'bad signature') event.content += 'tampered';
|
||||
await f.handler.handleSignedChatMessage(f.socket, { event }, accept);
|
||||
expect(f.speech()).toEqual([]);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
|
||||
test.each(['chat message', 'chat_signed'])('real socket dispatch binds current room speech: %s', async eventName => {
|
||||
const SocketHandlers = require('../src/network/socketHandlers');
|
||||
const f = fixture({ db: database() });
|
||||
const callbacks = new Map();
|
||||
f.socket.on = (event, fn) => callbacks.set(event, fn);
|
||||
const dispatch = Object.assign(Object.create(SocketHandlers.prototype), {
|
||||
connectionHandler: { handleConnection: async () => ({}) },
|
||||
_emitFairnessOffer() {}, _emitIdentity: async () => {},
|
||||
tavernManager: f.manager, chatHandler: f.handler
|
||||
});
|
||||
f.handler.addressManager = { detectInText: () => null };
|
||||
f.handler.sendChatHistoryToUser = async () => {};
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
await dispatch.handleConnection(f.socket);
|
||||
callbacks.get(eventName)(eventName === 'chat_signed' ? { event: signed() } : 'ordinary hello');
|
||||
await new Promise(setImmediate);
|
||||
expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id } });
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('session replacement during ordinary publish suppresses the captured bubble', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
f.manager.globalChatProvider.publish = async message => { f.sessions.set(f.socket.id, { id: 8 }); message.onLocalDelivery(); };
|
||||
await f.manager.chat(f.socket, { text: 'old session' });
|
||||
expect(f.speech()).toEqual([]);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('leaving during moderation cannot publish for a new visit on the same socket', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
f.manager.chatModeration.getOrCreateUser = async () => {
|
||||
f.manager.leave(f.socket);
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
return { id: 7 };
|
||||
};
|
||||
await f.manager.chat(f.socket, { text: 'old visit' });
|
||||
expect(f.speech()).toEqual([]);
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test.each([undefined, null, 0, 'false'])('strict real ban reader refuses unknown/malformed status: %p', async chat_banned => {
|
||||
const history = new ChatHistoryManager({ db: { query: async () => ({ rows: [{ chat_banned }] }) } });
|
||||
await expect(history.isUserChatBanned(7, { strict: true })).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('ephemeral Tavern without global moderation still delivers accepted room speech', async () => {
|
||||
const f = fixture();
|
||||
f.manager.globalChatProvider = null;
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Guest' });
|
||||
await f.manager.chat(f.socket, { text: 'local only' });
|
||||
expect(f.speech()[0]).toMatchObject({ channel: f.manager.channel, payload: { occupantId: f.socket.id, text: 'local only' } });
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
|
||||
test('deferred moderation admits only one concurrent send and one accepted bubble', async () => {
|
||||
const pending = deferred();
|
||||
const f = fixture({ db: database() });
|
||||
const lookup = jest.fn(() => pending.promise);
|
||||
f.manager.chatModeration.getOrCreateUser = lookup;
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const first = f.manager.chat(f.socket, { text: 'first' });
|
||||
const second = f.manager.chat(f.socket, { text: 'second' });
|
||||
await second;
|
||||
expect(lookup).toHaveBeenCalledTimes(1);
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]);
|
||||
pending.resolve({ id: 7 });
|
||||
await first;
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast').map(e => e.payload.message)).toEqual(['first']);
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['first']);
|
||||
expect(f.manager._chatInFlight.size).toBe(0);
|
||||
} finally { pending.resolve({ id: 7 }); f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('session switch during deferred moderation refuses before publishing', async () => {
|
||||
const pending = deferred();
|
||||
const f = fixture({ db: database() });
|
||||
f.manager.chatModeration.getOrCreateUser = () => pending.promise;
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const sending = f.manager.chat(f.socket, { text: 'stale account' });
|
||||
f.sessions.set(f.socket.id, { id: 8 });
|
||||
pending.resolve({ id: 7 });
|
||||
await sending;
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]);
|
||||
expect(f.speech()).toEqual([]);
|
||||
expect(f.manager._chatInFlight.size).toBe(0);
|
||||
} finally { pending.resolve({ id: 7 }); f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('failed moderation releases admission without suppressing an explicit immediate retry', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
const lookup = jest.fn().mockRejectedValueOnce(new Error('lookup unavailable')).mockResolvedValue({ id: 7 });
|
||||
f.manager.chatModeration.getOrCreateUser = lookup;
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
await f.manager.chat(f.socket, { text: 'refused' });
|
||||
await f.manager.chat(f.socket, { text: 'explicit retry' });
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['explicit retry']);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test.each(['ordinary', 'signed'])('local %s speech does not wait for pending/rejected relay or duplicate later', async kind => {
|
||||
const NostrChatProvider = require('../src/network/chat/NostrChatProvider');
|
||||
let rejectRelay;
|
||||
const relay = new Promise((_, reject) => { rejectRelay = reject; });
|
||||
relay.catch(() => {});
|
||||
const f = fixture({ db: database() });
|
||||
const transport = { publish: jest.fn(() => relay) };
|
||||
const provider = new NostrChatProvider({ local: new SocketChatProvider({ io: f.io }), transport,
|
||||
signer: { sign: template => ({ ...template, id: 'synthetic-bridge-event' }) } });
|
||||
f.manager.globalChatProvider = provider;
|
||||
f.handler.chatProvider = provider;
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const sending = kind === 'signed'
|
||||
? f.handler.handleSignedChatMessage(f.socket, { event: signed() }, f.manager.captureSpeech(f.socket))
|
||||
: f.manager.chat(f.socket, { text: 'immediate local speech' });
|
||||
await new Promise(setImmediate);
|
||||
expect(transport.publish).toHaveBeenCalled();
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toHaveLength(1);
|
||||
expect(f.speech()).toHaveLength(1);
|
||||
const localSpeech = f.speech()[0];
|
||||
rejectRelay(new Error('disposable relay refuses'));
|
||||
await sending;
|
||||
expect(f.speech()).toEqual([localSpeech]);
|
||||
} finally { rejectRelay(new Error('dispose pending relay')); f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('ordinary global session switch during deferred real moderation refuses before local delivery', async () => {
|
||||
const pending = deferred();
|
||||
const f = fixture({ db: database() });
|
||||
f.handler.gameModeManager.getOrCreateUser = () => pending.promise;
|
||||
f.handler.addressManager = { detectInText: () => null };
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const sending = f.handler.handleChatMessage(f.socket, 'stale global message', { acceptedSpeech: f.manager.captureSpeech(f.socket) });
|
||||
await new Promise(setImmediate);
|
||||
f.sessions.set(f.socket.id, { id: 8 });
|
||||
pending.resolve({ id: 7 });
|
||||
await sending;
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast')).toEqual([]);
|
||||
expect(f.speech()).toEqual([]);
|
||||
} finally { pending.resolve({ id: 7 }); f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('accepted room capability is single-use, including stale callback then restored session', async () => {
|
||||
const f = fixture({ db: database() });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const accepted = f.manager.captureSpeech(f.socket);
|
||||
accepted('first');
|
||||
accepted('duplicate');
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['first']);
|
||||
const stale = f.manager.captureSpeech(f.socket);
|
||||
const originalSession = f.sessions.get(f.socket.id);
|
||||
f.sessions.set(f.socket.id, { id: 8 });
|
||||
stale('stale');
|
||||
f.sessions.set(f.socket.id, originalSession);
|
||||
stale('cannot resurrect');
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['first']);
|
||||
} finally { f.handler.shutdown(); }
|
||||
});
|
||||
|
||||
test('an earlier pending relay cannot release a later send admission on the same visit', async () => {
|
||||
const NostrChatProvider = require('../src/network/chat/NostrChatProvider');
|
||||
const relay = deferred();
|
||||
const moderation = deferred();
|
||||
const f = fixture({ db: database() });
|
||||
const clock = jest.spyOn(Date, 'now').mockReturnValue(1800000000000);
|
||||
const lookup = jest.fn().mockResolvedValueOnce({ id: 7 }).mockImplementation(() => moderation.promise);
|
||||
f.manager.chatModeration.getOrCreateUser = lookup;
|
||||
f.manager.globalChatProvider = new NostrChatProvider({ local: new SocketChatProvider({ io: f.io }),
|
||||
transport: { publish: jest.fn().mockImplementationOnce(() => relay.promise).mockResolvedValue() },
|
||||
signer: { sign: template => ({ ...template, id: 'synthetic-bridge-event' }) } });
|
||||
try {
|
||||
await f.manager.join(f.socket, { name: 'Speaker' });
|
||||
const first = f.manager.chat(f.socket, { text: 'first' });
|
||||
await new Promise(setImmediate);
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['first']);
|
||||
clock.mockReturnValue(1800000000000 + f.manager.chatCooldownMs + 1);
|
||||
const second = f.manager.chat(f.socket, { text: 'second' });
|
||||
expect(lookup).toHaveBeenCalledTimes(2);
|
||||
relay.resolve();
|
||||
await first;
|
||||
const third = f.manager.chat(f.socket, { text: 'third' });
|
||||
await new Promise(setImmediate);
|
||||
expect(lookup).toHaveBeenCalledTimes(2);
|
||||
moderation.resolve({ id: 7 });
|
||||
await Promise.all([second, third]);
|
||||
expect(f.io.emitted.filter(e => e.event === 'chat_broadcast').map(e => e.payload.message)).toEqual(['first', 'second']);
|
||||
expect(f.speech().map(e => e.payload.text)).toEqual(['first', 'second']);
|
||||
} finally { relay.resolve(); moderation.resolve({ id: 7 }); f.handler.shutdown(); clock.mockRestore(); }
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
|
||||
function fixture() {
|
||||
const root = { RK: {} };
|
||||
vm.runInNewContext(fs.readFileSync(path.join(__dirname, '../html/js/render/threeRenderer.js'), 'utf8'), { window: root });
|
||||
const renderer = Object.create(root.RK.ThreeRenderer.prototype);
|
||||
const projected = { x: 0, y: 0, z: 0 };
|
||||
const local = [];
|
||||
renderer.THREE = { Vector3: class {
|
||||
constructor(x, y, z) { this.x = x; this.y = y; this.z = z; }
|
||||
project(camera) { camera.observedWorld = [this.x, this.y, this.z]; Object.assign(this, projected); return this; }
|
||||
} };
|
||||
renderer.host = { getBoundingClientRect: () => ({ left: 100, top: 60, width: 600, height: 400 }) };
|
||||
renderer.renderer = { domElement: { width: 1200, height: 800,
|
||||
getBoundingClientRect: () => ({ left: 110, top: 70, width: 500, height: 300 }) } };
|
||||
renderer.camera = { updateMatrixWorld: jest.fn() };
|
||||
renderer.entities = { speaker: { obj: {
|
||||
position: { x: 3, y: 0.1, z: -2 },
|
||||
updateWorldMatrix: jest.fn(),
|
||||
localToWorld(v) { local.push([v.x, v.y, v.z]); v.x += this.position.x; v.y += this.position.y; v.z += this.position.z; return v; }
|
||||
} } };
|
||||
return { renderer, projected, local };
|
||||
}
|
||||
|
||||
describe('Tavern 3D speech projection', () => {
|
||||
test('uses the current mesh position and CSS canvas bounds without device-pixel multiplication', () => {
|
||||
const { renderer, local } = fixture();
|
||||
expect(renderer.projectEntityHead('speaker')).toEqual({ x: 260, y: 160 });
|
||||
expect(local).toEqual([[0, 2, 0]]);
|
||||
expect(renderer.camera.observedWorld).toEqual([3, 2.1, -2]);
|
||||
expect(renderer.entities.speaker.obj.updateWorldMatrix).toHaveBeenCalledWith(true, false);
|
||||
});
|
||||
|
||||
test('tracks the live camera projection and resized viewport', () => {
|
||||
const { renderer, projected } = fixture();
|
||||
projected.x = 0.5; projected.y = -0.5;
|
||||
expect(renderer.projectEntityHead('speaker')).toEqual({ x: 385, y: 235 });
|
||||
renderer.renderer.domElement.getBoundingClientRect = () => ({ left: 100, top: 60, width: 300, height: 200 });
|
||||
expect(renderer.projectEntityHead('speaker')).toEqual({ x: 225, y: 150 });
|
||||
});
|
||||
|
||||
test.each(['x', 'y', 'z'])('suppresses an avatar outside the %s clip plane', axis => {
|
||||
const { renderer, projected } = fixture();
|
||||
projected[axis] = 1.01;
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
projected[axis] = -1.01;
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
projected[axis] = NaN;
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
});
|
||||
|
||||
test('suppresses points outside the host even when the canvas is panned', () => {
|
||||
const { renderer } = fixture();
|
||||
renderer.renderer.domElement.getBoundingClientRect = () => ({ left: -500, top: 60, width: 500, height: 300 });
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
});
|
||||
|
||||
test('removed, hidden, destroyed, and zero-size renderers have no bubble position', () => {
|
||||
const { renderer } = fixture();
|
||||
expect(renderer.projectEntityHead('absent')).toBeNull();
|
||||
expect(renderer.projectEntityHead('__proto__')).toBeNull();
|
||||
renderer.entities.speaker.obj.visible = false;
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
renderer.entities.speaker.obj.visible = true;
|
||||
renderer.host.getBoundingClientRect = () => ({ left: 0, top: 0, width: 0, height: 0 });
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
renderer._destroyed = true;
|
||||
expect(renderer.projectEntityHead('speaker')).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user