7 Commits

Author SHA1 Message Date
Ryan Hamamura
331c4c8759 docs: add AGENTS.md with coding guidelines for AI agents
All checks were successful
CI / Deploy / test (push) Successful in 15s
CI / Deploy / lint (push) Successful in 28s
CI / Deploy / deploy (push) Successful in 1m28s
Includes build/test commands, code style guidelines, naming conventions,
error handling patterns, and Go/templ/Datastar patterns used in this repo.
2026-03-03 10:53:14 -10:00
f6c5949247 Merge pull request 'Fix connection indicator script duplication on SSE patches' (#12) from fix/connection-indicator-script into main
All checks were successful
CI / Deploy / test (push) Successful in 18s
CI / Deploy / lint (push) Successful in 25s
CI / Deploy / deploy (push) Successful in 1m27s
2026-03-03 20:44:56 +00:00
Ryan Hamamura
d6e64763cc fix: use templ.NewOnceHandle to prevent script duplication on SSE patches
All checks were successful
CI / Deploy / test (pull_request) Successful in 15s
CI / Deploy / lint (pull_request) Successful in 25s
CI / Deploy / deploy (pull_request) Has been skipped
Replace ConnectionIndicatorWithScript wrapper with a single ConnectionIndicator
component that uses templ.NewOnceHandle() to ensure the watcher script is only
rendered once per page, even when the indicator is patched via SSE.
2026-03-03 10:43:23 -10:00
589d1f09e8 Merge pull request 'Refactor connection indicator to patch with timestamp' (#11) from refactor/patch-connection-indicator into main
All checks were successful
CI / Deploy / test (push) Successful in 14s
CI / Deploy / lint (push) Successful in 25s
CI / Deploy / deploy (push) Successful in 1m22s
2026-03-03 20:32:11 +00:00
Ryan Hamamura
06b3839c3a refactor: patch connection indicator with timestamp
All checks were successful
CI / Deploy / test (pull_request) Successful in 14s
CI / Deploy / lint (pull_request) Successful in 26s
CI / Deploy / deploy (pull_request) Has been skipped
Server patches the ConnectionIndicator element with a timestamp on
each heartbeat. Client-side JS checks every second if the timestamp
is stale (>20s) and toggles red/green accordingly.

This properly detects connection loss since the indicator will turn
red if no patches are received.
2026-03-03 10:30:55 -10:00
99f14ca170 Merge pull request 'Add connection status indicator with SSE heartbeat' (#10) from feat/sse-heartbeat into main
All checks were successful
CI / Deploy / test (push) Successful in 15s
CI / Deploy / lint (push) Successful in 27s
CI / Deploy / deploy (push) Successful in 1m23s
2026-03-03 20:15:29 +00:00
Ryan Hamamura
da82f31d46 feat: add connection status indicator with SSE heartbeat
All checks were successful
CI / Deploy / test (pull_request) Successful in 14s
CI / Deploy / lint (pull_request) Successful in 25s
CI / Deploy / deploy (pull_request) Has been skipped
- Add ConnectionIndicator component showing green/red dot
- Send lastPing signal every 15 seconds via SSE
- Indicator turns red if no ping received in 20 seconds
- Gives users confidence the live connection is active
2026-03-03 10:05:03 -10:00
7 changed files with 351 additions and 3 deletions

1
.gitignore vendored
View File

@@ -19,6 +19,7 @@
!.env.example
!LICENSE
!AGENTS.md
!assets/**/*

253
AGENTS.md Normal file
View File

@@ -0,0 +1,253 @@
# AGENTS.md
Instructions for AI coding agents working in this repository.
## Quick Reference
```bash
# Development
task live # Hot-reload dev server (templ + tailwind + air)
task build # Production build to bin/games
task run # Build and run server
# Quality
task test # Run all tests: go test ./...
task lint # Run linter: golangci-lint run
# Single test
go test -run TestName ./path/to/package
# Code generation
task build:templ # Compile .templ files
task build:styles # Build TailwindCSS
go generate ./... # Run sqlc for DB queries
```
## Workflow Rules
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
- Always use PRs via `tea` CLI - never push directly to main.
- Write semantic commit messages focusing on "why" not "what".
## Project Structure
```
games/
├── connect4/, snake/ # Game logic packages (pure Go)
├── features/ # Feature modules (handlers, routes, templates)
│ ├── auth/ # Login/register
│ ├── c4game/ # Connect 4 UI
│ ├── snakegame/ # Snake UI
│ ├── lobby/ # Game lobby
│ └── common/ # Shared components, layouts
├── chat/ # Reusable chat room (NATS + persistence)
├── db/ # SQLite, migrations, sqlc queries
├── assets/ # Static files (embedded)
└── config/, logging/, nats/, sessions/, router/ # Infrastructure
```
## Code Style
### Imports
Organize in three groups: stdlib, third-party, local. The linter enforces this.
```go
import (
"context"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
)
```
### Naming Conventions
| Type | Convention | Examples |
|------|------------|----------|
| Files | lowercase, underscores | `config_dev.go`, `handlers.go` |
| HTTP handlers | `Handle` prefix | `HandleGamePage`, `HandleLogin` |
| Constructors | `New` prefix | `NewStore`, `NewRoom` |
| Getters | `Get` prefix | `GetPlayerID`, `GetGame` |
| Setup functions | `Setup` prefix | `SetupRoutes`, `SetupLogger` |
| Types | PascalCase | `Game`, `Player`, `Instance` |
| Status enums | `Status` prefix | `StatusWaitingForPlayer`, `StatusInProgress` |
| Session keys | `Key` prefix | `KeyPlayerID`, `KeyUserID` |
### Error Handling
1. **Wrap errors with context:**
```go
return fmt.Errorf("loading game %s: %w", id, err)
```
2. **Return (result, error) tuples:**
```go
func loadGame(queries *repository.Queries, id string) (*Game, error)
```
3. **Best-effort operations** - use nolint comment:
```go
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
```
4. **HTTP errors:**
```go
http.Error(w, "game not found", http.StatusNotFound)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
```
### Comments
- Focus on **why**, not **how**. Avoid superfluous comments.
- Package comments at top of primary file:
```go
// Package connect4 implements Connect 4 game logic, state management, and persistence.
package connect4
```
- Function comments for exported functions:
```go
// DropPiece attempts to drop a piece in the given column.
// Returns (row placed, success).
func (g *Game) DropPiece(col, playerColor int) (int, bool)
```
## Go Patterns
### Dependency Injection via Closures
Handlers receive dependencies and return `http.HandlerFunc`:
```go
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// use store, sm here
}
}
```
### Mutex for Concurrent Access
```go
type Store struct {
games map[string]*Instance
gamesMu sync.RWMutex
}
func (s *Store) Get(id string) (*Instance, bool) {
s.gamesMu.RLock()
defer s.gamesMu.RUnlock()
inst, ok := s.games[id]
return inst, ok
}
```
### Build Tags for Environment
```go
//go:build dev
//go:build !dev
```
### Embedded Filesystems
```go
//go:embed assets
var assets embed.FS
//go:embed migrations/*.sql
var MigrationFS embed.FS
```
### Graceful Shutdown
```go
eg, egctx := errgroup.WithContext(ctx)
eg.Go(func() error { return server.ListenAndServe() })
eg.Go(func() error {
<-egctx.Done()
return server.Shutdown(context.Background())
})
return eg.Wait()
```
## Templ + Datastar Patterns
### SSE Connection with Disabled Cancellation
Datastar cancels SSE on user interaction by default. Disable for persistent connections:
```go
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
```
### Prevent Script Duplication on SSE Patches
Use `templ.NewOnceHandle()` for scripts in components that get patched:
```go
var scriptHandle = templ.NewOnceHandle()
templ MyComponent() {
<div id="my-component">...</div>
@scriptHandle.Once() {
@myScript()
}
}
```
### Conditional Classes with templ.KV
```go
class={
"status status-sm",
templ.KV("status-success", isConnected),
templ.KV("status-error", !isConnected),
}
```
### Datastar SSE Responses
```go
sse := datastar.NewSSE(w, r)
sse.MergeFragmentTempl(components.GameBoard(game))
```
## Tech Stack
| Layer | Technology |
|-------|------------|
| Templates | templ (type-safe HTML) |
| Reactivity | Datastar (SSE-driven) |
| CSS | TailwindCSS v4 + daisyUI |
| Router | chi/v5 |
| Sessions | scs/v2 |
| Database | SQLite (modernc.org/sqlite) |
| Migrations | goose |
| SQL codegen | sqlc |
| Pub/sub | Embedded NATS |
| Logging | zerolog |
## Testing
```bash
# All tests
task test
# Single test
go test -run TestDropPiece ./connect4
# With verbose output
go test -v -run TestDropPiece ./connect4
# Test a package
go test ./connect4/...
```
Use `testutil.SetupTestDB()` for tests requiring database access.

View File

@@ -16,6 +16,7 @@ import (
"github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
"github.com/ryanhamamura/games/features/c4game/pages"
sharedcomponents "github.com/ryanhamamura/games/features/common/components"
"github.com/ryanhamamura/games/sessions"
)
@@ -118,11 +119,21 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
}
// Send initial render
sendPing := func() error {
return sse.PatchElementTempl(sharedcomponents.ConnectionIndicator(time.Now().UnixMilli()))
}
// Send initial render and ping
if err := sendPing(); err != nil {
return
}
if err := patchAll(); err != nil {
return
}
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
// Subscribe to game state updates
gameCh := make(chan *nats.Msg, 64)
gameSub, err := nc.ChanSubscribe(connect4.GameSubject(gameID), gameCh)
@@ -140,6 +151,10 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
select {
case <-ctx.Done():
return
case <-heartbeat.C:
if err := sendPing(); err != nil {
return
}
case <-gameCh:
if err := patchAll(); err != nil {
return

View File

@@ -18,6 +18,7 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
data-signals="{chatMsg: ''}"
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
>
@sharedcomponents.ConnectionIndicator(0)
@GameContent(g, myColor, messages, chatCfg)
</main>
}

View File

@@ -1,6 +1,10 @@
package components
import "github.com/starfederation/datastar-go/datastar"
import (
"fmt"
"github.com/starfederation/datastar-go/datastar"
)
templ BackToLobby() {
<a class="link text-sm opacity-70" href="/">&larr; Back</a>
@@ -44,6 +48,62 @@ templ NicknamePrompt(returnPath string) {
</main>
}
func isStale(lastPing int64) bool {
return lastPing == 0
}
var connectionWatcherHandle = templ.NewOnceHandle()
// ConnectionIndicator shows a small dot indicating SSE connection status.
// Server patches this with a timestamp; client JS detects staleness.
templ ConnectionIndicator(lastPing int64) {
<div
id="connection-indicator"
class="fixed top-2 right-2"
data-last-ping={ fmt.Sprintf("%d", lastPing) }
>
<div class="inline-grid *:[grid-area:1/1]">
<div
id="connection-ping"
class={
"status status-sm",
templ.KV("status-success animate-ping", !isStale(lastPing)),
templ.KV("status-error", isStale(lastPing)),
}
></div>
<div
id="connection-dot"
class={
"status status-sm",
templ.KV("status-success", !isStale(lastPing)),
templ.KV("status-error", isStale(lastPing)),
}
></div>
</div>
</div>
@connectionWatcherHandle.Once() {
@connectionWatcher()
}
}
script connectionWatcher() {
setInterval(function() {
var el = document.getElementById('connection-indicator');
var dot = document.getElementById('connection-dot');
var ping = document.getElementById('connection-ping');
if (!el || !dot || !ping) return;
var lastPing = parseInt(el.dataset.lastPing, 10) || 0;
var stale = Date.now() - lastPing > 20000;
dot.classList.toggle('status-success', !stale);
dot.classList.toggle('status-error', stale);
ping.classList.toggle('status-success', !stale);
ping.classList.toggle('status-error', stale);
ping.classList.toggle('animate-ping', !stale);
}, 1000);
}
templ GameJoinPrompt(loginURL string, registerURL string, gamePath string) {
<main class="max-w-sm mx-auto mt-8 text-center">
<h1 class="text-3xl font-bold">Join Game</h1>

View File

@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"strconv"
"time"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
@@ -12,6 +13,7 @@ import (
"github.com/ryanhamamura/games/chat"
chatcomponents "github.com/ryanhamamura/games/chat/components"
sharedcomponents "github.com/ryanhamamura/games/features/common/components"
"github.com/ryanhamamura/games/features/snakegame/pages"
"github.com/ryanhamamura/games/sessions"
"github.com/ryanhamamura/games/snake"
@@ -123,11 +125,21 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
}
// Send initial render
sendPing := func() error {
return sse.PatchElementTempl(sharedcomponents.ConnectionIndicator(time.Now().UnixMilli()))
}
// Send initial render and ping
if err := sendPing(); err != nil {
return
}
if err := patchAll(); err != nil {
return
}
heartbeat := time.NewTicker(15 * time.Second)
defer heartbeat.Stop()
// Subscribe to game updates via NATS
gameCh := make(chan *nats.Msg, 64)
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
@@ -151,6 +163,11 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
case <-ctx.Done():
return
case <-heartbeat.C:
if err := sendPing(); err != nil {
return
}
case <-gameCh:
// Drain backed-up game updates
for {

View File

@@ -37,6 +37,7 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
tabindex="0"
>
@components.ConnectionIndicator(0)
@GameContent(sg, mySlot, messages, chatCfg, gameID)
</main>
}