feat(studio): ship JavaFX 2 Play and delegate integration tooling
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit

Launch the JavaFX 2 project shell on Java 25 with an interactive viewport,
managed Play lifecycle and project mutation guards. Preserve headless/MCP and
save compatibility, and qualify exact runtime executable bundles.
Separate unit JaCoCo gates from opt-in integration suites and use the internal
Pong fixture for the headless visual pilot.
Move maintenance and native conformance tools into tooling; retain the VS Code
extension and update current navigation links.

Validation: tooling make verify passed, including 1064 Studio unit tests,
JaCoCo thresholds and 22 headless integration tests.
This commit is contained in:
2026-11-19 17:32:03 +00:00
parent 1e17fc4d67
commit 71fb80efc3
163 changed files with 5929 additions and 4950 deletions
@@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
/** Uses the actual desktop toolkit; runtime, operation and document inputs are test consumers only. */
@org.junit.jupiter.api.Tag("integration")
class DevDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit() throws Exception {
@@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@org.junit.jupiter.api.Tag("integration")
class StudioApplicationConfigurationTest {
@Test
void bootsAndClosesWithoutAWebApplicationContext() {
@@ -0,0 +1,235 @@
package p.studio.app;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.application.Platform;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.stage.Stage;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import p.studio.api.execution.*;
import p.studio.api.project.*;
import p.studio.api.session.ProjectSessionFactory;
import p.studio.core.project.*;
import p.studio.core.execution.DefaultExecutionControllerFactory;
import p.studio.app.runtime.studio.StudioRuntimeGateway;
import p.studio.ui.javafx2.window.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
/** Actual new frontend, real compiler/packer and direct installed native process. */
@org.junit.jupiter.api.Tag("integration")
class StudioPlayDesktopTest {
@TempDir Path temporary;
static <T> T fx(Callable<T> action)throws Exception{
var future=new CompletableFuture<T>();Platform.runLater(()->{try{future.complete(action.call());}catch(Throwable f){future.completeExceptionally(f);}});
return future.get(15,TimeUnit.SECONDS);
}
@BeforeAll static void toolkit()throws Exception{
var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);
}
@AfterAll static void stopToolkit(){Platform.exit();}
private static void await(BooleanSupplier condition,Supplier<String> failure)throws Exception{
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
while(System.nanoTime()<deadline){if(condition.getAsBoolean())return;Thread.sleep(25);}fail(failure.get());
}
@Test void realPongProjectPlayZoomPauseFocusStopAndClose()throws Exception{
Path source=Path.of(System.getProperty("studio.test.pong")),root=temporary.resolve("Pong Project");
try(var files=Files.walk(source)){for(Path file:files.toList()){
Path relative=source.relativize(file);if(relative.toString().startsWith(".")||relative.toString().startsWith("build"))continue;
Path target=root.resolve(relative);if(Files.isDirectory(file))Files.createDirectories(target);else Files.copy(file,target);
}}
var resources=new WindowResources();
try(var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run()){
var catalog=app.getBean(ProjectCatalog.class);var setups=app.getBean(ProjectLocalStudioSetupStore.class);
var ref=catalog.openProject(root);setups.save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
var access=app.getBean(ProjectAccessRegistry.class);var executor=app.getBean("studioExecutor",ExecutorService.class);
var delayedPause=new java.util.concurrent.atomic.AtomicBoolean();
var oldPause=new java.util.concurrent.atomic.AtomicReference<CompletableFuture<Void>>();
var nativeGateway=new StudioRuntimeGateway(app.getBean(ObjectMapper.class));
p.studio.core.runtime.RuntimeGateway gateway=new p.studio.core.runtime.RuntimeGateway(){
public boolean interactive(){return true;}
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs)throws Exception{return start(p,s,logs,PlayOptions.PERSISTENT);}
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs,PlayOptions options)throws Exception{
var actual=nativeGateway.start(p,s,logs,options);
return new p.studio.core.runtime.RuntimeConnection(){
public CompletableFuture<Integer> completion(){return actual.completion();}
public CompletableFuture<Void> startExecution(){return actual.startExecution();}
public CompletableFuture<Void> pause(){
if(!delayedPause.getAndSet(false))return actual.pause();
var result=new CompletableFuture<Void>();oldPause.set(result);return actual.pause().thenCompose(v->result);
}
public CompletableFuture<Void> resume(){return actual.resume();}
public CompletableFuture<Void> stopAsync(){return actual.stopAsync();}
public ExecutionFrame acquireLatestFrame(){return actual.acquireLatestFrame();}
public void input(ExecutionInput value){actual.input(value);}
public void close(){actual.close();}
};
}
};
var factory=new DefaultExecutionControllerFactory(app.getBean(p.studio.api.shipper.Shipper.class),
gateway,app.getBean(p.studio.api.operation.OperationExecutor.class),access);
var known=new KnownProjects(){public List<ProjectReference> listKnownProjects(){return List.of(ref);}public void remember(ProjectReference r){}public void forget(ProjectReference r){}};
Stage stage=fx(Stage::new);
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,app.getBean(ProjectSessionFactory.class),factory,
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setups.save(project,setup);}},executor,resources));
try{
fx(()->{window.showLauncher();stage.toFront();stage.requestFocus();assertNotNull(stage.getScene().lookup("#studio-shell"));window.openProject(root);return null;});
await(()->{try{return fx(()->window.projectSession()!=null);}catch(Exception e){throw new RuntimeException(e);}},()->"Project did not open");
Supplier<String> facts=()->{try{capture(stage,"failure.png");return fx(()->"state="+window.projectSession().executionSession().snapshot().state()+" focused="+stage.isFocused()+" frames="+window.viewport().paintedFrames()+"\n"+((Label)stage.getScene().lookup("#studio-notice")).getText()+"\n"+((TextArea)stage.getScene().lookup("#execution-logs")).getText());}catch(Exception e){return e.toString();}};
focus(stage);
fire(stage,"play");running(window,stage,facts);
await(()->{try{return fx(()->window.viewport().paintedFrames()>3);}catch(Exception e){throw new RuntimeException(e);}},facts);
fx(()->{assertTrue(stage.getScene().lookup("#runtime-path").isDisabled());return null;});
assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root));
fx(()->{ComboBox<Integer> zoom=(ComboBox<Integer>)stage.getScene().lookup("#viewport-zoom");zoom.setValue(4);
var image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(1920,image.getFitWidth());assertFalse(image.isSmooth());
zoom.setValue(2);assertEquals(960,image.getFitWidth());zoom.setValue(1);assertEquals(480,image.getFitWidth());return null;});
// Deliver a real key edge through the viewport; Pong leaves its static menu.
// Zoom popup/native activation can transfer desktop focus. Establish the
// input precondition explicitly; the later focus-loss checks never resume.
running(window,stage,facts);
long before=imageHash(stage);
fx(()->{assertTrue(stage.isFocused(),"Keyboard qualification requires actual foreground focus");
assertEquals(ExecutionState.RUNNING,window.projectSession().executionSession().snapshot().state());
var surface=stage.getScene().lookup("#game-surface");surface.requestFocus();
surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));return null;});
try {
await(()->{try{return imageHash(stage)!=before;}catch(Exception e){throw new RuntimeException(e);}},
()->"Keyboard A must move Pong out of its menu\n"+facts.get());
} finally {
fx(()->{stage.getScene().lookup("#game-surface").fireEvent(new KeyEvent(KeyEvent.KEY_RELEASED,"a","a",KeyCode.A,false,false,false,false));return null;});
}
fire(stage,"pause");state(window,ExecutionState.PAUSED,facts);
long paused=fx(()->window.viewport().lastFrameId());Thread.sleep(200);
assertEquals(paused,fx(()->window.viewport().lastFrameId()));fire(stage,"resume");running(window,stage,facts);
// A window owned by Studio is not an application switch.
Stage owned=fx(()->{var s=new Stage();s.initOwner(stage);s.setScene(new javafx.scene.Scene(new Label("Studio dialog"),240,120));s.show();s.requestFocus();return s;});Thread.sleep(250);
assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state()));
fx(()->{owned.hide();stage.requestFocus();stage.setIconified(true);return null;});state(window,ExecutionState.PAUSED,facts);
fx(()->{stage.setIconified(false);stage.requestFocus();return null;});Thread.sleep(200);
assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts);
Stage other=fx(()->{var s=new Stage();s.setTitle("Other application focus probe");s.setScene(new javafx.scene.Scene(new Label("Focus probe"),300,150));s.show();s.requestFocus();return s;});state(window,ExecutionState.PAUSED,facts);
fx(()->{other.hide();stage.requestFocus();return null;});Thread.sleep(200);
assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts);
capture(stage,"play.png");
if(Boolean.getBoolean("studio.test.playStress")){
var process=runtime();long runtimeCpu=cpuNanos(process);
long javaCpu=cpuNanos(ProcessHandle.current());
long painted=fx(()->window.viewport().paintedFrames());
long heapBefore=java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
Thread.sleep(30_000);
double p95=fx(()->window.viewport().latencyP95Millis());System.out.println("RECEIVE_TO_PAINT_P95_MS="+p95);assertTrue(p95<=33.4,"Idle receive-to-paint p95 "+p95);
System.out.println("PAINT_FPS="+(fx(()->window.viewport().paintedFrames())-painted)/30.0);
System.out.println("RUNTIME_CPU_SECONDS="+(cpuNanos(process)-runtimeCpu)/1e9);
System.out.println("JAVA_CPU_SECONDS="+(cpuNanos(ProcessHandle.current())-javaCpu)/1e9);
System.out.println("HEAP_USED_BEFORE_AFTER="+heapBefore+","+java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed());
assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state()),facts);
assertTrue(fx(stage::isFocused),"Idle-host measurement requires the Studio to retain actual focus");
long frame=fx(()->window.viewport().lastFrameId());
fx(()->{Thread.sleep(500);return null;});Thread.sleep(70);
long afterFreeze=fx(()->window.viewport().lastFrameId());
System.out.println("FX_FREEZE_FRAME_IDS="+frame+","+afterFreeze);
assertTrue(afterFreeze>frame+15,()->"Runtime must advance while FX is blocked: "+frame+" -> "+afterFreeze+"\n"+facts.get());
for(int i=0;i<20;i++){fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);Thread.sleep(130);
assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads());
fire(stage,"play");running(window,stage,facts);Thread.sleep(50);
assertEquals(1,runtimeCount());assertEquals(1,heartbeatThreads());}
System.out.println("PLAY_STOP_CYCLES=20");
}
fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);
await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts);
try(var lease=access.enterManual(root)){}
assertFalse(Files.exists(root.resolve(".codex")),"Play must not prepare an AI client");
assertFalse(Files.exists(root.resolve("build.pmc")));
fire(stage,"play");running(window,stage,facts);
delayedPause.set(true);fire(stage,"pause");
await(()->oldPause.get()!=null,facts);
fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);
fire(stage,"play");running(window,stage,facts);
oldPause.get().completeExceptionally(new java.io.IOException("obsolete-pause-result"));
Thread.sleep(200);
assertFalse(fx(()->((Label)stage.getScene().lookup("#studio-notice")).getText().contains("obsolete-pause-result")),
"An old command must not replace a new execution's feedback");
runtime().destroyForcibly();state(window,ExecutionState.RUNTIME_FAILED,facts);
await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts);
assertTrue(fx(()->((TextArea)stage.getScene().lookup("#execution-logs")).getText().contains("Runtime")));
fire(stage,"play");running(window,stage,facts);
fx(()->{window.requestCloseProject();return null;});
await(()->{try{return fx(()->window.projectSession()==null);}catch(Exception e){throw new RuntimeException(e);}},facts);
fx(()->{assertNotNull(stage.getScene().lookup("#open-project"));return null;});capture(stage,"projects.png");
assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads());
}finally{fx(()->{window.close();stage.hide();return null;});}
}
}
static void fire(Stage stage,String id)throws Exception{fx(()->{Button button=(Button)stage.getScene().lookup("#"+id);assertFalse(button.isDisabled(),id+" disabled");button.fire();return null;});}
static void state(StudioWindowCoordinator2 w,ExecutionState expected,Supplier<String> facts)throws Exception{
await(()->{try{return fx(()->w.projectSession().executionSession().snapshot().state()==expected);}catch(Exception e){throw new RuntimeException(e);}},facts);
Thread.sleep(130);
}
static void running(StudioWindowCoordinator2 w,Stage stage,Supplier<String> facts)throws Exception{
focus(stage);
await(()->{try{return fx(()->{var state=w.projectSession().executionSession().snapshot().state();
if(state==ExecutionState.PAUSED){stage.requestFocus();((Button)stage.getScene().lookup("#resume")).fire();}
return state==ExecutionState.RUNNING && stage.isFocused();});}catch(Exception e){throw new RuntimeException(e);}},facts);Thread.sleep(150);
}
static void focus(Stage stage)throws Exception{fx(()->{stage.setIconified(false);stage.toFront();stage.requestFocus();
var point=stage.getScene().getRoot().localToScreen(10,10);
var robot=new javafx.scene.robot.Robot();robot.mouseMove(point);robot.mouseClick(MouseButton.PRIMARY);return null;});Thread.sleep(150);}
static void capture(Stage stage,String name)throws Exception{fx(()->{
var image=stage.getScene().snapshot(null);var output=new java.awt.image.BufferedImage((int)image.getWidth(),(int)image.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);
for(int y=0;y<output.getHeight();y++)for(int x=0;x<output.getWidth();x++)output.setRGB(x,y,image.getPixelReader().getArgb(x,y));
Path file=Path.of("build/studio-play-qualification",name);Files.createDirectories(file.getParent());javax.imageio.ImageIO.write(output,"png",file.toFile());return null;});}
static long imageHash(Stage stage)throws Exception{return fx(()->{var image=((ImageView)stage.getScene().lookup("#game-image")).getImage();long hash=1;
for(int y=0;y<(int)image.getHeight();y++)for(int x=0;x<(int)image.getWidth();x++)hash=31*hash+image.getPixelReader().getArgb(x,y);return hash;});}
static long runtimeCount(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).count();}
static ProcessHandle runtime(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).findFirst().orElseThrow();}
static long heartbeatThreads(){return Thread.getAllStackTraces().keySet().stream().filter(t->t.isAlive()&&t.getName().equals("studio-play-heartbeat")).count();}
static long cpuNanos(ProcessHandle process)throws Exception{
var cpu=process.info().totalCpuDuration();if(cpu.isPresent())return cpu.get().toNanos();
// HotSpot on this macOS does not expose child CPU duration through ProcessHandle.Info.
var query=new ProcessBuilder("/bin/ps","-p",Long.toString(process.pid()),"-o","cputime=").start();
String value=new String(query.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8).trim();
assertTrue(query.waitFor(2,TimeUnit.SECONDS));assertEquals(0,query.exitValue());
double seconds=0;for(String component:value.split(":"))seconds=seconds*60+Double.parseDouble(component);
return (long)(seconds*1e9);
}
@Test void viewportCopiesStablePixelsAndInvertsZoomWithoutClampingOutsideTouches()throws Exception{
var input=new java.util.concurrent.atomic.AtomicReference<>(ExecutionInput.NEUTRAL);
byte[] pixels=new byte[4*2*4];for(int i=0;i<pixels.length;i+=4){pixels[i+2]=(byte)255;pixels[i+3]=(byte)255;}
var frame=new java.util.concurrent.atomic.AtomicReference<>(new ExecutionFrame(4,2,1,1,pixels,()->{}));
ExecutionController controller=new ExecutionController(){
public p.studio.api.operation.OperationHandle<ExecutionSnapshot> play(){throw new UnsupportedOperationException();}
public void stop(){}public void close(){}public ExecutionFrame acquireLatestFrame(){return frame.getAndSet(null);}
public void input(ExecutionInput value){input.set(value);}
};
var viewport=fx(()->new p.studio.ui.javafx2.play.PlaybackViewport(()->controller,()->ExecutionState.RUNNING));
Stage stage=fx(()->{var s=new Stage();s.setScene(new javafx.scene.Scene(viewport,500,300));s.show();return s;});
try{
await(()->{try{return fx(()->viewport.paintedFrames()==1);}catch(Exception e){throw new RuntimeException(e);}},()->"Frame was not painted");
fx(()->{viewport.zoom(4);stage.getScene().getRoot().applyCss();stage.getScene().getRoot().layout();
ImageView image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(0xffff0000,image.getImage().getPixelReader().getArgb(1,1));
assertEquals(16,image.getFitWidth());
pointer(image,MouseEvent.MOUSE_PRESSED,6,6);assertEquals(new ExecutionInput(4096,1,1),input.get());
pointer(image,MouseEvent.MOUSE_DRAGGED,-1,6);assertEquals(0,input.get().buttons());assertEquals(-1,input.get().touchX());
pointer(image,MouseEvent.MOUSE_PRESSED,14,6);assertEquals(new ExecutionInput(4096,3,1),input.get());
pointer(image,MouseEvent.MOUSE_RELEASED,30,30);assertEquals(0,input.get().buttons());
var surface=stage.getScene().lookup("#game-surface");
surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));assertEquals(16,input.get().buttons());
viewport.neutralize();assertEquals(0,input.get().buttons());return null;});
}finally{fx(()->{viewport.close();stage.hide();return null;});}
}
static void pointer(ImageView image,javafx.event.EventType<MouseEvent> type,double x,double y){
var point=image.localToScene(x,y);
image.fireEvent(new MouseEvent(type,point.getX(),point.getY(),0,0,MouseButton.PRIMARY,1,
false,false,false,false,type!=MouseEvent.MOUSE_RELEASED,false,false,false,false,false,
new PickResult(image,point.getX(),point.getY())));
}
}
@@ -15,6 +15,7 @@ import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
/** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */
@org.junit.jupiter.api.Tag("integration")
class AnimationDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit()throws Exception{
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Production packaged runtime: canonical authoring -> generated PBS -> Composer -> pixels. */
@org.junit.jupiter.api.Tag("integration")
class AnimationInstalledRuntimeTest {
@TempDir Path root;
@Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{
@@ -24,6 +24,7 @@ import javax.imageio.ImageIO;
import static org.junit.jupiter.api.Assertions.*;
import static p.animation.AnimationDocument.*;
@org.junit.jupiter.api.Tag("integration")
class AnimationIntegrationTest {
@TempDir Path root;
final ObjectMapper mapper=new ObjectMapper();
@@ -28,6 +28,7 @@ import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
/** Actual Assets controls, shared preview/publication, capacity projection and grant inspection. */
@org.junit.jupiter.api.Tag("integration")
class AssetAuthoringDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit()throws Exception {
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Real packer/filesystem composition behind the same human/task service. */
@org.junit.jupiter.api.Tag("integration")
class AssetBatchIntegrationTest {
@TempDir Path root;
AnimationIntegrationTest fixture;FileAssetBatchWorkspace disk;AssetAuthoringService service;
@@ -0,0 +1,93 @@
package p.studio.app.assets;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.assets.AssetBudgets.*;
import p.studio.api.project.ProjectLocalStudioSetup;
import java.io.ByteArrayInputStream;
import java.nio.file.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class AssetCapacityProfilesTest {
@TempDir Path installation;
private final ObjectMapper json = new ObjectMapper();
private final byte[] evidence = "native qualification evidence".getBytes(java.nio.charset.StandardCharsets.UTF_8);
@Test void findsCompleteBundleAfterAnOlderProfileWithTheSameDispatcher() throws Exception {
var old = bundle("old", "old-headless", "old-runtime");
var current = bundle("current", "new-headless", "new-runtime");
install("new-headless", "new-runtime");
for (var order : List.of(List.of(old, current), List.of(current, old))) {
var selection = select(order, evidence);
assertEquals(QualificationState.known, selection.state(), selection.reason());
assertEquals("current", selection.profile().profileId());
}
}
@Test void rejectsComponentsStitchedFromDifferentQualifiedBundles() throws Exception {
install("old-headless", "new-runtime");
var selection = select(List.of(bundle("old", "old-headless", "old-runtime"),
bundle("new", "new-headless", "new-runtime")), evidence);
assertEquals(QualificationState.unknown, selection.state());
assertNull(selection.profile());
assertTrue(selection.reason().contains("component changed"), selection.reason());
}
@Test void rejectsChangedComponentAndCorruptOrMissingEvidence() throws Exception {
var current = bundle("current", "new-headless", "new-runtime");
install("modified-headless", "new-runtime");
assertEquals(QualificationState.unknown, select(List.of(current), evidence).state());
install("new-headless", "new-runtime");
for (byte[] resource : Arrays.asList("corrupt".getBytes(), null)) {
var selection = select(List.of(current), resource);
assertEquals(QualificationState.unknown, selection.state());
assertTrue(selection.reason().contains("evidence integrity"), selection.reason());
}
}
@Test void rejectsUnqualifiedDispatcherAndIncompleteIdentity() throws Exception {
var current = bundle("current", "new-headless", "new-runtime");
install("new-headless", "new-runtime");
Files.writeString(installation.resolve(executable("prometeu")), "unqualified-cli");
assertEquals(QualificationState.unknown, select(List.of(current), evidence).state());
install("new-headless", "new-runtime");
var incomplete = new AssetCapacityProfiles.Bundle(current.profile(), Map.of("prometeu", hash("cli")));
assertEquals(QualificationState.unknown, select(List.of(incomplete), evidence).state());
}
@Test void missingInstallationOrCatalogRemainsUnknown() throws Exception {
var service = new AssetCapacityProfiles(json, name -> null);
assertEquals(QualificationState.unknown, service.select(null).state());
assertEquals(QualificationState.unknown, service.select(ProjectLocalStudioSetup.defaults()).state());
install("headless", "runtime");
assertEquals(QualificationState.unknown, service.select(setup()).state());
}
private AssetCapacityProfiles.Bundle bundle(String id, String headless, String runtime) {
var profile = new Profile(1, id, "test", hash("cli"), Map.of(BankType.glyph, 16),
List.of(new BoundaryEvidence(BankType.glyph, 16, 17, "evidence.json", AssetWorkspaceFiles.hash(evidence))));
return new AssetCapacityProfiles.Bundle(profile, Map.of("prometeu", hash("cli"),
"prometeu-headless", hash(headless), "prometeu-runtime", hash(runtime)));
}
private ProfileSelection select(List<AssetCapacityProfiles.Bundle> bundles, byte[] record) throws Exception {
byte[] catalog = json.writeValueAsBytes(new AssetCapacityProfiles.Catalog(1, bundles));
return new AssetCapacityProfiles(json, name -> {
byte[] bytes = name.equals("asset-capacity/catalog.json") ? catalog : record;
return bytes == null ? null : new ByteArrayInputStream(bytes);
}).select(setup());
}
private ProjectLocalStudioSetup setup() { return new ProjectLocalStudioSetup(installation.toString(), null); }
private void install(String headless, String runtime) throws Exception {
Files.writeString(installation.resolve(executable("prometeu")), "cli");
Files.writeString(installation.resolve(executable("prometeu-headless")), headless);
Files.writeString(installation.resolve(executable("prometeu-runtime")), runtime);
}
private static String executable(String name) { return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : ""); }
private static String hash(String text) { return AssetWorkspaceFiles.hash(text.getBytes(java.nio.charset.StandardCharsets.UTF_8)); }
}
@@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class InstalledKnowledgeTest {
@TempDir Path outsideRepository;
@@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Real compiler/packer/project composition, no guest or runtime installation required. */
@org.junit.jupiter.api.Tag("integration")
class TargetBuildIntegrationTest {
@TempDir Path root;
ConfigurableApplicationContext app;ProjectSession project;TaskTools tools;String task;ObjectMapper mapper;
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class EvidenceIntegrationTest {
@TempDir Path root;
ExecutorService pool;DefaultAutomationSession session;ProjectAccessRegistry projects;ObjectMapper mapper=new ObjectMapper();
@@ -11,6 +11,7 @@ import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class InstalledConnectorTest {
@TempDir Path temporary;
@Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception {
@@ -67,12 +68,15 @@ class InstalledConnectorTest {
return builder;
}
public static class DesktopProbe {
public static void main(String[] args) {
public static void main(String[] args) throws Exception {
var application=new p.studio.app.App();application.init();
javafx.application.Platform.startup(() -> {
try {
var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX")));
stage.show(); stage.close(); System.exit(0);
} catch (Throwable failure) { System.exit(2); }
var stage = new javafx.stage.Stage();application.start(stage);
if(stage.getScene().lookup("#studio-shell")==null||stage.getScene().lookup("#open-project")==null)
throw new AssertionError("Installed app did not open the new project chooser");
application.stop();stage.hide();System.exit(0);
} catch (Throwable failure) { failure.printStackTrace();System.exit(2); }
});
}
}
@@ -17,6 +17,7 @@ import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class AutomationLspQueriesTest {
String httpAuthorization;
@TempDir Path temporary;
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.jupiter.api.Assertions.*;
/** Controlled protocol faults use real sockets; the stubborn child is an explicitly injected port. */
@org.junit.jupiter.api.Tag("integration")
class LanguageFailureContractTest {
@TempDir Path root;
@Test void protocolMechanismsBecomeNeutralFailuresAndLegacyFallbackStaysLimited() throws Exception {
@@ -8,6 +8,7 @@ import p.studio.lsp.services.LspServerLifecycleImpl;
import java.nio.file.*;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class LspDiscoveryTest {
@TempDir Path root;
final ObjectMapper mapper = new ObjectMapper();
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import p.studio.api.automation.*;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class LocalMcpServerTest {
final ObjectMapper mapper = new ObjectMapper();
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
@@ -13,6 +13,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class McpConnectionGuideTest {
@TempDir Path root;
@Test void preparationIsStableAndSeparateFromAuthority() throws Exception {
@@ -19,6 +19,7 @@ import java.util.concurrent.atomic.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class McpTaskToolsTest {
String httpAuthorization;
@TempDir Path root;
@@ -8,6 +8,7 @@ import java.nio.file.attribute.PosixFilePermissions;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class ProjectConnectionPublisherTest {
@TempDir Path temporary;
final ObjectMapper mapper = new ObjectMapper();
@@ -20,6 +20,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Frozen sources, production compiler/packer/LSP, authenticated loopback MCP. No runtime execution. */
@org.junit.jupiter.api.Tag("integration")
class StructuredDiagnosticsIntegrationTest {
@TempDir Path temporary;
final ObjectMapper json = new ObjectMapper();
@@ -11,6 +11,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class StudioMcpStdioTest {
@TempDir Path temporary;
final ObjectMapper mapper = new ObjectMapper();
@@ -10,6 +10,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Provider qualification precedes publication of a consumer capacity profile. No managed-guard bypass in production. */
@org.junit.jupiter.api.Tag("integration")
class AssetCapacityInstalledRuntimeTest {
@TempDir Path root;
@Test void actualInstalledPoolsAcceptSixteenAndRejectSeventeenGlyphAndScenePreloads()throws Exception {
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Real qualified build/preflight and process execution, independent of the provider boundary qualification. */
@org.junit.jupiter.api.Tag("integration")
class AssetManagedBuildInstalledRuntimeTest {
@TempDir Path root;
Map<String,String> files(Path directory)throws Exception {
@@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Required pilot on a disposable copy of the actual game, using only its existing public APIs. */
@org.junit.jupiter.api.Tag("integration")
class GuestTestPilotTest {
@TempDir Path root;
static Map<String,String> sources(Path root)throws Exception {
@@ -28,6 +28,7 @@ import java.util.function.Supplier;
import static org.junit.jupiter.api.Assertions.*;
/** Actual Tests workspace + authenticated HTTP MCP + installed provider, over one service. */
@org.junit.jupiter.api.Tag("integration")
class GuestTestsDesktopTest {
@TempDir Path root;
@BeforeAll static void toolkit()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(10,TimeUnit.SECONDS);}
@@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Actual installed provider and PBS/compiler/packer/shared runner; no simulated protocol. */
@org.junit.jupiter.api.Tag("integration")
class GuestTestsInstalledRuntimeTest {
@TempDir Path root;
ConfigurableApplicationContext app;ProjectSession session;GuestTestTools tests;ObjectMapper mapper;String task;
@@ -15,6 +15,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Explicit packaged-process gate, not satisfied by protocol fixtures. */
@org.junit.jupiter.api.Tag("integration")
class HeadlessInstalledRuntimeTest {
@TempDir Path root;
@Test void configuredDistributionBootsSavedBuildAndReturnsDeterministicCanonicalPixels() throws Exception {
@@ -30,6 +30,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Full real loop: external HTTP client -> app -> Rust JSONL -> MCP image and JavaFX DEV. */
@org.junit.jupiter.api.Tag("integration")
class HeadlessMcpDesktopTest {
@TempDir Path root;
final ObjectMapper mapper = new ObjectMapper();
@@ -10,6 +10,7 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
@org.junit.jupiter.api.Tag("integration")
class HeadlessProcessSessionTest {
@TempDir Path root;
final List<HeadlessProcessSession> sessions = new ArrayList<>();
@@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Actual app composition and saved-source services; no runtime/build/LSP doubles. */
@org.junit.jupiter.api.Tag("integration")
class HeadlessTaskIntegrationTest {
@TempDir Path root;
ConfigurableApplicationContext app;
@@ -120,12 +121,16 @@ class HeadlessTaskIntegrationTest {
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(Map.of("kind","native-checkpoint","artifact",artifact,"report",report.report(),"nativeAdvanceRequests",2,"persistenceExtraAdvanceOrCaptureRequests",0)));
}
@Test void zeldaPilotUsesDisposableCopyAndKeepsReferenceLimitationsExplicit() throws Exception {
Path originalProject=Path.of(System.getProperty("studio.test.zeldaProject", "../../zelda-1")).toAbsolutePath().normalize();
assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Zelda pilot checkout is required for this qualification");
project.close();Path copy=root.resolve("zelda-pilot");Files.createDirectories(copy);
@Test void pongPilotUsesDisposableCopyAndIndependentRegionReferences() throws Exception {
String fixture=System.getProperty("studio.test.pong");
assertNotNull(fixture,"Run headlessProcessTest to select Studio's test-projects/pong fixture");
Path originalProject=Path.of(fixture).toAbsolutePath().normalize();
assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Repository-owned Pong fixture is required");
String originalSource=Files.readString(originalProject.resolve("src/main.pbs"));
project.close();Path copy=root.resolve("Pong Headless");Files.createDirectories(copy);
for(String name:List.of("prometeu.json","src","assets")) {
Path from=originalProject.resolve(name);
if(!Files.exists(from))continue; // Pong has no external assets.
if(Files.isDirectory(from))try(var paths=Files.walk(from)) {
for(var p:paths.toList()){var target=copy.resolve(originalProject.relativize(p));if(Files.isDirectory(p))Files.createDirectories(target);else Files.copy(p,target);}
}else Files.copy(from,copy.resolve(name));
@@ -133,17 +138,20 @@ class HeadlessTaskIntegrationTest {
root=copy.toRealPath();var ref=app.getBean(ProjectCatalog.class).openProject(root);
app.getBean(ProjectLocalStudioSetupStore.class).save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
project=app.getBean(ProjectSessionFactory.class).open(ref);project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tasks.acquire(root).task().value();
String build=successfulBuild("zelda-pilot-build");tasks.headless(root,task,TaskTools.HeadlessAction.BOOT,build,Map.of("memcardChoice","memory_fresh"));
String build=successfulBuild("pong-pilot-build");call(TaskTools.HeadlessAction.BOOT,build);
var evidence=app.getBean(EvidenceTools.class);var measurements=new ArrayList<Map<String,Object>>();
var mcp=app.getBean(p.studio.app.mcp.McpToolRegistry.class);
long beforeWireBytes=0,afterWireBytes=0;int beforeCalls=0,afterCalls=0;
var legacyPaths=new ArrayList<String>();
String[] refs={"extracted/inventory_screen/validation/production_start.png","extracted/hud/runtime_initial.png","extracted/bomb_wall/validation/scroll_north_mid.png"};
String[] names={"screen","hud","scroll"};
String[] names={"menu-accent","serve-ball","moved-paddle"};
// Fixed expectations from the fixture's draw/input contract, never from a native capture.
Evidence.Rect[] regions={new Evidence.Rect(113,114,1,80),new Evidence.Rect(237,152,6,6),new Evidence.Rect(42,72,8,36)};
int[][] colors={{77,237,205},{236,244,250},{77,237,205}};
long totalPngBytes=0;
for(int i=0;i<names.length;i++) {
if(i>0)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of(i==1?"start":"right",true));
String request="zelda-"+names[i];tasks.advance(root,task,request,i==0?1:i==1?76:120);var operation=finished(request);
if(i==1)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",true));
if(i==2)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",false,"up",true));
String request="pong-"+names[i];tasks.advance(root,task,request,i==2?20:1);var operation=finished(request);
assertNull(operation.failure());assertNotNull(operation.runtimeResult().capture());
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task);
var before=mcp.call("studio_operation_get",args.deepCopy().put("clientRequestId",request)).wire();
@@ -154,13 +162,18 @@ class HeadlessTaskIntegrationTest {
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(persisted).length;
assertFalse(persisted.path("isError").asBoolean(),persisted.toString());
var actual=mapper.convertValue(persisted.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
Path reference=root.resolve("reference-"+names[i]+".png");Files.copy(originalProject.resolve(refs[i]),reference);
Path reference=root.resolve("reference-"+names[i]+".png");
byte[] rgba=new byte[480*270*4];
for(int pixel=0;pixel<rgba.length;pixel+=4){
rgba[pixel]=(byte)colors[i][0];rgba[pixel+1]=(byte)colors[i][1];rgba[pixel+2]=(byte)colors[i][2];rgba[pixel+3]=(byte)255;
}
Files.write(reference,new p.studio.app.evidence.PngEvidenceCodec().encode(new Evidence.Pixels(480,270,rgba)));
legacyPaths.add(reference.toString());legacyPaths.add(legacyActual.toString());
var imported=mcp.call("studio_evidence_import",args.deepCopy().put("clientRequestId","import-"+request).put("path",reference.toString())).wire();
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(imported).length;
assertFalse(imported.path("isError").asBoolean(),imported.toString());
var expected=mapper.convertValue(imported.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
Evidence.Rect roi=i==1?new Evidence.Rect(112,15,256,56):null;
Evidence.Rect roi=regions[i];
var params=new Evidence.Parameters(roi,List.of(),Evidence.Alpha.compare,0,0);
var comparisonArgs=args.deepCopy().put("clientRequestId","compare-"+request).put("expectedId",expected.id()).put("actualId",actual.id());
var parametersNode=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.valueToTree(params);
@@ -168,8 +181,12 @@ class HeadlessTaskIntegrationTest {
var compared=mcp.call("studio_evidence_compare",comparisonArgs).wire();afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(compared).length;
assertFalse(compared.path("isError").asBoolean(),compared.toString());
var report=mapper.convertValue(compared.path("structuredContent").path("value"),Evidence.Publication.class);
assertEquals(Evidence.Verdict.passed,report.report().verdict(),names[i]);
assertEquals((long)roi.width()*roi.height(),report.report().comparedPixels());
assertEquals(0,report.report().differentPixels());
assertArrayEquals(legacyPng,evidence.image(root,task,actual.id()));
totalPngBytes+=legacyPng.length;
measurements.add(Map.of("case",names[i],"referencePath",refs[i],"actual",actual,"report",report.report()));
measurements.add(Map.of("case",names[i],"referencePath",reference.getFileName().toString(),"actual",actual,"report",report.report()));
}
// Execute the former external comparison path against the same checkpoints; count actual calls/bytes/scripts.
Path script=root.resolve("LegacyVisualCompare.java");
@@ -187,10 +204,11 @@ class HeadlessTaskIntegrationTest {
var command=new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),script.toString()));command.addAll(legacyPaths);
var legacy=new ProcessBuilder(command).redirectErrorStream(true).start();assertTrue(legacy.waitFor(30,TimeUnit.SECONDS));
String legacyOutput=new String(legacy.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);assertEquals(0,legacy.exitValue(),legacyOutput);
var output=Map.of("kind","zelda-pilot","limitations","Saved port captures are contextual references, not an independent NES oracle; screen/HUD/scroll reference labels identify their provenance. Current checkpoints are observations and mismatch is retained as a comparison result.",
assertEquals(originalSource,Files.readString(originalProject.resolve("src/main.pbs")),"Build and runtime must use only the disposable copy");
var output=Map.of("kind","pong-pilot","limitations","Solid-color references specify only the declared ROIs independently of native captures. These checks cover menu, serve and input-driven paddle movement, not full-game visual equivalence.",
"results",measurements,"measurement",Map.of("sharedGuestAdvanceRequests",3,"before",Map.of("mcpCalls",beforeCalls,"wireResponseBytes",beforeWireBytes,"imagePngBytes",totalPngBytes,"externalComparisonScripts",1,"externalScriptOutput",legacyOutput),
"after",Map.of("mcpCalls",afterCalls,"wireResponseBytes",afterWireBytes,"imageTransferBytesForMetrics",0,"externalComparisonScripts",0),
"basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from the explicit HUD ROI by design."));
"basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from ROI-specific checks by design."));
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(output));
}
@@ -19,6 +19,7 @@ import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** PBS/shipper -> configured dispatcher -> distinct OS processes; no native injection. */
@org.junit.jupiter.api.Tag("integration")
class MemcardInstalledRuntimeTest {
@TempDir Path root;
final ObjectMapper mapper = new ObjectMapper();
@@ -0,0 +1,82 @@
package p.studio.app.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import p.studio.api.execution.*;
import p.studio.api.project.*;
import p.studio.api.automation.TaskTools;
import p.studio.api.runtime.RuntimeLogEntry;
import p.studio.core.project.*;
import p.studio.core.runtime.*;
import p.studio.core.shipper.StudioShipperService;
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
import p.studio.app.operation.ExecutorOperationExecutor;
import p.studio.app.runtime.studio.StudioRuntimeGateway;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.*;
/** Cross-mode save compatibility and actual interactive dirty-Stop refusal. */
@org.junit.jupiter.api.Tag("integration")
class StudioPlayInstalledRuntimeTest {
@TempDir Path root;
final ObjectMapper json=new ObjectMapper();
@Test void persistentDirtyStopRefusesThenGuestCommitsAndHeadlessReadsWhileDisposableNeverOverwrites()throws Exception{
Files.createDirectories(root.resolve("src"));
Files.writeString(root.resolve("prometeu.json"),"""
{"name":"studio-save","version":"1","language":"pbs","stdlib":"1","target":"Game","app_id":4294967295,"memcard_slots":1,"dependencies":[]}
""");
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String writer=MemcardInstalledRuntimeTest.WRITER
.replace(MemcardInstalledRuntimeTest.PREFIX,MemcardInstalledRuntimeTest.PREFIX+"import {Pad, Button} from @sdk:input;\n")
.replace("let commit = Mem.slot_commit(context, 0);","if Pad.down(Button.A) == false { return; }\nlet commit = Mem.slot_commit(context, 0);");
Files.writeString(root.resolve("src/main.pbs"),writer);
var store=new ProjectLocalStudioSetupStore(json);var project=new ProjectCatalogService(root,json,store).openProject(root);
Path image=root.resolve("development-save.pmc");var setup=new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null,null,image.toString());store.save(project,setup);
var logs=new CopyOnWriteArrayList<RuntimeLogEntry>();
try(var workers=Executors.newFixedThreadPool(2);var packer=p.packer.Packer.bootstrap(json,e->{})){
var shipper=new StudioShipperService(new CompilerBuildGatewayAdapter(),packer.workspaceService(),json,new ExecutorOperationExecutor(workers))
.withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(json,packer.workspaceService(),store::load));
var build=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(build.success(),build.diagnostics().toString());
var headless=new HeadlessProcessGateway(json,store::load);
var formatting=(HeadlessProcessSession)headless.boot(project,"format-test-media",build,
Map.of("memcard",Map.of("path",image.toString(),"action","create","access","read_write"),"memcardChoice","persistent"));
try{formatting.call(TaskTools.HeadlessAction.RESET,Map.of("discardUnsaved",true,"pendingWrites","cancel"));}
finally{formatting.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
assertTrue(Files.isRegularFile(image));
var gateway=new StudioRuntimeGateway(json);
var persistent=gateway.start(project,setup,logs::add,PlayOptions.PERSISTENT);
try{
persistent.startExecution().get(5,TimeUnit.SECONDS);awaitColor(persistent,0,0,255,logs); // BGRA red
var refusal=assertThrows(ExecutionException.class,()->persistent.stopAsync().get(5,TimeUnit.SECONDS));
assertInstanceOf(RuntimeStopRefusedException.class,refusal.getCause());assertFalse(persistent.completion().isDone());
persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0));
awaitColor(persistent,0,255,0,logs);persistent.input(ExecutionInput.NEUTRAL);
persistent.stopAsync().get(5,TimeUnit.SECONDS);assertEquals(0,persistent.completion().join());
}finally{if(!persistent.completion().isDone()){persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0));awaitColor(persistent,0,255,0,logs);persistent.stopAsync().get(5,TimeUnit.SECONDS);}}
byte[] saved=Files.readAllBytes(image);
var disposable=gateway.start(project,setup,logs::add,new PlayOptions(true));
try{disposable.startExecution().get(5,TimeUnit.SECONDS);awaitColor(disposable,0,0,255,logs);disposable.stopAsync().get(5,TimeUnit.SECONDS);}
finally{disposable.close();}
assertArrayEquals(saved,Files.readAllBytes(image),"Explicit disposable Play must leave selected persistent media intact");
Files.writeString(root.resolve("src/main.pbs"),MemcardInstalledRuntimeTest.READER);
var readBuild=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(readBuild.success(),readBuild.diagnostics().toString());
var reader=(HeadlessProcessSession)headless.boot(project,"read-studio-save",readBuild,
Map.of("memcard",Map.of("path",image.toString(),"action","open","access","read_write"),"memcardChoice","persistent"));
try{assertEquals(p.studio.api.automation.AutomationOutcome.Kind.SUCCEEDED,reader.advance(1,e->{}).kind());}
finally{reader.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
assertArrayEquals(saved,Files.readAllBytes(image),"Headless reader must not resave");
var missing=new ProjectLocalStudioSetup(setup.prometeuRuntimePath(),null,null,root.resolve("absent.pmc").toString());
assertThrows(java.io.IOException.class,()->gateway.start(project,missing,logs::add,PlayOptions.PERSISTENT));assertFalse(Files.exists(root.resolve("absent.pmc")));
}
}
static void awaitColor(RuntimeConnection connection,int b,int g,int r,List<RuntimeLogEntry> logs)throws Exception{
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(5);
while(System.nanoTime()<deadline){try(var frame=connection.acquireLatestFrame()){
if(frame!=null){var p=frame.pixels();if((p.get(0)&255)==b&&(p.get(1)&255)==g&&(p.get(2)&255)==r)return;}}
Thread.sleep(10);
}fail("Native image did not reach expected color: "+logs);
}
}
@@ -0,0 +1,23 @@
package p.studio.app.runtime.studio;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
class LatestFramePoolTest {
@Test void slowPresentationKeepsLeaseStableAndSkipsPendingFrames()throws Exception {
var pool=new LatestFramePool(2,1);
byte[] first=pool.receive();Arrays.fill(first,(byte)7);pool.publish(first,1,1);
var held=pool.acquire();assertNotNull(held);assertNull(pool.acquire());
for(int i=2;i<=100;i++){byte[] next=pool.receive();Arrays.fill(next,(byte)i);pool.publish(next,i,1);}
assertEquals(7,held.pixels().get(0));assertTrue(held.pixels().isReadOnly());
held.close();held.close();
try(var latest=pool.acquire()){assertEquals(100,latest.frameId());assertEquals(100,latest.pixels().get(0));}
assertNull(pool.acquire());pool.close();assertThrows(java.io.IOException.class,pool::receive);
}
@Test void rgbaConversionPremultipliesAndOrdersChannels(){
byte[] bytes=java.util.HexFormat.of().parseHex("ff0000ff0000ff80ffffffff");
LatestFramePool.rgbaToBgraPre(bytes);
assertArrayEquals(java.util.HexFormat.of().parseHex("0000ffff80000080ffffffff"),bytes);
}
}
@@ -0,0 +1,90 @@
package p.studio.app.runtime.studio;
import org.junit.jupiter.api.Test;
import p.studio.api.execution.ExecutionFrame;
import p.studio.api.runtime.RuntimeLogEntry;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
import java.nio.*;
import static org.junit.jupiter.api.Assertions.*;
import static p.studio.app.runtime.studio.StudioWire.*;
import p.studio.app.runtime.studio.StudioWire.Reader;
import p.studio.app.runtime.studio.StudioWire.Writer;
/** Java adapter against the actual Rust host and an existing native cartridge. */
@org.junit.jupiter.api.Tag("integration")
class StudioPlayProcessTest {
static final class Native implements AutoCloseable {
final ExecutorService io=Executors.newVirtualThreadPerTaskExecutor();
final List<String> logs=new CopyOnWriteArrayList<>();
Process process;Socket control,video;StudioRuntimeConnection connection;
Native()throws Exception {
try(ServerSocket c=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"));
ServerSocket v=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"))){
process=new ProcessBuilder(System.getProperty("studio.test.studioHost"),"--studio","--run",
System.getProperty("studio.test.studioCartridge")).start();
var stdout=StudioRuntimeGateway.drain(process.getInputStream(),false,e->logs.add(e.message()),io);
var stderr=StudioRuntimeGateway.drain(process.getErrorStream(),true,e->logs.add(e.message()),io);
byte[] session=new byte[16],token=new byte[32];Arrays.fill(session,(byte)3);Arrays.fill(token,(byte)7);
try(var input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,little(53)
.put(session).put(token).putShort((short)c.getLocalPort()).putShort((short)v.getLocalPort()).put((byte)1).array());}
c.setSoTimeout(10000);v.setSoTimeout(10000);control=c.accept();video=v.accept();
control.setSoTimeout(10000);video.setSoTimeout(10000);
Reader cr=new Reader(control.getInputStream()),vr=new Reader(video.getInputStream());
assertEquals(HELLO,cr.receive().header().kind());assertEquals(HELLO,vr.receive().header().kind());
var ready=cr.receive();assertEquals(READY,ready.header().kind());
var b=ByteBuffer.wrap(ready.payload()).order(ByteOrder.LITTLE_ENDIAN);int width=b.getInt(),height=b.getInt();
control.setSoTimeout(0);video.setSoTimeout(0);
connection=new StudioRuntimeConnection(process,control,video,cr,vr,session,width,height,e->logs.add(e.message()),io,stdout,stderr);
}catch(Throwable failure){close();throw failure;}
}
ExecutionFrame image()throws Exception {
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3);
while(System.nanoTime()<deadline){ExecutionFrame frame=connection.acquireLatestFrame();if(frame!=null)return frame;Thread.sleep(5);}
fail("No complete image: "+logs);return null;
}
@Override public void close(){
if(process!=null&&process.isAlive())process.destroyForcibly();
StudioRuntimeGateway.close(control);StudioRuntimeGateway.close(video);
if(process!=null)try{process.waitFor(3,TimeUnit.SECONDS);}catch(InterruptedException e){Thread.currentThread().interrupt();}
if(connection!=null)try{connection.completion().get(3,TimeUnit.SECONDS);}catch(Exception ignored){}
io.shutdownNow();
}
}
@Test void liveFramesRemainStableDuringSlowPresentationAndStopIsConfirmed()throws Exception {
try(var s=new Native()){
long pid=s.process.pid();s.connection.startExecution().get(3,TimeUnit.SECONDS);
long first;
try(var held=s.image()){
first=held.frameId();byte pixel=held.pixels().get(0);
Thread.sleep(150);assertEquals(pixel,held.pixels().get(0));assertNull(s.connection.acquireLatestFrame());
}
try(var recent=s.image()){assertTrue(recent.frameId()>first+1);}
s.connection.pause().get(3,TimeUnit.SECONDS);Thread.sleep(40);
try(var finalFrame=s.connection.acquireLatestFrame()){/* Drain an asynchronous final publication. */}
Thread.sleep(40);assertNull(s.connection.acquireLatestFrame());
s.connection.resume().get(3,TimeUnit.SECONDS);try(var resumed=s.image()){assertTrue(resumed.frameId()>first);}
assertEquals(pid,s.process.pid());s.connection.stopAsync().get(5,TimeUnit.SECONDS);
assertEquals(0,s.connection.completion().get(1,TimeUnit.SECONDS));assertFalse(s.process.isAlive());
assertTrue(s.logs.stream().anyMatch(line->line.contains("Runtime stopped")));
}
}
@Test void pauseBeforeStartWaitsForExplicitResume()throws Exception {
try(var s=new Native()){
s.connection.pause().get(3,TimeUnit.SECONDS);s.connection.startExecution().get(3,TimeUnit.SECONDS);
Thread.sleep(80);assertNull(s.connection.acquireLatestFrame());
s.connection.resume().get(3,TimeUnit.SECONDS);try(var image=s.image()){assertEquals(480,image.width());}
s.connection.stopAsync().get(5,TimeUnit.SECONDS);
}
}
@Test void brokenVideoAndControlKillTheOwnedProcessAndKeepLogs()throws Exception {
for(boolean video:new boolean[]{true,false})try(var s=new Native()){
s.connection.startExecution().get(3,TimeUnit.SECONDS);
if(video)s.video.close();else s.control.close();
assertThrows(ExecutionException.class,()->s.connection.completion().get(4,TimeUnit.SECONDS));
assertFalse(s.process.isAlive());assertTrue(s.logs.stream().anyMatch(line->line.contains("connection failed")));
}
}
}
@@ -0,0 +1,60 @@
package p.studio.app.runtime.studio;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.*;
import java.util.HexFormat;
import p.studio.app.runtime.studio.StudioWire.Reader;
import static org.junit.jupiter.api.Assertions.*;
import static p.studio.app.runtime.studio.StudioWire.*;
class StudioWireTest {
@Test void blankNativeLinesDoNotStopBoundedLogDrain() {
var logs=new java.util.ArrayList<p.studio.api.runtime.RuntimeLogEntry>();
String output="\n \r\nready\n"+"x".repeat(9000)+"\nlast";
StudioRuntimeGateway.drain(new ByteArrayInputStream(output.getBytes(java.nio.charset.StandardCharsets.UTF_8)),false,logs::add,Runnable::run).join();
assertEquals(3,logs.size());assertEquals("ready",logs.getFirst().message());
assertEquals(8193,logs.get(1).message().length());assertEquals("last",logs.getLast().message());
}
private byte[] fixture() throws IOException {
String hex=Files.readString(Path.of(System.getProperty("studio.test.protocolFixtures"),"pause.hex"));
return HexFormat.of().parseHex(hex.replaceAll("\\s+",""));
}
@Test void headerMatchesSharedRustFixture() throws Exception {
assertArrayEquals(fixture(),new Header(PAUSE,0,1,42).encode());
assertEquals(42,Header.decode(fixture()).request());
}
@Test void fragmentedReadsWorkButTruncationAndReplayFail() throws Exception {
byte[] bytes=fixture();
InputStream fragmented=new FilterInputStream(new ByteArrayInputStream(bytes)) {
@Override public int read(byte[] b,int off,int len)throws IOException {return super.read(b,off,Math.min(len,3));}
};
assertEquals(PAUSE,new Reader(fragmented).receive().header().kind());
assertThrows(EOFException.class,()->new Reader(new ByteArrayInputStream(bytes,0,31)).receive());
var twice=new ByteArrayOutputStream();twice.write(bytes);twice.write(bytes);
var reader=new Reader(new ByteArrayInputStream(twice.toByteArray()));reader.receive();
assertThrows(IOException.class,reader::receive);
}
@Test void validatesBeforeAllocatingPayload() throws Exception {
for(int offset:new int[]{0,4,6,8,10}) {byte[] bad=fixture();bad[offset]=(byte)255;
assertThrows(IOException.class,()->Header.decode(bad));}
byte[] huge=fixture();java.util.Arrays.fill(huge,12,16,(byte)255);
assertThrows(IOException.class,()->Header.decode(huge));
assertThrows(IOException.class,()->frameBytes(Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE));
assertThrows(IOException.class,()->frameBytes(480,270,481));
assertEquals(518400,frameBytes(480,270,480));
assertThrows(IOException.class,()->text(new byte[]{(byte)0xff},0));
}
@Test void rgbaPayloadMatchesSharedFixture() throws Exception {
byte[] bytes=HexFormat.of().parseHex(Files.readString(Path.of(
System.getProperty("studio.test.protocolFixtures"),"rgba.hex")).replaceAll("\\s+",""));
var reader=new Reader(new ByteArrayInputStream(bytes));var h=reader.nextHeader();
assertEquals(FRAME,h.kind());assertEquals(56,h.length());
byte[] metadata=new byte[48];reader.readFully(metadata,0,48);
var b=java.nio.ByteBuffer.wrap(metadata).order(java.nio.ByteOrder.LITTLE_ENDIAN);
b.position(16);assertEquals(1,b.getLong());assertEquals(7,b.getLong());
int width=b.getInt(),height=b.getInt(),stride=b.getInt();assertEquals(RGBA8,b.getInt());
byte[] pixels=new byte[frameBytes(width,height,stride)];reader.readFully(pixels,0,pixels.length);
assertArrayEquals(HexFormat.of().parseHex("ff0000ff0000ff80"),pixels);
}
}