implement DEV workspace and project automation authority

This commit is contained in:
2026-09-29 07:09:37 +01:00
parent 0ddf3ef70d
commit e3c3b2cbb7
62 changed files with 2180 additions and 354 deletions
@@ -0,0 +1,146 @@
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<Void>();
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<Void>();
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<Void> 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 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 = ""; }
}
}
@@ -12,6 +12,39 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
final class ExecutorOperationExecutorTest {
@Test
void cancellationDoesNotPretendAnUncooperativeWorkerHasStopped() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
final var started = new CountDownLatch(1);
final var finish = new CountDownLatch(1);
try {
var handle = new ExecutorOperationExecutor(executor).submit("stubborn worker", () -> {
started.countDown();
boolean done = false;
while (!done) try { finish.await(); done = true; } catch (InterruptedException ignored) { }
return 42;
});
assertTrue(started.await(2, TimeUnit.SECONDS));
handle.cancel();
assertTrue(handle.completion().toCompletableFuture().isCancelled());
org.junit.jupiter.api.Assertions.assertFalse(handle.termination().toCompletableFuture().isDone());
finish.countDown();
handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS);
} finally { finish.countDown(); executor.shutdownNow(); }
}
@Test
void cancellingQueuedWorkCompletesTerminationWithoutRunningItsBody() throws Exception {
final var executor = Executors.newSingleThreadExecutor();
final var finish = new CountDownLatch(1);
try {
executor.submit(() -> { try { finish.await(); } catch (InterruptedException ignored) { } });
var handle = new ExecutorOperationExecutor(executor).submit("queued", () -> { throw new AssertionError("must not execute"); });
handle.cancel();
handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS);
} finally { finish.countDown(); executor.shutdownNow(); }
}
@Test
void completesWithTypedResultAndTerminalSnapshot() throws Exception {
final var executor = Executors.newSingleThreadExecutor();