compose real headless runtime with task build and lifecycle

This commit is contained in:
2026-09-29 11:27:42 +01:00
parent bc76f08bbd
commit 379420e7a9
10 changed files with 272 additions and 27 deletions
+9 -5
View File
@@ -53,8 +53,9 @@ authorize edits or start a task.
and stop the external client separately: Studio cannot prevent its direct file writes.
The current production tools cover context, references, task control, LSP,
build/pack and operation lookup/cancellation. Headless tool handlers are tested,
but remain undiscoverable until the real runtime gateway is composed. DEV is an
build/pack, operation lookup/cancellation and headless execution (17 tools).
Headless requires a runtime installation configured for the project; missing or
incompatible installations fail explicitly. DEV is an
observation panel, not manual Play/input for the agent's session; **Debug** retains
the human testing workflow. Edits are preserved on cancellation; Git/review/recovery
remain the developer's responsibility.
@@ -62,8 +63,8 @@ remain the developer's responsibility.
See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md)
for schemas, authorization, limits and delivery boundaries.
The real headless process adapter can be verified independently of its pending
task-service composition, using an extracted runtime distribution:
The real headless process adapter and task-service composition can be verified
using an extracted runtime distribution:
```bash
./gradlew :prometeu-app:headlessProcessTest -PstudioRuntimeInstall=/absolute/path/to/runtime
@@ -71,7 +72,10 @@ task-service composition, using an extracted runtime distribution:
This gate builds an installed PBS example, launches the actual runtime, checks
canonical PNGs and explicit reset/reboot, cancels an advance and verifies process
cleanup. It does not download a runtime or substitute a protocol fixture.
cleanup. It also runs the actual app composition through saved-file LSP queries,
rebuilds and corrective loops after compile errors and guest faults. It does not
download a runtime or substitute a protocol fixture. Full HTTP/visual integration
and external-agent acceptance remain subsequent integration gates.
## Requirements
@@ -293,6 +293,15 @@ from that session and are enforced without clamping. Shutdown detaches only afte
managed cleanup finishes. Runtime process supervision and protocol mapping belong
to the application gateway delivered in step 22, not to MCP or the test doubles.
Reset leaves the attached process unbooted, marks the previous capture stale and
retains its build association. A subsequent explicit `studio_headless_boot` with
that same current buildId reboots the known cartridge within the session. Boot
without reset while a runtime is attached is rejected as busy. Reset does not
change task authority or implicitly start execution. Rebuilding ends and detaches
that process, invalidates previous buildIds and requires a fresh explicit boot.
Synchronous headless failures finish their worker before returning the error,
so a corrective call cannot race the failed worker's admission lock.
Task-local operation/build records are discarded after worker termination on
return, revocation or project closure. Cleanup failures never restore authority;
the records are still discarded after managed work stops. Neither connection
@@ -429,14 +438,17 @@ authentication, Origin, endpoint/method/version handling, tool dispatch, malform
or oversized input, closure, restart and old-token rejection. Provider doubles
exist only in tests. Composition starts/closes transport with Studio.
The production registry composes `studio_project_context`, `studio_reference_read`
and `studio_language_query`, plus control acquire/release, build start and operation
get/cancel as of step 20 (eight tools). Headless handlers are implemented and
tested against the neutral port, but are advertised only when a real
`HeadlessGateway` is composed in the integration phase. No fake runtime is shipped.
The production registry composes all 17 tools as of step 23, including headless
handlers bound to the actual `HeadlessProcessGateway`. Missing project runtime
configuration fails at boot with `RUNTIME_UNAVAILABLE`; tool discovery does not
grant authority or launch a process. No fake runtime is shipped.
DEV configuration-copy is connected as of step 21. The automated HTTP conformance
gate exercises all 17 tool contracts using real project knowledge/LSP and test-only
build/runtime ports; a separate HTTP test uses the real compiler/packer. This
completes MCP-phase conformance, not real-process or external-agent acceptance.
completes MCP-phase conformance. The packaged-runtime gate additionally exercises
actual app composition, project LSP, compiler/packer, saved edits, explicit
reset/reboot, build identity invalidation and corrective loops after compile
errors/guest faults. Full HTTP/visual and external-agent acceptance remain
subsequent integration gates, not implied by this service-composition gate.
API/Core and
JavaFX MUST NOT import MCP/HTTP implementations; architecture tests enforce it.
+2 -1
View File
@@ -32,7 +32,7 @@ javafx {
}
// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests.
tasks.named<Test>("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class") }
tasks.named<Test>("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class") }
tasks.register<Test>("devDesktopTest") {
group = "verification"
description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)."
@@ -63,5 +63,6 @@ tasks.register<Test>("headlessProcessTest") {
classpath = sourceSets["test"].runtimeClasspath
useJUnitPlatform()
include("**/HeadlessInstalledRuntimeTest.class")
include("**/HeadlessTaskIntegrationTest.class")
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
}
@@ -313,6 +313,11 @@ public class StudioApplicationConfiguration {
return new p.studio.core.language.TaskLanguageQueries(projects, language);
}
@Bean
p.studio.core.runtime.HeadlessGateway headlessGateway(ObjectMapper mapper, ProjectLocalStudioSetupStore setup) {
return new p.studio.app.runtime.HeadlessProcessGateway(mapper, setup::load);
}
@Bean
p.studio.api.automation.TaskTools taskTools(p.studio.core.project.ProjectAccessRegistry projects,
ProjectCatalog catalog, p.studio.core.shipper.SavedProjectPreparation shipper,
@@ -30,12 +30,13 @@ class StudioApplicationConfigurationTest {
assertFalse(executor.isShutdown());
assertTrue(mcp.isRunning());
var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors();
org.junit.jupiter.api.Assertions.assertEquals(8, tools.size());
org.junit.jupiter.api.Assertions.assertEquals(17, tools.size());
assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway);
org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText());
org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText());
assertTrue(tools.toString().contains("studio_language_query"));
assertTrue(tools.toString().contains("studio_build_start"));
assertFalse(tools.toString().contains("studio_headless_boot"));
assertTrue(tools.toString().contains("studio_headless_boot"));
}
assertTrue(executor.isShutdown());
assertFalse(mcp.isRunning());
@@ -56,7 +56,7 @@ class McpTaskToolsTest {
}
@AfterEach void close() throws Exception {
buildGate.countDown();
if (runtime != null) runtime.gate.countDown();
if (runtime != null) { runtime.gate.countDown(); runtime.shutdownGate.complete(null); }
session.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS);
workers.shutdownNow();
}
@@ -70,7 +70,7 @@ class McpTaskToolsTest {
JsonNode completed(String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
JsonNode result;
do { result = poll(request); if (!List.of("RUNNING", "PENDING").contains(result.path("state").asText())) return result; Thread.sleep(5); }
do { result = poll(request); if (result.path("workerTerminated").asBoolean()) return result; Thread.sleep(5); }
while (System.nanoTime() < deadline);
fail("Operation did not finish: " + result); return null;
}
@@ -156,6 +156,34 @@ class McpTaskToolsTest {
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void resetAllowsOnlyExplicitRebootOfTheSameKnownBuild() throws Exception {
acquire(); String build = buildAndBoot();
var original = runtime;
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
value(call("studio_headless_reset", args()));
error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", "unknown")));
value(call("studio_headless_boot", args().put("buildId", build)));
assertSame(original, runtime);
assertEquals(TaskTools.HeadlessAction.BOOT, runtime.lastAction);
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
}
@Test void rebuildWaitsForShutdownAcknowledgementBeforeTouchingArtifacts() throws Exception {
acquire(); String build = buildAndBoot();
runtime.shutdownGate = new CompletableFuture<>();
failBuild = true;
value(call("studio_build_start", args().put("clientRequestId", "blocked-rebuild")));
assertTrue(runtime.shutdownEntered.await(2, TimeUnit.SECONDS));
assertEquals(1, builds.get());
assertFalse(poll("blocked-rebuild").path("workerTerminated").asBoolean());
error("BUSY", call("studio_headless_boot", args().put("buildId", build)));
runtime.shutdownGate.complete(null);
assertEquals("FAILED", completed("blocked-rebuild").path("result").path("status").asText());
assertEquals(2, builds.get());
error("BUILD_NOT_FOUND", call("studio_headless_boot", args().put("buildId", build)));
assertEquals(ControlState.AGENT_WORKING, session.snapshot().state());
}
@Test void cancellationPreservesKnownProgressAndReclaimWaitsForWorkerTermination() throws Exception {
acquire(); buildAndBoot(); runtime.hold = true;
String operation = value(call("studio_headless_advance", args().put("clientRequestId", "long").put("frames", 50))).path("operationId").asText();
@@ -354,18 +382,22 @@ class McpTaskToolsTest {
final String id = UUID.randomUUID().toString(), build;
final AtomicInteger advances = new AtomicInteger();
final CountDownLatch entered = new CountDownLatch(1), gate = new CountDownLatch(1);
final CountDownLatch shutdownEntered = new CountDownLatch(1);
CompletableFuture<Void> shutdownGate = CompletableFuture.completedFuture(null);
TaskTools.HeadlessAction lastAction;
volatile boolean stopped, hold, cancelled;
volatile AutomationOutcome.Kind kind = AutomationOutcome.Kind.SUCCEEDED;
Map<String, Object> input;
FakeRuntime(String build) { this.build = build; }
public String sessionId() { return id; }
public void cancel() { cancelled = true; }
public CompletionStage<Void> shutdown() { stopped = true; return CompletableFuture.completedFuture(null); }
public CompletionStage<Void> shutdown() { shutdownEntered.countDown(); return shutdownGate.thenRun(() -> stopped = true); }
public long maxFramesPerAdvance() { return 600; }
CanonicalCapture capture(long logical) { return new CanonicalCapture(id, build, logical, 900, 1, 1, 1,
Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aK1kAAAAASUVORK5CYII=")); }
public TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, Map<String, Object> input) {
this.input = input;
lastAction = action;
return new TaskTools.HeadlessReply(Map.of("sessionId", id), action == TaskTools.HeadlessAction.CAPTURE ? capture(5) : null);
}
public AutomationOutcome advance(long frames, Consumer<TrackedOperation.Progress> progress) {
@@ -9,6 +9,8 @@ import java.util.*;
/** Deliberately adversarial child process. Never packaged into production. */
public final class HeadlessFixture {
static final ObjectMapper MAPPER = new ObjectMapper();
// Allow normal JVM startup under load; call/cancel deadlines remain deliberately short.
static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 5000, 500, 150);
static String mode;
static void emit(JsonNode value) throws Exception {
byte[] bytes = (value.toString() + "\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8);
@@ -28,7 +30,7 @@ public final class HeadlessFixture {
var hello = MAPPER.createObjectNode().put("type", "hello").put("sessionId", "fixture").put("runtimeVersion", "fixture-only");
hello.putObject("protocolVersion").put("major", mode.equals("major") ? 2 : 1).put("minor", 3);
hello.set("capabilities", MAPPER.valueToTree(mode.equals("capabilities") ? Set.of("boot") : HeadlessWire.CAPABILITIES));
hello.set("limits", MAPPER.valueToTree(new HeadlessLimits(600, 4096, 4096, 1000, 500, 150)));
hello.set("limits", MAPPER.valueToTree(LIMITS));
if (mode.equals("limits")) ((com.fasterxml.jackson.databind.node.ObjectNode) hello.path("limits")).put("maxFrames", 900);
emit(hello);
if (mode.equals("descendant")) {
@@ -12,7 +12,7 @@ import static org.junit.jupiter.api.Assertions.*;
class HeadlessProcessSessionTest {
@TempDir Path root;
static final HeadlessLimits LIMITS = new HeadlessLimits(600, 4096, 4096, 1000, 500, 150);
static final HeadlessLimits LIMITS = HeadlessFixture.LIMITS;
final List<HeadlessProcessSession> sessions = new ArrayList<>();
HeadlessProcessSession start(String mode) throws Exception {
var process = new ProcessBuilder(HeadlessFixture.java(), "-cp", System.getProperty("java.class.path"), HeadlessFixture.class.getName(), mode).directory(root.toFile()).start();
@@ -0,0 +1,176 @@
package p.studio.app.runtime;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import p.studio.api.automation.*;
import p.studio.api.project.*;
import p.studio.api.session.*;
import p.studio.api.shipper.Shipper;
import p.studio.app.StudioApplicationConfiguration;
import p.studio.core.project.ProjectLocalStudioSetupStore;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** Actual app composition and saved-source services; no runtime/build/LSP doubles. */
class HeadlessTaskIntegrationTest {
@TempDir Path root;
ConfigurableApplicationContext app;
ProjectSession project;
TaskTools tasks;
LanguageQueries language;
ObjectMapper mapper;
Path source;
String task, code;
final Set<ProcessHandle> ownedProcesses = new HashSet<>();
@BeforeEach void open() throws Exception {
root = root.toRealPath();
String installation = System.getProperty("studio.test.runtimeInstall", "");
assertFalse(installation.isBlank(), "Supply -PstudioRuntimeInstall=<runtime distribution>");
app = new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(true).run();
mapper = app.getBean(ObjectMapper.class);
for (var ref : p.studio.compiler.FrontendRegistryService.require("pbs").documentation().orElseThrow().references(1, p.studio.AppMode.Game)) {
if (!ref.id().startsWith("pbs:example:game:1:")) continue;
Path file = root.resolve(ref.id().substring("pbs:example:game:1:".length()));
Files.createDirectories(file.getParent()); Files.writeString(file, ref.text());
}
source = root.resolve("src/main.pbs"); code = Files.readString(source);
var reference = app.getBean(ProjectCatalog.class).openProject(root);
app.getBean(ProjectLocalStudioSetupStore.class).save(reference, new ProjectLocalStudioSetup(installation, null));
project = app.getBean(ProjectSessionFactory.class).open(reference);
tasks = app.getBean(TaskTools.class); language = app.getBean(LanguageQueries.class);
assertTrue(project.automation().grant(false).toCompletableFuture().get(5, TimeUnit.SECONDS).success());
task = tasks.acquire(root).task().value();
}
@AfterEach void close() {
try { if (project != null) project.close(); }
finally { if (app != null) app.close(); }
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Managed runtime processes must stop on project closure");
}
TrackedOperation finished(String request) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
do {
var result = tasks.operation(root, task, new OperationLookup(null, request));
if (result.workerTerminated()) return result;
Thread.sleep(5);
} while (System.nanoTime() < deadline);
throw new AssertionError("Operation did not finish: " + request);
}
TrackedOperation build(String request) throws Exception {
tasks.build(root, task, request); return finished(request);
}
String successfulBuild(String request) throws Exception {
var result = build(request); assertNull(result.failure());
assertNotNull(result.buildResult()); assertTrue(result.buildResult().success(), result.buildResult().diagnostics().toString());
assertNotNull(result.buildId()); return result.buildId();
}
TaskTools.HeadlessReply call(TaskTools.HeadlessAction action, String build) {
var reply = tasks.headless(root, task, action, build, Map.of());
if (action == TaskTools.HeadlessAction.BOOT) {
String installation = Path.of(System.getProperty("studio.test.runtimeInstall")).toAbsolutePath().toString();
ProcessHandle.current().descendants().filter(process -> process.info().command().orElse("").startsWith(installation + "/"))
.forEach(ownedProcesses::add);
assertFalse(ownedProcesses.isEmpty(), "Observe the actual packaged runtime process");
}
return reply;
}
AutomationOutcome advance(String request) throws Exception {
tasks.advance(root, task, request, 3);
var result = finished(request); assertNull(result.failure(), String.valueOf(result.failure()));
assertNotNull(result.runtimeResult()); return result.runtimeResult();
}
com.fasterxml.jackson.databind.JsonNode diagnostics() {
return mapper.valueToTree(language.query(root, task, "diagnostics", Map.of("uri", source.toUri().toString()))).path("result");
}
void authorityRetained() { assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); }
@Test void savedEditsRebuildRealArtifactsAndCorrelateDevWithoutSnapshots() throws Exception {
assertTrue(diagnostics().isEmpty());
assertThrows(ControlDeniedException.class, () -> app.getBean(Shipper.class).prepare(project.projectReference(), ignored -> {}));
String first = successfulBuild("first");
String session = (String) call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId");
var initial = advance("initial");
assertEquals(AutomationOutcome.Kind.SUCCEEDED, initial.kind());
assertEquals(first, initial.capture().buildId());
assertArrayEquals(initial.capture().png(), project.automation().snapshot().capture().png());
call(TaskTools.HeadlessAction.RESET, null);
assertTrue(project.automation().snapshot().stale());
assertEquals(AutomationFailure.Code.NO_FRAME_AVAILABLE, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.CAPTURE, null)).failure().code());
assertEquals(session, call(TaskTools.HeadlessAction.BOOT, first).values().get("sessionId"));
assertArrayEquals(initial.capture().png(), advance("rebooted").capture().png());
// Native agent-style edit: same project files, no clean-tree or apply step.
Files.writeString(source, code.replace("Color.rgb(16, 20, 28)", "Color.rgb(80, 40, 20)"));
assertTrue(diagnostics().isEmpty());
String second = successfulBuild("second");
assertNotEquals(first, second);
assertTrue(project.automation().snapshot().stale());
assertTrue(finished("initial").captureStale());
assertEquals(AutomationFailure.Code.SESSION_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.STATE, null)).failure().code());
assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, first)).failure().code());
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Rebuild must stop the previous runtime");
assertNotEquals(session, call(TaskTools.HeadlessAction.BOOT, second).values().get("sessionId"));
var changed = advance("changed");
assertFalse(Arrays.equals(initial.capture().png(), changed.capture().png()));
assertEquals(second, project.automation().snapshot().capture().buildId());
assertFalse(project.automation().snapshot().stale());
authorityRetained();
assertTrue(tasks.release(root, task).toCompletableFuture().get(7, TimeUnit.SECONDS).success());
assertTrue(project.automation().snapshot().manualAllowed());
assertTrue(ownedProcesses.stream().noneMatch(ProcessHandle::isAlive), "Release must stop the runtime before returning control");
assertTrue(Files.readString(source).contains("Color.rgb(80, 40, 20)"));
}
@Test void compileAndGuestFailuresKeepAuthorityForCorrectiveBuilds() throws Exception {
String original = successfulBuild("original");
call(TaskTools.HeadlessAction.BOOT, original); advance("before-error");
Files.writeString(source, "fn frame( {");
assertFalse(diagnostics().isEmpty());
var failed = build("compile-error");
assertFalse(failed.buildResult().success()); assertNull(failed.buildId());
assertFalse(failed.buildResult().diagnostics().isEmpty());
assertFalse(project.automation().snapshot().diagnostics().isEmpty());
assertTrue(project.automation().snapshot().stale()); authorityRetained();
assertEquals(AutomationFailure.Code.BUILD_NOT_FOUND, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, original)).failure().code());
Files.writeString(source, code.replace("x = x + 1;", "x = x / (x - x);"));
assertTrue(diagnostics().isEmpty());
call(TaskTools.HeadlessAction.BOOT, successfulBuild("guest-error"));
var fault = advance("fault");
assertEquals(AutomationOutcome.Kind.GUEST_FAULT, fault.kind());
assertFalse(fault.diagnostics().isEmpty());
assertNotNull(call(TaskTools.HeadlessAction.FAULT, null).values().get("fault"));
authorityRetained();
Files.writeString(source, code);
assertTrue(diagnostics().isEmpty());
call(TaskTools.HeadlessAction.BOOT, successfulBuild("corrected"));
assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("working-again").kind());
authorityRetained();
}
@Test void unavailableRuntimeIsExplicitAndCanBeConfiguredWithinTheSameTask() throws Exception {
String build = successfulBuild("build");
var setup = app.getBean(ProjectLocalStudioSetupStore.class);
setup.save(project.projectReference(), ProjectLocalStudioSetup.defaults());
assertEquals(AutomationFailure.Code.RUNTIME_UNAVAILABLE, assertThrows(AutomationException.class,
() -> call(TaskTools.HeadlessAction.BOOT, build)).failure().code());
authorityRetained();
setup.save(project.projectReference(), new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"), null));
call(TaskTools.HeadlessAction.BOOT, build);
assertEquals(AutomationOutcome.Kind.SUCCEEDED, advance("configured").kind());
authorityRetained();
}
}
@@ -121,22 +121,29 @@ public final class DefaultTaskTools implements TaskTools {
handle = session.submit(data.task, "headless " + action, () -> {
HeadlessReply result;
if (action == HeadlessAction.BOOT) {
if (data.runtime != null) throw failure(AutomationFailure.Code.BUSY, "A headless session is already active");
if (data.runtime != null && !data.reset) throw failure(AutomationFailure.Code.BUSY, "A headless session is already active");
var build = buildId == null ? null : data.builds.get(buildId);
if (build == null) throw failure(AutomationFailure.Code.BUILD_NOT_FOUND, "No successful current task build with this ID");
var port = gateway.orElseThrow(() -> failure(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Headless process adapter is not composed"));
var runtime = port.boot(catalog.openProject(data.task.projectRoot()), buildId, build);
try { session.attachRuntime(data.task, runtime); }
catch (RuntimeException denied) { runtime.cancel(); runtime.shutdown().toCompletableFuture().join(); throw denied; }
data.runtime = runtime;
result = new HeadlessReply(Map.of("sessionId", runtime.sessionId(), "buildId", buildId), null);
if (data.runtime != null) {
if (!buildId.equals(data.runtimeBuildId)) throw failure(AutomationFailure.Code.BUILD_NOT_FOUND, "Reset session belongs to another build");
result = data.runtime.call(HeadlessAction.BOOT, Map.of());
} else {
var port = gateway.orElseThrow(() -> failure(AutomationFailure.Code.RUNTIME_UNAVAILABLE, "Headless process adapter is not composed"));
var runtime = port.boot(catalog.openProject(data.task.projectRoot()), buildId, build);
try { session.attachRuntime(data.task, runtime); }
catch (RuntimeException denied) { runtime.cancel(); runtime.shutdown().toCompletableFuture().join(); throw denied; }
data.runtime = runtime;
data.runtimeBuildId = buildId;
result = new HeadlessReply(Map.of("sessionId", runtime.sessionId(), "buildId", buildId), null);
}
data.reset = false;
} else if (action == HeadlessAction.SHUTDOWN) {
String sessionId = requireRuntime(data).sessionId();
stopRuntime(data);
result = new HeadlessReply(Map.of("sessionId", sessionId), null);
} else {
result = requireRuntime(data).call(action, input);
if (action == HeadlessAction.RESET) session.markCaptureStale();
if (action == HeadlessAction.RESET) { data.reset = true; session.markCaptureStale(); }
}
reply.set(result);
return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), result.capture());
@@ -150,6 +157,7 @@ public final class DefaultTaskTools implements TaskTools {
handle.cancel(); Thread.currentThread().interrupt();
throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call interrupted");
} catch (ExecutionException error) {
handle.termination().toCompletableFuture().join();
if (error.getCause() instanceof RuntimeException cause) throw cause;
throw failure(AutomationFailure.Code.INFRASTRUCTURE_FAILURE, "Headless call failed");
} catch (CancellationException error) {
@@ -164,6 +172,8 @@ public final class DefaultTaskTools implements TaskTools {
runtime.shutdown().toCompletableFuture().join();
data.session.detachRuntime(data.task, runtime);
data.runtime = null;
data.runtimeBuildId = null;
data.reset = false;
}
private TaskData data(AutomationSession session, String id) {
@@ -229,6 +239,8 @@ public final class DefaultTaskTools implements TaskTools {
final Map<String, Record> requests = new HashMap<>(), operations = new HashMap<>();
final Map<String, ShipperPrepareResult> builds = new ConcurrentHashMap<>();
volatile HeadlessGateway.Session runtime;
String runtimeBuildId;
boolean reset;
TaskData(AutomationSession session, TaskIdentity task) { this.session = session; this.task = task; }
}
}