package p.studio.app; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.junit.jupiter.api.*; import org.junit.jupiter.api.io.TempDir; import p.studio.api.automation.*; import p.studio.api.operation.OperationSubscription; import p.studio.api.project.*; import p.studio.app.operation.ExecutorOperationExecutor; import p.studio.core.execution.DefaultExecutionSession; import p.studio.core.session.DefaultAutomationSession; import p.studio.ui.javafx.controls.forms.*; import p.studio.ui.javafx.events.StudioEventBus; import p.studio.ui.javafx.utilities.i18n.I18nService; import p.studio.ui.javafx.workspaces.*; import p.studio.ui.javafx.workspaces.debug.DebugWorkspace; import p.studio.ui.javafx.workspaces.dev.*; import java.nio.file.*; import java.util.List; import java.util.concurrent.*; 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. */ class DevDesktopTest { @TempDir Path root; @BeforeAll static void toolkit() throws Exception { var ready = new CompletableFuture(); Platform.startup(() -> { Platform.setImplicitExit(false); ready.complete(null); }); ready.get(10, TimeUnit.SECONDS); } @AfterAll static void stopToolkit() { Platform.exit(); } static void fx(Runnable work) throws Exception { var completed = new CompletableFuture(); Platform.runLater(() -> { try { work.run(); completed.complete(null); } catch (Throwable failure) { completed.completeExceptionally(failure); } }); completed.get(10, TimeUnit.SECONDS); } @Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception { var pool = Executors.newSingleThreadExecutor(); var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); var subscriptions = new AtomicInteger(); var observed = (AutomationSession) java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{AutomationSession.class}, (proxy, method, args) -> { var result = method.invoke(authority, args); if (method.getName().equals("subscribe")) { subscriptions.incrementAndGet(); return (OperationSubscription) () -> { ((OperationSubscription) result).unsubscribe(); subscriptions.decrementAndGet(); }; } return result; }); var stage = new Stage[1]; var host = new WorkspaceHost[1]; var dev = new DevWorkspace[1]; var locale = new I18nService(); try { fx(() -> { var project = new ProjectReference("DEV smoke", "1", "pbs", 1, ProjectTarget.Game, root); var events = new StudioEventBus(); host[0] = new WorkspaceHost(); dev[0] = new DevWorkspace(project, observed, locale, events); host[0].register(dev[0]); host[0].register(new DebugWorkspace(project, new DefaultExecutionSession(), locale, events)); stage[0] = new Stage(); stage[0].setTitle("DEV/Debug desktop verification"); stage[0].setScene(new Scene(host[0], 1050, 800)); stage[0].show(); host[0].change(WorkspaceId.DEV); }); fx(() -> { assertEquals(1, subscriptions.get()); assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled()); ((Button) dev[0].rootNode().lookup("#dev-grant")).fire(); assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get()); assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); host[0].change(WorkspaceId.DEV); }); fx(() -> assertEquals(1, subscriptions.get())); var task = authority.acquire(); // Intentionally outside the FX thread. authority.attachRuntime(task.task(), new ManagedHeadlessSession() { public String sessionId() { return "smoke-session"; } public void cancel() { } public CompletionStage shutdown() { return CompletableFuture.completedFuture(null); } }); // Real 1x1 PNG, supplied by the test runtime. Product never fabricates captures. var png = java.util.Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9l0AAAAASUVORK5CYII="); authority.submit(task.task(), "capture", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 4, 4, List.of(), new CanonicalCapture("smoke-session", "smoke-build", 4, 1, 1, 1, 1, png))).termination().toCompletableFuture().get(5, TimeUnit.SECONDS); fx(() -> { assertTrue(((Button) dev[0].rootNode().lookup("#dev-grant")).isDisabled()); assertTrue(dev[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) .map(n -> ((Label) n).getText()).anyMatch(t -> t.contains("logical=4") && t.contains("FrameId=1"))); ((Button) dev[0].rootNode().lookup("#dev-reclaim")).fire(); assertEquals(ControlState.MANUAL, authority.snapshot().state()); assertTrue(authority.snapshot().stale()); locale.setLocale(java.util.Locale.forLanguageTag("pt-BR")); host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get()); authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH); assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); }); } finally { fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); }); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow(); } } @Test void formsSaveFailurePreservesDraftAndReturnReadsExternalContent() throws Exception { var file = root.resolve("document.txt"); Files.writeString(file, "initial"); fx(() -> { var form = new TestForm(); form.draft = "edited"; form.dirty = true; form.fail = true; assertThrows(CompletionException.class, () -> form.saveForHandoff().toCompletableFuture().join()); assertTrue(form.hasUnsavedDraft()); assertEquals("edited", form.draft); form.fail = false; form.saveForHandoff().toCompletableFuture().join(); assertFalse(form.hasUnsavedDraft()); form.draft = "stale presentation"; try { Files.writeString(file, "external agent edit"); } catch (Exception failure) { throw new RuntimeException(failure); } form.discardDraftForHandoff(); try { form.draft = Files.readString(file); } catch (Exception failure) { throw new RuntimeException(failure); } assertEquals("external agent edit", form.draft); }); } @Test void copiesLiveConnectionWithoutGrantOrCredentialDisplayAndRefreshesAvailability() throws Exception { var mapper = new com.fasterxml.jackson.databind.ObjectMapper(); var projects = new p.studio.core.project.ProjectAccessRegistry(); var savedClipboard = new java.util.HashMap(); var copied = new java.util.concurrent.atomic.AtomicReference(); var view = new DevWorkspace[1]; var stage = new Stage[1]; try (var pool = Executors.newSingleThreadExecutor(); var server = new p.studio.app.mcp.LocalMcpServer(mapper, new p.studio.app.mcp.McpToolRegistry( new p.studio.app.mcp.McpToolCatalog(mapper), mapper, java.util.Map.of()))) { var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); var registration = projects.register(root, authority::enterManual, () -> !authority.snapshot().closed(), authority); var guide = new p.studio.app.mcp.McpConnectionGuide(server, projects, mapper); server.start(); try { fx(() -> { var clipboard = javafx.scene.input.Clipboard.getSystemClipboard(); clipboard.getContentTypes().forEach(type -> savedClipboard.put(type, clipboard.getContent(type))); var project = new ProjectReference("Connection smoke", "1", "pbs", 1, ProjectTarget.Game, root); view[0] = new DevWorkspace(project, authority, new I18nService(), new StudioEventBus(), guide); stage[0] = new Stage(); stage[0].setScene(new Scene(new VBox(view[0].rootNode()), 1050, 800)); stage[0].show(); view[0].load(); var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); button.fire(); copied.set(clipboard.getString()); assertEquals(ControlState.MANUAL, authority.snapshot().state()); assertEquals(server.connection().endpoint().toString(), ((Label) view[0].rootNode().lookup("#dev-mcp-endpoint")).getText()); assertTrue(view[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) .noneMatch(n -> ((Label) n).getText().contains(server.connection().authorizationHeader()))); }); var first = mapper.readTree(copied.get()); assertTrue(server.connection().authorizationHeader().equals(first.path("headers").path("Authorization").asText())); assertEquals(root.toRealPath().toString(), first.path("projectRoot").asText()); server.close(); fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); server.start(); authority.grant(false).toCompletableFuture().join(); fx(() -> { var button = (Button) view[0].rootNode().lookup("#dev-mcp-config"); assertFalse(button.isDisabled()); button.fire(); copied.set(javafx.scene.input.Clipboard.getSystemClipboard().getString()); assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); }); var next = mapper.readTree(copied.get()); assertFalse(first.path("headers").equals(next.path("headers"))); assertTrue(server.connection().authorizationHeader().equals(next.path("headers").path("Authorization").asText())); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); fx(() -> assertTrue(((Button) view[0].rootNode().lookup("#dev-mcp-config")).isDisabled())); } finally { fx(() -> { if (view[0] != null) view[0].unLoad(); if (stage[0] != null) stage[0].close(); javafx.scene.input.Clipboard.getSystemClipboard().setContent(savedClipboard); }); authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); registration.close(); } } } @Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception { fx(() -> { var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect"); inspect.getProperties().put(ManualProjectUiGuard.READ_ONLY_ACTION, true); var writes = new AtomicInteger(); var reads = new AtomicInteger(); mutate.setOnAction(e -> writes.incrementAndGet()); inspect.setOnAction(e -> reads.incrementAndGet()); root.getChildren().addAll(mutate, inspect); ManualProjectUiGuard.install(root, () -> false); mutate.fire(); inspect.fire(); assertEquals(0, writes.get()); assertEquals(1, reads.get()); }); } static class TestForm extends StudioFormSection { boolean dirty, fail; String draft = ""; TestForm() { super(new I18nService()); } protected String formSectionId() { return "test"; } protected String sectionTitle() { return "test"; } protected StudioFormMode formMode() { return StudioFormMode.EDITING; } protected boolean isDirty() { return dirty; } protected void renderSection() { } protected void beginEdit() { } protected void apply() { if (!fail) dirty = false; finishHandoffSave(!fail, "save failure"); } protected void reset() { } protected void cancel() { dirty = false; draft = ""; } } }