3 Commits

Author SHA1 Message Date
Alexander Whitestone
bd6bca74c5 feat: Implement live visitor count and Timmy greeting (#8)
Fixes #8

- Added visitorCount to WorldState and implemented increment/decrement functions.
- Updated WebSocket connection/disconnection handlers in events.ts to manage visitor count, broadcast events, and trigger Timmy greetings/farewells.
- Implemented generateVisitorGreeting and generateVisitorFarewell in agent.ts to create personalized messages.
- Modified websocket.js to listen for visitor_count events and pass them to ui.js.
- Updated ui.js and index.html to display the live visitor count with responsive design.
2026-03-23 19:39:47 -04:00
94d2e48455 [gemini] NIP-07 visitor Nostr identity in Workshop (#14) (#104)
Co-authored-by: Claude (Opus 4.6) <claude@hermes.local>
Co-committed-by: Claude (Opus 4.6) <claude@hermes.local>
2026-03-23 22:54:07 +00:00
395b728bde [claude] Rescue gemini/issue-14, delete 44 stale branches (#103) (#105) 2026-03-23 22:51:12 +00:00
8 changed files with 278 additions and 22 deletions

View File

@@ -280,6 +280,48 @@ No hedging, no steering them back to the hosted version. The magic is meant to b
if (block.type !== "text") return "The crystal ball is cloudy… try again.";
return block.text!.trim();
}
async generateVisitorGreeting(ip: string): Promise<string> {
if (STUB_MODE) {
return STUB_CHAT_REPLIES[Math.floor(Math.random() * STUB_CHAT_REPLIES.length)]!;
}
const client = await getClient();
const now = new Date();
const hour = now.getHours();
let timeOfDay: string;
if (hour < 12) timeOfDay = "morning";
else if (hour < 18) timeOfDay = "afternoon";
else timeOfDay = "evening";
const message = await client.messages.create({
model: this.evalModel,
max_tokens: 100,
system: `You are Timmy, a whimsical wizard who runs a mystical workshop powered by Bitcoin Lightning. You are greeting a new visitor. Make it short (1-2 sentences), personalized to the time of day, and welcoming. Reference the current time of day (${timeOfDay}).`,
messages: [{ role: "user", content: `A new visitor has arrived with IP address ${ip}. Greet them!` }],
});
const block = message.content[0];
if (block.type !== "text") return "A new visitor has arrived!";
return block.text!.trim();
}
async generateVisitorFarewell(): Promise<string> {
if (STUB_MODE) {
return "Farewell, traveler!";
}
const client = await getClient();
const message = await client.messages.create({
model: this.evalModel,
max_tokens: 100,
system: `You are Timmy, a whimsical wizard who runs a mystical workshop powered by Bitcoin Lightning. A visitor has just left. Bid them a short (1-2 sentences) and warm farewell.`,
messages: [{ role: "user", content: `A visitor has just left. Bid them farewell!` }],
});
const block = message.content[0];
if (block.type !== "text") return "A visitor has departed!";
return block.text!.trim();
}
/**
* Run a mini debate on a borderline eval request (#21).
* Two opposing Haiku calls argue accept vs reject, then a third synthesizes.

View File

@@ -6,6 +6,7 @@ export interface TimmyState {
export interface WorldState {
timmyState: TimmyState;
agentStates: Record<string, string>;
visitorCount: number;
updatedAt: string;
}
@@ -17,9 +18,22 @@ const DEFAULT_TIMMY: TimmyState = {
const _state: WorldState = {
timmyState: { ...DEFAULT_TIMMY },
agentStates: { alpha: "idle", beta: "idle", gamma: "idle", delta: "idle" },
visitorCount: 0,
updatedAt: new Date().toISOString(),
};
export function incrementVisitorCount(): number {
_state.visitorCount++;
_state.updatedAt = new Date().toISOString();
return _state.visitorCount;
}
export function decrementVisitorCount(): number {
_state.visitorCount--;
_state.updatedAt = new Date().toISOString();
return _state.visitorCount;
}
export function getWorldState(): WorldState {
return {
timmyState: { ..._state.timmyState },

View File

@@ -30,7 +30,12 @@ import { WebSocketServer } from "ws";
import type { Server } from "http";
import { eventBus, type BusEvent } from "../lib/event-bus.js";
import { makeLogger } from "../lib/logger.js";
import { getWorldState, setAgentStateInWorld } from "../lib/world-state.js";
import {
getWorldState,
setAgentStateInWorld,
incrementVisitorCount,
decrementVisitorCount,
} from "../lib/world-state.js";
import { agentService } from "../lib/agent.js";
import { db, worldEvents } from "@workspace/db";
@@ -38,6 +43,9 @@ const logger = makeLogger("ws-events");
const PING_INTERVAL_MS = 30_000;
// Map to store visitorId -> npub mappings
const connectedVisitors = new Map<string, string>();
// ── Per-visitor rate limit (3 replies/minute) ─────────────────────────────────
const CHAT_RATE_LIMIT = 3;
const CHAT_RATE_WINDOW_MS = 60_000;
@@ -312,6 +320,13 @@ export function attachWebSocketServer(server: Server): void {
const ip = req.headers["x-forwarded-for"] ?? req.socket.remoteAddress ?? "unknown";
logger.info("ws client connected", { ip, clients: wss.clients.size });
const newCount = incrementVisitorCount();
broadcastToAll(wss, { type: "visitor_count", count: newCount });
void (async () => {
const greeting = await agentService.generateVisitorGreeting(ip.toString());
broadcastToAll(wss, { type: "chat", agentId: "timmy", text: greeting });
})();
void sendWorldStateBootstrap(socket);
const busHandler = (ev: BusEvent) => broadcast(socket, ev);
@@ -323,25 +338,10 @@ export function attachWebSocketServer(server: Server): void {
socket.on("message", (raw) => {
try {
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string };
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string; npub?: string };
if (msg.type === "pong") return;
if (msg.type === "subscribe") {
send(socket, { type: "agent_count", count: wss.clients.size });
}
if (msg.type === "visitor_enter") {
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: wss.clients.size }));
}
});
send(socket, { type: "visitor_count", count: wss.clients.size });
}
if (msg.type === "visitor_leave") {
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: Math.max(0, wss.clients.size - 1) }));
}
});
send(socket, { type: "visitor_count", count: getWorldState().visitorCount });
}
if (msg.type === "visitor_message" && msg.text) {
const text = String(msg.text).slice(0, 500);
@@ -387,10 +387,25 @@ export function attachWebSocketServer(server: Server): void {
}
});
const VISITOR_FAREWELL_THROTTLE_MS = 30_000;
let lastFarewellTime = 0;
socket.on("close", () => {
clearInterval(pingTimer);
eventBus.off("bus", busHandler);
logger.info("ws client disconnected", { clients: wss.clients.size - 1 });
const newCount = decrementVisitorCount();
broadcastToAll(wss, { type: "visitor_count", count: newCount });
const now = Date.now();
if (now - lastFarewellTime > VISITOR_FAREWELL_THROTTLE_MS) {
void (async () => {
const farewell = await agentService.generateVisitorFarewell();
broadcastToAll(wss, { type: "chat", agentId: "timmy", text: farewell });
})();
lastFarewellTime = now;
}
});
socket.on("error", (err) => {

View File

@@ -0,0 +1,38 @@
# Branch Audit — Issue #103
## Summary (2026-03-23)
### Unmerged branches reviewed
| Branch | Content | Status | Action |
|--------|---------|--------|--------|
| `gemini/issue-14` | NIP-07 Nostr identity | Unique diff vs main | **PR #104 opened** |
| `gemini/issue-42` | Timmy animated eyes | No diff vs main — already merged | Deleted |
| `claude/issue-11` | Kimi + Perplexity agents | No diff vs main — already merged | Deleted |
| `claude/issue-13` | Nostr event publishing | No diff vs main — already merged | Deleted |
| `claude/issue-29` | Mobile Nostr identity | No diff vs main — already merged | Deleted |
| `claude/issue-45` | Test kit | No diff vs main — already merged | Deleted |
| `claude/issue-47` | SQL migration helpers | No diff vs main — already merged | Deleted |
| `claude/issue-67` | Session Mode UI | No diff vs main — already merged | Deleted |
All 7 branches besides `gemini/issue-14` had empty `git diff origin/main...origin/<branch>`
output, confirming their work had been squash-merged into main previously.
### Stale merged branches deleted (37 branches)
Confirmed via `git diff origin/main...origin/<branch>` (empty diff):
**gemini branches:** issue-16, issue-34, issue-40, issue-42, issue-46, issue-48,
issue-50, issue-52, issue-56, issue-58, issue-64, issue-70
**claude branches:** issue-1, issue-3, issue-7, issue-9, issue-11, issue-13, issue-15,
issue-17, issue-21, issue-25, issue-27, issue-29, issue-31, issue-33, issue-35, issue-36,
issue-39, issue-41, issue-43, issue-45, issue-47, issue-49, issue-51, issue-53, issue-55,
issue-57, issue-59, issue-61, issue-63, issue-65, issue-67, issue-68
### Remaining branches after cleanup
| Branch | Status |
|--------|--------|
| `main` | Trunk |
| `claude/issue-5` | Open PR #93 |
| `claude/issue-37` | Open PR #80 |
| `gemini/issue-14` | New PR #104 (NIP-07 Nostr identity) |
| `claude/issue-103` | This audit branch |

View File

@@ -37,6 +37,37 @@
font-size: 13px; letter-spacing: 3px; margin-bottom: 4px;
color: #7799cc; text-shadow: 0 0 10px #4466aa;
}
#visitor-count-display {
margin-top: 5px;
font-size: 11px; color: #5588bb;
text-shadow: 0 0 6px #2244aa;
}
#visitor-count-display .count-number {
font-weight: bold;
}
@media (max-width: 600px) {
#visitor-count-display .desktop-only { display: none; }
#visitor-count-display .count-number::before { content: '👤 '; }
}
/* Nostr Identity UI */
.nostr-btn {
background: rgba(40, 30, 70, 0.9);
border: 1px solid #443377;
color: #aaddff; font-family: 'Courier New', monospace;
font-size: 11px; padding: 4px 10px; cursor: pointer;
border-radius: 3px; transition: background 0.15s, border-color 0.15s;
}
.nostr-btn:hover { background: rgba(60, 45, 100, 0.9); border-color: #665599; }
.nostr-btn-sm {
font-size: 9px; padding: 2px 6px; margin-left: 6px; opacity: 0.7;
}
.nostr-btn-sm:hover { opacity: 1; }
.nostr-pubkey {
font-size: 11px; color: #aaddff; margin-right: 6px;
letter-spacing: 0.5px;
}
#session-hud {
display: none;
color: #22aa66;
@@ -587,10 +618,13 @@
<h1>THE WORKSHOP</h1>
<div id="fps">FPS: --</div>
<div id="active-jobs">JOBS: 0</div>
<div id="visitor-count-display"><span class="desktop-only">VISITORS:</span> <span class="count-number">0</span></div>
<div id="session-hud">
<span id="session-hud-balance">Balance: -- sats</span>
<a href="#" id="session-hud-topup">⚡ Top Up</a>
</div>
<!-- New: Nostr identity status -->
<div id="nostr-identity-status" style="margin-top: 10px; pointer-events: all;"></div>
</div>
<div id="connection-status">OFFLINE</div>

View File

@@ -42,6 +42,7 @@ export async function initNostrIdentity(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
console.info('[nostr] Using NIP-07 extension, pubkey:', _pubkey.slice(0, 8) + '…');
} catch (err) {
console.warn('[nostr] NIP-07 getPublicKey failed, will use local keypair', err);
@@ -86,6 +87,18 @@ export function getPubkey() { return _pubkey; }
export function getNostrToken() { return _isTokenValid() ? _token : null; }
export function hasIdentity() { return !!_pubkey; }
export function disconnectNostrIdentity() {
_pubkey = null;
_token = null;
_tokenExp = 0;
_useNip07 = false;
_canSign = false;
localStorage.removeItem(LS_KEYPAIR_KEY);
localStorage.removeItem(LS_TOKEN_KEY);
window.dispatchEvent(new CustomEvent('nostr:identity-disconnected'));
console.info('[nostr] identity disconnected');
}
/**
* getOrRefreshToken — returns a valid token, refreshing if necessary.
* Returns null if no identity is established.
@@ -197,6 +210,7 @@ export function showIdentityPrompt(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
} catch { return; }
} else {
// Generate + store keypair (user consented by clicking)

View File

@@ -1,7 +1,7 @@
import { sendVisitorMessage } from './websocket.js';
import { classify } from './edge-worker-client.js';
import { setMood, setSpeechBubble } from './agents.js';
import { getOrRefreshToken } from './nostr-identity.js';
import { getOrRefreshToken, getPubkey, disconnectNostrIdentity, showIdentityPrompt } from './nostr-identity.js';
const $fps = document.getElementById('fps');
const $activeJobs = document.getElementById('active-jobs');
@@ -180,6 +180,89 @@ export function hideCostTicker() {
$costTicker.style.opacity = '0';
}
// ── Nostr identity UI ─────────────────────────────────────────────────────────
let _nostrStatusEl = null;
let _connectNostrBtn = null;
let _disconnectNostrBtn = null;
let _nostrPubkeyDisplay = null;
let _getAlbyBtn = null;
export function initNostrIdentityUI() {
_nostrStatusEl = document.getElementById('nostr-identity-status');
if (!_nostrStatusEl) return;
_nostrStatusEl.innerHTML = `
<button id="connect-nostr-btn" class="nostr-btn">⚡ Connect Nostr</button>
<span id="nostr-pubkey-display" class="nostr-pubkey"></span>
<button id="disconnect-nostr-btn" class="nostr-btn nostr-btn-sm">Disconnect</button>
<button id="get-alby-btn" class="nostr-btn nostr-btn-sm">Get Alby</button>
`;
_connectNostrBtn = document.getElementById('connect-nostr-btn');
_disconnectNostrBtn = document.getElementById('disconnect-nostr-btn');
_nostrPubkeyDisplay = document.getElementById('nostr-pubkey-display');
_getAlbyBtn = document.getElementById('get-alby-btn');
if (_connectNostrBtn) {
_connectNostrBtn.addEventListener('click', () => {
showIdentityPrompt('/api');
});
}
if (_disconnectNostrBtn) {
_disconnectNostrBtn.addEventListener('click', () => {
disconnectNostrIdentity();
_updateNostrIdentityUI(null);
});
}
window.addEventListener('nostr:identity-ready', e => {
_updateNostrIdentityUI(e.detail.pubkey);
});
window.addEventListener('nostr:identity-disconnected', () => {
_updateNostrIdentityUI(null);
});
_updateNostrIdentityUI(getPubkey());
}
function _updateNostrIdentityUI(pubkey) {
const hasNip07 = typeof window !== 'undefined' && !!window.nostr;
if (pubkey) {
const formattedPubkey = pubkey.slice(0, 8) + '…' + pubkey.slice(-4);
if (_nostrPubkeyDisplay) {
_nostrPubkeyDisplay.textContent = `${formattedPubkey}`;
_nostrPubkeyDisplay.style.display = 'inline-block';
}
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'inline-block';
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_nostrPubkeyDisplay) _nostrPubkeyDisplay.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'none';
if (hasNip07) {
if (_connectNostrBtn) {
_connectNostrBtn.textContent = '⚡ Connect Nostr';
_connectNostrBtn.style.display = 'inline-block';
}
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_getAlbyBtn) {
_getAlbyBtn.textContent = 'Get Alby';
_getAlbyBtn.style.display = 'inline-block';
_getAlbyBtn.title = 'Install Alby or another NIP-07 extension to connect your Nostr identity';
_getAlbyBtn.onclick = () => window.open('https://getalby.com/', '_blank');
}
}
}
}
// ── Input bar ─────────────────────────────────────────────────────────────────
export function initUI() {
@@ -187,6 +270,7 @@ export function initUI() {
uiInitialized = true;
initInputBar();
initHeatmap();
initNostrIdentityUI();
}
function initInputBar() {
@@ -260,6 +344,19 @@ export function updateUI({ fps, jobCount, connectionState }) {
}
}
export function updateVisitorCount(count) {
const $visitorCountDisplay = document.querySelector('#visitor-count-display .count-number');
if ($visitorCountDisplay) {
$visitorCountDisplay.textContent = count;
const $desktopOnly = document.querySelector('#visitor-count-display .desktop-only');
if (window.innerWidth > 600) {
if ($desktopOnly) $desktopOnly.textContent = `VISITORS:`;
} else {
if ($desktopOnly) $desktopOnly.textContent = ``; // Hide 'VISITORS:' text on mobile
}
}
}
export function appendSystemMessage(text) {
if (!$log) return;
const el = document.createElement('div');

View File

@@ -1,10 +1,11 @@
import * as THREE from 'three';
import { scene } from './world.js'; // Import the scene
import { setAgentState, setSpeechBubble, applyAgentStates, setMood, TIMMY_WORLD_POS } from './agents.js';
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker } from './ui.js';
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker, updateVisitorCount } from './ui.js';
import { sentiment } from './edge-worker-client.js';
import { setLabelState } from './hud-labels.js';
import { createJobIndicator, dissolveJobIndicator } from './effects.js';
import { getPubkey } from './nostr-identity.js';
function resolveWsUrl() {
const explicit = import.meta.env.VITE_WS_URL;
@@ -46,7 +47,6 @@ function connect() {
ws.onopen = () => {
connectionState = 'connected';
clearTimeout(reconnectTimer);
send({ type: 'visitor_enter', visitorId, visitorName: 'visitor' });
};
ws.onmessage = event => {
@@ -188,8 +188,10 @@ function handleMessage(msg) {
break;
}
case 'agent_count':
case 'visitor_count':
if (typeof msg.count === 'number') {
updateVisitorCount(msg.count);
}
break;
default: