feat: chat on a world: world, tribe and direct channels with unread counts and live pushes

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-30 10:56:17 +01:00
parent fdb31123b6
commit 9f2a89b498
7 changed files with 362 additions and 1 deletions

193
app/Actions/Chat.php Normal file
View File

@ -0,0 +1,193 @@
<?php
namespace App\Actions;
use App\Game\GameRuleViolation;
use App\Models\ChatMessage;
use App\Models\Player;
use App\Models\User;
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Chat on a world (architecture.md, "Chat"). The client names channels from its own side:
* `world`, `tribe` (the player's tribe) and `dm:<player id>` (a conversation with that
* player); stored, they are `world`, `tribe:<id>` and `dm:<lower id>:<higher id>`. A new
* message is whispered as `chat:message` to every listener's sockets, in their naming.
*/
final class Chat
{
public const MAX_LENGTH = 500;
public const PAGE = 50;
/** Every channel the player can read, with unread counts, last message first for direct ones. */
public function channels(User $user, int $worldId): array
{
$me = $this->player($user, $worldId);
$channels = ['world' => 'world'];
if ($tribe = $me->tribeId()) {
$channels['tribe'] = "tribe:$tribe";
}
$direct = ChatMessage::where('world_id', $worldId)
->where(fn ($q) => $q->where('channel', 'like', "dm:{$me->id}:%")->orWhere('channel', 'like', "dm:%:{$me->id}"))
->groupBy('channel')->selectRaw('channel, MAX(id) as last')->orderByDesc('last')->pluck('channel');
$others = Player::whereIn('id', $direct->map(fn (string $c) => $this->other($c, $me->id)))->pluck('name', 'id');
foreach ($direct as $stored) {
$channels['dm:'.$this->other($stored, $me->id)] = $stored;
}
$reads = DB::table('chat_reads')->where('player_id', $me->id)->pluck('last_id', 'channel');
return collect($channels)->map(function (string $stored, string $channel) use ($me, $reads, $others, $worldId) {
$other = str_starts_with($channel, 'dm:') ? (int) substr($channel, 3) : null;
return [
'channel' => $channel,
'with' => $other ? ['id' => $other, 'name' => $others[$other] ?? '?'] : null,
'unread' => ChatMessage::where('world_id', $worldId)->where('channel', $stored)->where('player_id', '!=', $me->id)->where('id', '>', $reads[$stored] ?? 0)->count(),
];
})->values()->all();
}
/** The last messages of a channel (or those before an id), oldest first; reading marks them read. */
public function history(User $user, int $worldId, string $channel, ?int $before = null): array
{
$me = $this->player($user, $worldId);
$stored = $this->stored($me, $channel);
$messages = ChatMessage::with('player:id,name')->where('world_id', $worldId)->where('channel', $stored)
->when($before, fn ($q) => $q->where('id', '<', $before))
->orderByDesc('id')->limit(self::PAGE)->get()->reverse()->values();
if (! $before && $messages->isNotEmpty()) {
$this->markRead($me, $stored, $messages->last()->id);
}
return [
'channel' => $channel,
'messages' => $messages->map(fn (ChatMessage $m) => self::present($m))->all(),
'more' => $messages->count() === self::PAGE,
];
}
/** Open a conversation with a player by name: the channel to write in. */
public function open(User $user, int $worldId, string $name): array
{
$me = $this->player($user, $worldId);
$other = Player::where('world_id', $worldId)->where('name', trim($name))->first()
?? throw new GameRuleViolation('no_player', 'No player of that name here.');
if ($other->id === $me->id) {
throw new GameRuleViolation('no_player', 'That is you.');
}
return ['channel' => "dm:{$other->id}", 'with' => ['id' => $other->id, 'name' => $other->name], 'unread' => 0];
}
public function send(User $user, int $worldId, string $channel, string $body): array
{
$me = $this->player($user, $worldId);
$me->world->ensureOpen();
$body = trim($body);
if ($body === '' || mb_strlen($body) > self::MAX_LENGTH) {
throw new GameRuleViolation('chat_length', 'Messages are 1 to 500 characters.');
}
$stored = $this->stored($me, $channel);
// One message a second per player is plenty for talking.
if (! cache()->add("chat.{$me->id}", true, 1)) {
throw new GameRuleViolation('chat_slow', 'Slow down a little.');
}
$message = ChatMessage::create(['world_id' => $worldId, 'channel' => $stored, 'player_id' => $me->id, 'body' => $body, 'created_at' => now()->toImmutable()]);
$message->setRelation('player', $me);
$this->markRead($me, $stored, $message->id);
$this->push($message, $me);
return self::present($message);
}
/** The player has seen a channel up to its newest message. */
public function read(User $user, int $worldId, string $channel): array
{
$me = $this->player($user, $worldId);
$stored = $this->stored($me, $channel);
$last = ChatMessage::where('world_id', $worldId)->where('channel', $stored)->max('id');
if ($last) {
$this->markRead($me, $stored, (int) $last);
}
return ['channel' => $channel, 'unread' => 0];
}
/** The stored name of a channel the player may use. */
private function stored(Player $me, string $channel): string
{
if ($channel === 'world') {
return 'world';
}
if ($channel === 'tribe') {
return 'tribe:'.($me->tribeId() ?? throw new GameRuleViolation('no_tribe', 'You are not in a tribe.'));
}
if (preg_match('/^dm:(\d+)$/', $channel, $m) && (int) $m[1] !== $me->id && Player::where('world_id', $me->world_id)->whereKey((int) $m[1])->exists()) {
$ids = [$me->id, (int) $m[1]];
sort($ids);
return 'dm:'.implode(':', $ids);
}
throw new GameRuleViolation('not_found', 'No such channel.');
}
private function other(string $stored, int $me): int
{
[, $a, $b] = explode(':', $stored);
return (int) $a === $me ? (int) $b : (int) $a;
}
/** Everyone who reads the channel hears of the message, in their own naming of it. */
private function push(ChatMessage $message, Player $from): void
{
if (! ws_available()) {
return;
}
[$kind] = explode(':', $message->channel);
$listeners = match ($kind) {
'world' => Player::where('world_id', $message->world_id)->get(['id', 'user_id']),
'tribe' => Player::whereIn('id', DB::table('tribe_members')->where('tribe_id', (int) substr($message->channel, 6))->pluck('player_id'))->get(['id', 'user_id']),
default => Player::whereIn('id', array_map('intval', array_slice(explode(':', $message->channel), 1)))->get(['id', 'user_id']),
};
foreach ($listeners as $listener) {
$channel = $kind === 'dm' ? 'dm:'.($listener->id === $from->id ? $this->other($message->channel, $from->id) : $from->id) : $kind;
try {
$sockets = WebsocketService::getUserSocketIds($listener->user_id);
if ($sockets) {
ws_whisper('chat:message', ['world_id' => $message->world_id, 'channel' => $channel, 'message' => self::present($message)], $sockets);
}
} catch (Throwable $e) {
// The message is stored; a missed push shows on the next look.
report($e);
}
}
}
private function markRead(Player $me, string $stored, int $id): void
{
DB::table('chat_reads')->upsert([['player_id' => $me->id, 'channel' => $stored, 'last_id' => $id]], ['player_id', 'channel'], ['last_id']);
}
private function player(User $user, int $worldId): Player
{
return Player::with(['world', 'membership'])->where('user_id', $user->id)->where('world_id', $worldId)->first()
?? throw new GameRuleViolation('not_found', 'You have not joined this world.');
}
/** @return array{id: int, player: array{id: int, name: string}, body: string, at: string} */
private static function present(ChatMessage $m): array
{
return ['id' => $m->id, 'player' => ['id' => $m->player->id, 'name' => $m->player->name], 'body' => $m->body, 'at' => self::iso($m->created_at)];
}
private static function iso(CarbonImmutable $at): string
{
return $at->utc()->format('Y-m-d\TH:i:s.v\Z');
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ChatMessage extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s.v';
protected function casts(): array
{
return ['created_at' => 'immutable_datetime'];
}
public function player(): BelongsTo
{
return $this->belongsTo(Player::class);
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Websocket\Controllers;
use App\Actions\Chat;
use App\Websocket\GameController;
/** chat.channels|history|open|send|read, each with world_id; channels are world, tribe and dm:<player id>. */
class ChatController extends GameController
{
public function channels()
{
return $this->play(fn () => app(Chat::class)->channels(auth()->user(), (int) request('world_id')));
}
public function history()
{
return $this->play(fn () => app(Chat::class)->history(auth()->user(), (int) request('world_id'), (string) request('channel'), request('before') ? (int) request('before') : null));
}
public function open()
{
return $this->play(fn () => app(Chat::class)->open(auth()->user(), (int) request('world_id'), (string) request('player')));
}
public function send()
{
return $this->play(fn () => app(Chat::class)->send(auth()->user(), (int) request('world_id'), (string) request('channel'), (string) request('body')));
}
public function read()
{
return $this->play(fn () => app(Chat::class)->read(auth()->user(), (int) request('world_id'), (string) request('channel')));
}
}

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Chat on a world: one channel for everyone, one per tribe, one per pair of players.
return new class extends Migration
{
public function up(): void
{
Schema::create('chat_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('world_id')->constrained()->cascadeOnDelete();
// world, tribe:<id>, or dm:<lower player id>:<higher player id>
$table->string('channel', 40);
$table->foreignId('player_id')->constrained()->cascadeOnDelete();
$table->text('body');
$table->dateTime('created_at', 3);
$table->index(['world_id', 'channel', 'id']);
});
Schema::create('chat_reads', function (Blueprint $table) {
$table->id();
$table->foreignId('player_id')->constrained()->cascadeOnDelete();
$table->string('channel', 40);
$table->unsignedBigInteger('last_id');
$table->unique(['player_id', 'channel']);
});
}
public function down(): void
{
Schema::dropIfExists('chat_reads');
Schema::dropIfExists('chat_messages');
}
};

View File

@ -265,6 +265,13 @@ Players band together in tribes (`Tribes` action, `tribe.*` over WS, rules in `D
- Members of one tribe, allies and NAP partners can't attack each other (`own_tribe`, `pact` at the rally point). Support goes to anyone, as before.
- The tribe page (`tribe.show`) carries the members with points, the invites sent, the relations (holds, ending with `ends_at`, offered, incoming, enemy, hostile) and the last 30 events of its news; `tribe.list` every tribe with its size, points and relation. The village payload carries `tribe: {tribe, invites}` for the menu badge. The ranking has a tribe kind and tags players with their tribe.
## Chat
Players talk on their world (`Chat` action, `chat.*` over WS). The client names channels from its own side: `world` (everyone on the world), `tribe` (the player's tribe) and `dm:<player id>` (a conversation with that player, opened by name with `chat.open`). Stored (`chat_messages`), they are `world`, `tribe:<id>` and `dm:<lower id>:<higher id>`, so a tribe's talk stays with the tribe even as members come and go.
- `chat.send` takes 1 to 500 characters, one message a second per player, on open worlds only. Every reader of the channel gets `chat:message {world_id, channel, message}` whispered to their sockets, with the channel in their own naming.
- `chat.channels` lists the channels with unread counts (`chat_reads` keeps each player's last read message per channel; direct conversations newest first), `chat.history` the last 50 messages (or 50 before an id) and marks them read, `chat.read` marks a channel read.
## Seasons
A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`).

View File

@ -58,7 +58,8 @@ What Die Stämme has at this stage that the game still lacks.
- [x] Rename villages
- [ ] Player and village profile pages (from the map, reports and movements)
- [x] Ranking: players by points, villages by points, opponents defeated (attack and defence)
- [ ] Messages between players (inbox, threads)
- [x] Chat between players: the world, the tribe, and direct conversations, live
- [ ] Messages between players as letters (inbox, threads), if the chat isn't enough
- [ ] Notebook and account settings (vacation mode later)
## M4.6: Game loop

View File

@ -0,0 +1,64 @@
<?php
use App\Actions\Chat;
use App\Actions\Tribes;
use Carbon\CarbonImmutable;
beforeEach(fn () => $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00')));
function chat(): Chat
{
return app(Chat::class);
}
it('talks on the world channel and counts what is unread', function () {
$a = startVillage();
$b = startVillage();
$sent = chat()->send(owner($a), $a->world_id, 'world', ' Hello, neighbours! ');
expect($sent)->toMatchArray(['body' => 'Hello, neighbours!', 'player' => ['id' => $a->player_id, 'name' => $a->player->name]]);
expect(chat()->channels(owner($b), $b->world_id))->toBe([['channel' => 'world', 'with' => null, 'unread' => 1]])
->and(chat()->channels(owner($a), $a->world_id)[0]['unread'])->toBe(0);
$history = chat()->history(owner($b), $b->world_id, 'world');
expect($history['messages'])->toHaveCount(1)->and($history['more'])->toBeFalse()
->and(chat()->channels(owner($b), $b->world_id)[0]['unread'])->toBe(0);
});
it('keeps tribe talk inside the tribe', function () {
$a = startVillage();
$b = startVillage();
expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'tribe', 'Hi')))->toBe('no_tribe');
app(Tribes::class)->found(owner($a), $a->world_id, 'Dorfrat', 'DRF');
chat()->send(owner($a), $a->world_id, 'tribe', 'Council at dawn');
expect(collect(chat()->channels(owner($a), $a->world_id))->pluck('channel')->all())->toBe(['world', 'tribe'])
->and(chat()->history(owner($a), $a->world_id, 'tribe')['messages'][0]['body'])->toBe('Council at dawn')
->and(rule(fn () => chat()->history(owner($b), $b->world_id, 'tribe')))->toBe('no_tribe');
});
it('opens a conversation between two players by name', function () {
$a = startVillage();
$b = startVillage();
$c = startVillage();
$open = chat()->open(owner($a), $a->world_id, $b->player->name);
expect($open['channel'])->toBe("dm:{$b->player_id}");
chat()->send(owner($a), $a->world_id, $open['channel'], 'Truce?');
$theirs = collect(chat()->channels(owner($b), $b->world_id))->firstWhere('channel', "dm:{$a->player_id}");
expect($theirs)->toBe(['channel' => "dm:{$a->player_id}", 'with' => ['id' => $a->player_id, 'name' => $a->player->name], 'unread' => 1])
->and(chat()->history(owner($b), $b->world_id, "dm:{$a->player_id}")['messages'][0]['body'])->toBe('Truce?')
->and(collect(chat()->channels(owner($c), $c->world_id))->pluck('channel')->all())->toBe(['world'])
->and(rule(fn () => chat()->open(owner($a), $a->world_id, 'Nobody')))->toBe('no_player');
});
it('refuses empty, long and too quick messages', function () {
$a = startVillage();
expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', ' ')))->toBe('chat_length')
->and(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', str_repeat('a', 501))))->toBe('chat_length');
chat()->send(owner($a), $a->world_id, 'world', 'one');
expect(rule(fn () => chat()->send(owner($a), $a->world_id, 'world', 'two')))->toBe('chat_slow');
$this->travel(2)->seconds();
chat()->send(owner($a), $a->world_id, 'world', 'two');
expect(chat()->history(owner($a), $a->world_id, 'world')['messages'])->toHaveCount(2);
});