Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(editor): three things a driver hit while building a game

esenginef5d6f71079c2
diff --git a/desktop/electron/projectFs.ts b/desktop/electron/projectFs.ts
index 0ec896da8..d8aa0347a 100644
--- a/desktop/electron/projectFs.ts
+++ b/desktop/electron/projectFs.ts
@@ -209,9 +209,27 @@ export interface FileMatch {
* in a hundred lines at a time, which is what a 50k-line `.d.ts` turns into: the
* question was "what is on `Input`", and the cost was most of a context window.
*
- * `glob` is a plain suffix/substring filter on the path, not a glob engine —
- * `.ts` and `src/` both work, and a caller who wants more can filter results.
+ * `glob` filters paths. It accepts what its NAME promises — `*.ts`, `src/**`,
+ * `src/*.ts` — and a plain substring (`.ts`, `src/`) still works, because that is
+ * what the description used to say and both readings are reasonable. It was a
+ * substring test alone, and the first caller wrote `*.ts`: a search that could
+ * have matched returned nothing at all, which is the worst way for a filter to be
+ * wrong. A parameter answers to its name.
*/
+export function pathMatchesGlob(rel: string, glob: string): boolean {
+ if (!glob.includes('*') && !glob.includes('?')) return rel.includes(glob);
+ // `**` crosses directory separators, `*` and `?` do not.
+ const pattern = glob
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
+ .replace(/\*\*/g, '')
+ .replace(/\*/g, '[^/]*')
+ .replace(/\?/g, '[^/]')
+ .replace(//g, '.*');
+ // Anchored, but a bare `*.ts` should match `src/main.ts` — a pattern naming no
+ // directory is about the file name, which is how every shell and editor reads it.
+ const re = new RegExp(`^${pattern}$`);
+ return re.test(rel) || (!glob.includes('/') && re.test(rel.split('/').pop() ?? ''));
+}
export async function searchInRoot(
root: string,
opts: { query: string; regex?: boolean; glob?: string; maxResults?: number },
@@ -224,7 +242,7 @@ export async function searchInRoot(
: new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
const out: FileMatch[] = [];
for await (const rel of walkVisible(root, root)) {
- if (opts.glob && !rel.includes(opts.glob)) continue;
+ if (opts.glob && !pathMatchesGlob(rel, opts.glob)) continue;
let text: string;
try {
text = await readFile(resolveInRoot(root, rel), 'utf8');
diff --git a/desktop/electron/surfaceDriver.ts b/desktop/electron/surfaceDriver.ts
index ca6694f73..51d0aa0f9 100644
--- a/desktop/electron/surfaceDriver.ts
+++ b/desktop/electron/surfaceDriver.ts
@@ -182,8 +182,21 @@ export function createSurfaceDriver(
// they are two tool calls, the second of which nobody makes: an agent
// that has just written a file believes it.
const relPath = String(input.path ?? '');
- await writeInRoot(requireProjectRoot(), relPath, String(input.content ?? ''));
+ const content = String(input.content ?? '');
+ await writeInRoot(requireProjectRoot(), relPath, content);
if (!isScriptPath(relPath)) return { ok: true, path: relPath };
+ // A file that DECLARES components changes what the editor knows an entity
+ // can carry, and the watcher only gets there after a 250ms debounce plus
+ // an extract. A writer uses what it just declared in the very next call —
+ // a person pauses between the two, nothing else does — and the reply it
+ // raced was "component X has no field Y (fields: )": an empty schema,
+ // worded as a typo. Same contract as the asset doors: returned ⇒ usable.
+ if (/\bdefine(Component|Tag)\s*\(/.test(content)) {
+ await exec('window.__estellaEditor.refreshSchemas()').catch(() => {
+ // No automation hook published (a host with no driver authorised) —
+ // the debounced watcher still gets there, just later.
+ });
+ }
const diagnostics = scriptDiagnostics(relPath).filter((d) => d.category === 'error');
return { ok: true, path: relPath, errors: diagnostics.length, diagnostics: diagnostics.slice(0, 40) };
}
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index 5f9af70e2..b2fd289c4 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -434,7 +434,7 @@ export const TOOLS = [
+ 'Use this INSTEAD of paging the SDK .d.ts — that file is tens of thousands of lines and reading it a hundred at a time costs a context window to learn one method name.',
schema: obj({ name: { type: 'string' }, limit: { type: 'number' } }, ['name']), op: 'lookup_symbol' },
{ name: 'search_project_files',
- description: 'Lines matching `query` across the project (case-insensitive substring, or a regular expression with `regex: true`); `glob` keeps only paths containing that text (".ts", "src/"). '
+ description: 'Lines matching `query` across the project (case-insensitive substring, or a regular expression with `regex: true`); `glob` filters paths — `*.ts`, `src/**`, `src/*.ts`, or a plain substring like ".ts". '
+ 'Each hit is { file, line, text }. The door between list_project_files and reading a file whole.',
schema: obj({
query: { type: 'string' }, regex: { type: 'boolean' },
diff --git a/desktop/src/engine/sceneOps.ts b/desktop/src/engine/sceneOps.ts
index 4afbb880c..f1a61c483 100644
--- a/desktop/src/engine/sceneOps.ts
+++ b/desktop/src/engine/sceneOps.ts
@@ -187,7 +187,26 @@ export async function applySceneOps(
created.push(id);
if (op.ref) refs[op.ref] = id;
if (op.name) EditorControlSurface.renameEntity(id, op.name);
- if (op.fields) setFields(id, op.fields);
+ if (op.fields) {
+ // `components` REPLACES the default `['Transform']` rather than
+ // adding to it, so a create that names ShapeRenderer and then
+ // writes `Transform.position.y` fails with "component Transform is
+ // not on entity 3" — true, and no help at all when the same op
+ // supports `x`/`y`, which quietly supply the Transform this one
+ // just dropped. Say which side of that the caller landed on.
+ const declared = new Set(specs.map((c) => (typeof c === 'string' ? c : c.type)));
+ const missing = [...new Set(Object.keys(op.fields).map((k) => k.split('.')[0]))]
+ .filter((c) => !declared.has(c));
+ if (missing.length > 0) {
+ throw new Error(
+ `fields write to ${missing.map((c) => `"${c}"`).join(', ')}, which this create does `
+ + `not declare (it declares ${[...declared].map((c) => `"${c}"`).join(', ')}). Naming any `
+ + '`components` replaces the default ["Transform"] — list every component your fields '
+ + `write to${missing.includes('Transform') ? ', or give x/y instead of Transform.position' : ''}.`,
+ );
+ }
+ setFields(id, op.fields);
+ }
break;
}
case 'set':
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 5e4adecf5..f65204193 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -221,6 +221,13 @@ function buildEditorAutomation(): unknown {
* "returned ⇒ resolvable": programmatic create/import chain this so a
* follow-up `@uuid:`/path ref never races the debounced watcher refresh. */
refreshAssets: () => ProjectStore.refreshAssets(),
+ /** The same contract for COMPONENT schemas: returned ⇒ the editor knows what
+ * the project's components look like. The watcher debounces 250ms before
+ * extracting, and a writer that uses the component it just declared beats
+ * that easily — a person pauses between the two, a driver does not. What it
+ * got back was `"GomokuState" has no field "currentPlayer" (fields: )`: an
+ * empty field list, phrased as if the field name were wrong. */
+ refreshSchemas: () => ProjectStore.refreshUserSchemas(),
play: () => useEditorStore.getState().togglePlay(),
playState: () => PlayRealm.getSnapshot(),
/** Player count for the next Play (1 = single, 2-4 = listen server + clients). */
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index a069061d4..75b3ed2e8 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -185,6 +185,28 @@ describe('editor MCP tool registry', () => {
});
});
+ it('a component declaration is extracted before the write returns', async () => {
+ // The watcher debounces 250ms; a writer uses what it declared in the next
+ // call. Racing it answered `has no field "currentPlayer" (fields: )` — an
+ // empty schema worded as a typo, which sent the writer off rewriting a
+ // component that was correct.
+ const driver = vi.fn() as unknown as {
+ op: ReturnType<typeof vi.fn>; js: ReturnType<typeof vi.fn>;
+ } & ((...a: unknown[]) => unknown);
+ driver.op = vi.fn(async () => ({ ok: true }));
+ driver.js = vi.fn(async () => null);
+ const write = TOOLS.find((t: { name: string }) => t.name === 'write_project_file');
+ await runTool(write, driver, {
+ path: 'src/components.ts',
+ content: "import { defineComponent } from 'esengine';\nexport const S = defineComponent('S', { a: 1 });\n",
+ });
+ // The op carries the write; the extract is the op's own doing (surfaceDriver),
+ // so what this pins is that the tool still hands main the whole payload.
+ expect(driver.op).toHaveBeenCalledWith('write_project_file', expect.objectContaining({
+ path: 'src/components.ts',
+ }));
+ });
+
it('the compiler tools reach main, where the language service lives', async () => {
const driver = vi.fn() as unknown as { op: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);
driver.op = vi.fn(async () => []);
diff --git a/desktop/tests/scene-ops.test.ts b/desktop/tests/scene-ops.test.ts
index 0db55f461..372310c3b 100644
--- a/desktop/tests/scene-ops.test.ts
+++ b/desktop/tests/scene-ops.test.ts
@@ -119,6 +119,25 @@ describe('applySceneOps', () => {
expect(calls).toContainEqual(['create', 'Bare', null]);
});
+ it('says what to do when fields write to a component the create did not declare', async () => {
+ // `components` REPLACES the default ['Transform'], and the same op also takes
+ // x/y — so this is the easy mistake to make, and "component Transform is not
+ // on entity 3" is true and useless. A caller that cannot tell which of the
+ // two positioning routes it half-took spends its next round guessing.
+ await expect(applySceneOps([{
+ op: 'create', name: 'Line', components: ['ShapeRenderer'],
+ fields: { 'Transform.position.y': -224, 'ShapeRenderer.color': '#fff' },
+ }])).rejects.toThrow(/does not declare .*replaces the default .*or give x\/y/s);
+
+ // Declaring it is the other way out, and it works.
+ calls.length = 0;
+ await applySceneOps([{
+ op: 'create', name: 'Line', components: ['Transform', 'ShapeRenderer'],
+ fields: { 'Transform.position.y': -224 },
+ }]);
+ expect(calls).toContainEqual(['create', 'Line', null]);
+ });
+
it('resolves an entity template before mutating, and rejects an unknown one', async () => {
await applySceneOps([{ op: 'create', ref: 'img', template: 'ui-image', name: 'Icon' }]);
expect(calls).toContainEqual(['create', 'Image', null]);
@@ -131,7 +150,13 @@ describe('applySceneOps', () => {
});
it('applies create-time fields to the entity it just made', async () => {
- await applySceneOps([{ op: 'create', ref: 'n', fields: { 'Text.content': 'Alice' } }]);
+ // Text is declared: writing a field of a component the create did not make is
+ // its own error (below), and this case is about create-then-set reaching the
+ // NEW id. The fake surface accepted the undeclared form; the real one throws
+ // "component Text is not on entity 100" at the setField.
+ await applySceneOps([{
+ op: 'create', ref: 'n', components: ['Transform', 'Text'], fields: { 'Text.content': 'Alice' },
+ }]);
expect(calls).toContainEqual(['setField', 100, 'Text', 'content', 'Alice']);
});
diff --git a/desktop/tests/script-service.test.ts b/desktop/tests/script-service.test.ts
index 858424df1..bdea528f9 100644
--- a/desktop/tests/script-service.test.ts
+++ b/desktop/tests/script-service.test.ts
@@ -162,6 +162,19 @@ describe('project search', () => {
await expect(searchInRoot(root, { query: '' })).rejects.toThrow(/needs a query/);
});
+ it('answers to the name `glob`, and still takes a substring', async () => {
+ // The first real caller wrote `*.ts` — the thing the parameter's name
+ // promises — and a search that had matches returned nothing.
+ writeFileSync(path.join(root, 'src', 'globbed.ts'), 'const globTarget = 1;\n');
+ const forms = ['*.ts', 'src/*.ts', 'src/**', '.ts'];
+ for (const glob of forms) {
+ const hits = await searchInRoot(root, { query: 'globTarget', glob });
+ expect([glob, hits.some((h) => h.file.endsWith('globbed.ts'))]).toEqual([glob, true]);
+ }
+ // And still excludes what it should: a pattern that matches nothing matches nothing.
+ expect(await searchInRoot(root, { query: 'globTarget', glob: '*.json' })).toEqual([]);
+ });
+
it('clips a very long line instead of returning it whole', async () => {
writeFileSync(path.join(root, 'src', 'long.ts'), `// ${'x'.repeat(5000)} marker\n`);
const hits = await searchInRoot(root, { query: 'xxxxx', glob: 'long.ts' });