Skip to content

Commit 56e98c4

Browse files
santi1584claude
andcommitted
fix(logout): report connection loss after a refused logout (#493)
The logout flag was only cleared on session teardown, so if the server refused the logout (no-logout tile, fight, or an onLogout script) a later unrelated socket loss was treated as deliberate and the TV's connection-loss notice was suppressed. Scope the intent to the logout exchange: Jamera's Protocol76::logout either closes the connection in the same dispatcher task or refuses and keeps the session alive (script refusals may send nothing). Any inbound frame received more than one round trip after the request was therefore sent after a refusal, so the intent lapses on the first frame after a 5 s grace window (Jamera pings idle players every 5 s). PacketDispatcher's nextFrame now supports several concurrent waiters so this does not displace the TV resume probe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LSWCoMs13M8tAk61rMV9q3
1 parent 2fd88ab commit 56e98c4

5 files changed

Lines changed: 156 additions & 13 deletions

File tree

‎src/__tests__/logoutIntent.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { PacketDispatcher } from '../lib/net/common/PacketDispatcher';
3+
import { InputPacket } from '../lib/net/common/InputPacket';
4+
import { createLogoutIntent, LOGOUT_DECISION_GRACE_MS } from '../lib/jamera/logoutIntent';
5+
6+
const frame = (): InputPacket => new InputPacket(new Uint8Array([0x1e]).buffer);
7+
8+
function setup() {
9+
let time = 1000;
10+
const dispatcher = new PacketDispatcher();
11+
dispatcher.on(0x1e, () => {});
12+
const intent = createLogoutIntent(dispatcher, () => time);
13+
return { intent, dispatcher, advance: (ms: number) => { time += ms; } };
14+
}
15+
16+
describe('logout intent', () => {
17+
it('keeps a successful logout deliberate when the close follows in-flight frames', () => {
18+
const { intent, dispatcher, advance } = setup();
19+
intent.request();
20+
advance(120);
21+
dispatcher.dispatch(frame()); // sent before the server processed the logout
22+
advance(50);
23+
// Server closed the socket: onLeaveGame reads the intent.
24+
expect(intent.pending).toBe(true);
25+
});
26+
27+
it('treats a connection drop after a refused logout as unexpected', () => {
28+
const { intent, dispatcher, advance } = setup();
29+
intent.request();
30+
advance(200);
31+
dispatcher.dispatch(frame()); // "You may not logout during a fight" or similar
32+
expect(intent.pending).toBe(true);
33+
advance(LOGOUT_DECISION_GRACE_MS);
34+
dispatcher.dispatch(frame()); // idle ping: play continued
35+
advance(60_000);
36+
// Later unrelated socket loss.
37+
expect(intent.pending).toBe(false);
38+
});
39+
40+
it('covers silent script refusals through any later frame', () => {
41+
const { intent, dispatcher, advance } = setup();
42+
intent.request();
43+
advance(LOGOUT_DECISION_GRACE_MS + 1);
44+
dispatcher.dispatch(frame());
45+
expect(intent.pending).toBe(false);
46+
});
47+
48+
it('gives a repeated request its own window', () => {
49+
const { intent, dispatcher, advance } = setup();
50+
intent.request();
51+
advance(LOGOUT_DECISION_GRACE_MS - 10);
52+
intent.request();
53+
advance(20);
54+
dispatcher.dispatch(frame());
55+
expect(intent.pending).toBe(true);
56+
});
57+
58+
it('shares the frame observation with other waiters and stops on dispose', () => {
59+
const { intent, dispatcher, advance } = setup();
60+
let other = 0;
61+
dispatcher.nextFrame(() => { other++; });
62+
intent.request();
63+
intent.dispose();
64+
advance(LOGOUT_DECISION_GRACE_MS + 1);
65+
dispatcher.dispatch(frame());
66+
expect(other).toBe(1);
67+
expect(intent.pending).toBe(false);
68+
});
69+
});

‎src/lib/changelog.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export interface ChangelogEntry {
1414
}
1515

1616
export const CHANGELOG: ChangelogEntry[] = [
17+
{ date: '2026-11-29', text: 'If the server refuses to log you out, a later connection loss is still reported.' },
1718
{ date: '2026-11-29', text: 'Skulls and party shields appear with creature names on the map and in Battle. The labels show the skull colour or party role.' },
1819
{ date: '2026-11-29', text: 'A red square now marks the monster you are attacking until you stop, it dies, or it leaves your view.' },
1920
{ date: '2026-11-29', text: 'Settings lets you follow day and night or play at a fixed brightness, including full daylight.' },

‎src/lib/jamera/logoutIntent.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import type { PacketDispatcher } from '../net/common/PacketDispatcher';
2+
3+
/**
4+
* How long after a logout request an inbound frame still might predate the
5+
* server's decision. A frame received `t` ms after the request was sent at
6+
* or after `t - downlink`; the server decided at `uplink`. Once `t` exceeds
7+
* the round trip, the frame was sent after a refusal. Five seconds is well
8+
* above any playable round trip and matches Jamera's idle ping cadence.
9+
*/
10+
export const LOGOUT_DECISION_GRACE_MS = 5000;
11+
12+
export interface LogoutIntent {
13+
/** Record that the player asked to log out (after the request is sent). */
14+
request(): void;
15+
/** True while a logout request is outstanding and play has not resumed. */
16+
readonly pending: boolean;
17+
dispose(): void;
18+
}
19+
20+
/**
21+
* Scopes a logout request to its exchange with the server. Jamera's
22+
* Protocol76::logout either closes the connection in the same dispatcher
23+
* task or refuses (no-logout tile, fight, or an onLogout script) and keeps
24+
* the session alive, sometimes without any message. A successful logout
25+
* sends nothing after the close, so any frame that arrives after the grace
26+
* window shows the server refused and play continued. A later socket loss
27+
* is then reported as unexpected.
28+
*/
29+
export function createLogoutIntent(
30+
dispatcher: Pick<PacketDispatcher, 'nextFrame'>,
31+
now: () => number = () => performance.now(),
32+
graceMs = LOGOUT_DECISION_GRACE_MS,
33+
): LogoutIntent {
34+
let requestedAt = 0;
35+
let pending = false;
36+
let cancelFrame: (() => void) | null = null;
37+
38+
function onFrame(): void {
39+
cancelFrame = null;
40+
if (!pending) return;
41+
if (now() - requestedAt >= graceMs) {
42+
pending = false;
43+
return;
44+
}
45+
cancelFrame = dispatcher.nextFrame(onFrame);
46+
}
47+
48+
return {
49+
request() {
50+
requestedAt = now();
51+
pending = true;
52+
cancelFrame ??= dispatcher.nextFrame(onFrame);
53+
},
54+
get pending() { return pending; },
55+
dispose() {
56+
pending = false;
57+
cancelFrame?.();
58+
cancelFrame = null;
59+
},
60+
};
61+
}

‎src/lib/jamera/main.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { DatAttr } from '../dat';
5151
import { createAssetPipeline } from './assetPipeline';
5252
import { Application } from 'pixi.js';
5353
import { resolveProxyOverride } from './proxyUrl';
54+
import { createLogoutIntent, type LogoutIntent } from './logoutIntent';
5455
import { bindScreenWakeLock, loadKeepScreenAwake, type ScreenWakeLockHandle } from './screenWakeLock';
5556

5657
enableDiagnosticsDownload();
@@ -65,7 +66,9 @@ const tvFlag = params.get('tv');
6566
const tvMode = tvFlag === '1' || (tvFlag !== '0' && /web0s/i.test(navigator.userAgent));
6667
const padMode = tvMode || params.get('gamepad') === '1';
6768
let controller: Controller | null = null;
68-
let requestedLogout = false;
69+
// Scoped to the outstanding logout exchange: a refused logout (#493) must
70+
// not make a later, unrelated connection loss look deliberate.
71+
let logoutIntent: LogoutIntent | null = null;
6972
// Jamera closes the socket after a death; the death dialog already explains it.
7073
let diedThisSession = false;
7174
if (padMode) {
@@ -134,8 +137,9 @@ const login = mountLoginScreen(root, {
134137
window.dispatchEvent(new Event('tv-world-left'));
135138
document.querySelector('.tv-render-error')?.remove();
136139
}
137-
controller?.leave(!requestedLogout && !diedThisSession);
138-
requestedLogout = false;
140+
controller?.leave(!(logoutIntent?.pending ?? false) && !diedThisSession);
141+
logoutIntent?.dispose();
142+
logoutIntent = null;
139143
diedThisSession = false;
140144
// Disconnect/kick: drop the per-session surfaces instead of leaving
141145
// a live joystick and chat floating over the re-shown login screen.
@@ -215,6 +219,8 @@ const login = mountLoginScreen(root, {
215219
});
216220
};
217221
client.getDispatcher().on(client.getProtocol().serverOpcodes.ReloginWindow, onDeath);
222+
logoutIntent?.dispose();
223+
logoutIntent = createLogoutIntent(client.getDispatcher());
218224
startPingLoop(client);
219225
assetPipeline.load();
220226
const world = bindGameWorld(client);
@@ -401,12 +407,13 @@ const login = mountLoginScreen(root, {
401407
onSelect: () => {
402408
try {
403409
client.send(client.getProtocol().actions.buildLogout());
404-
requestedLogout = true;
410+
logoutIntent?.request();
405411
} catch (e) {
406412
debugConsole?.warn('[jamera] logout send failed:', e instanceof Error ? e.message : e);
407413
}
408414
// The server saves and closes; the disconnect flows through
409-
// onLeaveGame, which tears every per-session surface down.
415+
// onLeaveGame, which tears every per-session surface down. If it
416+
// refuses, frames keep arriving and logoutIntent lapses.
410417
},
411418
},
412419
]);

‎src/lib/net/common/PacketDispatcher.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,16 @@ import type { InputPacket } from './InputPacket';
55
export type OpcodeHandler = (packet: InputPacket) => void;
66

77
export class PacketDispatcher {
8-
private frameListener: (() => void) | null = null;
8+
private frameListeners = new Set<() => void>();
99

10-
/** One-shot liveness observation. Leaves opcode handlers and packet offsets intact. */
10+
/**
11+
* One-shot liveness observation. Leaves opcode handlers and packet offsets
12+
* intact. Several observers may wait at once (TV resume probe, logout intent).
13+
*/
1114
nextFrame(listener: () => void): () => void {
12-
this.frameListener = listener;
13-
return () => { if (this.frameListener === listener) this.frameListener = null; };
15+
const once = (): void => listener();
16+
this.frameListeners.add(once);
17+
return () => { this.frameListeners.delete(once); };
1418
}
1519

1620
private handlers = new Map<number, OpcodeHandler>();
@@ -38,10 +42,11 @@ export class PacketDispatcher {
3842
* Processes all opcodes in the packet (some server packets contain multiple).
3943
*/
4044
dispatch(packet: InputPacket): void {
41-
if (this.frameListener && packet.bytesLeft > 0) {
42-
const listener = this.frameListener;
43-
this.frameListener = null;
44-
listener();
45+
if (this.frameListeners.size > 0 && packet.bytesLeft > 0) {
46+
// Snapshot first: a listener may re-arm for the following frame.
47+
const listeners = [...this.frameListeners];
48+
this.frameListeners.clear();
49+
for (const listener of listeners) listener();
4550
}
4651
while (packet.bytesLeft > 0) {
4752
const opcode = packet.getU8();

0 commit comments

Comments
 (0)