Skip to content

Add targeted debug logs for blockId/blockKey mesh resolution#533

Open
tracygardner wants to merge 4 commits intomainfrom
codex/fix-mesh-color-not-updating-live
Open

Add targeted debug logs for blockId/blockKey mesh resolution#533
tracygardner wants to merge 4 commits intomainfrom
codex/fix-mesh-color-not-updating-live

Conversation

@tracygardner
Copy link
Copy Markdown
Contributor

@tracygardner tracygardner commented Apr 14, 2026

Summary

  • Added debug-only logging (guarded by flock.meshDebug) to trace block-to-mesh resolution in ui/blockmesh.js.
  • Logs now show:
    • direct lookup hits ([mesh-lookup:direct], [mesh-lookup:direct-many])
    • lookup misses ([mesh-lookup:miss], [mesh-lookup:miss-many])
    • fallback resolution details ([mesh-lookup:fallback]) including block id/key, variable name, and matched mesh metadata keys.
  • On misses, logs include a sample of known scene metadata.blockKey values to quickly spot key drift.

Why

This gives concrete runtime evidence of which IDs/keys are being used, so we can validate whether import-time key drift is the cause in affected projects.

Testing

  • npm run -s lint

Codex Task

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of object/mesh loading in block-based workflows by adding scene-aware fallback matching and binding so missing direct references are resolved more often.
  • Chores

    • Enhanced import diagnostics and workspace introspection with detailed logging of file drops, ID collisions, and post-import missing IDs to aid troubleshooting.

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages bot commented Apr 14, 2026

Deploying flockxr with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3ffbdc5
Status: ✅  Deploy successful!
Preview URL: https://3d0fee2f.flockxr.pages.dev
Branch Preview URL: https://codex-fix-mesh-color-not-upd.flockxr.pages.dev

View logs

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

📝 Walkthrough

Walkthrough

Adds workspace snapshotting and collision detection around Blockly JSON loads; implements block-aware fallback mesh resolution that derives user variable names from ID_VAR, finds candidate meshes (by base name and indexed suffix), rebinds meshes and descendants to block keys, and adds logging and index dirtying.

Changes

Cohort / File(s) Summary
Mesh resolution & lookup logic
ui/blockmesh.js
Added helper to derive a user var name from an ID_VAR field, locate candidate scene meshes by exact or indexed-suffix (<base>_<n>), and rebind matched meshes (and descendants) by setting mesh.metadata.blockKey and _meshIndexDirty = true. Added getFallbackMeshesForLoadBlock, updated getMeshFromBlock and getMeshesFromBlock to prefer direct get*FromBlockKey then fallback for load_object, load_multi_object, load_character, and added logging for hits/misses/fallbacks.
Workspace snapshot & collision detection
main/files.js
Added collectWorkspaceSnapshot, collectIncomingSnapshot, and intersectSets. Updated loadWorkspaceAndExecute to log entry counts, capture before/after workspace snapshots, compute/log block & variable ID collisions between existing and incoming data, and report incoming IDs missing after load. Added a console.log at start of processProjectFileDrop recording file name/size and target workspace id.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Loader as WorkspaceLoader
    participant Validator as JSONValidator
    participant Workspace as BlocklyWorkspace
    participant Snapshot as Snapshotter
    participant MeshIndex as MeshIndex
    participant MeshFinder as FallbackMatcher

    Caller->>Loader: loadWorkspaceAndExecute(json)
    Loader->>Validator: validate(json)
    Validator-->>Loader: validatedJson
    Loader->>Snapshot: collectWorkspaceSnapshot(before)
    Snapshot-->>Loader: beforeSnapshot
    Loader->>Loader: intersectSets(before, incoming)
    Loader->>Workspace: Blockly.serialization.workspaces.load(validatedJson)
    Workspace-->>Loader: loaded
    Loader->>Snapshot: collectWorkspaceSnapshot(after)
    Snapshot-->>Loader: afterSnapshot
    Loader->>Loader: compute missing incoming IDs
    alt mesh lookup for a load_* block
        Caller->>MeshIndex: getMeshFromBlockKey(blockKey)
        MeshIndex-->>Caller: miss
        Caller->>MeshFinder: getFallbackMeshesForLoadBlock(block)
        MeshFinder->>MeshIndex: set mesh.metadata.blockKey (rebind), set _meshIndexDirty = true
        MeshFinder-->>Caller: fallback meshes
    else direct hit
        MeshIndex-->>Caller: mesh (direct hit)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰
I hop through blocks and names that hide,
I sniff the meshes, find where they bide,
When keys are lost I gently bind,
And mark the indices to find,
A rabbit patch — now all aligned!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: adding debug logging for block-to-mesh resolution with blockId/blockKey, which is the primary purpose across both modified files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-mesh-color-not-updating-live

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ui/blockmesh.js (1)

1-1: ⚠️ Potential issue | 🟡 Minor

Address Prettier formatting issue flagged by CI.

The pipeline reports a Prettier formatting mismatch. Run npx prettier --write ui/blockmesh.js to resolve.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` at line 1, Prettier is flagging a formatting mismatch for
the module that begins with the line import * as Blockly from "blockly";—fix it
by running the Prettier formatter (npx prettier --write) on that module or
applying equivalent formatting rules so the file matches the repo Prettier
config; re-stage and commit the formatted file so CI passes.
🧹 Nitpick comments (3)
ui/blockmesh.js (3)

414-420: Minor inconsistency: miss-many logging omits knownSceneKeys sample.

The single-mesh [mesh-lookup:miss] logs a sample of known scene blockKeys to help diagnose key drift, but [mesh-lookup:miss-many] doesn't. For debugging parity, consider adding the same sample here.

🔧 Optional: Add knownSceneKeys to miss-many logging
   if (flock.meshDebug) {
     console.warn("[mesh-lookup:miss-many]", {
       blockType: block.type,
       blockId: block.id,
       blockKey,
+      knownSceneKeys: [...new Set((flock.scene?.meshes ?? [])
+        .map((m) => m?.metadata?.blockKey)
+        .filter(Boolean))].slice(0, 50),
     });
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 414 - 420, The miss-many debug log omits the
knownSceneKeys sample that the single-mesh handler logs; update the console.warn
inside the if (flock.meshDebug) block in ui/blockmesh.js (the one logging
"[mesh-lookup:miss-many]") to include the same knownSceneKeys sample (e.g., a
sliced/sample array property) alongside block.type, block.id and blockKey so it
matches the "[mesh-lookup:miss]" output for key-drift diagnostics.

244-268: Function name implies pure retrieval but performs rebinding side effect.

getFallbackMeshesForLoadBlock calls rebindMeshesToBlockKey, which mutates metadata.blockKey on matched meshes. Consider either:

  1. Renaming to getAndRebindFallbackMeshesForLoadBlock to signal mutation, or
  2. Adding a brief comment noting the side effect

This helps prevent surprises when callers assume the function is a pure lookup.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 244 - 268, getFallbackMeshesForLoadBlock
currently performs a lookup and also mutates matched meshes by calling
rebindMeshesToBlockKey, which is surprising given its "get" name; either rename
the function to getAndRebindFallbackMeshesForLoadBlock or add a one-line comment
above getFallbackMeshesForLoadBlock describing the side effect (that it calls
rebindMeshesToBlockKey and updates metadata.blockKey on returned meshes) so
callers know it is not a pure accessor; update any internal references if you
choose renaming to avoid breakage.

229-242: Rebinding mutates mesh metadata as a side effect of lookup—consider documenting this contract.

This function permanently changes metadata.blockKey on matched meshes. If the original blockKey is still used elsewhere (e.g., stored references in meshMap or external code), those references will become stale. The _meshIndexDirty = true ensures the index rebuilds, but any cached blockKey lookups performed before the rebuild may fail.

This appears intentional per the PR objectives (fixing key drift at import time), but the mutation-during-lookup behavior is non-obvious. A brief comment explaining when/why rebinding is safe would help future maintainers.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 229 - 242, The rebindMeshesToBlockKey function
mutates mesh.metadata.blockKey for meshes and their descendants as a side effect
of lookup, which can make previously held blockKey references stale; update the
function by adding a concise comment above rebindMeshesToBlockKey documenting
this mutation contract (what is mutated: mesh.metadata.blockKey on mesh and
descendants), why it’s safe here (e.g., done at import-time to fix key drift),
and that callers should expect in-place mutation and that _meshIndexDirty is set
to trigger index rebuilds if they rely on cached lookups; reference the symbols
rebindMeshesToBlockKey, mesh.metadata.blockKey, and _meshIndexDirty in the
comment so future maintainers can locate and understand the rationale.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@ui/blockmesh.js`:
- Line 1: Prettier is flagging a formatting mismatch for the module that begins
with the line import * as Blockly from "blockly";—fix it by running the Prettier
formatter (npx prettier --write) on that module or applying equivalent
formatting rules so the file matches the repo Prettier config; re-stage and
commit the formatted file so CI passes.

---

Nitpick comments:
In `@ui/blockmesh.js`:
- Around line 414-420: The miss-many debug log omits the knownSceneKeys sample
that the single-mesh handler logs; update the console.warn inside the if
(flock.meshDebug) block in ui/blockmesh.js (the one logging
"[mesh-lookup:miss-many]") to include the same knownSceneKeys sample (e.g., a
sliced/sample array property) alongside block.type, block.id and blockKey so it
matches the "[mesh-lookup:miss]" output for key-drift diagnostics.
- Around line 244-268: getFallbackMeshesForLoadBlock currently performs a lookup
and also mutates matched meshes by calling rebindMeshesToBlockKey, which is
surprising given its "get" name; either rename the function to
getAndRebindFallbackMeshesForLoadBlock or add a one-line comment above
getFallbackMeshesForLoadBlock describing the side effect (that it calls
rebindMeshesToBlockKey and updates metadata.blockKey on returned meshes) so
callers know it is not a pure accessor; update any internal references if you
choose renaming to avoid breakage.
- Around line 229-242: The rebindMeshesToBlockKey function mutates
mesh.metadata.blockKey for meshes and their descendants as a side effect of
lookup, which can make previously held blockKey references stale; update the
function by adding a concise comment above rebindMeshesToBlockKey documenting
this mutation contract (what is mutated: mesh.metadata.blockKey on mesh and
descendants), why it’s safe here (e.g., done at import-time to fix key drift),
and that callers should expect in-place mutation and that _meshIndexDirty is set
to trigger index rebuilds if they rely on cached lookups; reference the symbols
rebindMeshesToBlockKey, mesh.metadata.blockKey, and _meshIndexDirty in the
comment so future maintainers can locate and understand the rationale.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9f8fdada-ab2d-460b-bc15-46277137381a

📥 Commits

Reviewing files that changed from the base of the PR and between 6928646 and 7eea8f1.

📒 Files selected for processing (1)
  • ui/blockmesh.js

@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages bot commented Apr 14, 2026

Deploying flockdev with  Cloudflare Pages  Cloudflare Pages

Latest commit: 3ffbdc5
Status: ✅  Deploy successful!
Preview URL: https://b6f79bf7.flockdev.pages.dev
Branch Preview URL: https://codex-fix-mesh-color-not-upd.flockdev.pages.dev

View logs

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ui/blockmesh.js (1)

1-1: ⚠️ Potential issue | 🟡 Minor

Fix Prettier formatting issue.

The CI pipeline reports a Prettier formatting issue in this file. Run npx prettier --write ui/blockmesh.js or your project's formatting command to resolve.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` at line 1, The file ui/blockmesh.js fails Prettier
formatting; run your formatter (e.g., npx prettier --write ui/blockmesh.js) or
apply the project's formatting command to fix the import line (import * as
Blockly from "blockly";) and any surrounding whitespace/quote style so the file
passes CI.
🧹 Nitpick comments (3)
ui/blockmesh.js (2)

229-242: Side effect during lookup: rebindMeshesToBlockKey mutates mesh metadata.

This function modifies mesh.metadata.blockKey on matched meshes and their descendants, then marks the index dirty. While this "self-healing" rebinding is useful for resolving key drift, it occurs as a side effect within getFallbackMeshesForLoadBlock, which is called from getMeshFromBlock/getMeshesFromBlock.

This means a "get" operation can mutate state, which may be surprising. Consider documenting this behavior or renaming to signal the mutation (e.g., resolveAndBindFallbackMeshes).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 229 - 242, The helper rebindMeshesToBlockKey
currently mutates mesh.metadata.blockKey (and descendants) and flips
_meshIndexDirty during lookups invoked from getFallbackMeshesForLoadBlock (used
by getMeshFromBlock/getMeshesFromBlock), which causes surprising state changes
on reads; either rename the function to something that signals mutation (e.g.,
resolveAndBindFallbackMeshes) and update callers/docs, or change its behavior to
avoid mutating state by returning new mesh objects (or metadata copies) with the
corrected blockKey and leave _meshIndexDirty updates to an explicit binder
function; update references to rebindMeshesToBlockKey in
getFallbackMeshesForLoadBlock, getMeshFromBlock, and getMeshesFromBlock
accordingly and add a short docstring noting whether it mutates state.

253-262: Inconsistent debug log guarding.

Existing debug logs in this file (lines 83, 93, 108, 123, 138, etc.) are guarded by if (flock.meshDebug), but the new logs at lines 253, 321, 331, 397, and 406 are unconditional.

If "always emit" is intentional per the commit message, consider using console.debug instead of console.log/console.warn so they can be filtered in browser devtools. Otherwise, wrap them with the existing flock.meshDebug pattern for consistency.

🔧 Option A: Guard with meshDebug for consistency
-  console.log("[mesh-lookup:fallback]", {
+  if (flock.meshDebug) console.log("[mesh-lookup:fallback]", {
     blockType: block.type,
     ...
   });

Apply similarly to lines 321-328, 331-338, 397-403, and 406-410.

🔧 Option B: Use console.debug for always-on but filterable logs
-  console.log("[mesh-lookup:direct]", {
+  console.debug("[mesh-lookup:direct]", {
-  console.warn("[mesh-lookup:miss]", {
+  console.debug("[mesh-lookup:miss]", {

Also applies to: 321-328, 331-338, 397-403, 406-410

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 253 - 262, The new unconditional debug prints
(e.g., the console.log with tag "[mesh-lookup:fallback]" that logs blockType,
blockId, blockKey, variableName and matchedMeshes, and the other
console.log/console.warn calls added later) must follow the existing logging
pattern: either wrap each of those console.* calls with the same guard used
elsewhere (if (flock.meshDebug) { ... }) or convert them to console.debug(...)
so they are filterable; locate the instances by searching for the string
"[mesh-lookup:fallback]" and other new console.log/console.warn invocations and
update them to use flock.meshDebug guarding or console.debug to match the file's
existing behavior.
main/files.js (1)

397-427: Unconditional logging may be noisy in production.

The PR description states these are "debug-only logging (guarded by flock.meshDebug)", but these console.log calls are unconditional. In ui/blockmesh.js, existing debug logs (lines 83, 93, 108, etc.) are guarded by if (flock.meshDebug).

If the intent per the commit message is to "always emit mesh lookup debug logs", this is fine for diagnostics but will be verbose in production. If this should align with the existing debug pattern, consider adding a guard.

🔧 Optional: Guard logs with a debug flag
+    if (flock?.meshDebug) {
       console.log("[workspace-load:before]", {
         existingBlocks: before.blockCount,
         existingVariables: before.variableCount,
         incomingBlocks: incoming.blockCount,
         incomingVariables: incoming.variableCount,
       });
       console.log("[workspace-load:collisions]", {
         blockIdCollisions: collidingBlockIds.length,
         variableIdCollisions: collidingVariableIds.length,
         sampleBlockIds: collidingBlockIds.slice(0, 10),
         sampleVariableIds: collidingVariableIds.slice(0, 10),
       });
+    }

Similar change for the [workspace-load:after] log block.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main/files.js` around lines 397 - 427, The three unconditional console.log
calls labeled "[workspace-load:before]", "[workspace-load:collisions]" and
"[workspace-load:after]" are noisy and should be guarded like other debug logs;
wrap each of these log blocks in the existing debug check (if (flock.meshDebug)
{ ... }) used elsewhere (see ui/blockmesh.js) so they only emit when
flock.meshDebug is true, ensuring you include the entire logging objects
currently passed to console.log and preserving the surrounding logic that calls
Blockly.serialization.workspaces.load and collectWorkspaceSnapshot.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@ui/blockmesh.js`:
- Line 1: The file ui/blockmesh.js fails Prettier formatting; run your formatter
(e.g., npx prettier --write ui/blockmesh.js) or apply the project's formatting
command to fix the import line (import * as Blockly from "blockly";) and any
surrounding whitespace/quote style so the file passes CI.

---

Nitpick comments:
In `@main/files.js`:
- Around line 397-427: The three unconditional console.log calls labeled
"[workspace-load:before]", "[workspace-load:collisions]" and
"[workspace-load:after]" are noisy and should be guarded like other debug logs;
wrap each of these log blocks in the existing debug check (if (flock.meshDebug)
{ ... }) used elsewhere (see ui/blockmesh.js) so they only emit when
flock.meshDebug is true, ensuring you include the entire logging objects
currently passed to console.log and preserving the surrounding logic that calls
Blockly.serialization.workspaces.load and collectWorkspaceSnapshot.

In `@ui/blockmesh.js`:
- Around line 229-242: The helper rebindMeshesToBlockKey currently mutates
mesh.metadata.blockKey (and descendants) and flips _meshIndexDirty during
lookups invoked from getFallbackMeshesForLoadBlock (used by
getMeshFromBlock/getMeshesFromBlock), which causes surprising state changes on
reads; either rename the function to something that signals mutation (e.g.,
resolveAndBindFallbackMeshes) and update callers/docs, or change its behavior to
avoid mutating state by returning new mesh objects (or metadata copies) with the
corrected blockKey and leave _meshIndexDirty updates to an explicit binder
function; update references to rebindMeshesToBlockKey in
getFallbackMeshesForLoadBlock, getMeshFromBlock, and getMeshesFromBlock
accordingly and add a short docstring noting whether it mutates state.
- Around line 253-262: The new unconditional debug prints (e.g., the console.log
with tag "[mesh-lookup:fallback]" that logs blockType, blockId, blockKey,
variableName and matchedMeshes, and the other console.log/console.warn calls
added later) must follow the existing logging pattern: either wrap each of those
console.* calls with the same guard used elsewhere (if (flock.meshDebug) { ...
}) or convert them to console.debug(...) so they are filterable; locate the
instances by searching for the string "[mesh-lookup:fallback]" and other new
console.log/console.warn invocations and update them to use flock.meshDebug
guarding or console.debug to match the file's existing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bc5b31ed-1306-43fe-9a81-8609c0ff4b12

📥 Commits

Reviewing files that changed from the base of the PR and between 7eea8f1 and 7ac3c82.

📒 Files selected for processing (2)
  • main/files.js
  • ui/blockmesh.js

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@main/files.js`:
- Around line 830-834: The console.log call emitting file.name in the
"[workspace-import:start]" log exposes user-supplied filenames; update the log
in main/files.js so it no longer prints file?.name by default—either remove
file?.name from the logged object or wrap the log behind a debug flag (e.g.,
check a DEBUG/verbose setting) so filenames are only emitted when explicitly
enabled; keep file?.size and workspace?.id as needed and adjust the log call
that contains the "[workspace-import:start]" tag accordingly.

In `@ui/blockmesh.js`:
- Around line 255-267: The unconditional console.log tracing in ui/blockmesh.js
(e.g., inside updateOrCreateMeshFromBlock() fallback that prints matchedMeshes
and related info) should be guarded behind the flock.meshDebug flag so these
messages only appear in debug sessions; wrap those console.log blocks (including
the occurrences around the fallback trace and the other traces at the ranges you
noted) with a check like if (flock.meshDebug) { ... } so normal runs won’t emit
create-time miss warnings.
- Around line 229-242: The fallback rebinding in rebindMeshesToBlockKey is too
aggressive: only set mesh.metadata.blockKey (and descendants') when they do not
already have an explicit owner/blockKey (skip descendants where
child.metadata.blockKey or child.metadata.owner is present and differs), and
whenever you change a mesh's blockKey ensure you also update the global maps
(meshMap and meshBlockIdMap) so lookups can be recovered (handle the case
blockKey !== block.id by moving the mesh entry to the new blockKey in those
maps). Apply the same guarded-update logic to the other rebind site mentioned
(lines ~269-270) so you don't clobber separately-owned attached meshes and
mappings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: da3ba0c3-b1ae-4f3d-8f37-da121fa468c3

📥 Commits

Reviewing files that changed from the base of the PR and between 7ac3c82 and 3ffbdc5.

📒 Files selected for processing (2)
  • main/files.js
  • ui/blockmesh.js

Comment on lines +830 to +834
console.log("[workspace-import:start]", {
fileName: file?.name ?? null,
fileSize: file?.size ?? null,
workspaceId: workspace?.id ?? null,
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Don't log imported filenames by default.

file.name is user-supplied and can contain personal or project info. Emitting it on every drag-and-drop import exposes that data in normal browser console output; gate this behind a debug flag or omit the name.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main/files.js` around lines 830 - 834, The console.log call emitting
file.name in the "[workspace-import:start]" log exposes user-supplied filenames;
update the log in main/files.js so it no longer prints file?.name by
default—either remove file?.name from the logged object or wrap the log behind a
debug flag (e.g., check a DEBUG/verbose setting) so filenames are only emitted
when explicitly enabled; keep file?.size and workspace?.id as needed and adjust
the log call that contains the "[workspace-import:start]" tag accordingly.

Comment on lines +229 to +242
function rebindMeshesToBlockKey(meshes, blockKey) {
if (!blockKey || !Array.isArray(meshes) || meshes.length === 0) return;
for (const mesh of meshes) {
if (!mesh) continue;
mesh.metadata = mesh.metadata || {};
mesh.metadata.blockKey = blockKey;
const descendants = mesh.getDescendants?.(false) ?? [];
for (const child of descendants) {
child.metadata = child.metadata || {};
child.metadata.blockKey = blockKey;
}
}
_meshIndexDirty = true;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fallback rebinding is too broad and leaves owner state stale.

Line 235 rewrites every descendant's metadata.blockKey, so separately-owned attached meshes under that hierarchy can get reassigned too. The helper also never updates meshMap / meshBlockIdMap; when blockKey !== block.id, the later getBlockById(blockKey) recovery path cannot repair the mapping after this fallback.

Also applies to: 269-270

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 229 - 242, The fallback rebinding in
rebindMeshesToBlockKey is too aggressive: only set mesh.metadata.blockKey (and
descendants') when they do not already have an explicit owner/blockKey (skip
descendants where child.metadata.blockKey or child.metadata.owner is present and
differs), and whenever you change a mesh's blockKey ensure you also update the
global maps (meshMap and meshBlockIdMap) so lookups can be recovered (handle the
case blockKey !== block.id by moving the mesh entry to the new blockKey in those
maps). Apply the same guarded-update logic to the other rebind site mentioned
(lines ~269-270) so you don't clobber separately-owned attached meshes and
mappings.

Comment on lines +255 to +267
console.log("[mesh-lookup:fallback]", {
blockType: block.type,
blockId: block.id,
blockKey: blockKey || block.id,
workspaceId: ws?.id ?? null,
isFlyout: !!ws?.isFlyout,
isMainWorkspace: !!(ws && mainWs && ws === mainWs),
variableName,
matchedMeshes: matches.map((m) => ({
name: m?.name,
blockKey: m?.metadata?.blockKey ?? null,
})),
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Keep the new lookup tracing behind flock.meshDebug.

These traces are unconditional, unlike the rest of this file. Because updateOrCreateMeshFromBlock() resolves meshes before the create path, expected create-time misses now emit warnings outside debug sessions and can drown out real diagnostics.

🧰 Suggested guard pattern
-  console.warn("[mesh-lookup:miss]", {
-    blockType: block.type,
-    blockId: block.id,
-    blockKey,
-    workspaceId: ws?.id ?? null,
-    isFlyout: !!ws?.isFlyout,
-    isMainWorkspace: !!(ws && mainWs && ws === mainWs),
-    knownSceneKeys: [...new Set((flock.scene?.meshes ?? [])
-      .map((m) => m?.metadata?.blockKey)
-      .filter(Boolean))].slice(0, 50),
-  });
+  if (flock.meshDebug) {
+    console.warn("[mesh-lookup:miss]", {
+      blockType: block.type,
+      blockId: block.id,
+      blockKey,
+      workspaceId: ws?.id ?? null,
+      isFlyout: !!ws?.isFlyout,
+      isMainWorkspace: !!(ws && mainWs && ws === mainWs),
+      knownSceneKeys: [...new Set((flock.scene?.meshes ?? [])
+        .map((m) => m?.metadata?.blockKey)
+        .filter(Boolean))].slice(0, 50),
+    });
+  }

Also applies to: 324-355, 410-437

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ui/blockmesh.js` around lines 255 - 267, The unconditional console.log
tracing in ui/blockmesh.js (e.g., inside updateOrCreateMeshFromBlock() fallback
that prints matchedMeshes and related info) should be guarded behind the
flock.meshDebug flag so these messages only appear in debug sessions; wrap those
console.log blocks (including the occurrences around the fallback trace and the
other traces at the ranges you noted) with a check like if (flock.meshDebug) {
... } so normal runs won’t emit create-time miss warnings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant