Compare commits
4 Commits
684ae0ecf8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 48a45b5447 | |||
| 5bd6331ad9 | |||
| eb084e1f07 | |||
| 30649488bb |
8
.env_dist
Normal file
8
.env_dist
Normal file
@@ -0,0 +1,8 @@
|
||||
# Script saving configuration
|
||||
ENABLE_SAVE=true
|
||||
SAVE_SECRET=save
|
||||
SAVE_DIRECTORY=./data/scripts
|
||||
MAX_FILENAME_LENGTH=32
|
||||
|
||||
# Next.js environment
|
||||
NODE_ENV=production
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -4,3 +4,5 @@ node_modules
|
||||
target
|
||||
.DS_Store
|
||||
webui/src/wasm
|
||||
webui/data
|
||||
.env
|
||||
|
||||
30
Dockerfile
Normal file
30
Dockerfile
Normal file
@@ -0,0 +1,30 @@
|
||||
FROM rust:1.91 AS rust-builder
|
||||
|
||||
WORKDIR /app
|
||||
RUN cargo install wasm-pack
|
||||
|
||||
COPY rust/ ./rust/
|
||||
WORKDIR /app/rust/rhai-codemirror
|
||||
RUN wasm-pack build --target web --out-dir "../../webui/src/wasm/rhai-codemirror"
|
||||
|
||||
WORKDIR /app/rust/runner
|
||||
RUN wasm-pack build --target web --out-dir "../../webui/src/wasm/runner"
|
||||
|
||||
FROM node:24-alpine AS app
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN npm install -g bun
|
||||
COPY webui/package.json webui/bun.lock* ./webui/
|
||||
|
||||
WORKDIR /app/webui
|
||||
RUN bun install --frozen-lockfile
|
||||
COPY webui/ ./
|
||||
COPY --from=rust-builder /app/webui/src/wasm/ ./src/wasm/
|
||||
|
||||
RUN bun run build
|
||||
|
||||
RUN mkdir -p ../data/scripts
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["bun", "start"]
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
// Return a random valid action on the given board.
|
||||
// Used as a last resort.
|
||||
fn random_action(board) {
|
||||
@@ -59,8 +57,8 @@ fn compute_influence(board) {
|
||||
}
|
||||
|
||||
|
||||
// Sort by increasing absolute score
|
||||
influence.sort(|a, b| {
|
||||
// Sort by increasing absolute score
|
||||
influence.sort(|a, b| {
|
||||
let a_abs = a[1].abs();
|
||||
let b_abs = b[1].abs();
|
||||
|
||||
@@ -85,7 +83,6 @@ fn place_number(board, minimize) {
|
||||
return random_action(board);
|
||||
}
|
||||
|
||||
|
||||
// Get the most influential position
|
||||
let pos = influence[-1][0];
|
||||
let val = influence[-1][1];
|
||||
@@ -104,7 +101,7 @@ fn place_number(board, minimize) {
|
||||
if val > 0 {
|
||||
symbol = available_numbers[-1];
|
||||
} else {
|
||||
symbol = available_numbers[0];
|
||||
symbol = available_numbers[0];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,25 +136,20 @@ fn place_op(board, minimize) {
|
||||
return ();
|
||||
}
|
||||
|
||||
|
||||
// Main step function (shared between min and max)
|
||||
fn greed_step(board, minimize) {
|
||||
|
||||
let action = place_op(board, minimize);
|
||||
|
||||
// We could not place an op, so place a number
|
||||
if action == () {
|
||||
action = place_number(board, minimize);
|
||||
}
|
||||
|
||||
if board.can_play(action) {
|
||||
return action;
|
||||
}
|
||||
|
||||
// Prevent invalid moves, random fallback
|
||||
if board.can_play(action) { return action; }
|
||||
return random_action(board);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Minimizer step
|
||||
fn step_min(board) {
|
||||
greed_step(board, true)
|
||||
254
agents/greed-v2.rhai
Normal file
254
agents/greed-v2.rhai
Normal file
@@ -0,0 +1,254 @@
|
||||
// SECRET
|
||||
|
||||
// Return a random valid action on the given board.
|
||||
// Used as a last resort.
|
||||
fn random_action(board) {
|
||||
let symb = rand_symb();
|
||||
let pos = rand_int(0, 10);
|
||||
let action = Action(symb, pos);
|
||||
|
||||
while !board.can_play(action) {
|
||||
let symb = rand_symb();
|
||||
let pos = rand_int(0, 10);
|
||||
action = Action(symb, pos);
|
||||
}
|
||||
|
||||
return action
|
||||
}
|
||||
|
||||
|
||||
/// Returns an array of (idx, f32) for each empty slot in the board.
|
||||
/// - idx is the index of this slot
|
||||
/// - f32 is the "influence of" this slot
|
||||
fn compute_influence(board) {
|
||||
// Fill all empty slots with fives and compute starting value
|
||||
let filled = board;
|
||||
for i in filled.free_spots_idx() {
|
||||
filled[i] = 5;
|
||||
}
|
||||
|
||||
// Compute the value of the filled board
|
||||
let base = filled.evaluate();
|
||||
|
||||
// Exit early if the board is invalid.
|
||||
// This is usually caused by zero-division.
|
||||
if (base == ()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Increase each slot's value by 1
|
||||
// and record the effect on the expression's total value.
|
||||
//
|
||||
// `influence` is an array of (slot_idx, value)
|
||||
let influence = [];
|
||||
for i in 0..board.size() {
|
||||
let slot = board[i];
|
||||
|
||||
// Ignore slots that are not empty
|
||||
if slot != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Don't assign directly to `filled`,
|
||||
// we want to keep it full of fives.
|
||||
// Assigning to `b` make a copy of the board.
|
||||
let b = filled;
|
||||
b[i] = 6;
|
||||
|
||||
influence.push([i, b.evaluate() - base]);
|
||||
}
|
||||
|
||||
|
||||
// Sort by increasing absolute score
|
||||
influence.sort(|a, b| {
|
||||
let a_abs = a[1].abs();
|
||||
let b_abs = b[1].abs();
|
||||
|
||||
// Returns...
|
||||
// 1 if positive (a_abs > b_abs),
|
||||
// -1 if negative,
|
||||
// 0 if equal
|
||||
return sign(a_abs - b_abs);
|
||||
});
|
||||
|
||||
return influence;
|
||||
}
|
||||
|
||||
fn place_number(board, minimize) {
|
||||
let numbers = [0,1,2,3,4,5,6,7,8,9];
|
||||
let available_numbers = numbers.retain(|x| board.contains(x));
|
||||
|
||||
let influence = compute_influence(board);
|
||||
|
||||
// Stupid edge cases, fall back to random
|
||||
if influence.len() == 0 || available_numbers.len() == 0 {
|
||||
return random_action(board);
|
||||
}
|
||||
|
||||
|
||||
// Get the most influential position
|
||||
let pos = influence[-1][0];
|
||||
let val = influence[-1][1];
|
||||
|
||||
// Pick the number we should use,
|
||||
// This is always either the largest
|
||||
// or the smallest number available to us.
|
||||
let symbol = 0;
|
||||
if minimize {
|
||||
if val > 0 {
|
||||
symbol = available_numbers[0];
|
||||
} else {
|
||||
symbol = available_numbers[-1];
|
||||
}
|
||||
} else {
|
||||
if val > 0 {
|
||||
symbol = available_numbers[-1];
|
||||
} else {
|
||||
symbol = available_numbers[0];
|
||||
}
|
||||
}
|
||||
|
||||
return Action(symbol, pos);
|
||||
}
|
||||
|
||||
|
||||
fn op_value(board) {
|
||||
print(board);
|
||||
let actions = [];
|
||||
for o in ["+", "-", "*", "/"] {
|
||||
if board.contains(o) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for p in 0..=10 {
|
||||
let action = Action(o, p);
|
||||
if board.can_play(action) {
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No other operators can be placed, return value of fives
|
||||
if actions.is_empty() {
|
||||
let filled = board;
|
||||
for i in filled.free_spots_idx() {
|
||||
filled[i] = 5;
|
||||
}
|
||||
let v = filled.evaluate();
|
||||
if v == () {
|
||||
return ();
|
||||
} else {
|
||||
return [v, v];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let max = ();
|
||||
let min = ();
|
||||
for a in actions {
|
||||
let tmp = board;
|
||||
tmp.play(a);
|
||||
|
||||
let vals = op_value(tmp);
|
||||
if vals != () {
|
||||
for v in vals {
|
||||
if max == () || min == () {
|
||||
max = v;
|
||||
min = v;
|
||||
}
|
||||
|
||||
if v > max {
|
||||
max = v;
|
||||
} else if v < min {
|
||||
min = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if min == () || max == () {
|
||||
return ();
|
||||
}
|
||||
|
||||
return [min, max];
|
||||
}
|
||||
|
||||
fn place_op(board, minimize) {
|
||||
let ops = ["+", "-", "*", "/"];
|
||||
let available_ops = ops.retain(|x| board.contains(x));
|
||||
|
||||
// Performance optimization if board is empty.
|
||||
// This is the move we would pick, hard-coded.
|
||||
if available_ops.len() == 4 {
|
||||
if minimize {
|
||||
let act = Action("+", 3);
|
||||
if board.can_play(act) {return act}
|
||||
} else {
|
||||
let act = Action("/", 9);
|
||||
if board.can_play(act) {return act}
|
||||
}
|
||||
}
|
||||
|
||||
// All possible operator actions
|
||||
let actions = [];
|
||||
for o in ["+", "-", "*", "/"] {
|
||||
for p in 0..=10 {
|
||||
let action = Action(o, p);
|
||||
if board.can_play(action) {
|
||||
let tmp = board;
|
||||
tmp.play(action);
|
||||
let v = op_value(tmp);
|
||||
if v != () {
|
||||
actions.push([action, v]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if actions.is_empty() {
|
||||
return ();
|
||||
}
|
||||
|
||||
let action = ();
|
||||
if minimize {
|
||||
// Sort by increasing minimum score
|
||||
actions.sort(|a, b| sign(a[1][0] - b[1][0]));
|
||||
action = actions[0][0];
|
||||
} else {
|
||||
// Sort by increasing maximum score
|
||||
actions.sort(|a, b| sign(a[1][1] - b[1][1]));
|
||||
action = actions[-1][0];
|
||||
}
|
||||
|
||||
debug(action);
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
|
||||
// Main step function (shared between min and max)
|
||||
fn greed_step(board, minimize) {
|
||||
let action = place_op(board, minimize);
|
||||
if action == () {
|
||||
action = place_number(board, minimize);
|
||||
}
|
||||
|
||||
if board.can_play(action) {
|
||||
return action;
|
||||
}
|
||||
|
||||
// Prevent invalid moves, random fallback
|
||||
return random_action(board);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Minimizer step
|
||||
fn step_min(board) {
|
||||
greed_step(board, true)
|
||||
}
|
||||
|
||||
// Maximizer step
|
||||
fn step_max(board) {
|
||||
greed_step(board, false)
|
||||
}
|
||||
10
docker-compose.yml
Normal file
10
docker-compose.yml
Normal file
@@ -0,0 +1,10 @@
|
||||
services:
|
||||
webui:
|
||||
image: minimax
|
||||
ports:
|
||||
- "4000:3000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
env_file:
|
||||
- .env
|
||||
restart: unless-stopped
|
||||
@@ -80,7 +80,6 @@ pub struct RhaiAgent<R: Rng + 'static> {
|
||||
|
||||
engine: Engine,
|
||||
script: AST,
|
||||
scope: Scope<'static>,
|
||||
print_callback: Arc<dyn Fn(&str) + 'static>,
|
||||
}
|
||||
|
||||
@@ -118,7 +117,6 @@ impl<R: Rng + 'static> RhaiAgent<R> {
|
||||
|
||||
// Do not use FULL, rand_* functions are not pure
|
||||
engine.set_optimization_level(OptimizationLevel::Simple);
|
||||
|
||||
engine.disable_symbol("eval");
|
||||
engine.set_max_expr_depths(100, 100);
|
||||
engine.set_max_strings_interned(1024);
|
||||
@@ -201,13 +199,11 @@ impl<R: Rng + 'static> RhaiAgent<R> {
|
||||
};
|
||||
|
||||
let script = engine.compile(script)?;
|
||||
let scope = Scope::new(); // Not used
|
||||
|
||||
Ok(Self {
|
||||
rng,
|
||||
engine,
|
||||
script,
|
||||
scope,
|
||||
print_callback,
|
||||
})
|
||||
}
|
||||
@@ -227,7 +223,7 @@ impl<R: Rng + 'static> Agent for RhaiAgent<R> {
|
||||
fn step_min(&mut self, board: &Board) -> Result<PlayerAction, Self::ErrorType> {
|
||||
let res = self.engine.call_fn_with_options::<PlayerAction>(
|
||||
CallFnOptions::new().eval_ast(false),
|
||||
&mut self.scope,
|
||||
&mut Scope::new(),
|
||||
&self.script,
|
||||
"step_min",
|
||||
(board.clone(),),
|
||||
@@ -242,7 +238,7 @@ impl<R: Rng + 'static> Agent for RhaiAgent<R> {
|
||||
fn step_max(&mut self, board: &Board) -> Result<PlayerAction, Self::ErrorType> {
|
||||
let res = self.engine.call_fn_with_options::<PlayerAction>(
|
||||
CallFnOptions::new().eval_ast(false),
|
||||
&mut self.scope,
|
||||
&mut Scope::new(),
|
||||
&self.script,
|
||||
"step_max",
|
||||
(board.clone(),),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
mod ansi;
|
||||
mod gamestate;
|
||||
mod gamestatehuman;
|
||||
mod minmaxgame;
|
||||
mod minmaxgamehuman;
|
||||
mod terminput;
|
||||
|
||||
#[global_allocator]
|
||||
|
||||
@@ -9,7 +9,7 @@ use wasm_bindgen::prelude::*;
|
||||
use crate::{ansi, terminput::TermInput};
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct GameStateHuman {
|
||||
pub struct MinMaxGameHuman {
|
||||
/// Red player
|
||||
human: TermInput,
|
||||
|
||||
@@ -26,7 +26,7 @@ pub struct GameStateHuman {
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl GameStateHuman {
|
||||
impl MinMaxGameHuman {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(
|
||||
max_script: &str,
|
||||
@@ -34,7 +34,7 @@ impl GameStateHuman {
|
||||
max_debug_callback: js_sys::Function,
|
||||
|
||||
game_state_callback: js_sys::Function,
|
||||
) -> Result<GameStateHuman, String> {
|
||||
) -> Result<MinMaxGameHuman, String> {
|
||||
Self::new_native(
|
||||
max_script,
|
||||
move |s| {
|
||||
55
webui/src/app/api/get-script/route.ts
Normal file
55
webui/src/app/api/get-script/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readFile } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import { existsSync } from "fs";
|
||||
import { CONFIG } from "@/lib/config";
|
||||
|
||||
// Force dynamic rendering for this API route
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = request.nextUrl;
|
||||
const name = searchParams.get("name");
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json(
|
||||
{ error: "Script name is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate filename (same validation as save)
|
||||
if (!CONFIG.FILENAME_REGEX.test(name)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid script name" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const saveDir = CONFIG.SAVE_DIRECTORY;
|
||||
const filename = `${name}.rhai`;
|
||||
const filepath = join(saveDir, filename);
|
||||
|
||||
if (!existsSync(filepath)) {
|
||||
return NextResponse.json(
|
||||
{ error: `Script "${name}" not found` },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
let content = await readFile(filepath, "utf8");
|
||||
|
||||
return NextResponse.json({
|
||||
name,
|
||||
filename,
|
||||
content,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Get script error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to read script" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
40
webui/src/app/api/list-scripts/route.ts
Normal file
40
webui/src/app/api/list-scripts/route.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { readdir } from "fs/promises";
|
||||
import { existsSync } from "fs";
|
||||
import { CONFIG } from "@/lib/config";
|
||||
|
||||
// Force dynamic rendering for this API route
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const headers = {
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
|
||||
Pragma: "no-cache",
|
||||
Expires: "0",
|
||||
};
|
||||
|
||||
export async function GET(_request: NextRequest) {
|
||||
try {
|
||||
const saveDir = CONFIG.SAVE_DIRECTORY;
|
||||
|
||||
// If save directory doesn't exist, return empty array
|
||||
if (!existsSync(saveDir)) {
|
||||
return NextResponse.json({ scripts: [] }, { headers });
|
||||
}
|
||||
|
||||
// Read directory and filter for .rhai files
|
||||
const files = await readdir(saveDir);
|
||||
|
||||
const scripts = files
|
||||
.filter((file) => file.endsWith(".rhai"))
|
||||
.map((file) => file.replace(".rhai", ""))
|
||||
.sort(); // Sort alphabetically
|
||||
|
||||
return NextResponse.json({ scripts }, { headers });
|
||||
} catch (error) {
|
||||
console.error("List scripts error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to list scripts" },
|
||||
{ status: 500, headers }
|
||||
);
|
||||
}
|
||||
}
|
||||
92
webui/src/app/api/save-script/route.ts
Normal file
92
webui/src/app/api/save-script/route.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import { join } from "path";
|
||||
import { existsSync } from "fs";
|
||||
import { CONFIG } from "@/lib/config";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Check if saving is enabled
|
||||
if (!CONFIG.ENABLE_SAVE) {
|
||||
return NextResponse.json(
|
||||
{ error: "Script saving is disabled" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const { name, content, secret } = await request.json();
|
||||
|
||||
if (secret !== CONFIG.SAVE_SECRET) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid secret" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!name || !content) {
|
||||
return NextResponse.json(
|
||||
{ error: "Name and content are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (name.length > CONFIG.MAX_FILENAME_LENGTH) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `Filename must be ${CONFIG.MAX_FILENAME_LENGTH} characters or less`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (content.length > CONFIG.MAX_FILE_SIZE) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `File is too large`,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!CONFIG.FILENAME_REGEX.test(name)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Filename can only contain alphanumerics, underscores, spaces, and hyphens",
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Ensure save directory exists
|
||||
const saveDir = CONFIG.SAVE_DIRECTORY;
|
||||
if (!existsSync(saveDir)) {
|
||||
await mkdir(saveDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Check if file already exists
|
||||
const filename = `${name}.rhai`;
|
||||
const filepath = join(saveDir, filename);
|
||||
|
||||
if (existsSync(filepath)) {
|
||||
return NextResponse.json(
|
||||
{ error: `A script named "${name}" already exists` },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Save the file
|
||||
await writeFile(filepath, content, "utf8");
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Script saved as ${filename}`,
|
||||
filename,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Save script error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to save script" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -128,7 +128,8 @@ export const Editor = forwardRef<any, EditorProps>(function Editor(
|
||||
editorRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []); // DO NOT FILL ARRAY
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []); // DO NOT FILL ARRAY - intentionally empty to prevent re-initialization
|
||||
|
||||
// Update font size when it changes
|
||||
useEffect(() => {
|
||||
|
||||
@@ -42,37 +42,40 @@ fn step_max(board) {
|
||||
const AGENTS = {
|
||||
// special-cased below
|
||||
Self: undefined,
|
||||
|
||||
Random: `fn random_action(board) {
|
||||
let symb = rand_symb();
|
||||
let pos = rand_int(0, 10);
|
||||
let action = Action(symb, pos);
|
||||
|
||||
while !board.can_play(action) {
|
||||
let symb = rand_symb();
|
||||
let pos = rand_int(0, 10);
|
||||
action = Action(symb, pos);
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
||||
fn step_min(board) {
|
||||
return random_action(board);
|
||||
}
|
||||
|
||||
fn step_max(board) {
|
||||
return random_action(board);
|
||||
}`,
|
||||
};
|
||||
|
||||
export default function Playground() {
|
||||
const [isScriptRunning, setIsScriptRunning] = useState(false);
|
||||
const [isEditorReady, setIsEditorReady] = useState(false);
|
||||
const [fontSize, setFontSize] = useState(14);
|
||||
const [bulkRounds, setBulkRounds] = useState(1000);
|
||||
const [selectedAgent, setSelectedAgent] = useState("Random");
|
||||
const [fontSize, setFontSize] = useState(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
const saved = localStorage.getItem("playground-fontSize");
|
||||
return saved ? parseInt(saved, 10) : 14;
|
||||
}
|
||||
return 14;
|
||||
});
|
||||
const [bulkRounds, setBulkRounds] = useState(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
const saved = localStorage.getItem("playground-bulkRounds");
|
||||
return saved ? parseInt(saved, 10) : 1000;
|
||||
}
|
||||
return 1000;
|
||||
});
|
||||
const [selectedAgent, setSelectedAgent] = useState(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
const saved = localStorage.getItem("playground-selectedAgent");
|
||||
return saved || "Self";
|
||||
}
|
||||
return "Self";
|
||||
});
|
||||
const [isHelpOpen, setIsHelpOpen] = useState(false);
|
||||
const [scriptName, setScriptName] = useState("");
|
||||
const [saveSecret, setSaveSecret] = useState("");
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [availableAgents, setAvailableAgents] = useState<string[]>([]);
|
||||
const [savedScripts, setSavedScripts] = useState<Record<string, string>>(
|
||||
{}
|
||||
);
|
||||
|
||||
const editorRef = useRef<any>(null);
|
||||
const resultRef = useRef<HTMLTextAreaElement>(null);
|
||||
@@ -81,6 +84,86 @@ export default function Playground() {
|
||||
const runDisabled = isScriptRunning || !isEditorReady;
|
||||
const stopDisabled = !isScriptRunning;
|
||||
|
||||
// Fetch saved scripts and update available agents
|
||||
const loadSavedScripts = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch("/api/list-scripts");
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
const scripts = data.scripts || [];
|
||||
const scriptContents: Record<string, string> = {};
|
||||
|
||||
// Fetch content for each saved script
|
||||
await Promise.all(
|
||||
scripts.map(async (scriptName: string) => {
|
||||
try {
|
||||
const scriptResponse = await fetch(
|
||||
`/api/get-script?name=${encodeURIComponent(
|
||||
scriptName
|
||||
)}`
|
||||
);
|
||||
const scriptData = await scriptResponse.json();
|
||||
|
||||
if (scriptResponse.ok) {
|
||||
scriptContents[scriptName] = scriptData.content;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Failed to load script ${scriptName}:`,
|
||||
error
|
||||
);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
setSavedScripts(scriptContents);
|
||||
|
||||
// Combine hardcoded agents with saved scripts, ensuring Self and Random are first
|
||||
const combinedAgents = [
|
||||
"Self",
|
||||
...Object.keys(AGENTS).filter((key) => key !== "Self"),
|
||||
...scripts,
|
||||
];
|
||||
|
||||
setAvailableAgents(combinedAgents);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load saved scripts:", error);
|
||||
// Fallback to hardcoded agents only
|
||||
setAvailableAgents(Object.keys(AGENTS));
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Load saved scripts on component mount
|
||||
useEffect(() => {
|
||||
loadSavedScripts();
|
||||
}, [loadSavedScripts]);
|
||||
|
||||
// Save font size to localStorage
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("playground-fontSize", fontSize.toString());
|
||||
}
|
||||
}, [fontSize]);
|
||||
|
||||
// Save bulk rounds to localStorage
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem(
|
||||
"playground-bulkRounds",
|
||||
bulkRounds.toString()
|
||||
);
|
||||
}
|
||||
}, [bulkRounds]);
|
||||
|
||||
// Save selected agent to localStorage
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("playground-selectedAgent", selectedAgent);
|
||||
}
|
||||
}, [selectedAgent]);
|
||||
|
||||
const runHuman = useCallback(async () => {
|
||||
if (resultRef.current) {
|
||||
resultRef.current.value = "";
|
||||
@@ -141,11 +224,15 @@ export default function Playground() {
|
||||
terminalRef.current?.clear();
|
||||
terminalRef.current?.focus();
|
||||
|
||||
const agentCode = AGENTS[selectedAgent as keyof typeof AGENTS];
|
||||
// Get script content from either hardcoded agents or saved scripts
|
||||
const hardcodedAgent = AGENTS[selectedAgent as keyof typeof AGENTS];
|
||||
const savedScript = savedScripts[selectedAgent];
|
||||
|
||||
const agentScript = hardcodedAgent || savedScript;
|
||||
const blueScript =
|
||||
agentCode || (editorRef.current?.getValue() ?? "");
|
||||
agentScript || (editorRef.current?.getValue() ?? "");
|
||||
const redScript = editorRef.current?.getValue() ?? "";
|
||||
const opponentName = agentCode ? selectedAgent : "script";
|
||||
const opponentName = agentScript ? selectedAgent : "script";
|
||||
|
||||
await startScriptBulk(
|
||||
redScript,
|
||||
@@ -182,12 +269,92 @@ export default function Playground() {
|
||||
}
|
||||
|
||||
setIsScriptRunning(false);
|
||||
}, [runDisabled, bulkRounds, selectedAgent]);
|
||||
}, [runDisabled, bulkRounds, selectedAgent, savedScripts]);
|
||||
|
||||
const stopScriptHandler = useCallback(() => {
|
||||
stopScript();
|
||||
}, []);
|
||||
|
||||
const saveScript = useCallback(async () => {
|
||||
if (!scriptName.trim()) {
|
||||
alert("Please enter a script name");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!saveSecret.trim()) {
|
||||
alert("Please enter a secret");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!editorRef.current) {
|
||||
alert("No script content to save");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/save-script", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: scriptName.trim(),
|
||||
content: editorRef.current.getValue(),
|
||||
secret: saveSecret.trim(),
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
alert(result.message);
|
||||
setScriptName("");
|
||||
// Reload saved scripts to include the new one
|
||||
loadSavedScripts();
|
||||
} else {
|
||||
alert(result.error || "Failed to save script");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Save error:", error);
|
||||
alert("Network error: Failed to save script");
|
||||
}
|
||||
|
||||
setIsSaving(false);
|
||||
}, [scriptName, saveSecret, loadSavedScripts]);
|
||||
|
||||
const copyScriptToEditor = useCallback(() => {
|
||||
if (!selectedAgent || selectedAgent === "Self") {
|
||||
alert("Please select a script to copy to the editor");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the script content
|
||||
const hardcodedAgent = AGENTS[selectedAgent as keyof typeof AGENTS];
|
||||
const savedScript = savedScripts[selectedAgent];
|
||||
const scriptContent = hardcodedAgent || savedScript;
|
||||
|
||||
if (!scriptContent) {
|
||||
alert("No script content available for the selected agent");
|
||||
return;
|
||||
}
|
||||
|
||||
if (scriptContent.trim().startsWith("// SECRET")) {
|
||||
alert("This script is hidden :)");
|
||||
return;
|
||||
}
|
||||
|
||||
// Warn user about losing current content
|
||||
const confirmed = confirm(
|
||||
`This will replace your current script with "${selectedAgent}". Your current work will be lost. Continue?`
|
||||
);
|
||||
|
||||
if (confirmed && editorRef.current) {
|
||||
editorRef.current.setValue(scriptContent);
|
||||
}
|
||||
}, [selectedAgent, savedScripts]);
|
||||
|
||||
return (
|
||||
<div className={styles.playgroundRoot}>
|
||||
<header className={styles.header}>
|
||||
@@ -250,12 +417,69 @@ export default function Playground() {
|
||||
<div className={styles.configField}>
|
||||
<label>Bulk opponent</label>
|
||||
<AgentSelector
|
||||
agents={Object.keys(AGENTS)}
|
||||
agents={availableAgents}
|
||||
selectedAgent={selectedAgent}
|
||||
onSelect={setSelectedAgent}
|
||||
placeholder="Select an agent..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.configField}>
|
||||
<Button
|
||||
variant="info"
|
||||
onClick={copyScriptToEditor}
|
||||
disabled={
|
||||
!selectedAgent ||
|
||||
selectedAgent === "Self"
|
||||
}
|
||||
>
|
||||
Copy to Editor
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className={styles.saveSection}>
|
||||
<div className={styles.configField}>
|
||||
<label>Script name</label>
|
||||
<input
|
||||
type="text"
|
||||
className={styles.saveInput}
|
||||
placeholder="Enter script name..."
|
||||
value={scriptName}
|
||||
onChange={(e) =>
|
||||
setScriptName(
|
||||
e.target.value
|
||||
)
|
||||
}
|
||||
maxLength={32}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.configField}>
|
||||
<label>Secret</label>
|
||||
<input
|
||||
type="password"
|
||||
className={styles.saveInput}
|
||||
placeholder="Enter secret..."
|
||||
value={saveSecret}
|
||||
onChange={(e) =>
|
||||
setSaveSecret(
|
||||
e.target.value
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.configField}>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={saveScript}
|
||||
loading={isSaving}
|
||||
disabled={isSaving}
|
||||
>
|
||||
Save Script
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
9
webui/src/lib/config.ts
Normal file
9
webui/src/lib/config.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export const CONFIG = {
|
||||
ENABLE_SAVE: process.env.ENABLE_SAVE === "true" || true,
|
||||
SAVE_SECRET: process.env.SAVE_SECRET || "save",
|
||||
|
||||
SAVE_DIRECTORY: process.env.SAVE_DIRECTORY || "./data/scripts",
|
||||
MAX_FILENAME_LENGTH: parseInt(process.env.MAX_FILENAME_LENGTH || "32"),
|
||||
MAX_FILE_SIZE: parseInt(process.env.MAX_FILE_SIZE || "1048576"),
|
||||
FILENAME_REGEX: /^[a-zA-Z0-9_\s-]+$/,
|
||||
} as const;
|
||||
@@ -1,8 +1,8 @@
|
||||
import init, { GameState, GameStateHuman } from "../wasm/runner";
|
||||
import init, { MinMaxGameHuman } from "../wasm/runner";
|
||||
|
||||
let wasmReady = false;
|
||||
let wasmInitPromise: Promise<void> | null = null;
|
||||
let currentGame: GameStateHuman | null = null;
|
||||
let currentGame: MinMaxGameHuman | null = null;
|
||||
|
||||
async function initWasm(): Promise<void> {
|
||||
if (wasmReady) return;
|
||||
@@ -24,14 +24,18 @@ self.onmessage = async (event) => {
|
||||
|
||||
if (type === "data") {
|
||||
if (currentGame !== null) {
|
||||
currentGame.take_input(event_data.data);
|
||||
try {
|
||||
currentGame.take_input(event_data.data);
|
||||
|
||||
if (currentGame.is_error()) {
|
||||
currentGame = null;
|
||||
self.postMessage({ type: "complete" });
|
||||
} else if (currentGame.is_done()) {
|
||||
currentGame = null;
|
||||
self.postMessage({ type: "complete" });
|
||||
if (currentGame.is_error()) {
|
||||
currentGame = null;
|
||||
self.postMessage({ type: "complete" });
|
||||
} else if (currentGame.is_done()) {
|
||||
currentGame = null;
|
||||
self.postMessage({ type: "complete" });
|
||||
}
|
||||
} catch (error) {
|
||||
self.postMessage({ type: "error", error: String(error) });
|
||||
}
|
||||
}
|
||||
} else if (type === "init") {
|
||||
@@ -53,7 +57,7 @@ self.onmessage = async (event) => {
|
||||
self.postMessage({ type: "terminal", line });
|
||||
};
|
||||
|
||||
currentGame = new GameStateHuman(
|
||||
currentGame = new MinMaxGameHuman(
|
||||
event_data.script,
|
||||
appendOutput,
|
||||
appendOutput,
|
||||
|
||||
@@ -117,6 +117,31 @@
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.saveInput {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
background: #3c3c3c;
|
||||
color: #e0e0e0;
|
||||
border: 1px solid #555;
|
||||
border-radius: 3px;
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.saveInput:focus {
|
||||
border-color: #007acc;
|
||||
box-shadow: 0 0 3px rgba(0, 122, 204, 0.3);
|
||||
}
|
||||
|
||||
.saveInput::placeholder {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.saveSection {
|
||||
margin-top: 24px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid #444;
|
||||
}
|
||||
|
||||
.helpPanel {
|
||||
padding: 16px;
|
||||
|
||||
Reference in New Issue
Block a user