From ef416fae36dcb5e509eebc563aa911ee1d36493d Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:34:22 +0200 Subject: [PATCH 1/7] Resource packs say what the game will use - A data save into a world whose level.dat disables TotalDebug's datapack enabled it only when it sent a reload. A world-load save sends none, and a save into a closed world writes only the file, so in such a world the change was never used while Companion counted the pack as used. The game enables a datapack it has not seen when it loads a world, unless level.dat disables it. Now every data save enables the managed datapack, as the live reload and the resource pack in options.txt already do: in a closed world's level.dat, and through the data reload for a world-load save into a world whose server does not list it. - A texture saved into a pack that keeps its own .mcmeta played the animation of the copy shown before; the saved copy is decoded against the pack it went into, as a read of it would. - A pack whose description is [] or {} counted as a pack; the game's text component codec refuses both. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../catalog/PackFolders.java | 22 ++++++- .../pack/DatapackSelection.java | 22 +++++++ .../pack/ResourceEdits.java | 27 +++++++- .../editors/PackResourceEditor.java | 19 ++++-- .../catalog/PackFoldersTest.java | 8 ++- .../pack/ResourceEditsTest.java | 66 +++++++++++++++++++ .../components/editors/TextureEditorTest.java | 30 +++++++++ 7 files changed, 184 insertions(+), 10 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index fc5326dd..980f2bb2 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -14,6 +14,7 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; @@ -31,6 +32,9 @@ public final class PackFolders { public record Meta(String description, int format) { } + /** The keys naming a component's content, one per kind: text, translation, score, selector, key binding, NBT. */ + private static final List COMPONENT_CONTENTS = List.of("text", "translate", "score", "selector", "keybind", "nbt"); + private PackFolders() { } @@ -43,10 +47,22 @@ public static boolean isPack(Path entry) { if (!Files.isDirectory(entry) && !(Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(".zip"))) { return false; } - // The description is a text component: text, a list or an object; null or a number is none. return section(entry).filter(section -> section.get("pack_format") instanceof JsonPrimitive format && format.isNumber() - && (section.get("description") instanceof JsonPrimitive text && text.isString() - || section.get("description") instanceof JsonArray || section.get("description") instanceof JsonObject)).isPresent(); + && isComponent(section.get("description"))).isPresent(); + } + + /** + * Whether the game reads {@code value} as a text component (its {@code ComponentSerialization}): text, a list of at + * least one component, or an object with the content of one of its kinds. + */ + private static boolean isComponent(JsonElement value) { + if (value instanceof JsonPrimitive text) return text.isString(); + if (value instanceof JsonArray list) { + if (list.isEmpty()) return false; + for (JsonElement element : list) if (!isComponent(element)) return false; + return true; + } + return value instanceof JsonObject object && COMPONENT_CONTENTS.stream().anyMatch(object::has); } /** The {@code pack} section of a pack's {@code pack.mcmeta}, or empty without one it can read. */ diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java index dc448a6e..7169d999 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java @@ -107,6 +107,28 @@ public void writeFile(List>> writ } } + /** + * Enables {@code id} at the top of {@code world}'s datapacks where its {@code level.dat} disables it, and tells whether + * it did; a pack named in neither list the game enables itself when it loads the world. Blocking. + */ + static boolean enableDisabled(Path world, String id) throws IOException { + if (!strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Disabled").contains(id)) return false; + LevelDat.update(world, root -> { + if (!(root.tag().entries().get("Data") instanceof NbtData.CompoundTag data)) { + throw new IOException("The level.dat of " + world.getFileName() + " holds no world data"); + } + NbtData.CompoundTag packs = dataPacks(root.tag()); + List enabled = new ArrayList<>(strings(packs, "Enabled")); + List disabled = new ArrayList<>(strings(packs, "Disabled")); + enabled.remove(id); + enabled.add(id); + disabled.remove(id); + NbtData.CompoundTag written = LevelDat.with(LevelDat.with(packs, "Enabled", list(enabled)), "Disabled", list(disabled)); + return new LevelDat.Root(root.name(), LevelDat.with(root.tag(), "Data", LevelDat.with(data, "DataPacks", written))); + }); + return true; + } + /** The datapacks {@code world}'s {@code level.dat} enables, lowest first. Blocking. */ static List saved(Path world) throws IOException { return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Enabled"); diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 20079cbe..1f978049 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -601,6 +601,19 @@ private CompletableFuture apply(String path, List alsoWatched, Pa "The TotalDebug pack could not be enabled in options.txt: " + exception.getMessage())); } } + if (!assets && managed(pack) && !game.isOpen(world)) { + // A world enables a datapack it has not seen when it loads, but not one its level.dat disables, which the + // player did; a save into the managed pack enables it, as the reload of a live save does. + try { + if (DatapackSelection.enableDisabled(world, PACK_ID)) { + this.landed.incrementAndGet(); + this.packs.written(ChangeRecord.PackSide.DATA); + } + } catch (IOException | RuntimeException exception) { + return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), + "The TotalDebug datapack could not be enabled in the level.dat of " + world.getFileName() + ": " + exception.getMessage())); + } + } if (!assets && game.isOpen(world)) { // Written all the same: the game only reads a datapack, when it loads the world or its data again. return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "The world " + world.getFileName() @@ -609,11 +622,15 @@ private CompletableFuture apply(String path, List alsoWatched, Pa } return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "")); } + GameLocation.Connection connection = ((Access.Live) access).connection(); if (!assets && apply == ResourcePaths.Apply.WORLD_LOAD) { - return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); + if (!managed(pack) || serverEnables(PACK_ID)) return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); + // The world reads the file when it loads again, from the managed pack only if it is enabled: the data reload + // that enables it after any other save enables it here too. + return reload(connection, world, path, PACK_ID).handle((result, failure) -> new Saved(Effect.REJOIN, pack, List.of(), + failure != null ? message(failure) : result.error())); } // Files written beside it join the same reload, which they are part of. - GameLocation.Connection connection = ((Access.Live) access).connection(); String managedPack = managed(pack) ? PACK_ID : ""; for (String beside : alsoWatched) reload(connection, world, beside, managedPack); return reload(connection, world, path, managedPack).handle((result, failure) -> { @@ -626,6 +643,12 @@ private CompletableFuture apply(String path, List alsoWatched, Pa }); } + /** Whether the server of the world the game plays named {@code id} among its enabled datapacks. */ + private boolean serverEnables(String id) { + PackStackPayload datapacks = this.packs.datapacks(); + return datapacks != null && datapacks.enabled().stream().anyMatch(enabled -> enabled.id().equals(id)); + } + /** Asks the game to reload what {@code path} needs: the client's resources, or the data of {@code world}. */ private CompletableFuture reload(GameLocation.Connection connection, Path world, String path, String managedPack) { return world == null ? this.pipeline.reloads().resources(connection, kind(path), path, managedPack) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java index f2a1738a..b4ad6c8d 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java @@ -37,6 +37,7 @@ import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -487,6 +488,8 @@ private boolean save(Consumer after) { Map alongside = alongside(); String expected = this.baseline; String[] written = new String[1]; + // The saved copy as a read of it shows it: the pack saved into can keep an animation of its own for the pixels. + AtomicReference savedCopy = new AtomicReference<>(edited); // Encoding a large texture takes a while, so it runs with the rest of the save, and so does its hash. CompletableFuture.supplyAsync(() -> { try { @@ -502,7 +505,15 @@ private boolean save(Consumer after) { } catch (IOException exception) { throw new CompletionException(exception); } - }, Workers.files()).thenCompose(bytes -> this.edits.save(this.path, into, bytes, alongside, expected)) + }, Workers.files()).thenCompose(bytes -> this.edits.save(this.path, into, bytes, alongside, expected) + .thenApplyAsync(saved -> { + try { + savedCopy.set(decode(bytes, saved.pack())); + } catch (IOException | RuntimeException unreadable) { + // The bytes were encoded from what is shown; the copy stays as edited. + } + return saved; + }, Workers.files())) .whenComplete((saved, failure) -> SwingUtilities.invokeLater(() -> { // The reads go on afterwards, whatever happens here, unless another save takes the hold over. boolean savingAgain = false; @@ -532,10 +543,10 @@ private boolean save(Consumer after) { this.packHash = written[0]; boolean keepEdits = !same(shown(), edited); showPack(saved.pack()); - this.packContent = edited; + this.packContent = savedCopy.get(); this.managed = true; - if (keepEdits) markSaved(edited); - else load(edited); + if (keepEdits) markSaved(this.packContent); + else load(this.packContent); showSaved(saved); changed(); // Another tab's save that came while this one ran was not read then. diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index d13f31a8..7c846b78 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -36,8 +36,14 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { output.closeEntry(); } Files.writeString(folder.resolve("readme.txt"), ""); + // The game reads the description as a text component, and refuses a list without one or an object without content. + for (String[] pack : new String[][]{{"EmptyList", "[]"}, {"EmptyObject", "{}"}, {"HalfList", "[\"ok\",{}]"}, + {"Translated", "{\"translate\":\"pack.translated\"}"}}) { + Files.createDirectories(folder.resolve(pack[0])); + Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); + } - assertEquals(List.of("file/Faithful", "file/Old.zip"), List.copyOf(PackFolders.list(folder).keySet()), + assertEquals(List.of("file/Faithful", "file/Old.zip", "file/Translated"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); assertTrue(PackFolders.list(this.directory.resolve("missing")).isEmpty()); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index 18e65e2f..09fa3ef9 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -2,6 +2,7 @@ import com.github.minecraft_ta.totalDebugCompanion.change.ChangePipeline; import com.github.minecraft_ta.totalDebugCompanion.catalog.ConfigChanges; +import com.github.minecraft_ta.totalDebugCompanion.catalog.LevelDat; import com.github.minecraft_ta.totalDebugCompanion.catalog.LevelDatFixture; import com.github.minecraft_ta.totalDebugCompanion.change.Effect; import com.github.minecraft_ta.totalDebugCompanion.game.GameLocations; @@ -9,6 +10,7 @@ import com.github.minecraft_ta.totalDebugCompanion.storage.ResourceOriginals; import com.github.minecraft_ta.totaldebug.protocol.message.ClientPacksPayload; import com.github.minecraft_ta.totaldebug.protocol.message.PackStackPayload; +import com.github.minecraft_ta.totaldebug.protocol.nbt.NbtData; import com.github.minecraft_ta.totaldebug.protocol.message.PlayingPayload; import com.github.minecraft_ta.totaldebug.protocol.message.ReloadPayload; import com.github.minecraft_ta.totaldebug.protocol.message.ReloadResultPayload; @@ -38,6 +40,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -233,6 +236,69 @@ void dataGoesToTheWorldPlayedLastWhileNoneIsOpen() throws Exception { assertTrue(Files.readString(saved.pack().resolve("pack.mcmeta")).contains("\"pack_format\":48")); } + @Test + void aSaveIntoAClosedWorldThatDisabledTheManagedDatapackEnablesItThere() throws Exception { + Path world = this.directory.resolve("saves/World"); + Map data = LevelDatFixture.world("World"); + data.put("DataPacks", Map.of("Enabled", List.of("vanilla"), "Disabled", List.of(ResourceEdits.PACK_ID, "file/Off"))); + LevelDatFixture.write(world, data); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + + ResourceEdits.Saved saved = edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertEquals(Effect.WORLD_OPENS, saved.effect()); + assertEquals("", saved.reloadFailure()); + assertEquals(List.of("vanilla", ResourceEdits.PACK_ID), DatapackSelection.saved(world), "enabled at the top, as a reload enables it"); + NbtData.CompoundTag packs = (NbtData.CompoundTag) ((NbtData.CompoundTag) LevelDat.read(LevelDat.file(world)).tag() + .entries().get("Data")).entries().get("DataPacks"); + assertEquals(List.of(new NbtData.StringTag("file/Off")), ((NbtData.ListTag) packs.entries().get("Disabled")).items(), + "the player's other choices stay"); + } + + @Test + void aSaveIntoAClosedWorldThatDoesNotNameTheManagedDatapackLeavesItsLevelDat() throws Exception { + Path world = this.directory.resolve("saves/World"); + LevelDatFixture.write(world, LevelDatFixture.world("World")); + byte[] before = Files.readAllBytes(world.resolve("level.dat")); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + + edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertArrayEquals(before, Files.readAllBytes(world.resolve("level.dat")), "the game enables a new pack when it loads the world"); + } + + @Test + void aWorldLoadSaveAsksTheReloadThatEnablesTheManagedDatapackOnlyWhereTheServerDoesNotUseIt() throws Exception { + Path world = this.directory.resolve("saves/World"); + LevelDatFixture.write(world, LevelDatFixture.world("World")); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + List sent = new CopyOnWriteArrayList<>(); + edits.location().connected(message -> { + if (SentMessage.of(message).message() instanceof ReloadMessage reload) sent.add(reload.payload()); + return true; + }); + PlayingPayload playing = new PlayingPayload.Singleplayer(world.toString()); + edits.location().playing(playing); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + String biome = "data/testmod/worldgen/biome/glade.json"; + + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""), + new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""))), ""); + assertEquals(Effect.REJOIN, edits.save(biome, bytes("{}")).get(5, TimeUnit.SECONDS).effect()); + assertTrue(sent.isEmpty(), "the world reads the file when it loads again"); + + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""))), ""); + CompletableFuture saved = edits.save(biome, bytes("{\"a\":1}")); + awaitSent(sent, 1); + assertEquals(Set.of(ReloadPayload.Kind.DATA), sent.getFirst().kinds()); + assertEquals(ResourceEdits.PACK_ID, sent.getFirst().managedDataPack(), "the reload enables the managed datapack"); + edits.pipeline().reloads().relayFailed(sent.getFirst().requestId(), "The server does not have TotalDebug"); + assertEquals(Effect.REJOIN, saved.get(5, TimeUnit.SECONDS).effect()); + assertEquals("The server does not have TotalDebug", saved.get().reloadFailure()); + } + @Test void aDataReloadNamesTheWorldItsDataWasWrittenFor() throws Exception { Path world = this.directory.resolve("saves/World"); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java index 40dd4efb..8d540ed8 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java @@ -179,6 +179,36 @@ void thePacksCopyPlaysItsOwnAnimation() throws Exception { } } + @Test + void aSaveIntoAPackWithItsOwnAnimationPlaysThatAnimation() throws Exception { + ResourceEdits edits = ResourceEditsFixture.edits(GameLocations.of(this.directory, false), ChangeRecord.inMemory(), + new ResourceOriginals(this.directory.resolve("total-debug/originals")), Runnable::run, + InstanceState.inMemory()); + edits.packs().named(new ClientPacksPayload(new PackStackPayload(34, List.of(new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""))), 48)); + // The pack has the texture's animation but not the texture: the save keeps the pack's animation. + Path copy = edits.pack(TEXTURE).resolve(TEXTURE); + Files.createDirectories(copy.getParent()); + Files.writeString(copy.resolveSibling("gear.png.mcmeta"), "{\"animation\":{\"frametime\":2}}"); + + TextureEditor[] editor = new TextureEditor[1]; + SwingUtilities.invokeAndWait(() -> editor[0] = new TextureEditor(TEXTURE, "testmod.jar", null, + new LoadedResource.Image(new BufferedImage(4, 8, BufferedImage.TYPE_INT_ARGB), 100), edits, ignored -> { })); + SwingUtilities.invokeAndWait(() -> UiTestScope.showPages(editor[0])); + try { + awaitOnSwing(() -> editor[0].targetBox().getItemCount() > 0); + SwingUtilities.invokeAndWait(() -> { + selectTool(editor[0], "Pencil"); + click(editor[0], new Point(1, 2), 0); + editor[0].save(); + }); + awaitOnSwing(() -> Files.isRegularFile(copy) && !editor[0].modified()); + SwingUtilities.invokeAndWait(() -> assertEquals(4, editor[0].view().shownRegion().height, + "the saved copy plays the pack's animation, two frames of 4 x 4, as the game does")); + } finally { + SwingUtilities.invokeAndWait(editor[0]::dispose); + } + } + /** Clicks the toolbar button with the accessible name {@code name}. */ private static void selectTool(TextureEditor editor, String name) { for (Component component : allComponents(editor.view())) { From 5a79964dd53b796a5d3f858f2f88d2b211927697 Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:24:34 +0200 Subject: [PATCH 2/7] A pack's description is a component as the game's codec reads it, NeoForge's inserting kind too Co-Authored-By: Claude Opus 5.5 (1M context) --- .../catalog/PackFolders.java | 18 +++++++++++++----- .../catalog/PackFoldersTest.java | 10 +++++++--- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index 980f2bb2..0893d7d1 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -14,7 +14,6 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; -import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TreeMap; @@ -32,8 +31,12 @@ public final class PackFolders { public record Meta(String description, int format) { } - /** The keys naming a component's content, one per kind: text, translation, score, selector, key binding, NBT. */ - private static final List COMPONENT_CONTENTS = List.of("text", "translate", "score", "selector", "keybind", "nbt"); + /** + * The kinds of a component's content by the name its {@code type} gives, each with the key holding it: text, + * translation, key binding, score, selector, NBT, and NeoForge's insertion of a translation's argument. + */ + private static final Map COMPONENT_CONTENTS = Map.of("text", "text", "translatable", "translate", + "keybind", "keybind", "score", "score", "selector", "selector", "nbt", "nbt", "neoforge:inserting", "index"); private PackFolders() { } @@ -53,7 +56,8 @@ public static boolean isPack(Path entry) { /** * Whether the game reads {@code value} as a text component (its {@code ComponentSerialization}): text, a list of at - * least one component, or an object with the content of one of its kinds. + * least one component, or an object with the content of the kind its {@code type} names, or without a type, of any + * kind. */ private static boolean isComponent(JsonElement value) { if (value instanceof JsonPrimitive text) return text.isString(); @@ -62,7 +66,11 @@ private static boolean isComponent(JsonElement value) { for (JsonElement element : list) if (!isComponent(element)) return false; return true; } - return value instanceof JsonObject object && COMPONENT_CONTENTS.stream().anyMatch(object::has); + if (!(value instanceof JsonObject object)) return false; + if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(object::has); + String content = object.get("type") instanceof JsonPrimitive type && type.isString() + ? COMPONENT_CONTENTS.get(type.getAsString()) : null; + return content != null && object.has(content); } /** The {@code pack} section of a pack's {@code pack.mcmeta}, or empty without one it can read. */ diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index 7c846b78..dbdadc41 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -36,14 +36,18 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { output.closeEntry(); } Files.writeString(folder.resolve("readme.txt"), ""); - // The game reads the description as a text component, and refuses a list without one or an object without content. + // The game reads the description as a text component, and refuses a list without one, an object without content, + // and one whose type is unknown or names a kind whose content it lacks; NeoForge adds the inserting kind. for (String[] pack : new String[][]{{"EmptyList", "[]"}, {"EmptyObject", "{}"}, {"HalfList", "[\"ok\",{}]"}, - {"Translated", "{\"translate\":\"pack.translated\"}"}}) { + {"Translated", "{\"translate\":\"pack.translated\"}"}, + {"Typed", "{\"type\":\"translatable\",\"translate\":\"pack.typed\"}"}, + {"Mistyped", "{\"type\":\"translatable\",\"text\":\"x\"}"}, {"UnknownType", "{\"type\":\"bogus\",\"text\":\"x\"}"}, + {"Inserting", "{\"type\":\"neoforge:inserting\",\"index\":0}"}, {"InsertingUntyped", "{\"index\":0}"}}) { Files.createDirectories(folder.resolve(pack[0])); Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); } - assertEquals(List.of("file/Faithful", "file/Old.zip", "file/Translated"), List.copyOf(PackFolders.list(folder).keySet()), + assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); assertTrue(PackFolders.list(this.directory.resolve("missing")).isEmpty()); From a5ceb8dfaedd57671ebaa92f1d8d571157700165 Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:38:32 +0200 Subject: [PATCH 3/7] A world-load save's enabling reload reports its problems; a disabled pack in an open world says what enables it - The world-load save that reloads to enable the managed datapack went its own way and dropped the reload's problems with the file; it now takes the normal reload's path, with the files written beside it, and keeps its effect. - A data save into a world open in a game Companion cannot reach said the world uses it when loaded again, though its level.dat disables the managed pack, which the open world owns; it now says the next save after the world closes enables it. - A pack description's content is checked for the value the game's codec reads, not only its key: a string, a score's name and objective, a non-negative index. Probed against NeoForge 21.1.250's content codecs. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../catalog/PackFolders.java | 41 ++++++++++++++----- .../pack/DatapackSelection.java | 7 +++- .../pack/ResourceEdits.java | 41 +++++++++++-------- .../catalog/PackFoldersTest.java | 8 +++- .../pack/ResourceEditsTest.java | 29 +++++++++++++ 5 files changed, 96 insertions(+), 30 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index 0893d7d1..831a0a63 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Optional; import java.util.TreeMap; +import java.util.function.Predicate; import java.util.zip.ZipFile; /** @@ -31,12 +32,27 @@ public final class PackFolders { public record Meta(String description, int format) { } + /** A kind of a component's content: the key holding it, and whether the game reads the value there. */ + private record Content(String key, Predicate valid) { + boolean heldBy(JsonObject component) { + return this.valid.test(component.get(this.key)); + } + } + /** - * The kinds of a component's content by the name its {@code type} gives, each with the key holding it: text, - * translation, key binding, score, selector, NBT, and NeoForge's insertion of a translation's argument. + * The kinds of a component's content by the name its {@code type} gives: text, translation, key binding, score, + * selector, NBT, and NeoForge's insertion of a translation's argument. Selectors and NBT paths are not parsed. */ - private static final Map COMPONENT_CONTENTS = Map.of("text", "text", "translatable", "translate", - "keybind", "keybind", "score", "score", "selector", "selector", "nbt", "nbt", "neoforge:inserting", "index"); + private static final Map COMPONENT_CONTENTS = Map.of( + "text", new Content("text", PackFolders::isString), + "translatable", new Content("translate", PackFolders::isString), + "keybind", new Content("keybind", PackFolders::isString), + "score", new Content("score", value -> value instanceof JsonObject score + && isString(score.get("name")) && isString(score.get("objective"))), + "selector", new Content("selector", PackFolders::isString), + "nbt", new Content("nbt", PackFolders::isString), + "neoforge:inserting", new Content("index", value -> value instanceof JsonPrimitive index && index.isNumber() + && index.getAsNumber().intValue() >= 0)); private PackFolders() { } @@ -56,21 +72,24 @@ public static boolean isPack(Path entry) { /** * Whether the game reads {@code value} as a text component (its {@code ComponentSerialization}): text, a list of at - * least one component, or an object with the content of the kind its {@code type} names, or without a type, of any - * kind. + * least one component, or an object holding the content of the kind its {@code type} names, or without a type, of + * any kind. Read against NeoForge 21.1's codec. */ private static boolean isComponent(JsonElement value) { - if (value instanceof JsonPrimitive text) return text.isString(); + if (value instanceof JsonPrimitive) return isString(value); if (value instanceof JsonArray list) { if (list.isEmpty()) return false; for (JsonElement element : list) if (!isComponent(element)) return false; return true; } if (!(value instanceof JsonObject object)) return false; - if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(object::has); - String content = object.get("type") instanceof JsonPrimitive type && type.isString() - ? COMPONENT_CONTENTS.get(type.getAsString()) : null; - return content != null && object.has(content); + if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(content -> content.heldBy(object)); + Content content = isString(object.get("type")) ? COMPONENT_CONTENTS.get(object.get("type").getAsString()) : null; + return content != null && content.heldBy(object); + } + + private static boolean isString(JsonElement value) { + return value instanceof JsonPrimitive text && text.isString(); } /** The {@code pack} section of a pack's {@code pack.mcmeta}, or empty without one it can read. */ diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java index 7169d999..276aebd8 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java @@ -112,7 +112,7 @@ public void writeFile(List>> writ * it did; a pack named in neither list the game enables itself when it loads the world. Blocking. */ static boolean enableDisabled(Path world, String id) throws IOException { - if (!strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Disabled").contains(id)) return false; + if (!disables(world, id)) return false; LevelDat.update(world, root -> { if (!(root.tag().entries().get("Data") instanceof NbtData.CompoundTag data)) { throw new IOException("The level.dat of " + world.getFileName() + " holds no world data"); @@ -129,6 +129,11 @@ static boolean enableDisabled(Path world, String id) throws IOException { return true; } + /** Whether {@code world}'s {@code level.dat} lists {@code id} as disabled, which the player did. Blocking. */ + static boolean disables(Path world, String id) throws IOException { + return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Disabled").contains(id); + } + /** The datapacks {@code world}'s {@code level.dat} enables, lowest first. Blocking. */ static List saved(Path world) throws IOException { return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Enabled"); diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 1f978049..25bcd53e 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -615,34 +615,43 @@ private CompletableFuture apply(String path, List alsoWatched, Pa } } if (!assets && game.isOpen(world)) { - // Written all the same: the game only reads a datapack, when it loads the world or its data again. - return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "The world " + world.getFileName() - + (game.connected() ? " is open, and the game has not said yet that it plays it" : " is open in a game that is not connected to Companion") - + "; it uses the change when the world is loaded again")); + // Written all the same: the game only reads a datapack, when it loads the world or its data again. Its + // level.dat is the open world's to write, so a pack it disables stays disabled. + String open = "The world " + world.getFileName() + (game.connected() + ? " is open, and the game has not said yet that it plays it" : " is open in a game that is not connected to Companion"); + return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), managed(pack) && disablesManaged(world) + ? open + ", and its level.dat disables the TotalDebug datapack; the next save after the world closes enables it" + : open + "; it uses the change when the world is loaded again")); } return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "")); } GameLocation.Connection connection = ((Access.Live) access).connection(); - if (!assets && apply == ResourcePaths.Apply.WORLD_LOAD) { - if (!managed(pack) || serverEnables(PACK_ID)) return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); - // The world reads the file when it loads again, from the managed pack only if it is enabled: the data reload - // that enables it after any other save enables it here too. - return reload(connection, world, path, PACK_ID).handle((result, failure) -> new Saved(Effect.REJOIN, pack, List.of(), - failure != null ? message(failure) : result.error())); + // The world reads a world-load file when it loads again, from the managed pack only if it is enabled: such a save + // reloads only to enable it, as the reload after any other save does. + boolean worldLoad = !assets && apply == ResourcePaths.Apply.WORLD_LOAD; + if (worldLoad && (!managed(pack) || serverEnables(PACK_ID))) { + return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); } + Effect failed = assets ? Effect.GAME_STARTS : worldLoad ? Effect.REJOIN : Effect.WORLD_OPENS; // Files written beside it join the same reload, which they are part of. String managedPack = managed(pack) ? PACK_ID : ""; for (String beside : alsoWatched) reload(connection, world, beside, managedPack); return reload(connection, world, path, managedPack).handle((result, failure) -> { - if (failure != null) { - return new Saved(assets ? Effect.GAME_STARTS : Effect.WORLD_OPENS, pack, - List.of(), message(failure)); - } - return new Saved(result.error().isEmpty() ? Effect.NOW : assets ? Effect.GAME_STARTS - : Effect.WORLD_OPENS, pack, problemsOf(result, path, alsoWatched), result.error()); + if (failure != null) return new Saved(failed, pack, List.of(), message(failure)); + return new Saved(!result.error().isEmpty() ? failed : worldLoad ? Effect.REJOIN : Effect.NOW, pack, + problemsOf(result, path, alsoWatched), result.error()); }); } + /** Whether {@code world}'s level.dat disables the managed datapack; not when it cannot be read. Blocking. */ + private static boolean disablesManaged(Path world) { + try { + return DatapackSelection.disables(world, PACK_ID); + } catch (IOException | RuntimeException unreadable) { + return false; + } + } + /** Whether the server of the world the game plays named {@code id} among its enabled datapacks. */ private boolean serverEnables(String id) { PackStackPayload datapacks = this.packs.datapacks(); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index dbdadc41..110d9393 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -42,12 +42,16 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { {"Translated", "{\"translate\":\"pack.translated\"}"}, {"Typed", "{\"type\":\"translatable\",\"translate\":\"pack.typed\"}"}, {"Mistyped", "{\"type\":\"translatable\",\"text\":\"x\"}"}, {"UnknownType", "{\"type\":\"bogus\",\"text\":\"x\"}"}, - {"Inserting", "{\"type\":\"neoforge:inserting\",\"index\":0}"}, {"InsertingUntyped", "{\"index\":0}"}}) { + {"Inserting", "{\"type\":\"neoforge:inserting\",\"index\":0}"}, {"InsertingUntyped", "{\"index\":0}"}, + // What the game's codec refuses for its content's value, run against it. + {"NumberText", "{\"text\":1}"}, {"ObjectTranslation", "{\"type\":\"translatable\",\"translate\":{}}"}, + {"NegativeIndex", "{\"index\":-1}"}, {"HalfScore", "{\"score\":{\"name\":\"a\"}}"}, + {"NumberType", "{\"type\":1,\"text\":\"x\"}"}, {"Score", "{\"score\":{\"name\":\"a\",\"objective\":\"b\"}}"}}) { Files.createDirectories(folder.resolve(pack[0])); Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); } - assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), + assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); assertTrue(PackFolders.list(this.directory.resolve("missing")).isEmpty()); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index 09fa3ef9..6ae8b8ac 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -297,6 +297,13 @@ void aWorldLoadSaveAsksTheReloadThatEnablesTheManagedDatapackOnlyWhereTheServerD edits.pipeline().reloads().relayFailed(sent.getFirst().requestId(), "The server does not have TotalDebug"); assertEquals(Effect.REJOIN, saved.get(5, TimeUnit.SECONDS).effect()); assertEquals("The server does not have TotalDebug", saved.get().reloadFailure()); + + CompletableFuture parsed = edits.save(biome, bytes("{\"a\":2}")); + awaitSent(sent, 2); + edits.pipeline().reloads().answered(new ReloadResultPayload(sent.get(1).requestId(), 10, + List.of(new ReloadResultPayload.Problem(biome, "Unknown biome field a")), "")); + assertEquals(Effect.REJOIN, parsed.get(5, TimeUnit.SECONDS).effect()); + assertEquals(List.of("Unknown biome field a"), parsed.get().problems(), "the reload's problems with the file are the save's"); } @Test @@ -366,6 +373,28 @@ void aDatapackOfAWorldTheUnconnectedGameHasOpenIsWrittenForItsNextLoad() throws } } + @Test + void aDatapackOfAWorldTheUnconnectedGameHasOpenWithTheManagedPackDisabledSaysWhatEnablesIt() throws Exception { + Path world = this.directory.resolve("saves/World"); + Map data = LevelDatFixture.world("World"); + data.put("DataPacks", Map.of("Enabled", List.of("vanilla"), "Disabled", List.of(ResourceEdits.PACK_ID))); + LevelDatFixture.write(world, data); + byte[] levelDat = Files.readAllBytes(world.resolve("level.dat")); + Path pack = Files.createDirectories(world.resolve("datapacks/TotalDebug")); + Files.writeString(pack.resolve("pack.mcmeta"), "{\"pack\":{\"pack_format\":48,\"description\":\"\"}}"); + ResourceEdits edits = ResourceEditsFixture.edits(GameLocations.of(this.directory, true), ChangeRecord.inMemory(), + new ResourceOriginals(this.directory.resolve("total-debug/originals")), Runnable::run, InstanceState.inMemory()); + + try (FileChannel channel = FileChannel.open(world.resolve("session.lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE); + FileLock ignored = channel.lock()) { + ResourceEdits.Saved saved = edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertEquals("The world World is open in a game that is not connected to Companion, and its level.dat disables the " + + "TotalDebug datapack; the next save after the world closes enables it", saved.reloadFailure()); + } + assertArrayEquals(levelDat, Files.readAllBytes(world.resolve("level.dat")), "the open world's level.dat is its own to write"); + } + @Test void aWorldsDataReloadsInItsOwnQueueWhichLeavingTheWorldDrops() throws Exception { Path first = this.directory.resolve("saves/First"); From e6b48524bc5c38b311ebfda4f1faff6c811b628a Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:48:52 +0200 Subject: [PATCH 4/7] A save moves the managed datapack a closed world enables lower to the top; an NBT description needs its source - A closed world's level.dat that enabled the managed datapack below another pack kept it there, so a pack above it that supplies the same file still won at the next load; a save now moves it on top, as a live save's reload does. - An NBT component needs a block, entity or storage beside its path, as the game's codec does. What the game parses further (selectors, NBT paths, positions, ids) is taken as written, and the doc says so. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../catalog/PackFolders.java | 40 +++++++++---------- .../pack/DatapackSelection.java | 12 ++++-- .../pack/ResourceEdits.java | 7 ++-- .../catalog/PackFoldersTest.java | 6 ++- .../pack/ResourceEditsTest.java | 18 +++++++++ 5 files changed, 52 insertions(+), 31 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index 831a0a63..f98ce033 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -32,27 +32,23 @@ public final class PackFolders { public record Meta(String description, int format) { } - /** A kind of a component's content: the key holding it, and whether the game reads the value there. */ - private record Content(String key, Predicate valid) { - boolean heldBy(JsonObject component) { - return this.valid.test(component.get(this.key)); - } - } - /** - * The kinds of a component's content by the name its {@code type} gives: text, translation, key binding, score, - * selector, NBT, and NeoForge's insertion of a translation's argument. Selectors and NBT paths are not parsed. + * The kinds of a component's content by the name its {@code type} gives, each with whether a component holds the + * fields the game's codec requires of it: text, translation, key binding, score, selector, NBT with its source, and + * NeoForge's insertion of a translation's argument. What the game parses further, selectors, NBT paths, block + * positions and resource ids, is taken as written. */ - private static final Map COMPONENT_CONTENTS = Map.of( - "text", new Content("text", PackFolders::isString), - "translatable", new Content("translate", PackFolders::isString), - "keybind", new Content("keybind", PackFolders::isString), - "score", new Content("score", value -> value instanceof JsonObject score - && isString(score.get("name")) && isString(score.get("objective"))), - "selector", new Content("selector", PackFolders::isString), - "nbt", new Content("nbt", PackFolders::isString), - "neoforge:inserting", new Content("index", value -> value instanceof JsonPrimitive index && index.isNumber() - && index.getAsNumber().intValue() >= 0)); + private static final Map> COMPONENT_CONTENTS = Map.of( + "text", component -> isString(component.get("text")), + "translatable", component -> isString(component.get("translate")), + "keybind", component -> isString(component.get("keybind")), + "score", component -> component.get("score") instanceof JsonObject score + && isString(score.get("name")) && isString(score.get("objective")), + "selector", component -> isString(component.get("selector")), + "nbt", component -> isString(component.get("nbt")) && (isString(component.get("block")) + || isString(component.get("entity")) || isString(component.get("storage"))), + "neoforge:inserting", component -> component.get("index") instanceof JsonPrimitive index && index.isNumber() + && index.getAsNumber().intValue() >= 0); private PackFolders() { } @@ -83,9 +79,9 @@ private static boolean isComponent(JsonElement value) { return true; } if (!(value instanceof JsonObject object)) return false; - if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(content -> content.heldBy(object)); - Content content = isString(object.get("type")) ? COMPONENT_CONTENTS.get(object.get("type").getAsString()) : null; - return content != null && content.heldBy(object); + if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(content -> content.test(object)); + Predicate content = isString(object.get("type")) ? COMPONENT_CONTENTS.get(object.get("type").getAsString()) : null; + return content != null && content.test(object); } private static boolean isString(JsonElement value) { diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java index 276aebd8..bc01303b 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java @@ -108,11 +108,15 @@ public void writeFile(List>> writ } /** - * Enables {@code id} at the top of {@code world}'s datapacks where its {@code level.dat} disables it, and tells whether - * it did; a pack named in neither list the game enables itself when it loads the world. Blocking. + * Enables {@code id} at the top of {@code world}'s datapacks where its {@code level.dat} disables it or enables it + * lower, as the data reload of a live save does, and tells whether it changed them; a pack named in neither list the + * game enables itself on top when it loads the world. Blocking. */ - static boolean enableDisabled(Path world, String id) throws IOException { - if (!disables(world, id)) return false; + static boolean enableOnTop(Path world, String id) throws IOException { + NbtData.CompoundTag named = dataPacks(LevelDat.read(LevelDat.file(world)).tag()); + List enabledNow = strings(named, "Enabled"); + boolean disabledNow = strings(named, "Disabled").contains(id); + if (!disabledNow && (!enabledNow.contains(id) || enabledNow.getLast().equals(id))) return false; LevelDat.update(world, root -> { if (!(root.tag().entries().get("Data") instanceof NbtData.CompoundTag data)) { throw new IOException("The level.dat of " + world.getFileName() + " holds no world data"); diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 25bcd53e..d7849046 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -602,10 +602,11 @@ private CompletableFuture apply(String path, List alsoWatched, Pa } } if (!assets && managed(pack) && !game.isOpen(world)) { - // A world enables a datapack it has not seen when it loads, but not one its level.dat disables, which the - // player did; a save into the managed pack enables it, as the reload of a live save does. + // A world enables a datapack it has not seen on top when it loads, but not one its level.dat disables or + // keeps lower, as the player chose; a save into the managed pack enables it on top, as a live save's + // reload does. try { - if (DatapackSelection.enableDisabled(world, PACK_ID)) { + if (DatapackSelection.enableOnTop(world, PACK_ID)) { this.landed.incrementAndGet(); this.packs.written(ChangeRecord.PackSide.DATA); } diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index 110d9393..8beddf19 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -46,12 +46,14 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { // What the game's codec refuses for its content's value, run against it. {"NumberText", "{\"text\":1}"}, {"ObjectTranslation", "{\"type\":\"translatable\",\"translate\":{}}"}, {"NegativeIndex", "{\"index\":-1}"}, {"HalfScore", "{\"score\":{\"name\":\"a\"}}"}, - {"NumberType", "{\"type\":1,\"text\":\"x\"}"}, {"Score", "{\"score\":{\"name\":\"a\",\"objective\":\"b\"}}"}}) { + {"NumberType", "{\"type\":1,\"text\":\"x\"}"}, {"Score", "{\"score\":{\"name\":\"a\",\"objective\":\"b\"}}"}, + {"SourcelessNbt", "{\"nbt\":\"a\"}"}, {"StoredNbt", "{\"nbt\":\"a\",\"storage\":\"minecraft:x\"}"}}) { Files.createDirectories(folder.resolve(pack[0])); Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); } - assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), + assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", + "file/StoredNbt", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); assertTrue(PackFolders.list(this.directory.resolve("missing")).isEmpty()); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index 6ae8b8ac..4971e836 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -256,6 +256,24 @@ void aSaveIntoAClosedWorldThatDisabledTheManagedDatapackEnablesItThere() throws "the player's other choices stay"); } + @Test + void aSaveIntoAClosedWorldThatEnablesTheManagedDatapackLowerMovesItOnTop() throws Exception { + Path world = this.directory.resolve("saves/World"); + Map data = LevelDatFixture.world("World"); + data.put("DataPacks", Map.of("Enabled", List.of("vanilla", ResourceEdits.PACK_ID, "file/Other"), "Disabled", List.of())); + LevelDatFixture.write(world, data); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + + edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + assertEquals(List.of("vanilla", "file/Other", ResourceEdits.PACK_ID), DatapackSelection.saved(world), + "above a pack that may supply the same file, as a reload places it"); + + byte[] onTop = Files.readAllBytes(world.resolve("level.dat")); + edits.save("data/testmod/recipe/gear.json", bytes("{\"a\":1}")).get(5, TimeUnit.SECONDS); + assertArrayEquals(onTop, Files.readAllBytes(world.resolve("level.dat")), "a pack on top already stays as it is"); + } + @Test void aSaveIntoAClosedWorldThatDoesNotNameTheManagedDatapackLeavesItsLevelDat() throws Exception { Path world = this.directory.resolve("saves/World"); From d88371d455d9779cea2462feb99064043264c522 Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:00:55 +0200 Subject: [PATCH 5/7] A world-load save reloads unless the managed datapack is on top; a description's extra is a list of components Co-Authored-By: Claude Opus 5.5 (1M context) --- .../totalDebugCompanion/catalog/PackFolders.java | 6 +++++- .../totalDebugCompanion/pack/ResourceEdits.java | 11 +++++++---- .../totalDebugCompanion/catalog/PackFoldersTest.java | 6 ++++-- .../totalDebugCompanion/pack/ResourceEditsTest.java | 9 +++++++++ 4 files changed, 25 insertions(+), 7 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index f98ce033..c6cde520 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -36,7 +36,7 @@ public record Meta(String description, int format) { * The kinds of a component's content by the name its {@code type} gives, each with whether a component holds the * fields the game's codec requires of it: text, translation, key binding, score, selector, NBT with its source, and * NeoForge's insertion of a translation's argument. What the game parses further, selectors, NBT paths, block - * positions and resource ids, is taken as written. + * positions, resource ids and the style's fields (color, font, events), is taken as written. */ private static final Map> COMPONENT_CONTENTS = Map.of( "text", component -> isString(component.get("text")), @@ -79,6 +79,10 @@ private static boolean isComponent(JsonElement value) { return true; } if (!(value instanceof JsonObject object)) return false; + // Its siblings are components of their own, at least one. + if (object.has("extra") && !(object.get("extra") instanceof JsonArray extra && !extra.isEmpty() && isComponent(extra))) { + return false; + } if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(content -> content.test(object)); Predicate content = isString(object.get("type")) ? COMPONENT_CONTENTS.get(object.get("type").getAsString()) : null; return content != null && content.test(object); diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index d7849046..44ee5a6b 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -630,7 +630,7 @@ private CompletableFuture apply(String path, List alsoWatched, Pa // The world reads a world-load file when it loads again, from the managed pack only if it is enabled: such a save // reloads only to enable it, as the reload after any other save does. boolean worldLoad = !assets && apply == ResourcePaths.Apply.WORLD_LOAD; - if (worldLoad && (!managed(pack) || serverEnables(PACK_ID))) { + if (worldLoad && (!managed(pack) || serverHasOnTop(PACK_ID))) { return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); } Effect failed = assets ? Effect.GAME_STARTS : worldLoad ? Effect.REJOIN : Effect.WORLD_OPENS; @@ -653,10 +653,13 @@ private static boolean disablesManaged(Path world) { } } - /** Whether the server of the world the game plays named {@code id} among its enabled datapacks. */ - private boolean serverEnables(String id) { + /** + * Whether the server of the world the game plays named {@code id} as its highest enabled datapack, so no other one + * can supply a file it holds. A pack fixed above it makes every such save reload, which places it as high as it goes. + */ + private boolean serverHasOnTop(String id) { PackStackPayload datapacks = this.packs.datapacks(); - return datapacks != null && datapacks.enabled().stream().anyMatch(enabled -> enabled.id().equals(id)); + return datapacks != null && !datapacks.enabled().isEmpty() && datapacks.enabled().getLast().id().equals(id); } /** Asks the game to reload what {@code path} needs: the client's resources, or the data of {@code world}. */ diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index 8beddf19..ad0ab6b2 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -47,12 +47,14 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { {"NumberText", "{\"text\":1}"}, {"ObjectTranslation", "{\"type\":\"translatable\",\"translate\":{}}"}, {"NegativeIndex", "{\"index\":-1}"}, {"HalfScore", "{\"score\":{\"name\":\"a\"}}"}, {"NumberType", "{\"type\":1,\"text\":\"x\"}"}, {"Score", "{\"score\":{\"name\":\"a\",\"objective\":\"b\"}}"}, - {"SourcelessNbt", "{\"nbt\":\"a\"}"}, {"StoredNbt", "{\"nbt\":\"a\",\"storage\":\"minecraft:x\"}"}}) { + {"SourcelessNbt", "{\"nbt\":\"a\"}"}, {"StoredNbt", "{\"nbt\":\"a\",\"storage\":\"minecraft:x\"}"}, + {"ObjectExtra", "{\"text\":\"a\",\"extra\":{}}"}, {"EmptyExtra", "{\"text\":\"a\",\"extra\":[]}"}, + {"Extra", "{\"text\":\"a\",\"extra\":[\"b\",{\"text\":\"c\"}]}"}}) { Files.createDirectories(folder.resolve(pack[0])); Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); } - assertEquals(List.of("file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", + assertEquals(List.of("file/Extra", "file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", "file/StoredNbt", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index 4971e836..e742b33a 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -307,6 +307,15 @@ void aWorldLoadSaveAsksTheReloadThatEnablesTheManagedDatapackOnlyWhereTheServerD assertEquals(Effect.REJOIN, edits.save(biome, bytes("{}")).get(5, TimeUnit.SECONDS).effect()); assertTrue(sent.isEmpty(), "the world reads the file when it loads again"); + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""), + new PackStackPayload.Pack("file/Other", "Other", ""))), ""); + CompletableFuture below = edits.save(biome, bytes("{\"b\":1}")); + awaitSent(sent, 1); + assertEquals(ResourceEdits.PACK_ID, sent.getFirst().managedDataPack(), "a pack above it could supply the file; the reload places it on top"); + edits.pipeline().reloads().answered(new ReloadResultPayload(sent.getFirst().requestId(), 10, List.of(), "")); + assertEquals(Effect.REJOIN, below.get(5, TimeUnit.SECONDS).effect()); + sent.clear(); + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""))), ""); CompletableFuture saved = edits.save(biome, bytes("{\"a\":1}")); awaitSent(sent, 1); From a618367d3cf38fa10a85c7215655f9b9a4c2c36d Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:15:18 +0200 Subject: [PATCH 6/7] Leave pack descriptions and datapack order to the game - PackFolders goes back to how 1.21.1 reads a description: Companion cannot run the game's component codec, and a copy of it by hand never ends. Item 3 of the plan is dropped. - A save into a closed world takes the managed datapack off the ones level.dat disables, and moves nothing: the game enables it as a pack it has not seen, where it places any new pack. The enabled packs, which Companion records as the world's selection, stay as they are. - A world-load save reloads where the server does not enable the managed pack, as in round 1. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../catalog/PackFolders.java | 49 ++----------------- .../pack/DatapackSelection.java | 18 +++---- .../pack/ResourceEdits.java | 18 +++---- .../catalog/PackFoldersTest.java | 20 +------- .../pack/ResourceEditsTest.java | 29 +---------- 5 files changed, 19 insertions(+), 115 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java index c6cde520..fc5326dd 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFolders.java @@ -17,7 +17,6 @@ import java.util.Map; import java.util.Optional; import java.util.TreeMap; -import java.util.function.Predicate; import java.util.zip.ZipFile; /** @@ -32,24 +31,6 @@ public final class PackFolders { public record Meta(String description, int format) { } - /** - * The kinds of a component's content by the name its {@code type} gives, each with whether a component holds the - * fields the game's codec requires of it: text, translation, key binding, score, selector, NBT with its source, and - * NeoForge's insertion of a translation's argument. What the game parses further, selectors, NBT paths, block - * positions, resource ids and the style's fields (color, font, events), is taken as written. - */ - private static final Map> COMPONENT_CONTENTS = Map.of( - "text", component -> isString(component.get("text")), - "translatable", component -> isString(component.get("translate")), - "keybind", component -> isString(component.get("keybind")), - "score", component -> component.get("score") instanceof JsonObject score - && isString(score.get("name")) && isString(score.get("objective")), - "selector", component -> isString(component.get("selector")), - "nbt", component -> isString(component.get("nbt")) && (isString(component.get("block")) - || isString(component.get("entity")) || isString(component.get("storage"))), - "neoforge:inserting", component -> component.get("index") instanceof JsonPrimitive index && index.isNumber() - && index.getAsNumber().intValue() >= 0); - private PackFolders() { } @@ -62,34 +43,10 @@ public static boolean isPack(Path entry) { if (!Files.isDirectory(entry) && !(Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(".zip"))) { return false; } + // The description is a text component: text, a list or an object; null or a number is none. return section(entry).filter(section -> section.get("pack_format") instanceof JsonPrimitive format && format.isNumber() - && isComponent(section.get("description"))).isPresent(); - } - - /** - * Whether the game reads {@code value} as a text component (its {@code ComponentSerialization}): text, a list of at - * least one component, or an object holding the content of the kind its {@code type} names, or without a type, of - * any kind. Read against NeoForge 21.1's codec. - */ - private static boolean isComponent(JsonElement value) { - if (value instanceof JsonPrimitive) return isString(value); - if (value instanceof JsonArray list) { - if (list.isEmpty()) return false; - for (JsonElement element : list) if (!isComponent(element)) return false; - return true; - } - if (!(value instanceof JsonObject object)) return false; - // Its siblings are components of their own, at least one. - if (object.has("extra") && !(object.get("extra") instanceof JsonArray extra && !extra.isEmpty() && isComponent(extra))) { - return false; - } - if (!object.has("type")) return COMPONENT_CONTENTS.values().stream().anyMatch(content -> content.test(object)); - Predicate content = isString(object.get("type")) ? COMPONENT_CONTENTS.get(object.get("type").getAsString()) : null; - return content != null && content.test(object); - } - - private static boolean isString(JsonElement value) { - return value instanceof JsonPrimitive text && text.isString(); + && (section.get("description") instanceof JsonPrimitive text && text.isString() + || section.get("description") instanceof JsonArray || section.get("description") instanceof JsonObject)).isPresent(); } /** The {@code pack} section of a pack's {@code pack.mcmeta}, or empty without one it can read. */ diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java index bc01303b..b987d892 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java @@ -108,26 +108,20 @@ public void writeFile(List>> writ } /** - * Enables {@code id} at the top of {@code world}'s datapacks where its {@code level.dat} disables it or enables it - * lower, as the data reload of a live save does, and tells whether it changed them; a pack named in neither list the - * game enables itself on top when it loads the world. Blocking. + * Takes {@code id} off the datapacks {@code world}'s {@code level.dat} disables, and tells whether it was there. The + * game then enables it as a pack it has not seen when it loads the world, placing it as it places any new pack; the + * enabled packs, the selection Companion records, stay as they are. Blocking. */ - static boolean enableOnTop(Path world, String id) throws IOException { - NbtData.CompoundTag named = dataPacks(LevelDat.read(LevelDat.file(world)).tag()); - List enabledNow = strings(named, "Enabled"); - boolean disabledNow = strings(named, "Disabled").contains(id); - if (!disabledNow && (!enabledNow.contains(id) || enabledNow.getLast().equals(id))) return false; + static boolean enableDisabled(Path world, String id) throws IOException { + if (!disables(world, id)) return false; LevelDat.update(world, root -> { if (!(root.tag().entries().get("Data") instanceof NbtData.CompoundTag data)) { throw new IOException("The level.dat of " + world.getFileName() + " holds no world data"); } NbtData.CompoundTag packs = dataPacks(root.tag()); - List enabled = new ArrayList<>(strings(packs, "Enabled")); List disabled = new ArrayList<>(strings(packs, "Disabled")); - enabled.remove(id); - enabled.add(id); disabled.remove(id); - NbtData.CompoundTag written = LevelDat.with(LevelDat.with(packs, "Enabled", list(enabled)), "Disabled", list(disabled)); + NbtData.CompoundTag written = LevelDat.with(packs, "Disabled", list(disabled)); return new LevelDat.Root(root.name(), LevelDat.with(root.tag(), "Data", LevelDat.with(data, "DataPacks", written))); }); return true; diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 44ee5a6b..25bcd53e 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -602,11 +602,10 @@ private CompletableFuture apply(String path, List alsoWatched, Pa } } if (!assets && managed(pack) && !game.isOpen(world)) { - // A world enables a datapack it has not seen on top when it loads, but not one its level.dat disables or - // keeps lower, as the player chose; a save into the managed pack enables it on top, as a live save's - // reload does. + // A world enables a datapack it has not seen when it loads, but not one its level.dat disables, which the + // player did; a save into the managed pack enables it, as the reload of a live save does. try { - if (DatapackSelection.enableOnTop(world, PACK_ID)) { + if (DatapackSelection.enableDisabled(world, PACK_ID)) { this.landed.incrementAndGet(); this.packs.written(ChangeRecord.PackSide.DATA); } @@ -630,7 +629,7 @@ private CompletableFuture apply(String path, List alsoWatched, Pa // The world reads a world-load file when it loads again, from the managed pack only if it is enabled: such a save // reloads only to enable it, as the reload after any other save does. boolean worldLoad = !assets && apply == ResourcePaths.Apply.WORLD_LOAD; - if (worldLoad && (!managed(pack) || serverHasOnTop(PACK_ID))) { + if (worldLoad && (!managed(pack) || serverEnables(PACK_ID))) { return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); } Effect failed = assets ? Effect.GAME_STARTS : worldLoad ? Effect.REJOIN : Effect.WORLD_OPENS; @@ -653,13 +652,10 @@ private static boolean disablesManaged(Path world) { } } - /** - * Whether the server of the world the game plays named {@code id} as its highest enabled datapack, so no other one - * can supply a file it holds. A pack fixed above it makes every such save reload, which places it as high as it goes. - */ - private boolean serverHasOnTop(String id) { + /** Whether the server of the world the game plays named {@code id} among its enabled datapacks. */ + private boolean serverEnables(String id) { PackStackPayload datapacks = this.packs.datapacks(); - return datapacks != null && !datapacks.enabled().isEmpty() && datapacks.enabled().getLast().id().equals(id); + return datapacks != null && datapacks.enabled().stream().anyMatch(enabled -> enabled.id().equals(id)); } /** Asks the game to reload what {@code path} needs: the client's resources, or the data of {@code world}. */ diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java index ad0ab6b2..d13f31a8 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/catalog/PackFoldersTest.java @@ -36,26 +36,8 @@ void packsAreFoldersWithPackMcmetaOrZipFiles() throws Exception { output.closeEntry(); } Files.writeString(folder.resolve("readme.txt"), ""); - // The game reads the description as a text component, and refuses a list without one, an object without content, - // and one whose type is unknown or names a kind whose content it lacks; NeoForge adds the inserting kind. - for (String[] pack : new String[][]{{"EmptyList", "[]"}, {"EmptyObject", "{}"}, {"HalfList", "[\"ok\",{}]"}, - {"Translated", "{\"translate\":\"pack.translated\"}"}, - {"Typed", "{\"type\":\"translatable\",\"translate\":\"pack.typed\"}"}, - {"Mistyped", "{\"type\":\"translatable\",\"text\":\"x\"}"}, {"UnknownType", "{\"type\":\"bogus\",\"text\":\"x\"}"}, - {"Inserting", "{\"type\":\"neoforge:inserting\",\"index\":0}"}, {"InsertingUntyped", "{\"index\":0}"}, - // What the game's codec refuses for its content's value, run against it. - {"NumberText", "{\"text\":1}"}, {"ObjectTranslation", "{\"type\":\"translatable\",\"translate\":{}}"}, - {"NegativeIndex", "{\"index\":-1}"}, {"HalfScore", "{\"score\":{\"name\":\"a\"}}"}, - {"NumberType", "{\"type\":1,\"text\":\"x\"}"}, {"Score", "{\"score\":{\"name\":\"a\",\"objective\":\"b\"}}"}, - {"SourcelessNbt", "{\"nbt\":\"a\"}"}, {"StoredNbt", "{\"nbt\":\"a\",\"storage\":\"minecraft:x\"}"}, - {"ObjectExtra", "{\"text\":\"a\",\"extra\":{}}"}, {"EmptyExtra", "{\"text\":\"a\",\"extra\":[]}"}, - {"Extra", "{\"text\":\"a\",\"extra\":[\"b\",{\"text\":\"c\"}]}"}}) { - Files.createDirectories(folder.resolve(pack[0])); - Files.writeString(folder.resolve(pack[0] + "/pack.mcmeta"), "{\"pack\":{\"pack_format\":34,\"description\":" + pack[1] + "}}"); - } - assertEquals(List.of("file/Extra", "file/Faithful", "file/Inserting", "file/InsertingUntyped", "file/Old.zip", "file/Score", - "file/StoredNbt", "file/Translated", "file/Typed"), List.copyOf(PackFolders.list(folder).keySet()), + assertEquals(List.of("file/Faithful", "file/Old.zip"), List.copyOf(PackFolders.list(folder).keySet()), "a folder or zip without readable pack metadata at its root and other files are no packs, as for the game"); assertEquals("Old.zip", PackFolders.title(folder.resolve("Old.zip")), "the game titles a zip pack with its file name"); assertTrue(PackFolders.list(this.directory.resolve("missing")).isEmpty()); diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index e742b33a..ad2ed6df 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -249,31 +249,14 @@ void aSaveIntoAClosedWorldThatDisabledTheManagedDatapackEnablesItThere() throws assertEquals(Effect.WORLD_OPENS, saved.effect()); assertEquals("", saved.reloadFailure()); - assertEquals(List.of("vanilla", ResourceEdits.PACK_ID), DatapackSelection.saved(world), "enabled at the top, as a reload enables it"); + assertEquals(List.of("vanilla"), DatapackSelection.saved(world), + "the game enables it as a pack it has not seen, where it places any new pack; the recorded selection stays"); NbtData.CompoundTag packs = (NbtData.CompoundTag) ((NbtData.CompoundTag) LevelDat.read(LevelDat.file(world)).tag() .entries().get("Data")).entries().get("DataPacks"); assertEquals(List.of(new NbtData.StringTag("file/Off")), ((NbtData.ListTag) packs.entries().get("Disabled")).items(), "the player's other choices stay"); } - @Test - void aSaveIntoAClosedWorldThatEnablesTheManagedDatapackLowerMovesItOnTop() throws Exception { - Path world = this.directory.resolve("saves/World"); - Map data = LevelDatFixture.world("World"); - data.put("DataPacks", Map.of("Enabled", List.of("vanilla", ResourceEdits.PACK_ID, "file/Other"), "Disabled", List.of())); - LevelDatFixture.write(world, data); - ResourceEdits edits = edits(ChangeRecord.inMemory()); - edits.packs().named(new ClientPacksPayload(STACK, 48)); - - edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); - assertEquals(List.of("vanilla", "file/Other", ResourceEdits.PACK_ID), DatapackSelection.saved(world), - "above a pack that may supply the same file, as a reload places it"); - - byte[] onTop = Files.readAllBytes(world.resolve("level.dat")); - edits.save("data/testmod/recipe/gear.json", bytes("{\"a\":1}")).get(5, TimeUnit.SECONDS); - assertArrayEquals(onTop, Files.readAllBytes(world.resolve("level.dat")), "a pack on top already stays as it is"); - } - @Test void aSaveIntoAClosedWorldThatDoesNotNameTheManagedDatapackLeavesItsLevelDat() throws Exception { Path world = this.directory.resolve("saves/World"); @@ -307,14 +290,6 @@ void aWorldLoadSaveAsksTheReloadThatEnablesTheManagedDatapackOnlyWhereTheServerD assertEquals(Effect.REJOIN, edits.save(biome, bytes("{}")).get(5, TimeUnit.SECONDS).effect()); assertTrue(sent.isEmpty(), "the world reads the file when it loads again"); - edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""), - new PackStackPayload.Pack("file/Other", "Other", ""))), ""); - CompletableFuture below = edits.save(biome, bytes("{\"b\":1}")); - awaitSent(sent, 1); - assertEquals(ResourceEdits.PACK_ID, sent.getFirst().managedDataPack(), "a pack above it could supply the file; the reload places it on top"); - edits.pipeline().reloads().answered(new ReloadResultPayload(sent.getFirst().requestId(), 10, List.of(), "")); - assertEquals(Effect.REJOIN, below.get(5, TimeUnit.SECONDS).effect()); - sent.clear(); edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""))), ""); CompletableFuture saved = edits.save(biome, bytes("{\"a\":1}")); From 23e1921fca172f4079addb0648817969e39993b0 Mon Sep 17 00:00:00 2001 From: Pelotrio <45769595+Pelotrio@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:21:52 +0200 Subject: [PATCH 7/7] An open world whose level.dat cannot be read says so instead of promising the next load Co-Authored-By: Claude Opus 5.5 (1M context) --- .../totalDebugCompanion/pack/ResourceEdits.java | 15 ++++++++------- .../pack/ResourceEditsTest.java | 5 +++++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 25bcd53e..d6361f6f 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -619,9 +619,8 @@ private CompletableFuture apply(String path, List alsoWatched, Pa // level.dat is the open world's to write, so a pack it disables stays disabled. String open = "The world " + world.getFileName() + (game.connected() ? " is open, and the game has not said yet that it plays it" : " is open in a game that is not connected to Companion"); - return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), managed(pack) && disablesManaged(world) - ? open + ", and its level.dat disables the TotalDebug datapack; the next save after the world closes enables it" - : open + "; it uses the change when the world is loaded again")); + return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), open + (managed(pack) ? whenLoaded(world) + : "; it uses the change when the world is loaded again"))); } return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "")); } @@ -643,12 +642,14 @@ private CompletableFuture apply(String path, List alsoWatched, Pa }); } - /** Whether {@code world}'s level.dat disables the managed datapack; not when it cannot be read. Blocking. */ - private static boolean disablesManaged(Path world) { + /** Whether an open world uses a change to the managed datapack when it loads again, as its level.dat says. Blocking. */ + private static String whenLoaded(Path world) { try { - return DatapackSelection.disables(world, PACK_ID); + return DatapackSelection.disables(world, PACK_ID) + ? ", and its level.dat disables the TotalDebug datapack; the next save after the world closes enables it" + : "; it uses the change when the world is loaded again"; } catch (IOException | RuntimeException unreadable) { - return false; + return ", and whether its level.dat enables the TotalDebug datapack could not be read: " + unreadable.getMessage(); } } diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index ad2ed6df..647ffcb1 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -372,6 +372,11 @@ void aDatapackOfAWorldTheUnconnectedGameHasOpenIsWrittenForItsNextLoad() throws assertEquals(Effect.WORLD_OPENS, saved.effect()); assertEquals("The world World is open in a game that is not connected to Companion; it uses the change when the world is loaded again", saved.reloadFailure()); + + Files.write(world.resolve("level.dat"), new byte[]{1, 2, 3}); + String unread = edits.save("data/testmod/recipe/gear.json", bytes("{\"a\":1}")).get(5, TimeUnit.SECONDS).reloadFailure(); + assertTrue(unread.startsWith("The world World is open in a game that is not connected to Companion, and whether its " + + "level.dat enables the TotalDebug datapack could not be read: "), unread); } }