合并 master 到跳一跳分支
合入 origin/master 最新变更 解决跳一跳提示词测试与图集去背冲突
This commit is contained in:
@@ -5,6 +5,7 @@ name = "Genarrative"
|
||||
[setup]
|
||||
script = '''
|
||||
cp "$CODEX_SOURCE_TREE_PATH/.env.secrets.local" "$CODEX_WORKTREE_PATH/.env.secrets.local"
|
||||
git reset --hard
|
||||
npm install
|
||||
npm run codegraph:init
|
||||
npm run codegraph:index
|
||||
|
||||
@@ -1,229 +1,151 @@
|
||||
---
|
||||
name: spacetimedb-cli
|
||||
description: SpacetimeDB CLI reference for initializing projects, building modules, publishing databases, querying data, and managing servers
|
||||
triggers:
|
||||
- spacetime init
|
||||
- spacetime build
|
||||
- spacetime publish
|
||||
- spacetime dev
|
||||
- spacetime sql
|
||||
- spacetime call
|
||||
- spacetime logs
|
||||
- spacetime server
|
||||
- spacetime login
|
||||
- spacetime generate
|
||||
- how do I use the CLI
|
||||
- CLI command
|
||||
description: SpacetimeDB 2.5 CLI reference for Genarrative. Use for spacetime build, publish, generate, call, sql, logs, server management, local dev, explicit server targeting, version checks, and remote runtime verification.
|
||||
---
|
||||
|
||||
# SpacetimeDB CLI
|
||||
|
||||
Use this skill when the user needs help with the `spacetime` CLI tool - initializing projects, building modules, publishing databases, querying data, managing servers, or troubleshooting CLI issues.
|
||||
Use this skill when working with the `spacetime` CLI in Genarrative. Prefer repository scripts when they exist, and keep every operation pinned to an explicit target server or local process.
|
||||
|
||||
## Quick Reference
|
||||
## Genarrative Rules
|
||||
|
||||
### Project Initialization & Development
|
||||
- Do not rely on the default SpacetimeDB cloud target. Pass `--server` or `--server-url` explicitly in scripts, docs, smoke tests, and manual troubleshooting.
|
||||
- Do not introduce `maincloud` / `MAINCLOUD` commands, env vars, or docs. Treat old references as historical residue.
|
||||
- Do not use `spacetime --root-dir` in manual commands or docs. Use project scripts, `--data-dir`, explicit `--server`, or the configured running service.
|
||||
- For repository version upgrades, update `server-rs/Cargo.toml` exact pins, regenerate bindings, and verify the actual CLI/runtime version. Do not treat a local CLI reinstall as a repo upgrade.
|
||||
- For host upgrades, verify the running service binary, not just shell PATH: `systemctl show ... MainPID` -> `/proc/$pid/exe --version` -> `/v1/ping`.
|
||||
|
||||
## Core Commands
|
||||
|
||||
```bash
|
||||
# Initialize new project
|
||||
spacetime init my-project --lang rust|csharp|typescript|cpp
|
||||
spacetime init my-project --template <template-id>
|
||||
|
||||
# Build module
|
||||
spacetime build # release build
|
||||
spacetime build --debug # faster iteration, slower runtime
|
||||
spacetime build
|
||||
spacetime build --debug
|
||||
|
||||
# Dev mode (auto-rebuild, auto-publish, generates bindings)
|
||||
spacetime dev
|
||||
spacetime dev --client-lang typescript --module-bindings-path ./client/src/module_bindings
|
||||
# Publish to an explicit server
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --yes=migrate,break-clients
|
||||
|
||||
# Generate client bindings
|
||||
# Destructive publish only when explicitly intended
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=always --yes=delete-data,migrate
|
||||
|
||||
# Delete data only for breaking schema conflicts
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
|
||||
|
||||
# Generate bindings
|
||||
spacetime generate --lang typescript|csharp|rust|unrealcpp --out-dir ./bindings --module-path ./server
|
||||
```
|
||||
|
||||
### Publishing & Deployment
|
||||
## Genarrative Local Workflow
|
||||
|
||||
```bash
|
||||
# Publish to an explicit server
|
||||
spacetime publish my-database --server http://127.0.0.1:3101 --yes
|
||||
# Prefer project wrappers
|
||||
npm run dev:spacetime
|
||||
npm run dev:api-server
|
||||
npm run spacetime:generate
|
||||
|
||||
# Publish to local server
|
||||
spacetime publish my-database --server local --yes
|
||||
# Query local database
|
||||
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM players"
|
||||
|
||||
# Clear database and republish
|
||||
spacetime publish my-database --clear-database --yes
|
||||
# Logs
|
||||
spacetime logs my-db --server http://127.0.0.1:3101 -f
|
||||
```
|
||||
|
||||
### Database Interaction
|
||||
## Database Interaction
|
||||
|
||||
```bash
|
||||
# SQL queries
|
||||
spacetime sql my-database "SELECT * FROM users"
|
||||
spacetime sql my-database --interactive # REPL mode
|
||||
# SQL / describe
|
||||
spacetime sql my-db --server http://127.0.0.1:3101 "SELECT * FROM users"
|
||||
spacetime describe my-db --server http://127.0.0.1:3101 --json
|
||||
spacetime describe my-db table users --server http://127.0.0.1:3101 --json
|
||||
|
||||
# Call reducers
|
||||
spacetime call my-database my_reducer '{"arg1": "value", "arg2": 123}'
|
||||
# Reducer/procedure calls. Arguments are positional JSON values.
|
||||
spacetime call --server http://127.0.0.1:3101 my-db my_reducer '"value"' '123'
|
||||
|
||||
# Subscribe to changes
|
||||
spacetime subscribe my-database "SELECT * FROM users" --num-updates 10
|
||||
# 2.5 accepts hex strings for Identity arguments without full JSON tuple syntax.
|
||||
spacetime call --server http://127.0.0.1:3101 my-db reducer_needing_identity 0xabc123...
|
||||
|
||||
# View logs
|
||||
spacetime logs my-database -f # follow logs
|
||||
spacetime logs my-database -n 100 # up to 100 log lines
|
||||
|
||||
# Describe schema
|
||||
spacetime describe my-database --json
|
||||
spacetime describe my-database table users --json
|
||||
spacetime describe my-database reducer my_reducer --json
|
||||
# Subscribe from CLI
|
||||
spacetime subscribe my-db "SELECT * FROM users" --num-updates 10 --server http://127.0.0.1:3101
|
||||
```
|
||||
|
||||
### Database Management
|
||||
## Server & Auth
|
||||
|
||||
```bash
|
||||
# List databases
|
||||
spacetime list
|
||||
|
||||
# Delete database
|
||||
spacetime delete my-database
|
||||
|
||||
# Rename database
|
||||
spacetime rename <database-identity> --to new-name
|
||||
```
|
||||
|
||||
### Server Management
|
||||
|
||||
```bash
|
||||
# List configured servers
|
||||
spacetime server list
|
||||
|
||||
# Add server
|
||||
spacetime server add local --url http://localhost:3000 --default
|
||||
spacetime server add myserver --url https://my-spacetime.example.com
|
||||
spacetime server add genarrative-dev --url http://127.0.0.1:3101
|
||||
spacetime server ping genarrative-dev
|
||||
|
||||
# Set default server
|
||||
spacetime server set-default local
|
||||
|
||||
# Test connectivity
|
||||
spacetime server ping local
|
||||
|
||||
# Start local instance
|
||||
spacetime start
|
||||
|
||||
# Clear local data
|
||||
spacetime server clear
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
```bash
|
||||
# Login (opens browser)
|
||||
spacetime login
|
||||
|
||||
# Login with token
|
||||
spacetime login --token <token>
|
||||
|
||||
# Show login status
|
||||
spacetime login show
|
||||
|
||||
# Logout
|
||||
spacetime logout
|
||||
```
|
||||
|
||||
## Default Servers
|
||||
|
||||
| Name | URL | Description |
|
||||
|------|-----|-------------|
|
||||
| `local` | `http://127.0.0.1:3000` | Local development server |
|
||||
| `dev` | `http://127.0.0.1:3101` | Genarrative local development server |
|
||||
|
||||
## Common Workflows
|
||||
|
||||
### New Project Setup
|
||||
## Version & Runtime Verification
|
||||
|
||||
```bash
|
||||
# 1. Login
|
||||
spacetime login
|
||||
# CLI resolution can be misleading; compare all candidates when diagnosing.
|
||||
type -a spacetime
|
||||
spacetime --version
|
||||
spacetime version list
|
||||
|
||||
# 2. Create project
|
||||
spacetime init my-game --lang rust
|
||||
cd my-game
|
||||
|
||||
# 3. Start dev mode (auto-rebuilds and publishes)
|
||||
spacetime dev
|
||||
# Verify a systemd service binary actually changed.
|
||||
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
|
||||
readlink -f "/proc/${pid}/exe"
|
||||
"/proc/${pid}/exe" --version
|
||||
curl -fsS http://127.0.0.1:3101/v1/ping
|
||||
```
|
||||
|
||||
### Local Development
|
||||
## Flags
|
||||
|
||||
```bash
|
||||
# Start local server (in separate terminal)
|
||||
spacetime start
|
||||
|
||||
# Publish to local
|
||||
spacetime publish my-db --server local --clear-database --yes
|
||||
|
||||
# Query local database
|
||||
spacetime sql my-db --server local "SELECT * FROM players"
|
||||
```
|
||||
|
||||
### Generate Client Bindings
|
||||
|
||||
```bash
|
||||
# After building module
|
||||
spacetime build
|
||||
spacetime generate --lang typescript --out-dir ./client/src/bindings --module-path .
|
||||
|
||||
# Or use dev mode which auto-generates
|
||||
spacetime dev --client-lang typescript --module-bindings-path ./client/src/bindings
|
||||
```
|
||||
|
||||
## Common Flags
|
||||
|
||||
| Flag | Short | Description |
|
||||
|------|-------|-------------|
|
||||
| `--server` | `-s` | Target server (nickname, hostname, or URL) |
|
||||
| `--yes` | `-y` | Non-interactive mode (skip confirmations) |
|
||||
| `--anonymous` | | Use anonymous identity |
|
||||
| `--module-path` | `-p` | Path to module project |
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--server`, `-s` | Target server nickname, host, or URL |
|
||||
| `--yes`, `-y` | Non-interactive prompt skipping; in 2.5 prefer scoped values |
|
||||
| `--delete-data`, `-c` | Publish data policy: `always`, `on-conflict`, or `never` |
|
||||
| `--module-path`, `-p` | Module project path |
|
||||
| `--bin-path`, `-b` | Publish/generate from compiled wasm |
|
||||
| `--no-config` | Ignore `spacetime.json` |
|
||||
| `--env` | Select config file layering environment |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Not logged in"
|
||||
### Not Logged In
|
||||
|
||||
```bash
|
||||
spacetime login
|
||||
# Or use --anonymous for public operations
|
||||
```
|
||||
|
||||
### "Server not responding"
|
||||
### Server Not Responding
|
||||
|
||||
```bash
|
||||
spacetime server ping <server>
|
||||
# For local: ensure spacetime start is running
|
||||
curl -fsS http://127.0.0.1:3101/v1/ping
|
||||
```
|
||||
|
||||
### "Schema conflict"
|
||||
For local Genarrative work, start SpacetimeDB first with `npm run dev:spacetime`, then start `npm run dev:api-server`.
|
||||
|
||||
### Schema Conflict
|
||||
|
||||
```bash
|
||||
# Clear data and republish
|
||||
spacetime publish my-db --clear-database --yes
|
||||
# Clear data and republish only when conflict
|
||||
spacetime publish my-db --clear-database=on-conflict --yes
|
||||
spacetime publish my-db --server http://127.0.0.1:3101 --delete-data=on-conflict --yes=migrate
|
||||
```
|
||||
|
||||
### "Build failed"
|
||||
Use `--delete-data=always` only with explicit approval.
|
||||
|
||||
### Version Mismatch
|
||||
|
||||
```bash
|
||||
# Check Rust/C# toolchain
|
||||
rustup show
|
||||
# For Rust modules, ensure wasm32-unknown-unknown target
|
||||
rustup target add wasm32-unknown-unknown
|
||||
rg -n 'spacetimedb' server-rs/Cargo.toml
|
||||
spacetime --version
|
||||
spacetime version list
|
||||
pid="$(systemctl show spacetimedb.service -p MainPID --value)"
|
||||
"/proc/${pid}/exe" --version
|
||||
```
|
||||
|
||||
## Module Languages
|
||||
|
||||
**Server-side (modules):** Rust, C#, TypeScript, C++
|
||||
**Client SDKs:** TypeScript, C#, Rust, Python, Unreal Engine
|
||||
**CLI `generate` targets:** TypeScript, C#, Rust, Unreal C++
|
||||
|
||||
## Notes
|
||||
|
||||
- Many commands are marked UNSTABLE and may change
|
||||
- Genarrative scripts should pass `--server` or `--server-url` explicitly instead of relying on the CLI default
|
||||
- Use `--yes` flag in scripts to avoid interactive prompts
|
||||
- Dev mode watches files and auto-rebuilds on changes
|
||||
- Procedure calls are stable in 2.5; module HTTP handlers/webhooks, unstable view features, and RLS remain behind unstable gates per release notes.
|
||||
- 2.5 fixes `publish --delete-data` config fallback so `spacetime.json` can provide the database name.
|
||||
- Genarrative scripts should pass `--server` or `--server-url` explicitly instead of relying on CLI defaults.
|
||||
|
||||
@@ -1,345 +1,105 @@
|
||||
---
|
||||
name: spacetimedb-concepts
|
||||
description: Understand SpacetimeDB architecture and core concepts. Use when learning SpacetimeDB or making architectural decisions.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
description: Understand SpacetimeDB 2.5 architecture, reducer/procedure/table/view semantics, schema evolution, subscriptions, identity, and Genarrative-specific backend boundaries. Use when designing or reviewing SpacetimeDB-backed features.
|
||||
---
|
||||
|
||||
# SpacetimeDB Core Concepts
|
||||
|
||||
SpacetimeDB is a relational database that is also a server. It lets you upload application logic directly into the database via WebAssembly modules, eliminating the traditional web/game server layer entirely.
|
||||
SpacetimeDB is a relational database that also executes application logic in uploaded modules. In Genarrative, it is the data and transaction layer behind `server-rs + Axum + SpacetimeDB`, not a replacement for the `api-server` BFF or external platform adapters.
|
||||
|
||||
---
|
||||
## Genarrative Boundaries
|
||||
|
||||
## Critical Rules (Read First)
|
||||
- Domain rules live in `module-*`.
|
||||
- SpacetimeDB tables, reducers, procedures, migrations, row mappers, and read models live in `spacetime-module`.
|
||||
- Backend access goes through `spacetime-client` facades.
|
||||
- HTTP/SSE/BFF and external orchestration stay in `api-server`.
|
||||
- External side effects stay in `platform-*`.
|
||||
- Frontend renders backend truth and must not bypass BFF/projections to invent formal business state.
|
||||
|
||||
These five rules prevent the most common SpacetimeDB mistakes:
|
||||
## Critical Rules
|
||||
|
||||
1. **Reducers are transactional** — they do not return data to callers. Use subscriptions to read data.
|
||||
2. **Reducers must be deterministic** — no filesystem, network, timers, or random. All state must come from tables.
|
||||
3. **Read data via tables/subscriptions** — not reducer return values. Clients get data through subscribed queries.
|
||||
4. **Auto-increment IDs are not sequential** — gaps are normal, do not use for ordering. Use timestamps or explicit sequence columns.
|
||||
5. **`ctx.sender()` is the authenticated principal** — never trust identity passed as arguments. Always use `ctx.sender()` for authorization.
|
||||
|
||||
---
|
||||
|
||||
## Feature Implementation Checklist
|
||||
|
||||
When implementing a feature that spans backend and client:
|
||||
|
||||
1. **Backend:** Define table(s) to store the data
|
||||
2. **Backend:** Define reducer(s) to mutate the data
|
||||
3. **Client:** Subscribe to the table(s)
|
||||
4. **Client:** Call the reducer(s) from UI — **do not skip this step**
|
||||
5. **Client:** Render the data from the table(s)
|
||||
|
||||
**Common mistake:** Building backend tables/reducers but forgetting to wire up the client to call them.
|
||||
|
||||
---
|
||||
|
||||
## Debugging Checklist
|
||||
|
||||
When things are not working:
|
||||
|
||||
1. Is SpacetimeDB server running? (`spacetime start`)
|
||||
2. Is the module published? (`spacetime publish`)
|
||||
3. Are client bindings generated? (`spacetime generate`)
|
||||
4. Check server logs for errors (`spacetime logs <db-name>`)
|
||||
5. **Is the reducer actually being called from the client?**
|
||||
|
||||
---
|
||||
|
||||
## CLI Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <db-name> --module-path <module-path>
|
||||
spacetime publish <db-name> --clear-database -y --module-path <module-path>
|
||||
spacetime generate --lang <lang> --out-dir <out> --module-path <module-path>
|
||||
spacetime logs <db-name>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What SpacetimeDB Is
|
||||
|
||||
SpacetimeDB combines a database and application server into a single deployable unit. Clients connect directly to the database and execute application logic inside it. The system is optimized for real-time applications requiring maximum speed and minimum latency.
|
||||
|
||||
Key characteristics:
|
||||
|
||||
- **In-memory execution**: Application state is served from memory for very low-latency access
|
||||
- **Persistent storage**: Data is automatically persisted to a write-ahead log (WAL) for durability
|
||||
- **Real-time synchronization**: Changes are automatically pushed to subscribed clients
|
||||
- **Single deployment**: No separate servers, containers, or infrastructure to manage
|
||||
|
||||
## The Five Zen Principles
|
||||
|
||||
1. **Everything is a Table**: Your entire application state lives in tables. No separate cache layer, no Redis, no in-memory state to synchronize.
|
||||
2. **Everything is Persistent**: SpacetimeDB persists state by default (for example via WAL-backed durability).
|
||||
3. **Everything is Real-Time**: Clients are replicas of server state. Subscribe to data and it flows automatically.
|
||||
4. **Everything is Transactional**: Every reducer runs atomically. Either all changes succeed or all roll back.
|
||||
5. **Everything is Programmable**: Modules are real code (Rust, C#, TypeScript) running inside the database.
|
||||
1. **Reducers are transactional**: they do not return data to callers. Read through subscriptions, read models, views, or BFF endpoints.
|
||||
2. **Reducers are deterministic**: no filesystem, network, wall-clock, or external RNG. Use `ctx.timestamp`, `ctx.rng()` / `ctx.random()`, and tables.
|
||||
3. **Procedures are stable in 2.5**: they can use explicit transactions and outgoing HTTP via `ctx.http`.
|
||||
4. **Identity comes from context**: use `ctx.sender()` or language equivalent for authorization. Never trust identity passed as an argument.
|
||||
5. **Auto-increment IDs are not ordering guarantees**: gaps are normal. Use timestamps or explicit sequence columns for ordering.
|
||||
6. **Schema changes need migration discipline**: existing Genarrative table fields must be appended with defaults; update migration code, table catalog, generated bindings, and run `npm run check:spacetime-schema`.
|
||||
|
||||
## Tables
|
||||
|
||||
Tables store all data in SpacetimeDB. They use the relational model and support SQL queries for subscriptions.
|
||||
|
||||
### Defining Tables
|
||||
|
||||
Tables are defined using language-specific attributes. In 2.0, use `accessor` (not `name`) for the API name:
|
||||
|
||||
**Rust:**
|
||||
```rust
|
||||
#[spacetimedb::table(accessor = player, public)]
|
||||
pub struct Player {
|
||||
#[primary_key]
|
||||
#[auto_inc]
|
||||
id: u32,
|
||||
#[index(btree)]
|
||||
name: String,
|
||||
#[unique]
|
||||
email: String,
|
||||
}
|
||||
```
|
||||
|
||||
**C#:**
|
||||
```csharp
|
||||
[SpacetimeDB.Table(Accessor = "Player", Public = true)]
|
||||
public partial struct Player
|
||||
{
|
||||
[SpacetimeDB.PrimaryKey]
|
||||
[SpacetimeDB.AutoInc]
|
||||
public uint Id;
|
||||
[SpacetimeDB.Index.BTree]
|
||||
public string Name;
|
||||
[SpacetimeDB.Unique]
|
||||
public string Email;
|
||||
}
|
||||
```
|
||||
|
||||
**TypeScript:**
|
||||
```typescript
|
||||
const players = table(
|
||||
{ name: 'players', public: true },
|
||||
{
|
||||
id: t.u32().primaryKey().autoInc(),
|
||||
name: t.string().index('btree'),
|
||||
email: t.string().unique(),
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Table Visibility
|
||||
|
||||
- **Private tables** (default): Only accessible by reducers and the database owner
|
||||
- **Public tables**: Exposed for client read access through subscriptions. Writes still require reducers.
|
||||
|
||||
### Table Design Principles
|
||||
|
||||
Organize data by access pattern, not by entity:
|
||||
|
||||
**Decomposed approach (recommended):**
|
||||
```
|
||||
Player PlayerState PlayerStats
|
||||
id <-- player_id player_id
|
||||
name position_x total_kills
|
||||
position_y total_deaths
|
||||
velocity_x play_time
|
||||
```
|
||||
|
||||
Benefits: reduced bandwidth, cache efficiency, schema evolution, semantic clarity.
|
||||
- Private tables are the default; only reducers/procedures and database owners can access them.
|
||||
- Public tables are exposed to clients through subscriptions. Writes still go through reducers/procedures.
|
||||
- Organize data by access pattern when bandwidth or update frequency differs.
|
||||
- Existing persistent tables in Genarrative are conservative: no rename, delete, reorder, or type changes without a user-approved migration plan.
|
||||
|
||||
## Reducers
|
||||
|
||||
Reducers are transactional functions that modify database state. They are the primary client-invoked mutation path; procedures can also mutate tables by running explicit transactions.
|
||||
Reducers are deterministic transactional functions. They are the primary client-invoked mutation path.
|
||||
|
||||
### Key Properties
|
||||
- No global mutable state.
|
||||
- No filesystem, network, timers, or non-deterministic RNG.
|
||||
- Return `Result<(), String>` for expected sender-visible errors.
|
||||
- Use `ctx.sender()` for authorization.
|
||||
- Store persistent state in tables.
|
||||
|
||||
- **Transactional**: Run in isolated database transactions
|
||||
- **Atomic**: Either all changes succeed or all roll back
|
||||
- **Isolated**: Cannot interact with the outside world (no network, no filesystem)
|
||||
- **Callable**: Clients invoke reducers as remote procedure calls
|
||||
## Procedures
|
||||
|
||||
### Critical Reducer Rules
|
||||
Procedures are stable in 2.5. They can be scheduled, can open explicit transactions with `with_tx` / `try_with_tx`, and can use outgoing HTTP (`ctx.http`).
|
||||
|
||||
1. **No global state**: Relying on static variables is undefined behavior
|
||||
2. **No side effects**: Reducers cannot make network requests or access files
|
||||
3. **Store state in tables**: All persistent state must be in tables
|
||||
4. **No return data**: Reducers do not return data to callers — use subscriptions
|
||||
5. **Must be deterministic**: No random, no timers, no external I/O
|
||||
Genarrative default: keep external provider protocols in `platform-*` and orchestration in `api-server` unless a task explicitly moves a workflow into a module procedure.
|
||||
|
||||
### Defining Reducers
|
||||
Module HTTP handlers/webhooks, unstable view features, and RLS `client_visibility_filter` remain gated behind unstable according to the 2.5 release notes.
|
||||
|
||||
**Rust:**
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
pub fn create_user(ctx: &ReducerContext, name: String, email: String) -> Result<(), String> {
|
||||
if name.is_empty() {
|
||||
return Err("Name cannot be empty".to_string());
|
||||
}
|
||||
ctx.db.user().insert(User { id: 0, name, email });
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
## Views
|
||||
|
||||
**C#:**
|
||||
```csharp
|
||||
[SpacetimeDB.Reducer]
|
||||
public static void CreateUser(ReducerContext ctx, string name, string email)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
throw new ArgumentException("Name cannot be empty");
|
||||
ctx.Db.User.Insert(new User { Id = 0, Name = name, Email = email });
|
||||
}
|
||||
```
|
||||
Views expose computed read-only data. In 2.4.1 Rust and TypeScript gained primary key support for procedural views; in 2.5 C# gained the same. Clients can receive `OnUpdate` events when subscribed to such views with primary keys. Ensure the view never returns duplicate primary keys, because that can fail view refresh and roll back the triggering transaction.
|
||||
|
||||
### ReducerContext
|
||||
## Event Tables
|
||||
|
||||
Every reducer receives a `ReducerContext` providing:
|
||||
- **Database**: `ctx.db` (Rust field, TS property) / `ctx.Db` (C# property)
|
||||
- **Sender**: `ctx.sender()` (Rust method) / `ctx.Sender` (C# property) / `ctx.sender` (TS property)
|
||||
- **Connection ID**: `ctx.connection_id()` (Rust method) / `ctx.ConnectionId` (C# property) / `ctx.connectionId` (TS property)
|
||||
- **Timestamp**: `ctx.timestamp` (Rust field, TS property) / `ctx.Timestamp` (C# property)
|
||||
Event tables broadcast reducer/procedure-specific facts to subscribers and must be subscribed explicitly. They are excluded from `subscribe_to_all_tables()`.
|
||||
|
||||
## Event Tables (2.0)
|
||||
2.5 adds broader layout-altering automigrations for event tables, including column removal, reordering, and type changes that regular tables reject. This relaxed migration behavior is for event-only tables, not persistent tables.
|
||||
|
||||
Event tables are the preferred way to broadcast reducer-specific data to clients.
|
||||
Event-table primary keys and constraints are transaction-scoped. They can reject duplicate event rows within one transaction, but event rows are not retained in client cache, so clients observe event tables through insert callbacks only. Do not design Genarrative event tables around `OnUpdate` / `on_update` / `onUpdate`; use a persistent table or a primary-keyed procedural view when update callbacks are required.
|
||||
|
||||
```rust
|
||||
#[table(accessor = damage_event, public, event)]
|
||||
pub struct DamageEvent {
|
||||
pub target: Identity,
|
||||
pub amount: u32,
|
||||
}
|
||||
|
||||
#[reducer]
|
||||
fn deal_damage(ctx: &ReducerContext, target: Identity, amount: u32) {
|
||||
ctx.db.damage_event().insert(DamageEvent { target, amount });
|
||||
}
|
||||
```
|
||||
|
||||
Clients subscribe to event tables and use `on_insert` callbacks. Event tables must be subscribed explicitly and are excluded from `subscribe_to_all_tables()`.
|
||||
Official 2.4.1/2.5 release notes document primary-key-backed update callbacks for procedural views, not event tables.
|
||||
|
||||
## Subscriptions
|
||||
|
||||
Subscriptions replicate database rows to clients in real-time.
|
||||
1. Subscribe to SQL queries or generated table/query builders.
|
||||
2. Receive initial matching rows.
|
||||
3. Receive updates when subscribed rows change.
|
||||
4. Render from subscribed data, not reducer return values.
|
||||
|
||||
### How Subscriptions Work
|
||||
Best practices:
|
||||
|
||||
1. **Subscribe**: Register SQL queries describing needed data
|
||||
2. **Receive initial data**: All matching rows are sent immediately
|
||||
3. **Receive updates**: Real-time updates when subscribed rows change
|
||||
4. **React to changes**: Use callbacks (`onInsert`, `onDelete`, `onUpdate`)
|
||||
- Group subscriptions by lifetime.
|
||||
- Subscribe to new data before unsubscribing old data during transitions.
|
||||
- Avoid overlapping queries that duplicate row delivery.
|
||||
- Use indexes for subscribed filters.
|
||||
|
||||
### Subscription Best Practices
|
||||
## 2.2.0 to 2.5.0 Delta
|
||||
|
||||
1. **Group subscriptions by lifetime**: Keep always-needed data separate from temporary subscriptions
|
||||
2. **Subscribe before unsubscribing**: When updating subscriptions, subscribe to new data first
|
||||
3. **Avoid overlapping queries**: Distinct queries returning overlapping data cause redundant processing
|
||||
4. **Use indexes**: Queries on indexed columns are efficient; full table scans are expensive
|
||||
Genarrative introduced SpacetimeDB around 2.2.0. Important changes since then:
|
||||
|
||||
## Modules
|
||||
- **2.2.0**: v3 WebSocket transport and TS SDK default, safer production operations (`lock`/`unlock`, safer `delete`, better `publish --yes`), TS React `useProcedure`, table clearing APIs, empty-table drop automigration, primary-key migration fixes, bytes-key B-tree support, durability hardening.
|
||||
- **2.3.0**: first-party Godot SDK, more WebSocket pipelining/batching, HTTP/2 backend support, Vue `useProcedure`, Unity 6 WebGL support, commitlog compression/throughput improvements, Rust `DbContext` generics, `ReducerContext::identity` deprecated in favor of `database_identity`, connection lifecycle and unsubscribe fixes.
|
||||
- **2.4.0**: unstable module HTTP handlers/webhooks, faster synchronous WASM reducer runtime, commitlog resume truncation fix for silent data loss risk, better commitlog decode context, V8 heap metrics for procedure workers, JS execution-time billing regression reverted.
|
||||
- **2.4.1**: Rust and TypeScript procedural views can declare primary keys, enabling `OnUpdate` events for subscribed views; fixed index schema from ST tables.
|
||||
- **2.5.0**: procedures are stable, C# procedural views gain primary keys, event tables allow broader layout-altering automigrations, BTreeSet storage makes row insertion deterministic and avoids accidentally quadratic bulk insert behavior, `wasm_memory_bytes` billing metric semantics changed, template version constraints unified, `publish --delete-data` config fallback fixed, CLI `call` accepts hex Identity arguments.
|
||||
|
||||
Modules are WebAssembly bundles containing application logic that runs inside the database.
|
||||
## Debugging Checklist
|
||||
|
||||
### Module Components
|
||||
|
||||
- **Tables**: Define the data schema
|
||||
- **Reducers**: Define callable functions that modify state
|
||||
- **Views**: Define read-only computed queries
|
||||
- **Event Tables**: Broadcast reducer-specific data to clients (2.0)
|
||||
- **Procedures**: (Beta) Functions that can have side effects (HTTP requests)
|
||||
|
||||
### Module Languages
|
||||
|
||||
Server-side modules can be written in: Rust, C#, TypeScript (beta)
|
||||
|
||||
### Module Lifecycle
|
||||
|
||||
1. **Write**: Define tables and reducers in your chosen language
|
||||
2. **Compile**: Build to WebAssembly using the SpacetimeDB CLI
|
||||
3. **Publish**: Upload to a SpacetimeDB host with `spacetime publish`
|
||||
4. **Hot-swap**: Republish to update code without disconnecting clients
|
||||
|
||||
## Identity
|
||||
|
||||
Identity is SpacetimeDB's authentication system based on OpenID Connect (OIDC).
|
||||
|
||||
- **Identity**: A long-lived, globally unique identifier for a user.
|
||||
- **ConnectionId**: Identifies a specific client connection.
|
||||
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
pub fn do_something(ctx: &ReducerContext) {
|
||||
let caller_identity = ctx.sender(); // Who is calling?
|
||||
// NEVER trust identity passed as a reducer argument
|
||||
}
|
||||
```
|
||||
|
||||
### Authentication Providers
|
||||
|
||||
SpacetimeDB works with many OIDC providers, including SpacetimeAuth (built-in), Auth0, Clerk, Keycloak, Google, and GitHub.
|
||||
|
||||
## When to Use SpacetimeDB
|
||||
|
||||
### Ideal Use Cases
|
||||
|
||||
- **Real-time games**: MMOs, multiplayer games, turn-based games
|
||||
- **Collaborative applications**: Document editing, whiteboards, design tools
|
||||
- **Chat and messaging**: Real-time communication with presence
|
||||
- **Live dashboards**: Streaming analytics and monitoring
|
||||
|
||||
### Key Decision Factors
|
||||
|
||||
Choose SpacetimeDB when you need:
|
||||
- Sub-10ms latency for reads and writes
|
||||
- Automatic real-time synchronization
|
||||
- Transactional guarantees for all operations
|
||||
- Simplified architecture (no separate cache, queue, or server)
|
||||
|
||||
### Less Suitable For
|
||||
|
||||
- **Batch analytics**: Optimized for OLTP, not OLAP
|
||||
- **Large blob storage**: Better suited for structured relational data
|
||||
- **Stateless APIs**: Traditional REST APIs do not need real-time sync
|
||||
|
||||
## Common Patterns
|
||||
|
||||
**Authentication check in reducer:**
|
||||
```rust
|
||||
#[spacetimedb::reducer]
|
||||
fn admin_action(ctx: &ReducerContext) -> Result<(), String> {
|
||||
let admin = ctx.db.admin().identity().find(&ctx.sender())
|
||||
.ok_or("Not an admin")?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
**Scheduled reducer:**
|
||||
```rust
|
||||
#[spacetimedb::table(accessor = reminder, scheduled(send_reminder))]
|
||||
pub struct Reminder {
|
||||
#[primary_key]
|
||||
#[auto_inc]
|
||||
id: u64,
|
||||
scheduled_at: ScheduleAt,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[spacetimedb::reducer]
|
||||
fn send_reminder(ctx: &ReducerContext, reminder: Reminder) {
|
||||
log::info!("Reminder: {}", reminder.message);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
1. Is the Genarrative SpacetimeDB server running? Use `npm run dev:spacetime` locally or host-local `systemctl`.
|
||||
2. Is the module published to the same server the API uses?
|
||||
3. Are generated bindings current? Use `npm run spacetime:generate`.
|
||||
4. Is `api-server` using the same database and token?
|
||||
5. Is the reducer/procedure actually called?
|
||||
6. Did `/healthz` / `/readyz` pass while business SpacetimeDB calls still timeout? Inspect API logs and public route behavior.
|
||||
|
||||
## Editing Behavior
|
||||
|
||||
When modifying SpacetimeDB code:
|
||||
|
||||
- Make the smallest change necessary
|
||||
- Do NOT touch unrelated files, configs, or dependencies
|
||||
- Do NOT invent new SpacetimeDB APIs — use only what exists in docs or this repo
|
||||
- Make the smallest change necessary.
|
||||
- Do not invent SpacetimeDB APIs; verify against current docs, generated bindings, or source.
|
||||
- For Genarrative schema edits, update migration code, table catalog/docs, generated bindings, and relevant tests.
|
||||
- After schema edits, run `npm run spacetime:generate` and `npm run check:spacetime-schema`.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,489 +0,0 @@
|
||||
---
|
||||
name: spacetimedb-typescript
|
||||
description: Build TypeScript clients for SpacetimeDB. Use when connecting to SpacetimeDB from web apps, Node.js, Deno, Bun, or other JavaScript runtimes.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
---
|
||||
|
||||
# SpacetimeDB TypeScript SDK
|
||||
|
||||
Build real-time TypeScript clients that connect directly to SpacetimeDB modules. The SDK provides type-safe database access, automatic synchronization, and reactive updates for web apps, Node.js, Deno, Bun, and other JavaScript runtimes.
|
||||
|
||||
---
|
||||
|
||||
## HALLUCINATED APIs — DO NOT USE
|
||||
|
||||
**These APIs DO NOT EXIST. LLMs frequently hallucinate them.**
|
||||
|
||||
```typescript
|
||||
// WRONG PACKAGE — does not exist
|
||||
import { SpacetimeDBClient } from "@clockworklabs/spacetimedb-sdk";
|
||||
|
||||
// WRONG — these methods don't exist
|
||||
SpacetimeDBClient.connect(...);
|
||||
SpacetimeDBClient.call("reducer_name", [...]);
|
||||
connection.call("reducer_name", [arg1, arg2]);
|
||||
|
||||
// WRONG — positional reducer arguments
|
||||
conn.reducers.doSomething("value"); // WRONG!
|
||||
|
||||
// WRONG — old 1.0 patterns
|
||||
spacetimedb.reducer('reducer_name', params, fn); // Use export const name = spacetimedb.reducer(params, fn)
|
||||
schema(myTable); // Use schema({ myTable })
|
||||
schema(t1, t2, t3); // Use schema({ t1, t2, t3 })
|
||||
scheduled: 'run_cleanup' // Use scheduled: () => run_cleanup
|
||||
.withModuleName('db') // Use .withDatabaseName('db') (2.0)
|
||||
setReducerFlags.x('NoSuccessNotify') // Removed in 2.0
|
||||
```
|
||||
|
||||
### CORRECT PATTERNS:
|
||||
|
||||
```typescript
|
||||
// CORRECT IMPORTS
|
||||
import { DbConnection, tables } from './module_bindings'; // Generated!
|
||||
import { SpacetimeDBProvider, useTable } from 'spacetimedb/react';
|
||||
import { Identity } from 'spacetimedb';
|
||||
|
||||
// CORRECT REDUCER CALLS — object syntax, not positional!
|
||||
conn.reducers.doSomething({ value: 'test' });
|
||||
conn.reducers.updateItem({ itemId: 1n, newValue: 42 });
|
||||
|
||||
// CORRECT DATA ACCESS — useTable returns [rows, isReady]
|
||||
const [items, isReady] = useTable(tables.item);
|
||||
```
|
||||
|
||||
### DO NOT:
|
||||
- **Invent hooks** like `useItems()`, `useData()` — use `useTable(tables.tableName)`
|
||||
- **Import from fake packages** — only `spacetimedb`, `spacetimedb/react`, `./module_bindings`
|
||||
|
||||
---
|
||||
|
||||
## Common Mistakes Table
|
||||
|
||||
### Server-side errors
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Missing `package.json` | Create `package.json` | "could not detect language" |
|
||||
| Missing `tsconfig.json` | Create `tsconfig.json` | "TsconfigNotFound" |
|
||||
| Entrypoint not at `src/index.ts` | Use `src/index.ts` | Module won't bundle |
|
||||
| `indexes` in COLUMNS (2nd arg) | `indexes` in OPTIONS (1st arg) of `table()` | "reading 'tag'" error |
|
||||
| Index without `algorithm` | `algorithm: 'btree'` | "reading 'tag'" error |
|
||||
| `filter({ ownerId })` | `filter(ownerId)` | "does not exist in type 'Range'" |
|
||||
| `.filter()` on unique column | `.find()` on unique column | TypeError |
|
||||
| `insert({ ...without id })` | `insert({ id: 0n, ... })` | "Property 'id' is missing" |
|
||||
| `const id = table.insert(...)` | `const row = table.insert(...)` | `.insert()` returns ROW, not ID |
|
||||
| `.unique()` + explicit index | Just use `.unique()` | "name is used for multiple entities" |
|
||||
| Import spacetimedb from index.ts | Import from schema.ts | "Cannot access before initialization" |
|
||||
| Incorrect multi-column `.filter()` range shape | Match index prefix/tuple shape | Empty results or range/type errors |
|
||||
| `.iter()` in views | Use index lookups only | Views can't scan tables |
|
||||
| `ctx.db` in procedures | `ctx.withTx(tx => tx.db...)` | Procedures need explicit transactions |
|
||||
|
||||
### Client-side errors
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Inline `connectionBuilder` | `useMemo(() => ..., [])` | Reconnects every render |
|
||||
| `const rows = useTable(table)` | `const [rows, isReady] = useTable(table)` | Tuple destructuring |
|
||||
| Optimistic UI updates | Let subscriptions drive state | Desync issues |
|
||||
| `<SpacetimeDBProvider builder={...}>` | `connectionBuilder={...}` | Wrong prop name |
|
||||
|
||||
---
|
||||
|
||||
## Hard Requirements
|
||||
|
||||
1. **`schema({ table })`** — use a single tables object; optional module settings are allowed as a second argument
|
||||
2. **Reducer/procedure names from exports** — `export const name = spacetimedb.reducer(params, fn)`; never `reducer('name', ...)`
|
||||
3. **Reducer calls use object syntax** — `{ param: 'value' }` not positional args
|
||||
4. **Import `DbConnection` from `./module_bindings`** — not from `spacetimedb`
|
||||
5. **DO NOT edit generated bindings** — regenerate with `spacetime generate`
|
||||
6. **Indexes go in OPTIONS (1st arg)** — not in COLUMNS (2nd arg) of `table()`
|
||||
7. **Use BigInt for u64/i64 fields** — `0n`, `1n`, not `0`, `1`
|
||||
8. **Reducers are transactional** — they do not return data
|
||||
9. **Reducers must be deterministic** — no filesystem, network, timers, random
|
||||
10. **Views should use index lookups** — `.iter()` causes severe performance issues
|
||||
11. **Procedures need `ctx.withTx()`** — `ctx.db` doesn't exist in procedures
|
||||
12. **Sum type values** — use `{ tag: 'variant', value: payload }` not `{ variant: payload }`
|
||||
13. **Use `.withDatabaseName()`** — not `.withModuleName()` (2.0)
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install spacetimedb
|
||||
```
|
||||
|
||||
For Node.js environments without native fetch/WebSocket support, install `undici`.
|
||||
|
||||
## Generating Type Bindings
|
||||
|
||||
```bash
|
||||
spacetime generate --lang typescript --out-dir ./src/module_bindings --module-path ./server
|
||||
```
|
||||
|
||||
## Client Connection
|
||||
|
||||
```typescript
|
||||
import { DbConnection } from './module_bindings';
|
||||
|
||||
const connection = DbConnection.builder()
|
||||
.withUri('ws://localhost:3000')
|
||||
.withDatabaseName('my_database')
|
||||
.withToken(localStorage.getItem('spacetimedb_token') ?? undefined)
|
||||
.onConnect((conn, identity, token) => {
|
||||
// identity: your unique Identity for this database
|
||||
console.log('Connected as:', identity.toHexString());
|
||||
|
||||
// Save token for reconnection (preserves identity across sessions)
|
||||
localStorage.setItem('spacetimedb_token', token);
|
||||
|
||||
conn.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Cache ready'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
})
|
||||
.onDisconnect((ctx) => console.log('Disconnected'))
|
||||
.onConnectError((ctx, error) => console.error('Connection failed:', error))
|
||||
.build();
|
||||
```
|
||||
|
||||
## Subscribing to Tables
|
||||
|
||||
```typescript
|
||||
// Basic subscription
|
||||
connection.subscriptionBuilder()
|
||||
.onApplied((ctx) => console.log('Cache ready'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
|
||||
// Multiple queries
|
||||
connection.subscriptionBuilder()
|
||||
.subscribe(['SELECT * FROM player', 'SELECT * FROM game_state']);
|
||||
|
||||
// Subscribe to all tables (development only — cannot mix with Subscribe)
|
||||
connection.subscriptionBuilder().subscribeToAllTables();
|
||||
|
||||
// Subscription handle for later unsubscribe
|
||||
const handle = connection.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Subscribed'))
|
||||
.subscribe('SELECT * FROM player');
|
||||
|
||||
handle.unsubscribeThen(() => console.log('Unsubscribed'));
|
||||
```
|
||||
|
||||
## Accessing Table Data
|
||||
|
||||
```typescript
|
||||
for (const player of connection.db.player.iter()) { console.log(player.name); }
|
||||
const players = Array.from(connection.db.player.iter());
|
||||
const count = connection.db.player.count();
|
||||
const player = connection.db.player.id.find(42n);
|
||||
```
|
||||
|
||||
## Table Event Callbacks
|
||||
|
||||
```typescript
|
||||
connection.db.player.onInsert((ctx, player) => console.log('New:', player.name));
|
||||
connection.db.player.onDelete((ctx, player) => console.log('Left:', player.name));
|
||||
connection.db.player.onUpdate((ctx, old, new_) => console.log(`${old.score} -> ${new_.score}`));
|
||||
```
|
||||
|
||||
## Calling Reducers
|
||||
|
||||
**CRITICAL: Use object syntax, not positional arguments.**
|
||||
|
||||
```typescript
|
||||
connection.reducers.createPlayer({ name: 'Alice', location: { x: 0, y: 0 } });
|
||||
```
|
||||
|
||||
### Snake_case to camelCase conversion
|
||||
- Server: `export const do_something = spacetimedb.reducer(...)`
|
||||
- Client: `conn.reducers.doSomething({ ... })`
|
||||
|
||||
---
|
||||
|
||||
## Identity and Authentication
|
||||
|
||||
- `identity` and `token` are provided in the `onConnect` callback (see Client Connection above)
|
||||
- `identity.toHexString()` for display or logging
|
||||
- Omit `.withToken()` for anonymous connection — server assigns a new identity
|
||||
- Pass a stale/invalid token: server issues a new identity and token in `onConnect`
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
Connection-level errors (`.onConnectError`, `.onDisconnect`) are shown in the Client Connection example above.
|
||||
|
||||
```typescript
|
||||
// Subscription error
|
||||
connection.subscriptionBuilder()
|
||||
.onApplied(() => console.log('Subscribed'))
|
||||
.onError((ctx) => console.error('Subscription error:', ctx.event))
|
||||
.subscribe('SELECT * FROM player');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Server-Side Module Development
|
||||
|
||||
### Table Definition
|
||||
|
||||
```typescript
|
||||
import { schema, table, t } from 'spacetimedb/server';
|
||||
|
||||
export const Task = table({
|
||||
name: 'task',
|
||||
public: true,
|
||||
indexes: [{ name: 'task_owner_id', algorithm: 'btree', columns: ['ownerId'] }]
|
||||
}, {
|
||||
id: t.u64().primaryKey().autoInc(),
|
||||
ownerId: t.identity(),
|
||||
title: t.string(),
|
||||
createdAt: t.timestamp(),
|
||||
});
|
||||
```
|
||||
|
||||
### Column types
|
||||
|
||||
```typescript
|
||||
t.identity() // User identity
|
||||
t.u64() // Unsigned 64-bit integer (use for IDs)
|
||||
t.string() // Text
|
||||
t.bool() // Boolean
|
||||
t.timestamp() // Timestamp
|
||||
t.scheduleAt() // For scheduled tables only
|
||||
t.object('Name', {}) // Product types (nested objects)
|
||||
t.enum('Name', {}) // Sum types (tagged unions)
|
||||
t.string().optional() // Nullable
|
||||
```
|
||||
|
||||
> BigInt syntax: All `u64`/`i64` fields use `0n`, `1n`, not `0`, `1`.
|
||||
|
||||
### Schema export
|
||||
|
||||
```typescript
|
||||
const spacetimedb = schema({ Task, Player });
|
||||
export default spacetimedb;
|
||||
```
|
||||
|
||||
### Reducer Definition (2.0)
|
||||
|
||||
**Name comes from the export — NOT from a string argument.**
|
||||
|
||||
```typescript
|
||||
import spacetimedb from './schema';
|
||||
import { t, SenderError } from 'spacetimedb/server';
|
||||
|
||||
export const create_task = spacetimedb.reducer(
|
||||
{ title: t.string() },
|
||||
(ctx, { title }) => {
|
||||
if (!title) throw new SenderError('title required');
|
||||
ctx.db.task.insert({ id: 0n, ownerId: ctx.sender, title, createdAt: ctx.timestamp });
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Update Pattern
|
||||
|
||||
```typescript
|
||||
const existing = ctx.db.task.id.find(taskId);
|
||||
if (!existing) throw new SenderError('Task not found');
|
||||
ctx.db.task.id.update({ ...existing, title: newTitle, updatedAt: ctx.timestamp });
|
||||
```
|
||||
|
||||
### Lifecycle Hooks
|
||||
|
||||
```typescript
|
||||
spacetimedb.clientConnected((ctx) => { /* ctx.sender is the connecting identity */ });
|
||||
spacetimedb.clientDisconnected((ctx) => { /* clean up */ });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Event Tables (2.0)
|
||||
|
||||
Reducer callbacks are removed in 2.0. Use event tables + `onInsert` instead.
|
||||
|
||||
```typescript
|
||||
export const DamageEvent = table(
|
||||
{ name: 'damage_event', public: true, event: true },
|
||||
{ target: t.identity(), amount: t.u32() }
|
||||
);
|
||||
|
||||
export const deal_damage = spacetimedb.reducer(
|
||||
{ target: t.identity(), amount: t.u32() },
|
||||
(ctx, { target, amount }) => {
|
||||
ctx.db.damageEvent.insert({ target, amount });
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Client subscribes and uses `onInsert`:
|
||||
```typescript
|
||||
conn.db.damageEvent.onInsert((ctx, evt) => {
|
||||
playDamageAnimation(evt.target, evt.amount);
|
||||
});
|
||||
```
|
||||
|
||||
Event tables must be subscribed explicitly — they are excluded from `subscribeToAllTables()`.
|
||||
|
||||
---
|
||||
|
||||
## Views
|
||||
|
||||
### ViewContext vs AnonymousViewContext
|
||||
|
||||
```typescript
|
||||
// ViewContext — has ctx.sender, result varies per user
|
||||
spacetimedb.view({ name: 'my_items', public: true }, t.array(Item.rowType), (ctx) => {
|
||||
return [...ctx.db.item.by_owner.filter(ctx.sender)];
|
||||
});
|
||||
|
||||
// AnonymousViewContext — no ctx.sender, same result for everyone (better perf)
|
||||
spacetimedb.anonymousView({ name: 'leaderboard', public: true }, t.array(Player.rowType), (ctx) => {
|
||||
return ctx.from.player.where(p => p.score.gt(1000));
|
||||
});
|
||||
```
|
||||
|
||||
Views can only use index lookups — `.iter()` is NOT allowed.
|
||||
|
||||
---
|
||||
|
||||
## Scheduled Tables
|
||||
|
||||
```typescript
|
||||
export const CleanupJob = table({
|
||||
name: 'cleanup_job',
|
||||
scheduled: () => run_cleanup // function returning the exported reducer
|
||||
}, {
|
||||
scheduledId: t.u64().primaryKey().autoInc(),
|
||||
scheduledAt: t.scheduleAt(),
|
||||
targetId: t.u64(),
|
||||
});
|
||||
|
||||
export const run_cleanup = spacetimedb.reducer(
|
||||
{ arg: CleanupJob.rowType },
|
||||
(ctx, { arg }) => { /* arg.scheduledId, arg.targetId available */ }
|
||||
);
|
||||
|
||||
// Schedule a job
|
||||
import { ScheduleAt } from 'spacetimedb';
|
||||
ctx.db.cleanupJob.insert({
|
||||
scheduledId: 0n,
|
||||
scheduledAt: ScheduleAt.time(ctx.timestamp.microsSinceUnixEpoch + 60_000_000n),
|
||||
targetId: someId
|
||||
});
|
||||
```
|
||||
|
||||
### ScheduleAt on Client
|
||||
|
||||
```typescript
|
||||
// ScheduleAt is a tagged union on the client
|
||||
// { tag: 'Time', value: Timestamp } or { tag: 'Interval', value: TimeDuration }
|
||||
const schedule = row.scheduledAt;
|
||||
if (schedule.tag === 'Time') {
|
||||
const date = new Date(Number(schedule.value.microsSinceUnixEpoch / 1000n));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Timestamps
|
||||
|
||||
### Server-side
|
||||
```typescript
|
||||
ctx.db.item.insert({ id: 0n, createdAt: ctx.timestamp });
|
||||
const future = ctx.timestamp.microsSinceUnixEpoch + 300_000_000n;
|
||||
```
|
||||
|
||||
### Client-side
|
||||
```typescript
|
||||
// Timestamps are objects with BigInt, not numbers
|
||||
const date = new Date(Number(row.createdAt.microsSinceUnixEpoch / 1000n));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Procedures (Beta)
|
||||
|
||||
```typescript
|
||||
export const fetch_data = spacetimedb.procedure(
|
||||
{ url: t.string() }, t.string(),
|
||||
(ctx, { url }) => {
|
||||
const response = ctx.http.fetch(url);
|
||||
ctx.withTx(tx => { tx.db.myTable.insert({ id: 0n, content: response.text() }); });
|
||||
return response.text();
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
Procedures don't have `ctx.db` — use `ctx.withTx(tx => tx.db...)`.
|
||||
|
||||
---
|
||||
|
||||
## React Integration
|
||||
|
||||
```tsx
|
||||
import { useMemo } from 'react';
|
||||
import { SpacetimeDBProvider, useTable } from 'spacetimedb/react';
|
||||
import { DbConnection, tables } from './module_bindings';
|
||||
|
||||
function Root() {
|
||||
const connectionBuilder = useMemo(() =>
|
||||
DbConnection.builder()
|
||||
.withUri('ws://localhost:3000')
|
||||
.withDatabaseName('my_game')
|
||||
.withToken(localStorage.getItem('auth_token') || undefined)
|
||||
.onConnect((conn, identity, token) => {
|
||||
localStorage.setItem('auth_token', token);
|
||||
conn.subscriptionBuilder().subscribe(tables.player);
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<SpacetimeDBProvider connectionBuilder={connectionBuilder}>
|
||||
<App />
|
||||
</SpacetimeDBProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function PlayerList() {
|
||||
const [players, isReady] = useTable(tables.player);
|
||||
if (!isReady) return <div>Loading...</div>;
|
||||
return <ul>{players.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Server (`backend/spacetimedb/`)
|
||||
```
|
||||
src/schema.ts -> Tables, export spacetimedb
|
||||
src/index.ts -> Reducers, lifecycle, import schema
|
||||
package.json -> { "type": "module", "dependencies": { "spacetimedb": "^2.0.0" } }
|
||||
tsconfig.json -> Standard config
|
||||
```
|
||||
|
||||
### Client (`client/`)
|
||||
```
|
||||
src/module_bindings/ -> Generated (spacetime generate)
|
||||
src/main.tsx -> Provider, connection setup
|
||||
src/App.tsx -> UI components
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <module-name> --module-path <backend-dir>
|
||||
spacetime publish <module-name> --clear-database -y --module-path <backend-dir>
|
||||
spacetime generate --lang typescript --out-dir <client>/src/module_bindings --module-path <backend-dir>
|
||||
spacetime logs <module-name>
|
||||
```
|
||||
@@ -1,292 +0,0 @@
|
||||
---
|
||||
name: spacetimedb-unity
|
||||
description: Integrate SpacetimeDB with Unity game projects. Use when building Unity clients with MonoBehaviour lifecycle, FrameTick, and PlayerPrefs token persistence.
|
||||
license: Apache-2.0
|
||||
metadata:
|
||||
author: clockworklabs
|
||||
version: "2.0"
|
||||
tested_with: "SpacetimeDB 2.0, Unity 2022.3+"
|
||||
---
|
||||
|
||||
# SpacetimeDB Unity Integration
|
||||
|
||||
This skill covers Unity-specific patterns for connecting to SpacetimeDB. For server-side module development and general C# SDK usage, see the `spacetimedb-csharp` skill.
|
||||
|
||||
---
|
||||
|
||||
## HALLUCINATED APIs — DO NOT USE
|
||||
|
||||
```csharp
|
||||
// WRONG — these do not exist in Unity SDK
|
||||
SpacetimeDBClient.instance.Connect(...); // Use DbConnection.Builder()
|
||||
SpacetimeDBClient.instance.Subscribe(...); // Use conn.SubscriptionBuilder()
|
||||
NetworkManager.RegisterReducer(...); // SpacetimeDB is not a Unity networking plugin
|
||||
|
||||
// WRONG — old 1.0 patterns
|
||||
.WithModuleName("my-db") // Use .WithDatabaseName() (2.0)
|
||||
ScheduleAt.Time(futureTime) // Use new ScheduleAt.Time(futureTime)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
| Wrong | Right | Error |
|
||||
|-------|-------|-------|
|
||||
| Not calling `FrameTick()` | `conn?.FrameTick()` in `Update()` | No callbacks fire |
|
||||
| Accessing `conn.Db` from background thread | Copy data in callback, use on main thread | Data races / crashes |
|
||||
| Forgetting `DontDestroyOnLoad` | Add to manager `Awake()` | Connection lost on scene load |
|
||||
| Connecting in `Update()` | Connect in `Start()` or on user action | Reconnects every frame |
|
||||
| Not saving auth token | `PlayerPrefs.SetString(...)` in `OnConnect` | New identity every session |
|
||||
| Missing generated bindings | Run `spacetime generate --lang csharp` | Compile errors |
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
Add via Unity Package Manager using the git URL:
|
||||
|
||||
```
|
||||
https://github.com/clockworklabs/com.clockworklabs.spacetimedbsdk.git
|
||||
```
|
||||
|
||||
**Window > Package Manager > + > Add package from git URL**
|
||||
|
||||
---
|
||||
|
||||
## Generate Module Bindings
|
||||
|
||||
```bash
|
||||
spacetime generate --lang csharp --out-dir Assets/SpacetimeDB/module_bindings --module-path PATH_TO_MODULE
|
||||
```
|
||||
|
||||
Place generated files in your Assets folder so Unity compiles them.
|
||||
|
||||
---
|
||||
|
||||
## SpacetimeManager Singleton
|
||||
|
||||
The core pattern for Unity integration. This MonoBehaviour manages the connection lifecycle.
|
||||
|
||||
```csharp
|
||||
using UnityEngine;
|
||||
using SpacetimeDB;
|
||||
using SpacetimeDB.Types;
|
||||
|
||||
public class SpacetimeManager : MonoBehaviour
|
||||
{
|
||||
private const string TOKEN_KEY = "SpacetimeAuthToken";
|
||||
private const string SERVER_URI = "http://localhost:3000";
|
||||
private const string DATABASE_NAME = "my-game";
|
||||
|
||||
public static SpacetimeManager Instance { get; private set; }
|
||||
public DbConnection Connection { get; private set; }
|
||||
public Identity LocalIdentity { get; private set; }
|
||||
|
||||
void Awake()
|
||||
{
|
||||
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
|
||||
Instance = this;
|
||||
DontDestroyOnLoad(gameObject);
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
string savedToken = PlayerPrefs.GetString(TOKEN_KEY, null);
|
||||
|
||||
Connection = DbConnection.Builder()
|
||||
.WithUri(SERVER_URI)
|
||||
.WithDatabaseName(DATABASE_NAME)
|
||||
.WithToken(savedToken)
|
||||
.OnConnect(OnConnected)
|
||||
.OnConnectError(err => Debug.LogError($"Connection failed: {err}"))
|
||||
.OnDisconnect((conn, err) => {
|
||||
if (err != null) Debug.LogError($"Disconnected: {err}");
|
||||
})
|
||||
.Build();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
Connection?.FrameTick();
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
Connection?.Disconnect();
|
||||
}
|
||||
|
||||
private void OnConnected(DbConnection conn, Identity identity, string authToken)
|
||||
{
|
||||
LocalIdentity = identity;
|
||||
PlayerPrefs.SetString(TOKEN_KEY, authToken);
|
||||
PlayerPrefs.Save();
|
||||
|
||||
Debug.Log($"Connected as: {identity}");
|
||||
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.SubscribeToAllTables();
|
||||
}
|
||||
|
||||
private void OnSubscriptionApplied(SubscriptionEventContext ctx)
|
||||
{
|
||||
Debug.Log("Subscription applied — game state loaded");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## FrameTick — Critical
|
||||
|
||||
**`FrameTick()` must be called every frame in `Update()`.** The SDK queues all network messages and only processes them when you call `FrameTick()`. Without it:
|
||||
- No callbacks fire (OnInsert, OnUpdate, OnDelete, reducer callbacks)
|
||||
- The client appears frozen
|
||||
|
||||
```csharp
|
||||
void Update()
|
||||
{
|
||||
Connection?.FrameTick();
|
||||
}
|
||||
```
|
||||
|
||||
**Thread safety**: `FrameTick()` processes messages on the calling thread (the main thread in Unity). Do NOT call it from a background thread. Do NOT access `conn.Db` from background threads.
|
||||
|
||||
---
|
||||
|
||||
## Subscribing to Tables
|
||||
|
||||
Subscribe in the `OnConnected` callback:
|
||||
|
||||
```csharp
|
||||
private void OnConnected(DbConnection conn, Identity identity, string authToken)
|
||||
{
|
||||
// ...save token...
|
||||
|
||||
// Development: subscribe to all
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.SubscribeToAllTables();
|
||||
|
||||
// Production: subscribe to specific tables
|
||||
conn.SubscriptionBuilder()
|
||||
.OnApplied(OnSubscriptionApplied)
|
||||
.Subscribe(new[] {
|
||||
"SELECT * FROM player",
|
||||
"SELECT * FROM game_state"
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Row Callbacks for Game State
|
||||
|
||||
Register callbacks to update Unity GameObjects when table data changes.
|
||||
|
||||
```csharp
|
||||
void RegisterCallbacks()
|
||||
{
|
||||
Connection.Db.Player.OnInsert += (EventContext ctx, Player player) => {
|
||||
SpawnPlayerObject(player);
|
||||
};
|
||||
|
||||
Connection.Db.Player.OnDelete += (EventContext ctx, Player player) => {
|
||||
DestroyPlayerObject(player.Id);
|
||||
};
|
||||
|
||||
Connection.Db.Player.OnUpdate += (EventContext ctx, Player oldPlayer, Player newPlayer) => {
|
||||
UpdatePlayerObject(newPlayer);
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
Register these in `OnSubscriptionApplied` (after initial data is loaded) or in `Start()` before connecting.
|
||||
|
||||
---
|
||||
|
||||
## Calling Reducers from UI
|
||||
|
||||
```csharp
|
||||
public class GameUI : MonoBehaviour
|
||||
{
|
||||
public void OnMoveButtonClicked(Vector2 direction)
|
||||
{
|
||||
SpacetimeManager.Instance.Connection.Reducers.MovePlayer(direction.x, direction.y);
|
||||
}
|
||||
|
||||
public void OnSendChat(string message)
|
||||
{
|
||||
SpacetimeManager.Instance.Connection.Reducers.SendMessage(message);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Reducer Callbacks
|
||||
|
||||
```csharp
|
||||
SpacetimeManager.Instance.Connection.Reducers.OnSendMessage += (ReducerEventContext ctx, string text) => {
|
||||
if (ctx.Event.Status is Status.Committed)
|
||||
Debug.Log($"Message sent: {text}");
|
||||
else if (ctx.Event.Status is Status.Failed(var reason))
|
||||
Debug.LogError($"Send failed: {reason}");
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reading the Client Cache
|
||||
|
||||
```csharp
|
||||
// Find by primary key
|
||||
if (Connection.Db.Player.Id.Find(playerId) is Player player)
|
||||
{
|
||||
Debug.Log($"Player: {player.Name}");
|
||||
}
|
||||
|
||||
// Iterate all
|
||||
foreach (var p in Connection.Db.Player.Iter())
|
||||
{
|
||||
Debug.Log(p.Name);
|
||||
}
|
||||
|
||||
// Filter by index
|
||||
foreach (var p in Connection.Db.Player.Level.Filter(5))
|
||||
{
|
||||
Debug.Log($"Level 5: {p.Name}");
|
||||
}
|
||||
|
||||
// Count
|
||||
int total = Connection.Db.Player.Count;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Unity-Specific Considerations
|
||||
|
||||
### Main Thread Only
|
||||
All SpacetimeDB SDK calls (`FrameTick`, `conn.Db` access, reducer calls) must happen on the main thread. If you need to pass data to a background thread, copy it first in the callback.
|
||||
|
||||
### Scene Loading
|
||||
Use `DontDestroyOnLoad(gameObject)` on the SpacetimeManager to prevent the connection from being destroyed during scene transitions. Without it, the connection drops every time you load a new scene.
|
||||
|
||||
### IL2CPP / AOT
|
||||
The SpacetimeDB SDK uses code generation. If you encounter issues with IL2CPP builds:
|
||||
- Ensure generated bindings are up to date
|
||||
- Check that `link.xml` preserves SpacetimeDB types if you use assembly stripping
|
||||
|
||||
### Token Persistence
|
||||
Token save/load via `PlayerPrefs` is demonstrated in the SpacetimeManager singleton above. If the token is stale or invalid, the server issues a new identity and token in the `OnConnect` callback.
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
spacetime start
|
||||
spacetime publish <module-name> --module-path <backend-dir>
|
||||
spacetime publish <module-name> --clear-database -y --module-path <backend-dir>
|
||||
spacetime generate --lang csharp --out-dir Assets/SpacetimeDB/module_bindings --module-path <backend-dir>
|
||||
spacetime logs <module-name>
|
||||
```
|
||||
@@ -22,6 +22,7 @@ tmp
|
||||
.env.secrets.*
|
||||
spacetime.local.json
|
||||
deploy/container/api-server.env
|
||||
deploy/container/worker-smoke
|
||||
|
||||
server-rs/target
|
||||
server-rs/target-*
|
||||
|
||||
+11
@@ -28,6 +28,11 @@ temp-build-goal-check/
|
||||
/public/generated-custom-world-scenes
|
||||
temp*build*/
|
||||
/server-rs/target/
|
||||
/apps/desktop-shell/src-tauri/target/
|
||||
/apps/desktop-shell/src-tauri/gen/
|
||||
/apps/desktop-shell/src-tauri/permissions/autogenerated/
|
||||
/apps/mobile-shell/.expo/
|
||||
/apps/mobile-shell/.expo-export-smoke/
|
||||
/server-rs/.spacetimedb/
|
||||
/server-rs/.data/
|
||||
/public/generated-animations
|
||||
@@ -37,11 +42,17 @@ temp*build*/
|
||||
/.app/
|
||||
/target/
|
||||
/logs
|
||||
/.codegraph/
|
||||
/.playwright-cli/
|
||||
**/.playwright-cli/
|
||||
/output/playwright/
|
||||
/server-rs/crates/*/logs/
|
||||
.worktrees/
|
||||
.rag/
|
||||
.env.secrets.local
|
||||
spacetime.local.json
|
||||
deploy/container/api-server.env
|
||||
deploy/container/worker-smoke/
|
||||
|
||||
# Local load-test data extracted from private migration files
|
||||
scripts/loadtest/data/*.local.json
|
||||
|
||||
+7
-33
@@ -1,30 +1,21 @@
|
||||
# Genarrative 团队 Hermes 共享记忆
|
||||
# Genarrative Hermes 工具目录
|
||||
|
||||
本目录用于在仓库内共享团队级 Hermes 上下文,供 3 名开发人员在各自本地 Hermes 中读取、更新和同步。
|
||||
本目录只保留 Hermes 专用的仓库级工具资源,例如 Hermes skills、plugins 和启用说明。项目知识本体、长期记忆、计划和 TODO 不再放在 `.hermes/`,统一迁移到 `docs/project-memory/`。
|
||||
|
||||
## 使用原则
|
||||
|
||||
- `.hermes/` 中只保存可以进入 Git 的团队共享内容。
|
||||
- `.hermes/` 中只保存 Hermes 工具运行或加载所需内容。
|
||||
- 项目长期知识、架构约定、排障经验、协作规则、计划和 TODO 统一放在 `docs/project-memory/`。
|
||||
- 不提交个人配置、API Key、会话转录、模型密钥、本地路径密钥等敏感内容。
|
||||
- 个人 Hermes 的 `~/.hermes/config.yaml`、`~/.hermes/.env`、`~/.hermes/sessions/` 不应复制到本仓库。
|
||||
- 开发前先阅读本目录下与任务相关的记忆文件;开发后如产生稳定知识,更新对应文档。
|
||||
- 后续新增的 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`,便于团队跨目录检索。
|
||||
- 若本目录内容与 `docs/` 或代码事实冲突,以当前代码和最新 `docs/` 为准,并同步修正过期记忆。
|
||||
- 阶段性计划、一次性 TODO 和已关闭实验不再长期沉淀为仓库文档;仍有效内容应合并进 `docs/` 当前融合文档或 `.hermes/shared-memory/`。
|
||||
- 若 `.hermes/` 中的工具说明与代码或 `docs/` 冲突,以当前代码和最新 `docs/` 为准。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```text
|
||||
.hermes/
|
||||
├─ README.md # 本说明
|
||||
├─ shared-memory/
|
||||
│ ├─ project-overview.md # 项目概览与当前技术路线
|
||||
│ ├─ team-conventions.md # 团队协作约定
|
||||
│ ├─ development-workflow.md # 开发、测试、提交流程
|
||||
│ ├─ document-map.md # README / AGENTS / docs 阅读索引
|
||||
│ ├─ decision-log.md # 长期决策记录
|
||||
│ ├─ pitfalls.md # 踩坑与排障记录
|
||||
│ └─ handoff-template.md # 任务交接模板
|
||||
├─ README.md # Hermes 工具目录说明
|
||||
├─ skills/ # 仓库级 Hermes skills
|
||||
└─ plugins/ # 仓库级 Hermes plugins(需显式启用项目 plugin)
|
||||
```
|
||||
@@ -71,22 +62,5 @@ HERMES_ENABLE_PROJECT_PLUGINS=1 HERMES_PLUGINS_DEBUG=1 hermes chat -q "请读取
|
||||
在本仓库中开始复杂任务时,可以先对 Hermes 说:
|
||||
|
||||
```text
|
||||
请先读取 AGENTS.md 以及 .hermes/shared-memory/ 下与本任务相关的团队共享记忆,再开始分析。若任务完成后产生稳定项目知识,请更新 .hermes/shared-memory/ 对应文件。
|
||||
请先读取 AGENTS.md 以及 docs/project-memory/shared-memory/ 下与本任务相关的团队共享记忆,再开始分析。若任务完成后产生稳定项目知识,请更新 docs/project-memory/shared-memory/ 对应文件。
|
||||
```
|
||||
|
||||
## 需要沉淀到这里的内容
|
||||
|
||||
- 长期有效的架构约定
|
||||
- 反复会用到的本地开发/测试流程
|
||||
- 已确认的接口契约或模块边界
|
||||
- 重要技术决策及原因
|
||||
- 踩坑、排障方式、验证命令
|
||||
- 团队协作规则和任务交接规范
|
||||
|
||||
## 不应沉淀到这里的内容
|
||||
|
||||
- API Key、Token、Cookie、私有密钥
|
||||
- 个人账号、个人本地绝对路径、个人隐私信息
|
||||
- 大段临时聊天记录
|
||||
- 尚未确认的一次性猜测
|
||||
- 构建产物、日志、缓存、数据库 dump
|
||||
|
||||
@@ -284,7 +284,7 @@ fn anonymous_user_cannot_publish_generated_draft() {
|
||||
| 正式产品验收 / PRD 场景 | 当前 `docs/` 融合文档,必要时新增 `docs/【产品验收】<功能名>BDD场景-YYYY-MM-DD.md` | 产品、测试、开发都需要长期参考的验收标准、用户故事、功能边界。 |
|
||||
| 技术/API/领域行为场景 | 当前 `docs/` 融合文档,必要时新增 `docs/【技术验收】<功能名>BDD场景-YYYY-MM-DD.md` | 后端 API、领域规则、状态机、SpacetimeDB reducer/table、SSE/异步任务、埋点副作用。 |
|
||||
| 自动化 Gherkin feature 文件 | `tests/features/*.feature` 或 `e2e/features/*.feature` | 项目已接入 Cucumber/Playwright BDD 等 Gherkin runner 时。未接入前不要随意新建测试 runner 目录。 |
|
||||
| 稳定流程或团队经验 | `.hermes/shared-memory/` 或 `.hermes/skills/` | 不是某个功能验收,而是长期可复用的团队流程、坑点、执行规范。 |
|
||||
| 稳定流程或团队经验 | `docs/project-memory/shared-memory/` 或 `.hermes/skills/` | 不是某个功能验收,而是长期可复用的团队流程、坑点、执行规范。 |
|
||||
|
||||
默认规则:
|
||||
|
||||
@@ -311,7 +311,7 @@ e2e/features/invite-code.feature
|
||||
- 实施计划:当前任务上下文或 `.tmp/<task-name>.md`
|
||||
- 产品/验收文档:当前 `docs/` 融合文档,必要时新增 `docs/【产品验收】中文标题-YYYY-MM-DD.md`
|
||||
- 技术设计:当前 `docs/` 融合文档,必要时新增 `docs/【技术方案】中文标题-YYYY-MM-DD.md`
|
||||
- 共享经验或稳定流程:`.hermes/shared-memory/` 或 `.hermes/skills/`
|
||||
- 共享经验或稳定流程:`docs/project-memory/shared-memory/` 或 `.hermes/skills/`
|
||||
|
||||
BDD 文档建议包含:
|
||||
|
||||
@@ -389,4 +389,4 @@ npm run test -- --run <相关测试文件>
|
||||
```
|
||||
|
||||
- [ ] 若涉及后端 Rust/API,按相关 DDD/SpacetimeDB 文档运行对应 cargo/npm/API smoke 验证。
|
||||
- [ ] 若产生长期有效经验,已同步到 `.hermes/shared-memory/` 或合适的仓库级 skill。
|
||||
- [ ] 若产生长期有效经验,已同步到 `docs/project-memory/shared-memory/` 或合适的仓库级 skill。
|
||||
|
||||
@@ -21,7 +21,7 @@ metadata:
|
||||
- 处理 `3000`、`3101`、`3102`、`8082` 等端口被占用导致本地开发栈启动失败。
|
||||
- 排查 Vite 代理仍指向旧 api-server 端口、前端打开了旧 dev server、后台代理错配。
|
||||
- 调整 SpacetimeDB standalone、publish、Rust `api-server`、主站 Vite、后台 Vite 的启动顺序。
|
||||
- 修改本地联调文档或 `.hermes/shared-memory/pitfalls.md` 中的 dev 启动口径。
|
||||
- 修改本地联调文档或 `docs/project-memory/shared-memory/pitfalls.md` 中的 dev 启动口径。
|
||||
|
||||
## 当前端口职责
|
||||
|
||||
@@ -75,7 +75,7 @@ Linux 多用户并发开发时,`GENARRATIVE_DEV_PORT_RANGE` 或 `--port-range`
|
||||
- `scripts/dev.mjs`
|
||||
- `scripts/dev-utils.mjs`
|
||||
- `docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md`
|
||||
- `.hermes/shared-memory/pitfalls.md`
|
||||
- `docs/project-memory/shared-memory/pitfalls.md`
|
||||
2. 优先改公共端口工具,不要把端口探测逻辑复制到多个脚本。
|
||||
3. 修改 `scripts/dev.mjs` 时确认变量顺序:先解析参数和端口,再构造 `SPACETIME_SERVER` / `RUST_SERVER_TARGET`,最后启动对应 service。
|
||||
4. 修改 watch 时保持模块边界:SpacetimeDB 只监听 `spacetime-module` 且改动后重新 publish,不重启 standalone 宿主;api-server 排除 `spacetime-module`;web/admin-web 源码变化交给 Vite 自身 HMR,外层调度器不要再监听前端目录重启 Vite。
|
||||
@@ -124,5 +124,5 @@ node scripts/dev-stack-port-utils.mjs resolve-dev-stack spacetime:127.0.0.1:0 ap
|
||||
- [ ] `npm run dev` 的 SpacetimeDB、publish、api-server、主站 Vite、后台 Vite 都使用实际端口。
|
||||
- [ ] `npm run dev:web` 在主站端口不可用时能切换到可用端口。
|
||||
- [ ] 文档同步更新 `docs/technical/RUST_LOCAL_AND_REMOTE_DEPLOYMENT_SCRIPTS_2026-04-22.md`。
|
||||
- [ ] 长期踩坑同步更新 `.hermes/shared-memory/pitfalls.md`。
|
||||
- [ ] 长期踩坑同步更新 `docs/project-memory/shared-memory/pitfalls.md`。
|
||||
- [ ] 修改中文文件后运行 `npm run check:encoding`。
|
||||
|
||||
@@ -47,13 +47,13 @@ description: 在 Genarrative 新增、开放或重构玩法创作工具时,按
|
||||
先读:
|
||||
|
||||
- `AGENTS.md`
|
||||
- `.hermes/shared-memory/`
|
||||
- `docs/project-memory/shared-memory/`
|
||||
- `CONTEXT.md`
|
||||
- `docs/README.md`
|
||||
- `docs/【玩法创作】平台入口与玩法链路-2026-05-15.md`
|
||||
- 相关玩法 PRD 或设计文档
|
||||
|
||||
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `.hermes/shared-memory/`。
|
||||
如果文档不能精确指导字段、契约、资产槽位、生成流程和恢复语义,先补文档再编码。新增长期约定时同步 `docs/project-memory/shared-memory/`。
|
||||
|
||||
### 2. 定玩法边界
|
||||
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@
|
||||
11. 接 `api-server`:
|
||||
- `src/runtime_profile.rs`:Query params / parser / handler / response builder。
|
||||
- `src/app.rs`:挂路由,例如 profile 或 admin analytics endpoint;选择路径前确认产品定位。
|
||||
12. 最后更新当前 `docs/` 文档和必要的 `.hermes/shared-memory/` 摘要,并确认 diff 不只是生成物。
|
||||
12. 最后更新当前 `docs/` 文档和必要的 `docs/project-memory/shared-memory/` 摘要,并确认 diff 不只是生成物。
|
||||
|
||||
## 验证命令示例
|
||||
|
||||
|
||||
@@ -1,86 +1,65 @@
|
||||
# AGENTS.md
|
||||
|
||||
## 团队 Hermes 共享记忆
|
||||
- 本仓库的团队级 Hermes 共享内容位于 [`.hermes/`](.hermes/),用于在 3 名开发人员各自本地 Hermes 之间同步长期项目记忆。
|
||||
- 开始复杂开发任务前,除阅读本文件外,还应优先读取:
|
||||
- [`.hermes/README.md`](.hermes/README.md)
|
||||
- [`.hermes/shared-memory/project-overview.md`](.hermes/shared-memory/project-overview.md)
|
||||
- [`.hermes/shared-memory/team-conventions.md`](.hermes/shared-memory/team-conventions.md)
|
||||
- [`.hermes/shared-memory/development-workflow.md`](.hermes/shared-memory/development-workflow.md)
|
||||
- 与任务相关的 [`.hermes/shared-memory/decision-log.md`](.hermes/shared-memory/decision-log.md) 和 [`.hermes/shared-memory/pitfalls.md`](.hermes/shared-memory/pitfalls.md)
|
||||
- 如果本次任务产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则,应同步更新 `.hermes/shared-memory/` 中对应文件。
|
||||
- 仓库 `.hermes/` 只保存可进入 Git 的团队共享内容;禁止提交个人 `~/.hermes` 配置、`.env`、API Key、Token、会话记录、认证文件和本地私密路径。
|
||||
- 若 `.hermes/shared-memory/` 与当前代码或 `docs/` 最新文档冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
## 入口定位
|
||||
|
||||
## Agent skills
|
||||
- 本文件只保留 Agent 进入仓库后必须立即遵守的最高优先级规则;完整执行细则见 [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
- 团队级长期项目记忆位于 [`docs/project-memory/`](docs/project-memory/),供 3 名开发人员和各自本地 Agent 通过 Git 同步。
|
||||
- [`.hermes/`](.hermes/) 只保存 Hermes 专用仓库级工具资源,例如 skills、plugins 和启用说明;长期项目知识不要写入 `.hermes/`。
|
||||
- 若 `docs/project-memory/shared-memory/` 与当前代码或最新 `docs/` 冲突,以代码和最新 `docs/` 为准,并同步修正过期共享记忆。
|
||||
|
||||
### Issue tracker
|
||||
## 开始任务前
|
||||
|
||||
Issues are tracked in the self-hosted Gitea remote for this repo. Use Gitea Issues via the configured Gitea UI/API or `tea` CLI when available; do not use GitHub `gh` or GitLab `glab` unless the repo is migrated. Current issue workflow is summarized in `docs/【开发运维】本地开发验证与生产运维-2026-05-15.md`.
|
||||
- 简单自包含任务可以直接执行;复杂开发、跨模块修改、后端 / UI / 文档体系调整前,按顺序读取:
|
||||
1. 本文件。
|
||||
2. [`docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md`](docs/【协作规范】Agent工作入口与执行准则-2026-06-22.md)。
|
||||
3. [`docs/project-memory/README.md`](docs/project-memory/README.md)、[`project-overview.md`](docs/project-memory/shared-memory/project-overview.md)、[`team-conventions.md`](docs/project-memory/shared-memory/team-conventions.md)、[`development-workflow.md`](docs/project-memory/shared-memory/development-workflow.md)。
|
||||
4. 与任务相关的 [`decision-log.md`](docs/project-memory/shared-memory/decision-log.md)、[`pitfalls.md`](docs/project-memory/shared-memory/pitfalls.md)、[`docs/README.md`](docs/README.md) 和当前专题文档。
|
||||
- 落地工程修改前,先确认是否已有足够具体的 PRD、技术方案或当前融合文档;文档仍存在编码级歧义时,先补文档再编码。
|
||||
- 本仓库的本地 RAG 位于 [`scripts/rag/`](scripts/rag/);RAG 只作为候选上下文,不替代打开源文件核对。默认不安装 RAG 运行时依赖,需要启用时必须先询问用户,并只安装到 gitignored 的 `.rag/runtime/`。
|
||||
|
||||
### Triage labels
|
||||
## 绝对约束
|
||||
|
||||
Use the default canonical triage labels: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`.
|
||||
- 禁止提交个人 `~/.hermes` 配置、`.env`、API Key、Token、Cookie、会话记录、认证文件、本地私密路径、构建产物、日志、缓存和数据库 dump。
|
||||
- 不要在 `.gitignore` 中新增 `.env.local`。
|
||||
- 不要擅自把现有中文文案、注释、剧情或文档改写成英文;看到中文乱码时先确认真实编码,不要沿用乱码或用英文替换。
|
||||
- 修改包含中文的文件时优先局部补丁,避免整文件重写;修改后优先运行仓库编码检查。
|
||||
- 后续新增 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`;历史文档不要求批量重命名,除非本次任务明确涉及。
|
||||
- 工程修改要同步更新对应 `docs/` 文档;产生长期有效的架构约定、接口变化、排障经验、开发流程或协作规则时,同步更新 `docs/project-memory/shared-memory/`。
|
||||
- 默认保持系统简洁:优先复用、修改、扩展现有系统、页面和公共组件,不新建平行系统或平行页面。
|
||||
- UI 面板中不要默认写功能说明、规则描述或开发解释文案;移动端优先,同时保证网页端可正常显示和操作。
|
||||
- 点击按钮弹出独立面板的设计,不要实现成在当前面板下面追加内容。
|
||||
|
||||
### Domain docs
|
||||
## 任务路由
|
||||
|
||||
Single-context layout: read root `CONTEXT.md` when present. Current architecture and product constraints are consolidated under `docs/`.
|
||||
- Issue 使用自托管 Gitea;优先用 Gitea UI/API 或 `tea` CLI,不使用 GitHub `gh` 或 GitLab `glab`,除非仓库已迁移。默认 triage 标签:`needs-triage`、`needs-info`、`ready-for-agent`、`ready-for-human`、`wontfix`。
|
||||
- 需要仓库级 Hermes skills/plugins 时,再读取 [`.hermes/README.md`](.hermes/README.md)。
|
||||
- 新增、补齐、迁移或重构玩法入口、玩法类型、创作工作台、生成页、结果页、发布、运行态、作品架、广场或公开 read model 前,必须读取并按 [`genarrative-play-type-integration`](.codex/skills/genarrative-play-type-integration/SKILL.md) 执行。
|
||||
- 涉及 `npm run dev` / `npm run dev:spacetime` / `npm run dev:api-server` / `npm run dev:web` / `npm run dev:admin-web` 的端口探测、端口漂移、SpacetimeDB publish server、api-server 环境变量、Vite 代理目标或后台 dev 端口时,按 [`.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md`](.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md) 执行。
|
||||
- 涉及 SpacetimeDB 的设计、实现、脚本、调试、发布、绑定生成、schema、reducer、procedure、view 或 Rust API 时,必须读取并按 [`spacetimedb-cli`](.codex/skills/spacetimedb-cli/SKILL.md)、[`spacetimedb-rust`](.codex/skills/spacetimedb-rust/SKILL.md)、[`spacetimedb-concepts`](.codex/skills/spacetimedb-concepts/SKILL.md) 中相关 skill 执行。
|
||||
|
||||
### 新增玩法接入
|
||||
## 后端红线
|
||||
|
||||
- 凡是新增、补齐、迁移或重构任何玩法入口、玩法类型、创作工作台、生成页、结果页、发布、运行态、作品架、广场或公开 read model 的任务,开始前必须显式读取并按 [$genarrative-play-type-integration](.codex\skills\genarrative-play-type-integration\SKILL.md) 执行;未先使用该 skill 的,不允许进入编码。
|
||||
|
||||
## 项目约束
|
||||
- 代码需要有完善的中文注释
|
||||
- 在落地工程修改前检查是否有详细指导本次落地的文档,若没有文档或文档的完善程度仍有落地过程中编码级别的歧义优先优化文档后落地工程迭代。
|
||||
- 对工程的修改不仅要落地到代码更面,还要更改对应文档,若没有生成新的文档,文档统一存在doc目录中
|
||||
- 后续新增的 Markdown 文档文件名必须以分类标签开头,格式为 `【标签名】中文标题-日期.md`;例如 `【后端架构】api-server能力模块化与图片资产Adapter收口计划-2026-05-14.md`。不要求批量重命名历史文档,除非本次任务明确涉及该文档。
|
||||
- 不要擅自把现有中文文案、注释、剧情、文档改写成英文,除非用户明确要求翻译。
|
||||
- 看到中文乱码时,不要直接沿用乱码文本,也不要用英文替换;先确认文件真实编码,再决定是否修改。
|
||||
- 在 PowerShell 5.1 中读取或写入文本时,必须显式使用 UTF-8;如果终端输出疑似乱码,要用 `Get-Content -Encoding UTF8`、Python 或 Node 再次核对原文。
|
||||
- 非必要不要整文件重写,尤其是包含中文的文件;优先做局部补丁,避免把未改动的中文内容重新编码。
|
||||
- 修改包含中文的文件后,优先运行仓库里的编码检查,确保没有把文本写坏。
|
||||
- UI面板中不要默认写一些规则描述文案,清爽一些,按照游戏UI设计规范设计即可。
|
||||
- UI设计需要兼顾网页端、移动端双端的使用体验,确保在不同设备上都能正常显示和操作,移动端优先考虑。
|
||||
- 不要在gitignore中添加.env.local文件。
|
||||
- 提交代码时,提交标题必须使用中文;标题后必须逐行写明本次提交修改了什么,每条变更单独一行。
|
||||
- 严格遵循简洁的代码风格
|
||||
- 请默认保持系统的简洁性,能复用、修改、扩展现有系统、页面就不新建新系统新页面。
|
||||
- 禁止将功能说明描述类的文本默认写入UI界面中。
|
||||
- prd文档中每个模块的描述要落地设计到可以精准编码到位,不能出现需求落地漂移。
|
||||
- 点击按钮弹出独立的面板的设计不要实现成在当前面板下面显示内容。
|
||||
- 每个阶段任务完成后自动压缩上下文,确保后续阶段在清晰、低噪音的上下文基础上继续推进。
|
||||
|
||||
## 后端技术约束
|
||||
- 后端最新技术约束以 [`docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md`](docs/【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md) 为准。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- SpacetimeDB 表结构、自动迁移限制和冲突处理以当前后端架构文档的 schema 变更规则和表目录为准;涉及 table、reducer、procedure、row shape 或绑定变化时,必须同步 `migration.rs`、表目录和生成绑定。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值(例如 `#[default(...)]`);需要修改字段名时,必须先询问用户并确认迁移计划,再改代码,同时更新 `server-rs/crates/spacetime-module/src/migration.rs`、表目录和生成绑定。
|
||||
- 修改 SpacetimeDB schema 后必须运行 `npm run check:spacetime-schema`;该检查会拦截新增字段缺 default、字段不在末尾、字段删除/改名/重排/改类型,以及漏改 `migration.rs`、表目录或生成绑定。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`。旧 `server-node`、Express、PostgreSQL 不再作为兼容目标;历史实现只能作为迁移参考,若旧文档与 DDD 约束冲突,先修正文档和方案再编码。
|
||||
- 后端路线固定为 `server-rs + Axum + SpacetimeDB`;旧 `server-node`、Express、PostgreSQL、Go 服务端、`maincloud` / `Maincloud` / `MAINCLOUD` 只作为历史残留,不作为兼容目标。
|
||||
- DDD 分层边界按总纲执行:领域规则沉到 `module-*`,SpacetimeDB 表和事务编排留在 `spacetime-module`,后端访问 SpacetimeDB 统一经 `spacetime-client` facade,HTTP/SSE/BFF 留在 `api-server`,外部副作用留在 `platform-*`,前后端 DTO 留在 `shared-contracts`。
|
||||
- 前端只做表现、交互和临时 UI 状态,不承接正式业务真相,不绕过后端投影或后端 API 直接实现业务规则。
|
||||
- 修改后端代码后,按对应 DDD 文档中的验收命令执行测试;涉及 API smoke 时使用 `npm run api-server` 重新拉起后端并执行相应自动测试,同时确认 `/healthz`。
|
||||
- `maincloud` / `Maincloud` / `MAINCLOUD` 相关脚本、环境变量、测试、文档要求和命名全部视为历史残留,禁止新增、运行或引用;若旧材料仍要求 `api-server:maincloud` 或 `GENARRATIVE_SPACETIME_MAINCLOUD_*`,以当前后端架构文档和本文件为准。
|
||||
- 除 CI/CD 脚本内部受控用法外,人工命令、本地联调、排障步骤和文档示例禁止继续使用 `spacetime --root-dir`。本地数据隔离使用项目脚本或 `--data-dir`,发布目标必须显式传 `--server` / `--server-url`,身份问题通过同一 CLI 登录态、专用运行用户或显式 token 处理;若旧文档仍推荐 `--root-dir`,先修正文档口径再执行。
|
||||
- 凡是涉及 SpacetimeDB 的设计、实现、脚本、调试、前端绑定接入,统一显式使用以下 skill 作为执行依据:
|
||||
- [$spacetimedb-cli](.codex\\skills\\spacetimedb-cli\\SKILL.md)
|
||||
- [$spacetimedb-rust](.codex\\skills\\spacetimedb-rust\\SKILL.md)
|
||||
- [$spacetimedb-concepts](.codex\\skills\\spacetimedb-concepts\\SKILL.md)
|
||||
- [$spacetimedb-typescript](.codex\\skills\\spacetimedb-typescript\\SKILL.md)
|
||||
- 涉及 `spacetime` CLI、发布、绑定生成、本地联调时,按 `spacetimedb-cli` 执行。
|
||||
- 涉及 `npm run dev` / `npm run dev:rust` / `npm run dev:web` 的端口探测、端口漂移、SpacetimeDB publish server、api-server 环境变量、Vite 代理目标或后台 dev 端口时,按 [`.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md`](.hermes/skills/genarrative-dev-stack-port-routing/SKILL.md) 执行。
|
||||
- 涉及 `crates/spacetime-module` 的表、reducer、view、Rust API 使用时,按 `spacetimedb-rust` 与 `spacetimedb-concepts` 执行。
|
||||
- 涉及前端或 Node 侧的 SpacetimeDB TypeScript SDK、订阅、绑定使用时,按 `spacetimedb-typescript` 与 `spacetimedb-concepts` 执行。
|
||||
- 若仓库内旧实现或旧文档与这些 skill 冲突,先修正文档和方案,再继续编码。
|
||||
- 修改后端代码后,必须使用 `npm run api-server` 自动重新运行后端,并执行相应自动测试;不要再使用旧的后端重启命令。
|
||||
- 数据库表结构更改后,需要对齐migration.rs
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值;需要删除、改名、重排或改类型时,必须先询问用户并确认迁移计划。
|
||||
- 修改 SpacetimeDB schema 后必须同步 `migration.rs`、表目录和生成绑定,并运行 `npm run check:spacetime-schema`。
|
||||
- 除 CI/CD 脚本内部受控用法外,人工命令、本地联调、排障步骤和文档示例禁止继续使用 `spacetime --root-dir`。
|
||||
|
||||
## 验证与提交
|
||||
|
||||
- 修改后按范围运行定向测试、类型检查、`npm run check:encoding` 和 `git diff --check`;后端 API smoke 使用 `npm run dev:api-server` 拉起后端并检查 `/healthz`。
|
||||
- 修改 SpacetimeDB schema 后追加 `npm run check:spacetime-schema`;涉及发布或生产运维时按当前开发运维文档和脚本门禁执行。
|
||||
- 提交代码时,提交标题必须使用中文;标题后逐行写明本次提交修改了什么,每条变更单独一行。
|
||||
|
||||
## 文档图谱
|
||||
|
||||
```text
|
||||
docs/
|
||||
├─ README.md
|
||||
├─ 【协作规范】Agent工作入口与执行准则-2026-06-22.md
|
||||
├─ 【项目基线】当前产品与工程约束-2026-05-15.md
|
||||
├─ 【后端架构】server-rs与SpacetimeDB数据契约-2026-05-15.md
|
||||
├─ 【玩法创作】平台入口与玩法链路-2026-05-15.md
|
||||
|
||||
+16
@@ -12,6 +12,22 @@ _Avoid_: 默认对话式 Agent 工作台、默认轻输入 Agent 工作台、复
|
||||
角色形象、UI 背景、容器、封面、分享图等单张图资产的统一输入与重生成方式,统一通过 `CreativeImageInputPanel` 表达上传、AI 重绘、参考图、历史图和删除确认。
|
||||
_Avoid_: 在玩法页面内手写上传、参考图、重绘、预览、删除确认
|
||||
|
||||
**图片画布工程**:
|
||||
独立 `/editor` 中可保存、恢复和继续编辑的图片画布工作状态,包含画布视图、图层布局和资源引用;用于多图对比、生成结果衍生和画布级编辑,不替代玩法页面内的单图资产编辑。
|
||||
_Avoid_: 玩法结果页单图槽位、发布态作品、只存在前端内存里的临时画布
|
||||
|
||||
**画布资源**:
|
||||
图片画布工程中可被一个或多个图层引用的图片资源记录,保存 OSS 对象引用、上传 / 生成来源、提示词、模型、任务和尺寸等资源元数据;同一资源可以在工程布局中出现多次。
|
||||
_Avoid_: 图层位置、前端 hover / selected 状态、直接内嵌图片二进制
|
||||
|
||||
**图层布局**:
|
||||
图片画布工程中描述资源实例如何摆放的画布结构,包含 resourceId、位置、尺寸、缩放、层级和选中所需的稳定图层 ID;布局属于工程快照,不属于画布资源本身。
|
||||
_Avoid_: 把同一资源的全局元数据和某一次摆放坐标混在同一条资源记录里
|
||||
|
||||
**生成资源**:
|
||||
由图片生成或图片修改流程产生的画布资源,必须记录来源资源、提示词、实际提示词、模型、provider、任务 ID 和生成时间;本期 `/editor` 的生成修改先允许 mock 生成资源,但仍按生成资源元数据形状保存。
|
||||
_Avoid_: 无来源的静态素材、只显示在 UI 但不落工程资源记录的生成结果
|
||||
|
||||
**系列素材图集生成**:
|
||||
一组同类素材的统一批量生成方式,采用批量规划、sheet 生图、后端切图、透明化、OSS 持久化和局部重生成的通用流水线。
|
||||
_Avoid_: 为每个玩法单独发明素材流水线、把系列素材建模成任一玩法专属 DTO
|
||||
|
||||
+177
File diff suppressed because one or more lines are too long
@@ -2,6 +2,8 @@ import type {
|
||||
AdminUpsertCreationEntryEventBannersRequest,
|
||||
AdminUpsertCreationEntryTypeConfigRequest,
|
||||
AdminCreationEntryConfigResponse,
|
||||
AdminDashboardQuery,
|
||||
AdminDashboardResponse,
|
||||
AdminDebugHttpRequest,
|
||||
AdminDebugHttpResponse,
|
||||
AdminDisableProfileRedeemCodeRequest,
|
||||
@@ -20,11 +22,13 @@ import type {
|
||||
AdminUpsertProfileRechargeProductRequest,
|
||||
AdminUpsertProfileRedeemCodeRequest,
|
||||
AdminUpsertProfileTaskConfigRequest,
|
||||
AdminUpsertProfileWalletConfigRequest,
|
||||
AdminUpsertPublicWorkInteractionConfigRequest,
|
||||
AdminWorkVisibilityListResponse,
|
||||
ApiErrorEnvelope,
|
||||
ApiMeta,
|
||||
ApiSuccessEnvelope,
|
||||
EditorGenerationPricingConfigPayload,
|
||||
ProfileInviteCodeAdminListResponse,
|
||||
ProfileInviteCodeAdminResponse,
|
||||
ProfileRechargeProductConfigAdminListResponse,
|
||||
@@ -33,6 +37,7 @@ import type {
|
||||
ProfileRedeemCodeAdminResponse,
|
||||
ProfileTaskConfigAdminListResponse,
|
||||
ProfileTaskConfigAdminResponse,
|
||||
ProfileWalletConfigAdminResponse,
|
||||
} from './adminApiTypes';
|
||||
|
||||
const API_RESPONSE_ENVELOPE_HEADER = 'x-genarrative-response-envelope';
|
||||
@@ -142,6 +147,16 @@ export function getAdminOverview(token: string) {
|
||||
return request<AdminOverviewResponse>('/admin/api/overview', { token });
|
||||
}
|
||||
|
||||
export function getAdminDashboard(
|
||||
token: string,
|
||||
query: AdminDashboardQuery = {},
|
||||
) {
|
||||
return request<AdminDashboardResponse>(
|
||||
`/admin/api/dashboard${buildDashboardQuery(query)}`,
|
||||
{ token },
|
||||
);
|
||||
}
|
||||
|
||||
export function getAdminDatabaseTables(token: string) {
|
||||
return request<AdminDatabaseTableListResponse>('/admin/api/database/tables', {
|
||||
token,
|
||||
@@ -228,6 +243,27 @@ export function upsertAdminPublicWorkInteractions(
|
||||
);
|
||||
}
|
||||
|
||||
export function getAdminEditorGenerationPricing(token: string) {
|
||||
return request<EditorGenerationPricingConfigPayload>(
|
||||
'/admin/api/editor-generation-pricing',
|
||||
{ token },
|
||||
);
|
||||
}
|
||||
|
||||
export function upsertAdminEditorGenerationPricing(
|
||||
token: string,
|
||||
payload: EditorGenerationPricingConfigPayload,
|
||||
) {
|
||||
return request<EditorGenerationPricingConfigPayload>(
|
||||
'/admin/api/editor-generation-pricing',
|
||||
{
|
||||
method: 'POST',
|
||||
token,
|
||||
body: payload,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function listAdminWorkVisibility(token: string) {
|
||||
return request<AdminWorkVisibilityListResponse>(
|
||||
'/admin/api/works/visibility',
|
||||
@@ -337,6 +373,27 @@ export function disableProfileTaskConfig(
|
||||
);
|
||||
}
|
||||
|
||||
export function getProfileWalletConfig(token: string) {
|
||||
return request<ProfileWalletConfigAdminResponse>(
|
||||
'/admin/api/profile/wallet-config',
|
||||
{ token },
|
||||
);
|
||||
}
|
||||
|
||||
export function upsertProfileWalletConfig(
|
||||
token: string,
|
||||
payload: AdminUpsertProfileWalletConfigRequest,
|
||||
) {
|
||||
return request<ProfileWalletConfigAdminResponse>(
|
||||
'/admin/api/profile/wallet-config',
|
||||
{
|
||||
method: 'POST',
|
||||
token,
|
||||
body: payload,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function listProfileRechargeProducts(token: string) {
|
||||
return request<ProfileRechargeProductConfigAdminListResponse>(
|
||||
'/admin/api/profile/recharge-products',
|
||||
@@ -380,6 +437,16 @@ function buildQueryString(query: AdminTrackingEventListQuery) {
|
||||
return queryString ? `?${queryString}` : '';
|
||||
}
|
||||
|
||||
function buildDashboardQuery(query: AdminDashboardQuery) {
|
||||
const params = new URLSearchParams();
|
||||
appendQueryParam(params, 'granularity', query.granularity);
|
||||
appendQueryParam(params, 'anchor', query.anchor);
|
||||
appendQueryParam(params, 'startDate', query.startDate);
|
||||
appendQueryParam(params, 'endDate', query.endDate);
|
||||
const queryString = params.toString();
|
||||
return queryString ? `?${queryString}` : '';
|
||||
}
|
||||
|
||||
function buildDatabaseTableRowsQuery(query: AdminDatabaseTableRowsQuery) {
|
||||
const params = new URLSearchParams();
|
||||
appendQueryParam(params, 'search', query.search);
|
||||
|
||||
@@ -54,6 +54,77 @@ export interface AdminOverviewResponse {
|
||||
database: AdminDatabaseOverviewPayload;
|
||||
}
|
||||
|
||||
export type AdminDashboardGranularity = 'day' | 'week' | 'month' | 'period';
|
||||
|
||||
export interface AdminDashboardQuery {
|
||||
granularity?: AdminDashboardGranularity;
|
||||
anchor?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
}
|
||||
|
||||
export interface AdminDashboardResponse {
|
||||
range: AdminDashboardRangePayload;
|
||||
metrics: AdminDashboardMetricsPayload;
|
||||
charts: AdminDashboardChartPayload[];
|
||||
operations: AdminDashboardOperationsPayload;
|
||||
warnings: string[];
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export interface AdminDashboardRangePayload {
|
||||
granularity: AdminDashboardGranularity;
|
||||
anchorDate: string;
|
||||
periodStartDate: string;
|
||||
periodEndDate: string;
|
||||
periodLabel: string;
|
||||
}
|
||||
|
||||
export interface AdminDashboardMetricsPayload {
|
||||
generatedAssets: number;
|
||||
consumedMudPoints: number;
|
||||
totalRegisteredUsers: number;
|
||||
newRegisteredUsers: number;
|
||||
visitUsers: number;
|
||||
totalVisitUsers: number;
|
||||
visitCount: number;
|
||||
totalVisitCount: number;
|
||||
currentUsers: number;
|
||||
}
|
||||
|
||||
export interface AdminDashboardChartPayload {
|
||||
id: string;
|
||||
title: string;
|
||||
unit: string;
|
||||
total: number;
|
||||
buckets: AdminDashboardChartBucketPayload[];
|
||||
}
|
||||
|
||||
export interface AdminDashboardChartBucketPayload {
|
||||
key: string;
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface AdminDashboardOperationsPayload {
|
||||
cards: AdminDashboardOperationMetricPayload[];
|
||||
assetKindBreakdown: AdminDashboardBreakdownRowPayload[];
|
||||
moduleVisitBreakdown: AdminDashboardBreakdownRowPayload[];
|
||||
}
|
||||
|
||||
export interface AdminDashboardOperationMetricPayload {
|
||||
id: string;
|
||||
label: string;
|
||||
value: number;
|
||||
unit: string;
|
||||
}
|
||||
|
||||
export interface AdminDashboardBreakdownRowPayload {
|
||||
key: string;
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface AdminServiceOverviewPayload {
|
||||
bindHost: string;
|
||||
bindPort: number;
|
||||
@@ -210,6 +281,19 @@ export interface AdminUpsertPublicWorkInteractionConfigRequest {
|
||||
publicWorkInteractions: PublicWorkInteractionConfigPayload[];
|
||||
}
|
||||
|
||||
/** 图片画布生成模型泥点定价配置。 */
|
||||
export type EditorGenerationPricingUnitPayload = 'perGeneration' | 'perSecond';
|
||||
|
||||
export interface EditorGenerationModelPricingPayload {
|
||||
unit: EditorGenerationPricingUnitPayload;
|
||||
price?: number;
|
||||
prices?: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface EditorGenerationPricingConfigPayload {
|
||||
models: Record<string, EditorGenerationModelPricingPayload>;
|
||||
}
|
||||
|
||||
/** 后台统一创作工作台契约表单的传输结构。 */
|
||||
export interface UnifiedCreationSpecPayload {
|
||||
playId: string;
|
||||
@@ -312,6 +396,10 @@ export interface AdminUpsertProfileRechargeProductRequest {
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
export interface AdminUpsertProfileWalletConfigRequest {
|
||||
initialMudPoints: number;
|
||||
}
|
||||
|
||||
export interface ProfileRedeemCodeAdminResponse {
|
||||
code: string;
|
||||
mode: ProfileRedeemCodeMode;
|
||||
@@ -388,6 +476,15 @@ export interface ProfileRechargeProductConfigAdminListResponse {
|
||||
entries: ProfileRechargeProductConfigAdminResponse[];
|
||||
}
|
||||
|
||||
export interface ProfileWalletConfigAdminResponse {
|
||||
configId: string;
|
||||
initialMudPoints: number;
|
||||
createdBy: string;
|
||||
createdAt: string;
|
||||
updatedBy: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface AdminTrackingEventEntryPayload {
|
||||
eventId: string;
|
||||
eventKey: string;
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ProfileRechargeProductConfigAdminResponse,
|
||||
ProfileRedeemCodeAdminResponse,
|
||||
ProfileTaskConfigAdminResponse,
|
||||
ProfileWalletConfigAdminResponse,
|
||||
} from '../api/adminApiTypes';
|
||||
import {
|
||||
clearStoredAdminToken,
|
||||
@@ -19,11 +20,14 @@ import {
|
||||
setStoredAdminToken,
|
||||
} from '../auth/adminAuthStore';
|
||||
import {AdminCreationEntrySwitchPage} from '../pages/AdminCreationEntrySwitchPage';
|
||||
import {AdminDashboardPage} from '../pages/AdminDashboardPage';
|
||||
import {AdminDebugHttpPage} from '../pages/AdminDebugHttpPage';
|
||||
import {AdminDatabaseTablesPage} from '../pages/AdminDatabaseTablesPage';
|
||||
import {AdminInviteCodePage} from '../pages/AdminInviteCodePage';
|
||||
import {AdminLoginPage} from '../pages/AdminLoginPage';
|
||||
import {AdminEditorGenerationPricingPage} from '../pages/AdminEditorGenerationPricingPage';
|
||||
import {AdminOverviewPage} from '../pages/AdminOverviewPage';
|
||||
import {AdminProfileWalletConfigPage} from '../pages/AdminProfileWalletConfigPage';
|
||||
import {AdminRechargeProductPage} from '../pages/AdminRechargeProductPage';
|
||||
import {AdminRedeemCodePage} from '../pages/AdminRedeemCodePage';
|
||||
import {AdminTaskConfigPage} from '../pages/AdminTaskConfigPage';
|
||||
@@ -50,6 +54,8 @@ export function AdminApp() {
|
||||
useState<ProfileInviteCodeAdminResponse | null>(null);
|
||||
const [taskConfigResult, setTaskConfigResult] =
|
||||
useState<ProfileTaskConfigAdminResponse | null>(null);
|
||||
const [profileWalletConfigResult, setProfileWalletConfigResult] =
|
||||
useState<ProfileWalletConfigAdminResponse | null>(null);
|
||||
const [rechargeProductResult, setRechargeProductResult] =
|
||||
useState<ProfileRechargeProductConfigAdminResponse | null>(null);
|
||||
|
||||
@@ -60,6 +66,7 @@ export function AdminApp() {
|
||||
setRedeemResult(null);
|
||||
setInviteResult(null);
|
||||
setTaskConfigResult(null);
|
||||
setProfileWalletConfigResult(null);
|
||||
setRechargeProductResult(null);
|
||||
setStatus('guest');
|
||||
setLoginNotice(message);
|
||||
@@ -130,6 +137,7 @@ export function AdminApp() {
|
||||
setRedeemResult(null);
|
||||
setInviteResult(null);
|
||||
setTaskConfigResult(null);
|
||||
setProfileWalletConfigResult(null);
|
||||
setRechargeProductResult(null);
|
||||
setLoginNotice('');
|
||||
setStatus('authenticated');
|
||||
@@ -166,6 +174,9 @@ export function AdminApp() {
|
||||
onLogout={handleLogout}
|
||||
onRouteChange={handleRouteChange}
|
||||
>
|
||||
{routeId === 'dashboard' ? (
|
||||
<AdminDashboardPage token={token} onUnauthorized={handleUnauthorized} />
|
||||
) : null}
|
||||
{routeId === 'overview' ? (
|
||||
<AdminOverviewPage token={token} onUnauthorized={handleUnauthorized} />
|
||||
) : null}
|
||||
@@ -227,6 +238,14 @@ export function AdminApp() {
|
||||
onResultChange={setTaskConfigResult}
|
||||
/>
|
||||
) : null}
|
||||
{routeId === 'profile-wallet' ? (
|
||||
<AdminProfileWalletConfigPage
|
||||
result={profileWalletConfigResult}
|
||||
token={token}
|
||||
onUnauthorized={handleUnauthorized}
|
||||
onResultChange={setProfileWalletConfigResult}
|
||||
/>
|
||||
) : null}
|
||||
{routeId === 'recharge-products' ? (
|
||||
<AdminRechargeProductPage
|
||||
result={rechargeProductResult}
|
||||
@@ -235,6 +254,12 @@ export function AdminApp() {
|
||||
onResultChange={setRechargeProductResult}
|
||||
/>
|
||||
) : null}
|
||||
{routeId === 'editor-generation-pricing' ? (
|
||||
<AdminEditorGenerationPricingPage
|
||||
token={token}
|
||||
onUnauthorized={handleUnauthorized}
|
||||
/>
|
||||
) : null}
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import {
|
||||
Activity,
|
||||
Bug,
|
||||
BadgeDollarSign,
|
||||
Coins,
|
||||
LayoutDashboard,
|
||||
LogOut,
|
||||
Megaphone,
|
||||
Eye,
|
||||
WalletCards,
|
||||
ShieldCheck,
|
||||
ListChecks,
|
||||
SlidersHorizontal,
|
||||
@@ -28,14 +31,17 @@ interface AdminShellProps {
|
||||
}
|
||||
|
||||
const routeIcons = {
|
||||
overview: LayoutDashboard,
|
||||
dashboard: LayoutDashboard,
|
||||
overview: Activity,
|
||||
tables: Database,
|
||||
debug: Bug,
|
||||
tracking: Table2,
|
||||
redeem: TicketPercent,
|
||||
invite: TicketCheck,
|
||||
'profile-wallet': WalletCards,
|
||||
tasks: ListChecks,
|
||||
'recharge-products': BadgeDollarSign,
|
||||
'editor-generation-pricing': Coins,
|
||||
'creation-announcement': Megaphone,
|
||||
'creation-entry': SlidersHorizontal,
|
||||
'work-visibility': Eye,
|
||||
|
||||
@@ -2,6 +2,17 @@ import {expect, test} from 'vitest';
|
||||
|
||||
import {adminRoutes, resolveAdminRoute, routeHash} from './adminRoutes';
|
||||
|
||||
test('后台默认进入 Dashboard', () => {
|
||||
expect(adminRoutes[0]).toEqual({
|
||||
id: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
hash: '#dashboard',
|
||||
});
|
||||
expect(resolveAdminRoute('')).toBe('dashboard');
|
||||
expect(resolveAdminRoute('#unknown')).toBe('dashboard');
|
||||
expect(routeHash('dashboard')).toBe('#dashboard');
|
||||
});
|
||||
|
||||
// 中文注释:后台入口公告必须作为独立导航存在,避免公告表单被误藏在入口开关页。
|
||||
test('后台入口公告路由可通过导航和 hash 访问', () => {
|
||||
expect(adminRoutes).toContainEqual({
|
||||
@@ -14,3 +25,17 @@ test('后台入口公告路由可通过导航和 hash 访问', () => {
|
||||
);
|
||||
expect(routeHash('creation-announcement')).toBe('#creation-announcement');
|
||||
});
|
||||
|
||||
test('后台模型定价路由可通过导航和 hash 访问', () => {
|
||||
expect(adminRoutes).toContainEqual({
|
||||
id: 'editor-generation-pricing',
|
||||
label: '模型定价',
|
||||
hash: '#editor-generation-pricing',
|
||||
});
|
||||
expect(resolveAdminRoute('#editor-generation-pricing')).toBe(
|
||||
'editor-generation-pricing',
|
||||
);
|
||||
expect(routeHash('editor-generation-pricing')).toBe(
|
||||
'#editor-generation-pricing',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
/** 后台单页应用可导航的路由标识,入口公告独立于入口开关维护。 */
|
||||
export type AdminRouteId =
|
||||
| 'dashboard'
|
||||
| 'overview'
|
||||
| 'tables'
|
||||
| 'debug'
|
||||
| 'tracking'
|
||||
| 'redeem'
|
||||
| 'invite'
|
||||
| 'profile-wallet'
|
||||
| 'tasks'
|
||||
| 'recharge-products'
|
||||
| 'editor-generation-pricing'
|
||||
| 'creation-announcement'
|
||||
| 'creation-entry'
|
||||
| 'work-visibility';
|
||||
@@ -20,25 +23,28 @@ export interface AdminRouteDefinition {
|
||||
}
|
||||
|
||||
export const adminRoutes: AdminRouteDefinition[] = [
|
||||
{id: 'overview', label: '总览', hash: '#overview'},
|
||||
{id: 'dashboard', label: 'Dashboard', hash: '#dashboard'},
|
||||
{id: 'overview', label: '服务总览', hash: '#overview'},
|
||||
{id: 'tables', label: '表查询', hash: '#tables'},
|
||||
{id: 'debug', label: 'API 调试', hash: '#debug'},
|
||||
{id: 'tracking', label: '埋点数据', hash: '#tracking'},
|
||||
{id: 'redeem', label: '兑换码', hash: '#redeem'},
|
||||
{id: 'invite', label: '邀请码', hash: '#invite'},
|
||||
{id: 'profile-wallet', label: '账号配置', hash: '#profile-wallet'},
|
||||
{id: 'tasks', label: '任务配置', hash: '#tasks'},
|
||||
{id: 'recharge-products', label: '充值商品', hash: '#recharge-products'},
|
||||
{id: 'editor-generation-pricing', label: '模型定价', hash: '#editor-generation-pricing'},
|
||||
{id: 'creation-announcement', label: '入口公告', hash: '#creation-announcement'},
|
||||
{id: 'creation-entry', label: '入口开关', hash: '#creation-entry'},
|
||||
{id: 'work-visibility', label: '作品可见性', hash: '#work-visibility'},
|
||||
];
|
||||
|
||||
/** 根据地址栏 hash 解析后台路由,未知 hash 回落到总览页。 */
|
||||
/** 根据地址栏 hash 解析后台路由,未知 hash 回落到 Dashboard。 */
|
||||
export function resolveAdminRoute(hash: string): AdminRouteId {
|
||||
const normalizedHash = hash.trim().toLowerCase().split('?')[0] ?? '';
|
||||
return (
|
||||
adminRoutes.find((route) => route.hash === normalizedHash)?.id ??
|
||||
'overview'
|
||||
'dashboard'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,6 +53,6 @@ export function routeHash(routeId: AdminRouteId) {
|
||||
return (
|
||||
adminRoutes.find((route) => route.id === routeId)?.hash ??
|
||||
adminRoutes[0]?.hash ??
|
||||
'#overview'
|
||||
'#dashboard'
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/* @vitest-environment jsdom */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import { getAdminDashboard } from '../api/adminApiClient';
|
||||
import type { AdminDashboardResponse } from '../api/adminApiTypes';
|
||||
import { AdminDashboardPage } from './AdminDashboardPage';
|
||||
|
||||
vi.mock('../api/adminApiClient', () => ({
|
||||
formatAdminApiError: vi.fn((error: unknown) =>
|
||||
error instanceof Error ? error.message : '请求失败',
|
||||
),
|
||||
getAdminDashboard: vi.fn(),
|
||||
isAdminApiError: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
const dashboardResponse: AdminDashboardResponse = {
|
||||
range: {
|
||||
granularity: 'day',
|
||||
anchorDate: '2026-06-23',
|
||||
periodStartDate: '2026-06-23',
|
||||
periodEndDate: '2026-06-23',
|
||||
periodLabel: '2026-06-23',
|
||||
},
|
||||
metrics: {
|
||||
generatedAssets: 12,
|
||||
consumedMudPoints: 88,
|
||||
totalRegisteredUsers: 1200,
|
||||
newRegisteredUsers: 16,
|
||||
visitUsers: 34,
|
||||
totalVisitUsers: 456,
|
||||
visitCount: 98,
|
||||
totalVisitCount: 9876,
|
||||
currentUsers: 7,
|
||||
},
|
||||
charts: [
|
||||
{
|
||||
id: 'generated-assets',
|
||||
title: '生产素材',
|
||||
unit: '个',
|
||||
total: 12,
|
||||
buckets: [{ key: '2026-06-23', label: '2026-06-23', value: 12 }],
|
||||
},
|
||||
],
|
||||
operations: {
|
||||
cards: [
|
||||
{
|
||||
id: 'period-generated-assets',
|
||||
label: '生产素材',
|
||||
value: 12,
|
||||
unit: '个',
|
||||
},
|
||||
],
|
||||
assetKindBreakdown: [
|
||||
{ key: 'editor_generated_image', label: '画板图片', value: 9 },
|
||||
],
|
||||
moduleVisitBreakdown: [{ key: 'auth', label: '认证', value: 30 }],
|
||||
},
|
||||
warnings: [],
|
||||
generatedAt: '2026-06-23T12:00:00Z',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getAdminDashboard).mockResolvedValue(dashboardResponse);
|
||||
});
|
||||
|
||||
test('Dashboard 默认加载今日指标并支持运营汇总页签', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminDashboardPage token="admin-token" onUnauthorized={vi.fn()} />);
|
||||
|
||||
expect(await screen.findByText('本日总生产素材数')).toBeTruthy();
|
||||
expect(screen.getByText('总注册用户')).toBeTruthy();
|
||||
expect(screen.getByText('本日新增用户数')).toBeTruthy();
|
||||
expect(screen.getByText('当前使用人数(五分钟统计一次)')).toBeTruthy();
|
||||
expect(screen.getByText('生产素材')).toBeTruthy();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '运营汇总' }));
|
||||
|
||||
expect(screen.getByText('素材类型分布')).toBeTruthy();
|
||||
expect(screen.getByText('画板图片')).toBeTruthy();
|
||||
expect(screen.getByText('访问模块分布')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('Dashboard 选择本周时按当前终止日期填充整周范围', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminDashboardPage token="admin-token" onUnauthorized={vi.fn()} />);
|
||||
|
||||
await screen.findByText('本日总生产素材数');
|
||||
fireEvent.change(screen.getByLabelText('终止日期'), {
|
||||
target: { value: '2026-07-02' },
|
||||
});
|
||||
await user.click(screen.getByRole('button', { name: '本周' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getAdminDashboard).toHaveBeenLastCalledWith('admin-token', {
|
||||
granularity: 'week',
|
||||
anchor: '2026-07-05',
|
||||
startDate: '2026-06-29',
|
||||
endDate: '2026-07-05',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('Dashboard 选择本月时按当前终止日期填充整月范围', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AdminDashboardPage token="admin-token" onUnauthorized={vi.fn()} />);
|
||||
|
||||
await screen.findByText('本日总生产素材数');
|
||||
fireEvent.change(screen.getByLabelText('终止日期'), {
|
||||
target: { value: '2026-07-12' },
|
||||
});
|
||||
await user.click(screen.getByRole('button', { name: '本月' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getAdminDashboard).toHaveBeenLastCalledWith('admin-token', {
|
||||
granularity: 'month',
|
||||
anchor: '2026-07-31',
|
||||
startDate: '2026-07-01',
|
||||
endDate: '2026-07-31',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('Dashboard 手动选择起止日期时使用本时段查询', async () => {
|
||||
render(<AdminDashboardPage token="admin-token" onUnauthorized={vi.fn()} />);
|
||||
|
||||
await screen.findByText('本日总生产素材数');
|
||||
fireEvent.change(screen.getByLabelText('起始日期'), {
|
||||
target: { value: '2026-06-01' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('终止日期'), {
|
||||
target: { value: '2026-06-12' },
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getAdminDashboard).toHaveBeenLastCalledWith('admin-token', {
|
||||
granularity: 'period',
|
||||
anchor: undefined,
|
||||
startDate: '2026-06-01',
|
||||
endDate: '2026-06-12',
|
||||
});
|
||||
});
|
||||
expect(screen.getByText('本时段新增用户数')).toBeTruthy();
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user