Hermes Bot commited on
Commit
a1847c4
·
unverified ·
1 Parent(s): a5a0af7

feat(tinybard): infinite play, save/load, exit button

Browse files

- Remove step >= 4 win condition; adventure cycles infinitely via step % 3
- Add genre field to all API response dicts
- Add 4 save/load endpoints (POST save, GET saves, POST load, DELETE save)
- Saves stored as JSON in projects/tinybard/saves/
- Add X exit button with save dialog (Save & Exit / Exit Without Saving / Cancel)
- Add SAVES dropdown listing server + localStorage saves
- Add RESUME buttons on genre selector for recent saves
- Add localStorage backup for persistence across server restarts
- All new UI follows cedar-copper solarpunk CRT aesthetic

projects/tinybard/app.py CHANGED
@@ -156,7 +156,8 @@ def generate_procedural_step(genre: str, step: int, health: int, choice: str = "
156
  "choices": genre_data["nodes"][0]["choices"],
157
  "health": health,
158
  "step": 1,
159
- "game_over": False
 
160
  }
161
 
162
  health_delta = random.choice([-15, 0, 10])
@@ -168,16 +169,8 @@ def generate_procedural_step(genre: str, step: int, health: int, choice: str = "
168
  "choices": [],
169
  "health": 0,
170
  "step": step + 1,
171
- "game_over": True
172
- }
173
-
174
- if step >= 4:
175
- return {
176
- "story": f"After choosing: '{choice}'. " + genre_data["win"],
177
- "choices": [],
178
- "health": new_health,
179
- "step": step + 1,
180
- "game_over": True
181
  }
182
 
183
  node = genre_data["nodes"][step % len(genre_data["nodes"])]
@@ -186,7 +179,8 @@ def generate_procedural_step(genre: str, step: int, health: int, choice: str = "
186
  "choices": node["choices"],
187
  "health": new_health,
188
  "step": step + 1,
189
- "game_over": False
 
190
  }
191
 
192
 
@@ -332,14 +326,7 @@ def create_gradio_app() -> gr.Blocks:
332
  [], 0, step + 1, True, json.dumps(history)
333
  )
334
 
335
- if step >= 4:
336
- instruction = "Narrate the final glorious victory. The adventure ends in success."
337
- story = generate_llm_story(genre, history, instruction)
338
- return (
339
- story or "You have achieved your goal! You are victorious!",
340
- [], new_health, step + 1, True, json.dumps(history)
341
- )
342
-
343
  instruction = "Narrate what happens next as a result of the player's choice."
344
  story = generate_llm_story(genre, history, instruction)
345
  if not story:
@@ -437,6 +424,7 @@ def _run_turn(choice: str, genre: str, step: int, health: int, history: List[Dic
437
  return {
438
  "story": story, "choices": choices[:3], "health": 100,
439
  "step": 1, "game_over": False, "history": history,
 
440
  }
441
 
442
  # Subsequent turn
@@ -453,16 +441,7 @@ def _run_turn(choice: str, genre: str, step: int, health: int, history: List[Dic
453
  return {
454
  "story": story or "Your strength fails. The adventure ends in darkness.",
455
  "choices": [], "health": 0, "step": step + 1, "game_over": True,
456
- "history": history,
457
- }
458
-
459
- if step >= 4:
460
- instruction = "Narrate the final glorious victory. The adventure ends in success."
461
- story = generate_llm_story(genre, history, instruction)
462
- return {
463
- "story": story or "You have achieved your goal! You are victorious!",
464
- "choices": [], "health": new_health, "step": step + 1, "game_over": True,
465
- "history": history,
466
  }
467
 
468
  instruction = "Narrate what happens next as a result of the player's choice."
@@ -477,6 +456,7 @@ def _run_turn(choice: str, genre: str, step: int, health: int, history: List[Dic
477
  return {
478
  "story": story, "choices": choices[:3], "health": new_health,
479
  "step": step + 1, "game_over": False, "history": history,
 
480
  }
481
 
482
 
@@ -509,6 +489,132 @@ async def game_choice(payload: dict):
509
  history=payload.get("history", []),
510
  )
511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  # Mount static files
513
  fastapi_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
514
 
 
156
  "choices": genre_data["nodes"][0]["choices"],
157
  "health": health,
158
  "step": 1,
159
+ "game_over": False,
160
+ "genre": genre,
161
  }
162
 
163
  health_delta = random.choice([-15, 0, 10])
 
169
  "choices": [],
170
  "health": 0,
171
  "step": step + 1,
172
+ "game_over": True,
173
+ "genre": genre,
 
 
 
 
 
 
 
 
174
  }
175
 
176
  node = genre_data["nodes"][step % len(genre_data["nodes"])]
 
179
  "choices": node["choices"],
180
  "health": new_health,
181
  "step": step + 1,
182
+ "game_over": False,
183
+ "genre": genre,
184
  }
185
 
186
 
 
326
  [], 0, step + 1, True, json.dumps(history)
327
  )
328
 
329
+ # No step cap — adventure continues infinitely until health reaches 0
 
 
 
 
 
 
 
330
  instruction = "Narrate what happens next as a result of the player's choice."
331
  story = generate_llm_story(genre, history, instruction)
332
  if not story:
 
424
  return {
425
  "story": story, "choices": choices[:3], "health": 100,
426
  "step": 1, "game_over": False, "history": history,
427
+ "genre": genre,
428
  }
429
 
430
  # Subsequent turn
 
441
  return {
442
  "story": story or "Your strength fails. The adventure ends in darkness.",
443
  "choices": [], "health": 0, "step": step + 1, "game_over": True,
444
+ "history": history, "genre": genre,
 
 
 
 
 
 
 
 
 
445
  }
446
 
447
  instruction = "Narrate what happens next as a result of the player's choice."
 
456
  return {
457
  "story": story, "choices": choices[:3], "health": new_health,
458
  "step": step + 1, "game_over": False, "history": history,
459
+ "genre": genre,
460
  }
461
 
462
 
 
489
  history=payload.get("history", []),
490
  )
491
 
492
+ # ---------------------------------------------------------------------------
493
+ # Save/Load System
494
+ # ---------------------------------------------------------------------------
495
+ SAVES_DIR = BASE_DIR / "saves"
496
+ SAVES_DIR.mkdir(exist_ok=True)
497
+
498
+
499
+ @fastapi_app.post("/api/game/save")
500
+ async def game_save(payload: dict):
501
+ """Save current game state to a named slot.
502
+
503
+ Body: {slot_name, genre, step, health, history, game_over}
504
+ """
505
+ slot_name = payload.get("slot_name", "autosave")
506
+ # Sanitize slot name for filesystem
507
+ safe_name = "".join(c for c in slot_name if c.isalnum() or c in "-_ ").strip()
508
+ if not safe_name:
509
+ safe_name = "autosave"
510
+
511
+ save_data = {
512
+ "slot_name": safe_name,
513
+ "genre": payload.get("genre", "fantasy"),
514
+ "step": int(payload.get("step", 0)),
515
+ "health": int(payload.get("health", 100)),
516
+ "history": payload.get("history", []),
517
+ "game_over": payload.get("game_over", False),
518
+ "timestamp": __import__("time").time(),
519
+ }
520
+
521
+ save_path = SAVES_DIR / f"{safe_name}.json"
522
+ save_path.write_text(json.dumps(save_data, indent=2))
523
+ log.info(f"Game saved to slot: {safe_name}")
524
+ return {"status": "ok", "slot_name": safe_name, "timestamp": save_data["timestamp"]}
525
+
526
+
527
+ @fastapi_app.get("/api/game/saves")
528
+ async def game_saves():
529
+ """List all saved games."""
530
+ saves = []
531
+ for f in sorted(SAVES_DIR.glob("*.json")):
532
+ try:
533
+ data = json.loads(f.read_text())
534
+ saves.append({
535
+ "slot_name": data.get("slot_name", f.stem),
536
+ "genre": data.get("genre", "unknown"),
537
+ "step": data.get("step", 0),
538
+ "health": data.get("health", 0),
539
+ "timestamp": data.get("timestamp", 0),
540
+ "game_over": data.get("game_over", False),
541
+ })
542
+ except Exception:
543
+ continue
544
+ return {"saves": saves}
545
+
546
+
547
+ @fastapi_app.post("/api/game/load")
548
+ async def game_load(payload: dict):
549
+ """Load a saved game by slot name.
550
+
551
+ Body: {slot_name}
552
+ """
553
+ slot_name = payload.get("slot_name", "")
554
+ safe_name = "".join(c for c in slot_name if c.isalnum() or c in "-_ ").strip()
555
+ save_path = SAVES_DIR / f"{safe_name}.json"
556
+
557
+ if not save_path.exists():
558
+ return {"status": "error", "message": f"Save '{safe_name}' not found"}
559
+
560
+ try:
561
+ data = json.loads(save_path.read_text())
562
+ return {
563
+ "status": "ok",
564
+ "slot_name": data.get("slot_name", safe_name),
565
+ "genre": data.get("genre", "fantasy"),
566
+ "step": data.get("step", 0),
567
+ "health": data.get("health", 100),
568
+ "history": data.get("history", []),
569
+ "game_over": data.get("game_over", False),
570
+ }
571
+ except Exception as e:
572
+ return {"status": "error", "message": str(e)}
573
+
574
+
575
+ @fastapi_app.delete("/api/game/save/{slot_name}")
576
+ async def game_delete_save(slot_name: str):
577
+ """Delete a saved game."""
578
+ safe_name = "".join(c for c in slot_name if c.isalnum() or c in "-_ ").strip()
579
+ save_path = SAVES_DIR / f"{safe_name}.json"
580
+
581
+ if save_path.exists():
582
+ save_path.unlink()
583
+ log.info(f"Deleted save: {safe_name}")
584
+ return {"status": "ok", "deleted": safe_name}
585
+ return {"status": "error", "message": f"Save '{safe_name}' not found"}
586
+
587
+
588
+ class UserConfig(BaseModel):
589
+ hf_token: Optional[str] = None
590
+ model: Optional[str] = None
591
+
592
+
593
+ @fastapi_app.post("/api/config")
594
+ async def update_config(cfg: UserConfig):
595
+ with _USER_CONFIG_LOCK:
596
+ if cfg.hf_token:
597
+ _USER_CONFIG["hf_token"] = cfg.hf_token.strip() or None
598
+ if cfg.model and cfg.model.strip():
599
+ _USER_CONFIG["model"] = cfg.model.strip()
600
+ current = dict(_USER_CONFIG)
601
+ return {
602
+ "status": "ok",
603
+ "model": current["model"] or TINYBARD_MODEL,
604
+ "has_token": bool(current["hf_token"]),
605
+ }
606
+
607
+
608
+ @fastapi_app.get("/api/config")
609
+ async def get_config():
610
+ with _USER_CONFIG_LOCK:
611
+ current = dict(_USER_CONFIG)
612
+ return {
613
+ "model": current["model"] or TINYBARD_MODEL,
614
+ "has_token": bool(current["hf_token"]),
615
+ }
616
+
617
+
618
  # Mount static files
619
  fastapi_app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
620
 
projects/tinybard/static/index.html CHANGED
@@ -23,7 +23,18 @@
23
  <div class="terminal" id="terminal">
24
  <div class="terminal-header">
25
  <span class="prompt">ᐴ TINYBARD v1.0 ᔔ · GIIZHI-AADIZOKED</span>
26
- <span class="status" id="health-bar">NOOSISKAAZOWIN: <span id="health-val">100</span></span>
 
 
 
 
 
 
 
 
 
 
 
27
  </div>
28
 
29
  <div class="terminal-body" id="output">
@@ -69,5 +80,46 @@
69
  </div>
70
 
71
  <script type="module" src="/static/main.js"></script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  </body>
73
  </html>
 
23
  <div class="terminal" id="terminal">
24
  <div class="terminal-header">
25
  <span class="prompt">ᐴ TINYBARD v1.0 ᔔ · GIIZHI-AADIZOKED</span>
26
+ <span class="header-controls">
27
+ <span class="status" id="health-bar">NOOSISKAAZOWIN: <span id="health-val">100</span></span>
28
+ <button id="saves-btn" class="header-btn" title="Saved Games">◈ SAVES</button>
29
+ <button id="config-btn" class="header-btn" title="Configuration">⚙ CONFIG</button>
30
+ <button id="exit-btn" class="header-btn exit-btn" title="Save & Exit">✕</button>
31
+ </span>
32
+ </div>
33
+
34
+ <div class="saves-dropdown" id="saves-dropdown" style="display:none;">
35
+ <div class="saves-header">◈ SAVED JOURNEYS</div>
36
+ <div class="saves-list" id="saves-list"></div>
37
+ </div>
38
  </div>
39
 
40
  <div class="terminal-body" id="output">
 
80
  </div>
81
 
82
  <script type="module" src="/static/main.js"></script>
83
+
84
+ <!-- User config modal -->
85
+ <div id="tb-config-modal" class="tb-modal-overlay" style="display:none;">
86
+ <div class="tb-modal">
87
+ <button class="tb-close" id="tb-config-close">✕</button>
88
+ <h3>⚙ Inference Configuration</h3>
89
+ <p style="font-size:0.8rem;color:var(--asp-moss,#588157);">
90
+ Provide your own HuggingFace token to unlock models that need auth.
91
+ Your token lives in browser memory only — never sent anywhere except api.huggingface.co.
92
+ </p>
93
+ <label for="tb-model-input">Model ID</label>
94
+ <input type="text" id="tb-model-input" placeholder="Qwen/Qwen2.5-1.5B-Instruct" />
95
+
96
+ <label for="tb-token-input">HF Token (optional)</label>
97
+ <input type="password" id="tb-token-input" placeholder="hf_..." />
98
+
99
+ <button id="tb-config-save">Save & Reload</button>
100
+ <span id="tb-config-status" style="margin-left:0.5rem;color:var(--asp-moss,#588157);"></span>
101
+ </div>
102
+ </div>
103
+
104
+ <!-- Save/Exit dialog modal -->
105
+ <div id="tb-save-modal" class="tb-modal-overlay" style="display:none;">
106
+ <div class="tb-modal save-modal">
107
+ <h3>◈ SAVE YOUR JOURNEY?</h3>
108
+ <p style="font-size:0.8rem;color:var(--asp-moss,#588157);margin-bottom:12px;">
109
+ Your adventure awaits. Save your progress to continue later.
110
+ </p>
111
+ <label for="tb-save-name">Slot Name</label>
112
+ <input type="text" id="tb-save-name" placeholder="my-adventure" />
113
+ <div class="save-modal-actions">
114
+ <button id="tb-save-and-exit" class="save-action-btn">◈ Save & Exit</button>
115
+ <button id="tb-exit-no-save" class="save-action-btn exit-no-save">✕ Exit Without Saving</button>
116
+ <button id="tb-save-cancel" class="save-action-btn cancel-btn">← Cancel</button>
117
+ </div>
118
+ <span id="tb-save-status" style="display:block;margin-top:8px;color:var(--asp-moss,#588157);font-size:0.75rem;"></span>
119
+ </div>
120
+ </div>
121
+
122
+ <!-- Resume section (injected into genre selector by JS) -->
123
+
124
  </body>
125
  </html>
projects/tinybard/static/main.js CHANGED
@@ -14,7 +14,8 @@ let gameState = {
14
  step: 0,
15
  health: 100,
16
  history: [],
17
- gameActive: false
 
18
  };
19
 
20
  // ---------------------------------------------------------------------------
@@ -54,12 +55,9 @@ async function checkModelStatus() {
54
  }
55
  }
56
 
57
- // Poll model status every 2s so cooldown countdown updates
58
  setInterval(checkModelStatus, 2000);
 
59
  async function apiCall(endpoint, payload) {
60
- // Use the FastAPI clean-JSON endpoints (returns a dict directly).
61
- // /api/game/start -> start_game
62
- // /api/game/choice -> make_choice
63
  const path = endpoint === "/start_game"
64
  ? "/api/game/start"
65
  : "/api/game/choice";
@@ -105,7 +103,7 @@ function showChoices(choices) {
105
  choicesEl.innerHTML = "";
106
  choicesEl.style.display = "flex";
107
 
108
- choices.forEach((choice, i) => {
109
  const btn = document.createElement("button");
110
  btn.className = "choice-btn";
111
  btn.textContent = choice;
@@ -132,7 +130,7 @@ function hideInput() {
132
  // Game Logic
133
  // ---------------------------------------------------------------------------
134
  async function startGame(genre) {
135
- gameState = { genre, step: 0, health: 100, history: [], gameActive: true };
136
  genreSelector.style.display = "none";
137
  clearBoot();
138
 
@@ -208,7 +206,6 @@ function endGame(data) {
208
 
209
  appendOutput(`<div class="${className}">${label}<br><small>Final Health: ${data.health}</small></div>`, "");
210
 
211
- // New game button
212
  const btn = document.createElement("button");
213
  btn.className = "new-game-btn";
214
  btn.textContent = "[ NEW ADVENTURE ]";
@@ -220,17 +217,393 @@ function endGame(data) {
220
  function resetGame() {
221
  output.innerHTML = "";
222
  hideChoices();
223
- gameState = { genre: "", step: 0, health: 100, history: [], gameActive: false };
224
  healthVal.textContent = "100";
225
  healthVal.style.color = "#00ff41";
226
  genreSelector.style.display = "flex";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  }
228
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  // ---------------------------------------------------------------------------
230
  // Event Listeners
231
  // ---------------------------------------------------------------------------
232
  document.querySelectorAll(".genre-option").forEach(el => {
233
  el.addEventListener("click", () => {
 
234
  const genre = el.dataset.genre;
235
  startGame(genre);
236
  });
@@ -243,8 +616,53 @@ cmdInput.addEventListener("keydown", (e) => {
243
  }
244
  });
245
 
246
- // Boot
247
  // ---------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  (async () => {
249
  await checkModelStatus();
 
250
  })();
 
14
  step: 0,
15
  health: 100,
16
  history: [],
17
+ gameActive: false,
18
+ saveSlot: null
19
  };
20
 
21
  // ---------------------------------------------------------------------------
 
55
  }
56
  }
57
 
 
58
  setInterval(checkModelStatus, 2000);
59
+
60
  async function apiCall(endpoint, payload) {
 
 
 
61
  const path = endpoint === "/start_game"
62
  ? "/api/game/start"
63
  : "/api/game/choice";
 
103
  choicesEl.innerHTML = "";
104
  choicesEl.style.display = "flex";
105
 
106
+ choices.forEach((choice) => {
107
  const btn = document.createElement("button");
108
  btn.className = "choice-btn";
109
  btn.textContent = choice;
 
130
  // Game Logic
131
  // ---------------------------------------------------------------------------
132
  async function startGame(genre) {
133
+ gameState = { genre, step: 0, health: 100, history: [], gameActive: true, saveSlot: null };
134
  genreSelector.style.display = "none";
135
  clearBoot();
136
 
 
206
 
207
  appendOutput(`<div class="${className}">${label}<br><small>Final Health: ${data.health}</small></div>`, "");
208
 
 
209
  const btn = document.createElement("button");
210
  btn.className = "new-game-btn";
211
  btn.textContent = "[ NEW ADVENTURE ]";
 
217
  function resetGame() {
218
  output.innerHTML = "";
219
  hideChoices();
220
+ gameState = { genre: "", step: 0, health: 100, history: [], gameActive: false, saveSlot: null };
221
  healthVal.textContent = "100";
222
  healthVal.style.color = "#00ff41";
223
  genreSelector.style.display = "flex";
224
+ loadResumeButtons();
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Save / Load System
229
+ // ---------------------------------------------------------------------------
230
+ const LS_KEY = "tinybard_saves";
231
+
232
+ function getLocalSaves() {
233
+ try {
234
+ return JSON.parse(localStorage.getItem(LS_KEY) || "[]");
235
+ } catch {
236
+ return [];
237
+ }
238
+ }
239
+
240
+ function setLocalSaves(saves) {
241
+ localStorage.setItem(LS_KEY, JSON.stringify(saves));
242
+ }
243
+
244
+ function saveToLocal(slotName, data) {
245
+ const saves = getLocalSaves();
246
+ const idx = saves.findIndex(s => s.slot_name === slotName);
247
+ const entry = {
248
+ slot_name: slotName,
249
+ genre: data.genre,
250
+ step: data.step,
251
+ health: data.health,
252
+ history: data.history,
253
+ game_over: data.game_over || false,
254
+ timestamp: Date.now() / 1000
255
+ };
256
+ if (idx >= 0) saves[idx] = entry;
257
+ else saves.push(entry);
258
+ setLocalSaves(saves);
259
+ }
260
+
261
+ function deleteLocalSave(slotName) {
262
+ const saves = getLocalSaves().filter(s => s.slot_name !== slotName);
263
+ setLocalSaves(saves);
264
+ }
265
+
266
+ async function saveToServer(slotName, data) {
267
+ try {
268
+ const resp = await fetch(`${GRADIO_CLIENT_URL}/api/game/save`, {
269
+ method: "POST",
270
+ headers: { "Content-Type": "application/json" },
271
+ body: JSON.stringify({
272
+ slot_name: slotName,
273
+ genre: data.genre,
274
+ step: data.step,
275
+ health: data.health,
276
+ history: data.history,
277
+ game_over: data.game_over || false
278
+ })
279
+ });
280
+ return await resp.json();
281
+ } catch {
282
+ return { status: "error" };
283
+ }
284
+ }
285
+
286
+ async function fetchSaves() {
287
+ let serverSaves = [];
288
+ try {
289
+ const resp = await fetch(`${GRADIO_CLIENT_URL}/api/game/saves`);
290
+ const data = await resp.json();
291
+ serverSaves = data.saves || [];
292
+ } catch {}
293
+
294
+ const localSaves = getLocalSaves();
295
+ const merged = new Map();
296
+ for (const s of localSaves) merged.set(s.slot_name, s);
297
+ for (const s of serverSaves) {
298
+ if (!merged.has(s.slot_name) || s.timestamp > (merged.get(s.slot_name).timestamp || 0)) {
299
+ merged.set(s.slot_name, s);
300
+ }
301
+ }
302
+ return Array.from(merged.values()).sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
303
+ }
304
+
305
+ async function loadSaveFromServer(slotName) {
306
+ try {
307
+ const resp = await fetch(`${GRADIO_CLIENT_URL}/api/game/load`, {
308
+ method: "POST",
309
+ headers: { "Content-Type": "application/json" },
310
+ body: JSON.stringify({ slot_name: slotName })
311
+ });
312
+ return await resp.json();
313
+ } catch {
314
+ return null;
315
+ }
316
+ }
317
+
318
+ async function deleteSaveFromServer(slotName) {
319
+ try {
320
+ await fetch(`${GRADIO_CLIENT_URL}/api/game/save/${encodeURIComponent(slotName)}`, {
321
+ method: "DELETE"
322
+ });
323
+ } catch {}
324
  }
325
 
326
+ // ---------------------------------------------------------------------------
327
+ // Save Dialog
328
+ // ---------------------------------------------------------------------------
329
+ const saveModal = document.getElementById("tb-save-modal");
330
+ const saveNameInput = document.getElementById("tb-save-name");
331
+ const saveAndExitBtn = document.getElementById("tb-save-and-exit");
332
+ const exitNoSaveBtn = document.getElementById("tb-exit-no-save");
333
+ const saveCancelBtn = document.getElementById("tb-save-cancel");
334
+ const saveStatus = document.getElementById("tb-save-status");
335
+
336
+ function showSaveDialog() {
337
+ if (!gameState.gameActive || gameState.game_over) {
338
+ resetGame();
339
+ return;
340
+ }
341
+ const defaultName = `${gameState.genre}-step${gameState.step}`;
342
+ saveNameInput.value = gameState.saveSlot || defaultName;
343
+ saveStatus.textContent = "";
344
+ saveModal.style.display = "flex";
345
+ saveNameInput.focus();
346
+ }
347
+
348
+ function hideSaveDialog() {
349
+ saveModal.style.display = "none";
350
+ }
351
+
352
+ if (saveModal) {
353
+ saveCancelBtn.addEventListener("click", hideSaveDialog);
354
+
355
+ saveModal.addEventListener("click", (e) => {
356
+ if (e.target === saveModal) hideSaveDialog();
357
+ });
358
+
359
+ exitNoSaveBtn.addEventListener("click", () => {
360
+ hideSaveDialog();
361
+ resetGame();
362
+ });
363
+
364
+ saveAndExitBtn.addEventListener("click", async () => {
365
+ const slotName = saveNameInput.value.trim() || `${gameState.genre}-step${gameState.step}`;
366
+ saveAndExitBtn.disabled = true;
367
+ saveStatus.textContent = "Saving...";
368
+
369
+ const saveData = {
370
+ genre: gameState.genre,
371
+ step: gameState.step,
372
+ health: gameState.health,
373
+ history: gameState.history,
374
+ game_over: !gameState.gameActive
375
+ };
376
+
377
+ saveToLocal(slotName, saveData);
378
+ const serverResult = await saveToServer(slotName, saveData);
379
+
380
+ saveStatus.textContent = serverResult.status === "ok"
381
+ ? `✓ Saved to "${slotName}"`
382
+ : `✓ Saved locally as "${slotName}"`;
383
+ saveStatus.style.color = "var(--asp-sun)";
384
+
385
+ setTimeout(() => {
386
+ hideSaveDialog();
387
+ resetGame();
388
+ }, 600);
389
+ });
390
+ }
391
+
392
+ // ---------------------------------------------------------------------------
393
+ // Saves Dropdown
394
+ // ---------------------------------------------------------------------------
395
+ const savesBtn = document.getElementById("saves-btn");
396
+ const savesDropdown = document.getElementById("saves-dropdown");
397
+ const savesList = document.getElementById("saves-list");
398
+
399
+ function toggleSavesDropdown() {
400
+ if (savesDropdown.style.display === "none") {
401
+ refreshSavesList();
402
+ savesDropdown.style.display = "block";
403
+ } else {
404
+ savesDropdown.style.display = "none";
405
+ }
406
+ }
407
+
408
+ async function refreshSavesList() {
409
+ const saves = await fetchSaves();
410
+ savesList.innerHTML = "";
411
+
412
+ if (saves.length === 0) {
413
+ savesList.innerHTML = '<div class="saves-empty">No saved journeys yet.</div>';
414
+ return;
415
+ }
416
+
417
+ for (const save of saves) {
418
+ const item = document.createElement("div");
419
+ item.className = "save-item";
420
+
421
+ const ts = save.timestamp ? new Date(save.timestamp * 1000).toLocaleDateString() : "";
422
+ const genreLabel = (save.genre || "unknown").toUpperCase();
423
+ const statusIcon = save.game_over ? "☠" : "◈";
424
+
425
+ item.innerHTML = `
426
+ <div class="save-info" data-slot="${save.slot_name}">
427
+ <span class="save-genre">${genreLabel}</span>
428
+ <span class="save-name">${save.slot_name}</span>
429
+ <span class="save-meta">Step ${save.step} · HP ${save.health} ${ts ? "· " + ts : ""}</span>
430
+ </div>
431
+ <button class="save-delete-btn" data-slot="${save.slot_name}" title="Delete">✕</button>
432
+ `;
433
+
434
+ item.querySelector(".save-info").addEventListener("click", () => {
435
+ loadSavedGame(save.slot_name);
436
+ });
437
+
438
+ item.querySelector(".save-delete-btn").addEventListener("click", async (e) => {
439
+ e.stopPropagation();
440
+ await deleteSaveFromServer(save.slot_name);
441
+ deleteLocalSave(save.slot_name);
442
+ refreshSavesList();
443
+ });
444
+
445
+ savesList.appendChild(item);
446
+ }
447
+ }
448
+
449
+ async function loadSavedGame(slotName) {
450
+ savesDropdown.style.display = "none";
451
+
452
+ let saveData = null;
453
+
454
+ const localSaves = getLocalSaves();
455
+ const localMatch = localSaves.find(s => s.slot_name === slotName);
456
+ if (localMatch && localMatch.history && localMatch.history.length > 0) {
457
+ saveData = localMatch;
458
+ }
459
+
460
+ if (!saveData) {
461
+ const serverResult = await loadSaveFromServer(slotName);
462
+ if (serverResult && serverResult.status === "ok") {
463
+ saveData = serverResult;
464
+ saveToLocal(slotName, saveData);
465
+ }
466
+ }
467
+
468
+ if (!saveData) {
469
+ appendOutput(`<span class="error">ERROR: Could not load save "${slotName}"</span>`, "line error");
470
+ return;
471
+ }
472
+
473
+ output.innerHTML = "";
474
+ hideChoices();
475
+ genreSelector.style.display = "none";
476
+ clearBoot();
477
+
478
+ gameState = {
479
+ genre: saveData.genre || "fantasy",
480
+ step: saveData.step || 0,
481
+ health: saveData.health || 100,
482
+ history: saveData.history || [],
483
+ gameActive: !saveData.game_over,
484
+ saveSlot: slotName
485
+ };
486
+
487
+ updateHealth(gameState.health);
488
+
489
+ appendOutput(
490
+ `<span class="narrator-prefix">> RESUMING: ${slotName} (${gameState.genre.toUpperCase()}, Step ${gameState.step})</span>`,
491
+ "line amber"
492
+ );
493
+
494
+ if (gameState.history.length > 0) {
495
+ const lastNarrator = [...gameState.history].reverse().find(h => h.role === "narrator");
496
+ if (lastNarrator) {
497
+ const storyEl = document.createElement("div");
498
+ storyEl.className = "story-text";
499
+ storyEl.textContent = lastNarrator.text;
500
+ output.appendChild(storyEl);
501
+ }
502
+ }
503
+
504
+ if (saveData.game_over) {
505
+ endGame({ health: gameState.health });
506
+ } else {
507
+ const lastNode = gameState.history.length > 0
508
+ ? gameState.history[gameState.history.length - 1]
509
+ : null;
510
+
511
+ try {
512
+ const resp = await fetch(`${GRADIO_CLIENT_URL}/api/game/choice`, {
513
+ method: "POST",
514
+ headers: { "Content-Type": "application/json" },
515
+ body: JSON.stringify({
516
+ choice: "(resuming journey)",
517
+ genre: gameState.genre,
518
+ step: gameState.step,
519
+ health: gameState.health,
520
+ history: gameState.history
521
+ })
522
+ });
523
+ const data = await resp.json();
524
+
525
+ gameState.step = data.step || gameState.step;
526
+ gameState.history = data.history || gameState.history;
527
+ updateHealth(data.health ?? gameState.health);
528
+
529
+ if (data.story && data.story !== lastNarrator?.text) {
530
+ const storyEl = document.createElement("div");
531
+ storyEl.className = "story-text";
532
+ storyEl.textContent = data.story;
533
+ output.appendChild(storyEl);
534
+ }
535
+
536
+ if (data.game_over) {
537
+ endGame(data);
538
+ } else if (data.choices && data.choices.length > 0) {
539
+ showChoices(data.choices);
540
+ }
541
+ } catch {
542
+ showChoices(["Continue onward", "Look around", "Rest"]);
543
+ }
544
+ }
545
+
546
+ scrollToBottom();
547
+ }
548
+
549
+ // ---------------------------------------------------------------------------
550
+ // Resume Buttons on Genre Selector
551
+ // ---------------------------------------------------------------------------
552
+ async function loadResumeButtons() {
553
+ const existing = genreSelector.querySelector(".resume-section");
554
+ if (existing) existing.remove();
555
+
556
+ const saves = await fetchSaves();
557
+ if (saves.length === 0) return;
558
+
559
+ const section = document.createElement("div");
560
+ section.className = "resume-section";
561
+ section.innerHTML = '<div class="resume-header">◈ RESUME JOURNEY</div>';
562
+
563
+ for (const save of saves.slice(0, 3)) {
564
+ const btn = document.createElement("div");
565
+ btn.className = "genre-option resume-option";
566
+ const genreIcon = save.genre === "fantasy" ? "☼" : save.genre === "scifi" ? "◈" : "◆";
567
+ const genreLabel = (save.genre || "").toUpperCase();
568
+ btn.innerHTML = `
569
+ <span class="icon">${genreIcon}</span>
570
+ RESUME: ${save.slot_name}
571
+ <span class="resume-meta">${genreLabel} · Step ${save.step} · HP ${save.health}</span>
572
+ `;
573
+ btn.addEventListener("click", () => loadSavedGame(save.slot_name));
574
+ section.appendChild(btn);
575
+ }
576
+
577
+ genreSelector.appendChild(section);
578
+ }
579
+
580
+ // ---------------------------------------------------------------------------
581
+ // Exit Button
582
+ // ---------------------------------------------------------------------------
583
+ const exitBtn = document.getElementById("exit-btn");
584
+ if (exitBtn) {
585
+ exitBtn.addEventListener("click", showSaveDialog);
586
+ }
587
+
588
+ if (savesBtn) {
589
+ savesBtn.addEventListener("click", (e) => {
590
+ e.stopPropagation();
591
+ toggleSavesDropdown();
592
+ });
593
+ }
594
+
595
+ document.addEventListener("click", (e) => {
596
+ if (savesDropdown && !savesDropdown.contains(e.target) && e.target !== savesBtn) {
597
+ savesDropdown.style.display = "none";
598
+ }
599
+ });
600
+
601
  // ---------------------------------------------------------------------------
602
  // Event Listeners
603
  // ---------------------------------------------------------------------------
604
  document.querySelectorAll(".genre-option").forEach(el => {
605
  el.addEventListener("click", () => {
606
+ if (el.classList.contains("resume-option")) return;
607
  const genre = el.dataset.genre;
608
  startGame(genre);
609
  });
 
616
  }
617
  });
618
 
 
619
  // ---------------------------------------------------------------------------
620
+ // User Config Modal
621
+ // ---------------------------------------------------------------------------
622
+ const configBtn = document.getElementById('config-btn');
623
+ const configModal = document.getElementById('tb-config-modal');
624
+ const configClose = document.getElementById('tb-config-close');
625
+ const configSave = document.getElementById('tb-config-save');
626
+ const modelInput = document.getElementById('tb-model-input');
627
+ const tokenInput = document.getElementById('tb-token-input');
628
+ const configStatus = document.getElementById('tb-config-status');
629
+
630
+ if (configBtn && configModal) {
631
+ configBtn.addEventListener('click', async () => {
632
+ const cfg = await fetch('/api/config').then(r => r.json());
633
+ modelInput.value = cfg.model || '';
634
+ tokenInput.value = '';
635
+ configStatus.textContent = '';
636
+ configModal.style.display = 'flex';
637
+ });
638
+
639
+ configClose.addEventListener('click', () => {
640
+ configModal.style.display = 'none';
641
+ });
642
+
643
+ configModal.addEventListener('click', (e) => {
644
+ if (e.target === configModal) configModal.style.display = 'none';
645
+ });
646
+
647
+ configSave.addEventListener('click', async () => {
648
+ const body = {};
649
+ if (modelInput.value.trim()) body.model = modelInput.value.trim();
650
+ if (tokenInput.value.trim()) body.hf_token = tokenInput.value.trim();
651
+
652
+ const resp = await fetch('/api/config', {
653
+ method: 'POST',
654
+ headers: { 'Content-Type': 'application/json' },
655
+ body: JSON.stringify(body),
656
+ });
657
+ const data = await resp.json();
658
+ configStatus.textContent = data.status === 'ok' ? '✓ Saved' : '✗ Failed';
659
+ configStatus.style.color = data.status === 'ok' ? 'var(--asp-sun)' : 'var(--asp-ember)';
660
+ setTimeout(() => { configModal.style.display = 'none'; }, 800);
661
+ });
662
+ }
663
+
664
+ // Boot
665
  (async () => {
666
  await checkModelStatus();
667
+ await loadResumeButtons();
668
  })();
projects/tinybard/static/style.css CHANGED
@@ -217,6 +217,38 @@ body {
217
  }
218
  #health-val { color: var(--asp-sun); font-weight: bold; }
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  /* === TERMINAL OUTPUT ================================================== */
221
  .terminal-body {
222
  flex: 1;
@@ -485,6 +517,180 @@ body {
485
  100% { transform: scaleY(1); box-shadow: inset 0 0 80px rgba(27, 73, 50, 0.5); }
486
  }
487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
  /* === MOBILE ========================================================== */
489
  @media (max-width: 600px) {
490
  .crt-container {
 
217
  }
218
  #health-val { color: var(--asp-sun); font-weight: bold; }
219
 
220
+ .header-controls {
221
+ display: flex;
222
+ align-items: center;
223
+ gap: 6px;
224
+ }
225
+
226
+ .header-btn {
227
+ background: none;
228
+ border: 1px solid var(--asp-amber, #FFB347);
229
+ color: var(--asp-sun, #F2A93B);
230
+ cursor: pointer;
231
+ font-family: monospace;
232
+ font-size: 0.7rem;
233
+ padding: 0.1rem 0.35rem;
234
+ border-radius: 2px;
235
+ transition: all 0.15s;
236
+ }
237
+ .header-btn:hover {
238
+ background: rgba(242, 169, 59, 0.15);
239
+ color: var(--asp-sunlight);
240
+ }
241
+
242
+ .exit-btn {
243
+ border-color: rgba(231, 111, 81, 0.5);
244
+ color: var(--asp-stone);
245
+ }
246
+ .exit-btn:hover {
247
+ background: rgba(231, 111, 81, 0.25);
248
+ color: var(--asp-ember);
249
+ border-color: var(--asp-ember);
250
+ }
251
+
252
  /* === TERMINAL OUTPUT ================================================== */
253
  .terminal-body {
254
  flex: 1;
 
517
  100% { transform: scaleY(1); box-shadow: inset 0 0 80px rgba(27, 73, 50, 0.5); }
518
  }
519
 
520
+ /* === SAVES DROPDOWN =================================================== */
521
+ .saves-dropdown {
522
+ position: absolute;
523
+ top: 45px;
524
+ right: 15px;
525
+ z-index: 50;
526
+ background: linear-gradient(160deg, #0F1A2C 0%, #1A2A1F 100%);
527
+ border: 1px solid rgba(91, 164, 217, 0.4);
528
+ border-radius: 4px;
529
+ padding: 8px;
530
+ min-width: 260px;
531
+ max-height: 300px;
532
+ overflow-y: auto;
533
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
534
+ }
535
+ .saves-header {
536
+ font-size: 0.7rem;
537
+ color: var(--asp-sun);
538
+ text-transform: uppercase;
539
+ letter-spacing: 1.5px;
540
+ padding-bottom: 6px;
541
+ border-bottom: 1px solid rgba(91, 164, 217, 0.2);
542
+ margin-bottom: 6px;
543
+ }
544
+ .saves-empty {
545
+ font-size: 0.75rem;
546
+ color: var(--asp-stone);
547
+ text-align: center;
548
+ padding: 12px 0;
549
+ }
550
+ .save-item {
551
+ display: flex;
552
+ justify-content: space-between;
553
+ align-items: center;
554
+ padding: 6px 8px;
555
+ border-radius: 3px;
556
+ cursor: pointer;
557
+ transition: background 0.15s;
558
+ }
559
+ .save-item:hover {
560
+ background: rgba(91, 164, 217, 0.1);
561
+ }
562
+ .save-info {
563
+ display: flex;
564
+ flex-direction: column;
565
+ gap: 2px;
566
+ flex: 1;
567
+ }
568
+ .save-genre {
569
+ font-size: 0.6rem;
570
+ color: var(--asp-sun);
571
+ text-transform: uppercase;
572
+ letter-spacing: 1px;
573
+ }
574
+ .save-name {
575
+ font-size: 0.78rem;
576
+ color: var(--asp-frost);
577
+ }
578
+ .save-meta {
579
+ font-size: 0.65rem;
580
+ color: var(--asp-stone);
581
+ }
582
+ .save-delete-btn {
583
+ background: none;
584
+ border: none;
585
+ color: var(--asp-stone);
586
+ cursor: pointer;
587
+ font-size: 0.75rem;
588
+ padding: 2px 4px;
589
+ border-radius: 2px;
590
+ transition: all 0.15s;
591
+ }
592
+ .save-delete-btn:hover {
593
+ color: var(--asp-ember);
594
+ background: rgba(231, 111, 81, 0.15);
595
+ }
596
+
597
+ /* === SAVE MODAL ====================================================== */
598
+ .save-modal h3 {
599
+ color: var(--asp-sun);
600
+ font-family: Georgia, serif;
601
+ margin-bottom: 4px;
602
+ }
603
+ .save-modal label {
604
+ display: block;
605
+ font-size: 0.75rem;
606
+ color: var(--asp-frost);
607
+ margin: 10px 0 4px;
608
+ text-transform: uppercase;
609
+ letter-spacing: 1px;
610
+ }
611
+ .save-modal input[type="text"] {
612
+ width: 100%;
613
+ padding: 6px 10px;
614
+ background: rgba(15, 26, 44, 0.6);
615
+ border: 1px solid rgba(91, 164, 217, 0.3);
616
+ border-radius: 3px;
617
+ color: var(--asp-birch);
618
+ font-family: 'MonoFallback', monospace;
619
+ font-size: 0.82rem;
620
+ }
621
+ .save-modal input[type="text"]:focus {
622
+ outline: none;
623
+ border-color: var(--asp-sun);
624
+ }
625
+ .save-modal-actions {
626
+ display: flex;
627
+ gap: 8px;
628
+ margin-top: 14px;
629
+ flex-wrap: wrap;
630
+ }
631
+ .save-action-btn {
632
+ padding: 8px 14px;
633
+ border: 1px solid rgba(91, 164, 217, 0.4);
634
+ border-radius: 3px;
635
+ background: rgba(15, 26, 44, 0.5);
636
+ color: var(--asp-frost);
637
+ font-family: 'MonoFallback', monospace;
638
+ font-size: 0.75rem;
639
+ cursor: pointer;
640
+ transition: all 0.15s;
641
+ }
642
+ .save-action-btn:hover {
643
+ background: rgba(242, 169, 59, 0.15);
644
+ border-color: var(--asp-sun);
645
+ color: var(--asp-sunlight);
646
+ }
647
+ .exit-no-save:hover {
648
+ background: rgba(231, 111, 81, 0.15);
649
+ border-color: var(--asp-ember);
650
+ color: var(--asp-ember);
651
+ }
652
+ .cancel-btn:hover {
653
+ background: rgba(91, 164, 217, 0.1);
654
+ color: var(--asp-frost);
655
+ }
656
+
657
+ /* === RESUME SECTION ================================================== */
658
+ .resume-section {
659
+ width: 100%;
660
+ display: flex;
661
+ flex-wrap: wrap;
662
+ gap: 10px;
663
+ justify-content: center;
664
+ padding-top: 10px;
665
+ border-top: 1px solid rgba(91, 164, 217, 0.2);
666
+ margin-top: 10px;
667
+ }
668
+ .resume-header {
669
+ width: 100%;
670
+ text-align: center;
671
+ font-size: 0.65rem;
672
+ color: var(--asp-sun);
673
+ text-transform: uppercase;
674
+ letter-spacing: 1.5px;
675
+ padding-bottom: 4px;
676
+ }
677
+ .resume-option {
678
+ border-color: rgba(242, 169, 59, 0.4) !important;
679
+ background: rgba(242, 169, 59, 0.05) !important;
680
+ position: relative;
681
+ }
682
+ .resume-option .resume-meta {
683
+ display: block;
684
+ font-size: 0.6rem;
685
+ color: var(--asp-stone);
686
+ margin-top: 2px;
687
+ letter-spacing: 0.5px;
688
+ }
689
+ .resume-option:hover {
690
+ border-color: var(--asp-sun) !important;
691
+ background: rgba(242, 169, 59, 0.12) !important;
692
+ }
693
+
694
  /* === MOBILE ========================================================== */
695
  @media (max-width: 600px) {
696
  .crt-container {