mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
694231f8c1 |
No files matched your search
@@ -185,26 +185,12 @@ function files(req: IncomingMessage, res: ServerResponse, url: URL) {
|
||||
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
|
||||
}
|
||||
|
||||
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
|
||||
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
|
||||
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
|
||||
* line with no out, err or exit. */
|
||||
const KEEPALIVE_MS = 30_000
|
||||
function streamOpen(res: ServerResponse) {
|
||||
res.writeHead(200, { "content-type": "application/x-ndjson" })
|
||||
res.flushHeaders()
|
||||
const beat = setInterval(() => res.write("{}\n"), KEEPALIVE_MS)
|
||||
const stop = () => clearInterval(beat)
|
||||
res.on("finish", stop)
|
||||
res.on("close", stop)
|
||||
}
|
||||
|
||||
async function run(req: IncomingMessage, res: ServerResponse) {
|
||||
const { args, cwd } = JSON.parse((await body(req)).toString() || "{}") as { args?: unknown; cwd?: string }
|
||||
if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) return json(res, { error: "args must be an array of strings: raea's own arguments" }, 400)
|
||||
const dir = resolve(cwd ?? ".")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
streamOpen(res)
|
||||
res.writeHead(200, { "content-type": "application/x-ndjson" })
|
||||
const child = spawn(RAEA, args, { cwd: dir, env: childEnv(), stdio: ["ignore", "pipe", "pipe"] })
|
||||
const line = (v: unknown) => res.write(JSON.stringify(v) + "\n")
|
||||
child.stdout.setEncoding("utf8").on("data", (out: string) => line({ out }))
|
||||
@@ -216,8 +202,6 @@ async function run(req: IncomingMessage, res: ServerResponse) {
|
||||
}
|
||||
|
||||
const SHELL_DEFAULT_MS = 600_000
|
||||
/** an ACP agent silent both ways this long is ended (the /v1/acp socket below) */
|
||||
const IDLE_AGENT_MS = Number(process.env.RAEA_CLOUD_IDLE_AGENT_MS ?? 45 * 60_000)
|
||||
const SHELL_MAX_MS = 3_600_000
|
||||
|
||||
async function shell(req: IncomingMessage, res: ServerResponse) {
|
||||
@@ -226,7 +210,7 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
|
||||
const ms = typeof timeout_ms === "number" && timeout_ms > 0 ? Math.min(timeout_ms, SHELL_MAX_MS) : SHELL_DEFAULT_MS
|
||||
const dir = resolve(cwd ?? ".")
|
||||
mkdirSync(dir, { recursive: true })
|
||||
streamOpen(res)
|
||||
res.writeHead(200, { "content-type": "application/x-ndjson" })
|
||||
// the shell on any OS: bash and a process group here, RAEA_CLOUD_BASH and taskkill on Windows (shell-os.ts)
|
||||
const { bash, groupOpts, shellEnv, stopTree } = await import("./shell-os.ts")
|
||||
// in a process group of its own, so a timeout or a caller leaving stops what the command started too
|
||||
@@ -386,19 +370,8 @@ server.on("upgrade", (req, socket, head) => {
|
||||
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
|
||||
// never sees it
|
||||
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
|
||||
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
|
||||
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
|
||||
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
|
||||
// on raea-3 for 2 h, counted as running, so no box update could go on)
|
||||
let heard = Date.now()
|
||||
const idle = setInterval(() => {
|
||||
if (Date.now() - heard < IDLE_AGENT_MS) return
|
||||
process.stderr.write(`raea-cloud: ${agent.id} said nothing and was sent nothing for ${Math.round(IDLE_AGENT_MS / 60_000)} min: ended\n`)
|
||||
ws.terminate()
|
||||
stopAll()
|
||||
}, Math.min(60_000, IDLE_AGENT_MS / 2))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
|
||||
child.on("exit", () => (running.delete(child), clearInterval(idle)))
|
||||
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat)))
|
||||
child.on("exit", () => running.delete(child))
|
||||
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
|
||||
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
|
||||
child.stderr.setEncoding("utf8").on("data", (c: string) => {
|
||||
@@ -408,11 +381,10 @@ server.on("upgrade", (req, socket, head) => {
|
||||
let buf = ""
|
||||
// ACP messages are newline-delimited JSON: split on \n only
|
||||
child.stdout.setEncoding("utf8").on("data", (c: string) => {
|
||||
heard = Date.now()
|
||||
buf += c
|
||||
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
|
||||
})
|
||||
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
|
||||
ws.on("message", (m) => child.stdin.write(m.toString() + "\n"))
|
||||
ws.on("close", stopAll)
|
||||
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
|
||||
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createRoot } from "react-dom/client";
|
||||
import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
|
||||
import { Input } from "@raea/playable/host/input";
|
||||
import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect";
|
||||
import { patchShaderModules } from "./wgsl";
|
||||
|
||||
/** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */
|
||||
export interface RaeaEngine {
|
||||
@@ -31,6 +32,8 @@ const loaded = new WeakMap<() => Promise<RaeaWebModule>, Promise<RaeaWebModule>>
|
||||
export function loadRaea(load: () => Promise<RaeaWebModule>): Promise<RaeaWebModule> {
|
||||
let p = loaded.get(load);
|
||||
if (!p) {
|
||||
// Safari reads WGSL to the letter: Bevy's shaders are made to its rules first (wgsl.ts)
|
||||
patchShaderModules();
|
||||
p = load().then(async (m) => (await m.default(), m));
|
||||
loaded.set(load, p);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Safari's WGSL (WebKit) holds to the spec: a `let` can't hold a texture or a sampler (they aren't constructible
|
||||
// types), while Chrome's Tint lets it through. Bevy's PBR shaders do it (bevy_pbr pbr_fragment.wesl,
|
||||
// `let texture = pbr_bindings::base_color_texture;`), in every mesh with UVs, so raea-web drew nothing in Safari
|
||||
// ("Fragment module is invalid", 12-02). Each such `let` is inlined here before the module is made: its name is replaced
|
||||
// by what it held (a global binding, or an index into a binding array) through the rest of its block.
|
||||
|
||||
/** the global bindings of handle types (textures, samplers, arrays of either) a shader declares */
|
||||
function handles(code: string): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const m of code.matchAll(/\bvar\s+(\w+)\s*:\s*(?:texture_|sampler|binding_array\s*<\s*(?:texture_|sampler))/g)) out.add(m[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** where the block holding `at` closes (the index of its `}`), or the end */
|
||||
function blockEnd(code: string, at: number): number {
|
||||
let depth = 0;
|
||||
for (let i = at; i < code.length; i++) {
|
||||
const c = code[i];
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
if (depth === 0) return i;
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
return code.length;
|
||||
}
|
||||
|
||||
/** The shader with every `let` that holds a texture or sampler inlined; the same text when there's none. */
|
||||
export function inlineHandleLets(code: string): string {
|
||||
const globals = handles(code);
|
||||
if (!globals.size) return code;
|
||||
const decl = /\blet\s+(\w+)\s*(?::\s*[^=]+)?=\s*([^;]+);/g;
|
||||
for (let guard = 0; guard < 10_000; guard++) {
|
||||
decl.lastIndex = 0;
|
||||
let m: RegExpExecArray | null, found: RegExpExecArray | null = null;
|
||||
while ((m = decl.exec(code))) {
|
||||
const root = /^\s*(?:\w+::)*(\w+)/.exec(m[2])?.[1];
|
||||
if (root && globals.has(root)) { found = m; break; }
|
||||
}
|
||||
if (!found) return code;
|
||||
const [whole, name, held] = found;
|
||||
const from = found.index + whole.length;
|
||||
const end = blockEnd(code, from);
|
||||
const value = held.trim().replace(/\s+/g, " ");
|
||||
const rest = code.slice(from, end).replace(new RegExp(`\\b${name}\\b`, "g"), () => value);
|
||||
code = code.slice(0, found.index) + rest + code.slice(end);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
let patched = false;
|
||||
/** Makes every WebGPU shader module from its inlined text (once per page; nothing where there's no WebGPU). */
|
||||
export function patchShaderModules() {
|
||||
const G = (globalThis as { GPUDevice?: { prototype: { createShaderModule(d: { code: string }): unknown } } }).GPUDevice;
|
||||
if (patched || !G) return;
|
||||
patched = true;
|
||||
const make = G.prototype.createShaderModule;
|
||||
G.prototype.createShaderModule = function (d: { code: string }) {
|
||||
return make.call(this, typeof d?.code === "string" ? { ...d, code: inlineHandleLets(d.code) } : d);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// wgsl.ts: a `let` holding a texture or sampler is inlined for Safari; everything else is left as it was
|
||||
import { expect, test } from "bun:test";
|
||||
import { inlineHandleLets } from "../../src/wgsl";
|
||||
|
||||
const head = `@group(2) @binding(1) var base_color_texture: texture_2d<f32>;
|
||||
@group(2) @binding(2) var base_color_sampler: sampler;
|
||||
@group(2) @binding(3) var bindless_textures_2d: binding_array<texture_2d<f32>, 16>;
|
||||
`;
|
||||
|
||||
test("a texture and a sampler held by lets are used directly, in their block only", () => {
|
||||
const code = `${head}fn f(uv: vec2<f32>) -> vec4<f32> {
|
||||
var c = vec4(1.0);
|
||||
if (true) {
|
||||
let texture = base_color_texture;
|
||||
let sampler_ = base_color_sampler;
|
||||
let coords = uv;
|
||||
c *= textureSampleBias(texture, sampler_, coords, 0.0);
|
||||
}
|
||||
let texture_scale = 2.0;
|
||||
return c * texture_scale;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).not.toContain("let texture =");
|
||||
expect(out).not.toContain("let sampler_ =");
|
||||
expect(out).toContain("textureSampleBias(base_color_texture, base_color_sampler, coords, 0.0)");
|
||||
expect(out).toContain("let coords = uv;");
|
||||
expect(out).toContain("let texture_scale = 2.0;");
|
||||
expect(out).toContain("return c * texture_scale;");
|
||||
});
|
||||
|
||||
test("a binding array's element, over lines, and the same name again in the next block", () => {
|
||||
const code = `${head}fn g(i: u32, uv: vec2<f32>) -> f32 {
|
||||
var a = 0.0;
|
||||
{
|
||||
let texture = bindless_textures_2d[
|
||||
i
|
||||
];
|
||||
a += textureSample(texture, base_color_sampler, uv).r;
|
||||
}
|
||||
{
|
||||
let texture = base_color_texture;
|
||||
a += textureSample(texture, base_color_sampler, uv).g;
|
||||
}
|
||||
return a;
|
||||
}`;
|
||||
const out = inlineHandleLets(code);
|
||||
expect(out).toContain("textureSample(bindless_textures_2d[ i ], base_color_sampler, uv).r");
|
||||
expect(out).toContain("textureSample(base_color_texture, base_color_sampler, uv).g");
|
||||
expect(out).not.toMatch(/let texture\b/);
|
||||
});
|
||||
|
||||
test("a module path (naga_oil's pbr_bindings::) is a binding all the same; a shader with no handles is untouched", () => {
|
||||
expect(inlineHandleLets(`${head}fn h() { let t = pbr_bindings::base_color_texture; textureDimensions(t); }`)).toContain("textureDimensions(pbr_bindings::base_color_texture)");
|
||||
const plain = "fn k() -> f32 { let x = 1.0; return x; }";
|
||||
expect(inlineHandleLets(plain)).toBe(plain);
|
||||
});
|
||||
Reference in new issue
Block a user