xonecas.io
5875
Os

ollama-space-molt-player / commit 9595f0c

feat: add login prompt on reconnect after manual logout

- Add promptForLogin method to handle re-authentication via LLM
- Update handleWelcome to call login prompt instead of skipping
- Add comprehensive logout/reconnect test suite
- Improves user experience by allowing re-login without restarting

xonecas2026-02-03 9595f0c8b293a7962171f695179b2a14cf152cb9 parent c14c70c

2 files changed

packages/client/src/game-client.ts+62−2
@@ -182,8 +182,12 @@ export class GameClient {
182182 });
183183 });
184184 } else {
185- logClientEvent(this.getLogContext(activeUsername.username), "Skipping auto-login", {
186- reason: "Player manually logged out",
185+ await this.promptForLogin(activeUsername.username, activeUsername.token).catch((error) => {
186+ logClientError(this.getLogContext(activeUsername.username), "Login prompt error", error);
187+ this.db.saveMessage(this.currentTick, "client", {
188+ error: "Login prompt failed",
189+ code: "LOGIN_PROMPT_ERROR",
190+ });
187191 });
188192 }
189193 }
@@ -372,6 +376,62 @@ Your JSON response:`;
372376 }
373377 }
374378
379+ private async promptForLogin(username: string, token: string): Promise<void> {
380+ const minimalContext = {
381+ api: this.getApiSubset(["login"]),
382+ available_account: username,
383+ note: "You previously logged out. Login to continue playing.",
384+ };
385+
386+ const contextJson = JSON.stringify(minimalContext);
387+ const loginPrompt = `You are playing a multiplayer space game called SpaceMolt, 🦞 **The Crustacean Cosmos** 🦞. You need to login to continue playing.
388+
389+Game Context:
390+${contextJson}
391+
392+CRITICAL: You must respond with a SINGLE, VALID JSON OBJECT
393+
394+JSON Format:
395+{"type": "login", "payload": {"username": "${username}", "token": "${token}"}}
396+
397+Your JSON response:`;
398+
399+ try {
400+ const result = await this.ollama.generate(loginPrompt);
401+
402+ if (result.thinking) {
403+ logThinking(this.getLogContext(username), result.thinking);
404+ }
405+
406+ let command: BaseCommand;
407+ try {
408+ command = JSON.parse(result.response);
409+ } catch {
410+ command = this.extractJSON(result.response);
411+ }
412+
413+ if (command.type !== "login" || !command.payload) {
414+ throw new Error("Invalid login command: missing type or payload");
415+ }
416+
417+ const payload = command.payload as { username: string; token: string };
418+ if (!payload.username || !payload.token) {
419+ throw new Error("Invalid login payload: missing username or token");
420+ }
421+
422+ logClientCommand(this.getLogContext(payload.username), command);
423+
424+ this.ws.send(command);
425+ this.db.saveMessage(this.currentTick, "client", command);
426+ } catch (error) {
427+ logClientError(this.getLogContext(username), "Login prompt failed", error);
428+ this.db.saveMessage(this.currentTick, "client", {
429+ error: error instanceof Error ? error.message : "Login prompt failed",
430+ code: "LOGIN_PROMPT_FAILED",
431+ });
432+ }
433+ }
434+
375435 private handleLoggedIn(_message: LoggedInMessage): void {
376436 this.db.setLoggedOut(false);
377437 }
packages/client/tests/logout-reconnect.test.ts+108−0
@@ -0,0 +1,108 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { GameDatabase } from "../src/db.ts";
3+import { MockGameServer } from "./mock-server.ts";
4+import { GameWebSocketClient } from "../src/ws-client.ts";
5+import type { BaseCommand, ServerMessage } from "../src/types.ts";
6+
7+describe("Logout and Reconnect", () => {
8+ let db: GameDatabase;
9+ let server: MockGameServer;
10+ let testInstanceId: string;
11+
12+ beforeEach(async () => {
13+ testInstanceId = `test-logout-${Date.now()}`;
14+ db = new GameDatabase(testInstanceId);
15+ server = new MockGameServer({ port: 0 });
16+ await server.start();
17+ });
18+
19+ afterEach(() => {
20+ db.close();
21+ server.stop();
22+
23+ const fs = require("node:fs");
24+ const dbFile = `memory-${testInstanceId}.sqlite`;
25+ if (fs.existsSync(dbFile)) {
26+ fs.unlinkSync(dbFile);
27+ }
28+ });
29+
30+ describe("Database state transitions", () => {
31+ test("logged_out should be false by default", () => {
32+ expect(db.isLoggedOut()).toBe(false);
33+ });
34+
35+ test("logged_out should be true after setLoggedOut(true)", () => {
36+ db.setLoggedOut(true);
37+ expect(db.isLoggedOut()).toBe(true);
38+ });
39+
40+ test("logged_out should be false after setLoggedOut(false)", () => {
41+ db.setLoggedOut(true);
42+ db.setLoggedOut(false);
43+ expect(db.isLoggedOut()).toBe(false);
44+ });
45+ });
46+
47+ describe("Reconnect after manual logout", () => {
48+ test("state preconditions for logout-reconnect scenario", () => {
49+ db.saveUsername("TestPlayer", "test-token-123", "Test prompt", "player-id", 100);
50+ db.setLoggedOut(true);
51+
52+ const activeUsername = db.getActiveUsername();
53+ const isLoggedOut = db.isLoggedOut();
54+
55+ expect(activeUsername).not.toBeNull();
56+ expect(activeUsername?.username).toBe("TestPlayer");
57+ expect(isLoggedOut).toBe(true);
58+ });
59+
60+ test("handleWelcome cases coverage", () => {
61+ const cases = [
62+ {
63+ name: "no username, not logged out -> prompt registration",
64+ hasUsername: false,
65+ loggedOut: false,
66+ expectedAction: "promptForRegistration",
67+ },
68+ {
69+ name: "has username, not logged out -> auto-login",
70+ hasUsername: true,
71+ loggedOut: false,
72+ expectedAction: "autoLogin",
73+ },
74+ {
75+ name: "has username, logged out -> should prompt for login (BUG: currently does nothing)",
76+ hasUsername: true,
77+ loggedOut: true,
78+ expectedAction: "promptForLogin",
79+ },
80+ ];
81+
82+ for (const testCase of cases) {
83+ if (testCase.hasUsername) {
84+ db.saveUsername(`Player-${testCase.name}`, "token", "prompt", "id", Date.now());
85+ }
86+ if (testCase.loggedOut) {
87+ db.setLoggedOut(true);
88+ }
89+
90+ const activeUsername = db.getActiveUsername();
91+ const wasLoggedOut = db.isLoggedOut();
92+
93+ let action: string;
94+ if (activeUsername && !wasLoggedOut) {
95+ action = "autoLogin";
96+ } else if (!activeUsername) {
97+ action = "promptForRegistration";
98+ } else {
99+ action = "promptForLogin";
100+ }
101+
102+ expect(action).toBe(testCase.expectedAction);
103+
104+ db.setLoggedOut(false);
105+ }
106+ });
107+ });
108+});