Compare commits
9
Commits
1471b427f1
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
666a36d133
|
||
|
|
71b62a8e0a
|
||
|
|
da0b1008cc
|
||
|
|
23522f7589
|
||
|
|
71fb80efc3
|
||
|
|
1e17fc4d67
|
||
|
|
fa37d0d0c7
|
||
|
|
cd001ce2d9
|
||
|
|
e1e13b47ac
|
@@ -25,9 +25,5 @@ build
|
||||
|
||||
.DS_Store
|
||||
|
||||
# Discussion workflow state is local; only consolidated lessons are versioned.
|
||||
discussion/*
|
||||
!discussion/lessons/
|
||||
!discussion/lessons/**
|
||||
temp/
|
||||
temp/**
|
||||
|
||||
@@ -1,270 +1,100 @@
|
||||
# Prometeu Studio
|
||||
|
||||
Prometeu Studio is the desktop development environment for the Prometeu toolchain.
|
||||
|
||||
This repository packages the Studio shell together with the embedded services it depends on: compiler pipeline integration, asset packing, runtime/debug orchestration, and project-local Studio state. The current implementation is a Java/JavaFX multi-module Gradle build.
|
||||
|
||||
## What Lives Here
|
||||
|
||||
The root project is a monorepo with these main areas:
|
||||
|
||||
- `prometeu-app`: Spring Boot non-web composition, concrete adapters, packaging, and JavaFX entry point (`p.studio.app.StudioLauncher`).
|
||||
- `prometeu-studio-api`: toolkit-neutral Studio contracts and operation surfaces.
|
||||
- `prometeu-studio-core`: JavaFX-free project, session, assets, shipper, runtime, and execution services.
|
||||
- `prometeu-studio-ui-javafx`: the current human-facing JavaFX adapter.
|
||||
- `prometeu-packer`: embedded packer APIs and implementation used by Studio.
|
||||
- `prometeu-compiler`: compiler core, build pipeline, frontend APIs, and the PBS frontend.
|
||||
- `prometeu-infra`: shared infrastructure used across modules.
|
||||
- `docs/`: normative specifications and architectural references.
|
||||
- `discussion/`: workflow artifacts for agendas, decisions, plans, and lessons.
|
||||
- `test-projects/`: sample workspaces used for local development and tests.
|
||||
|
||||
## Current Product Shape
|
||||
|
||||
The Studio shell currently organizes the product around four workspaces:
|
||||
|
||||
- Assets
|
||||
- Debug
|
||||
- DEV (external-agent authorization and observation)
|
||||
- Shipper
|
||||
|
||||
At runtime, the app boots an embedded packer, restores project-local Studio state, and opens the Studio launcher window. Project creation currently scaffolds a Prometeu workspace with `prometeu.json`, `src/`, `assets/`, `build/`, `cartridge/`, `.workspace/`, and local Studio metadata.
|
||||
|
||||
## External Coding Agents (MCP)
|
||||
|
||||
Studio includes its own `mcp --project <absolute-root>` mode. Configure the native
|
||||
client once; project grants and desktop restarts no longer require copying ports
|
||||
or tokens. The initial integration targets Codex on macOS.
|
||||
|
||||
1. Install/stage Studio with its bundled Java runtime (see below). New projects
|
||||
prepare the local client entry during scaffolding. Opening an existing project
|
||||
also prepares its enabled integration automatically; Studio starts the shared
|
||||
MCP server itself. **DEV → Prepare assistant** retries preparation after resolving
|
||||
a reported setup conflict. Opening a project does not grant agent control.
|
||||
2. Open the coding client in the project directory. Trust the project and reload
|
||||
MCP once if the client requests it. Studio does not alter client approval policy.
|
||||
Tools can initialize/list even before the desktop is open or access is granted.
|
||||
3. Open the project in Studio and grant control in DEV (save first if prompted).
|
||||
Active Debug prevents granting. The connector discovers access automatically.
|
||||
4. The agent acquires a task, consults project/language/SDK references, edits saved
|
||||
project files with its native tools and validates through LSP/build. SDK and
|
||||
external libraries remain read-only.
|
||||
5. Recover uncertain operations by operationId/clientRequestId lookup within the
|
||||
same task; never replay build/advance blindly. Explicitly release control when
|
||||
done. Human reclaim also revokes access; stop direct external file edits separately.
|
||||
|
||||
The client invokes the same Studio artifact over stdio. It forwards to Studio's
|
||||
project-scoped loopback service using protected, transient
|
||||
`.studio/mcp/connection.json`. The permanent `.codex/config.toml` entry contains
|
||||
installed Java/classpath/root arguments, not credentials. Both local outputs are
|
||||
ignored by Git. Unrelated client settings are preserved; tracked or conflicting
|
||||
Studio entries require deliberate resolution. `.studio/setup.json` preserves
|
||||
neutral integration intent and existing runtime/editor settings.
|
||||
|
||||
After desktop restart, grant again in DEV. Keep the same client session and
|
||||
configuration; old task identities and operation receipts are not restored.
|
||||
DEV displays connection separately from project authority. No project-local
|
||||
launcher, Python transport script or embedded chat is required.
|
||||
|
||||
### Reading external source code
|
||||
|
||||
VS Code F12 opens SDK/core and admitted libraries as read-only documents, with
|
||||
hover, continued F12 and syntax highlighting. SDK/core stay bundled; no editorial
|
||||
copies are created. After a source revision changes or a session ends, navigate
|
||||
again instead of reusing old positions.
|
||||
|
||||
For MCP, use `studio_language_query` with `operation: "definition"`, then pass a
|
||||
returned `prometeu-source:` URI to `operation: "readExternalSource"`. The response
|
||||
contains `descriptor` and `text`; hover and definition accept the same URI within
|
||||
the owning task. Another task cannot reuse it. MCP does not require VS Code open.
|
||||
External or mixed edit proposals are refused in full. Library installation/cache
|
||||
management is outside this feature. See the [extension guide](tools/vscode-extension/README.md).
|
||||
|
||||
### Installation and IntelliJ development
|
||||
|
||||
Build and stage the complete distribution, including its Java runtime:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:stageStudioInstallation
|
||||
```
|
||||
|
||||
The macOS default is `~/Library/Application Support/Prometeu/Studio/current`.
|
||||
Staging validates a new version before atomically changing `current`, retaining
|
||||
older versions for rollback and running processes. Native client registration
|
||||
uses absolute paths and argument arrays, independent of shell PATH:
|
||||
|
||||
```text
|
||||
command: <installation>/current/runtime/bin/java
|
||||
args: ["-cp", "<installation>/current/lib/*", "p.studio.app.StudioLauncher", "mcp", "--project", "<absolute-project-root>"]
|
||||
```
|
||||
|
||||
For development, use an isolated installation:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:stageStudioInstallation -PstudioInstallationRoot=/absolute/dev-installation
|
||||
```
|
||||
|
||||
In IntelliJ, run/debug `p.studio.app.StudioLauncher` with the `prometeu-app`
|
||||
runtime classpath and VM option `-Dstudio.installationRoot=/absolute/dev-installation`.
|
||||
The desktop and client-owned connector are separate JVMs. To debug the latter,
|
||||
add the development-only VM argument
|
||||
`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005`
|
||||
before `-cp` in the local MCP entry, restart that MCP process, then use IntelliJ's
|
||||
**Remote JVM Debug** on localhost:5005. Do not commit this local configuration.
|
||||
Because manual edits to the managed entry are protected, restore its original
|
||||
content before using preparation again. Regular registration never enables JDWP.
|
||||
|
||||
The packaged automated gate checks bundled Java, upgrade/rollback, project paths
|
||||
with spaces, minimal environment, scaffold/preparation and JavaFX startup:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:installedConnectorTest
|
||||
```
|
||||
|
||||
The current production tools cover context, references, task control, LSP,
|
||||
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.
|
||||
|
||||
See the [MCP contract](docs/specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md)
|
||||
for schemas, authorization, limits and delivery boundaries.
|
||||
|
||||
### Troubleshooting automation
|
||||
|
||||
| Symptom | Action |
|
||||
| --- | --- |
|
||||
| Waiting for access / desktop restarted | Open the project and grant again in DEV. Keep the existing client configuration. |
|
||||
| Stale connection / incompatible catalog | Grant fresh access, or update the installed Studio when versions differ. Do not edit transient credentials. |
|
||||
| Preparation conflict | Preserve the existing client settings; resolve a tracked/user-owned/edited Studio table explicitly, then prepare again. |
|
||||
| Acquisition rejected or project busy | Grant control in DEV first; stop manual Debug before granting. Query an existing operation instead of starting another; serialize headless calls. |
|
||||
| `RUNTIME_UNAVAILABLE` or handshake incompatibility | Check the project's configured runtime installation and its packaged headless command. Studio does not download a substitute. |
|
||||
| `NO_FRAME_AVAILABLE` | Advance at least one frame before requesting a capture. |
|
||||
| Advance/page limit rejected | Respect advertised limits and use reference pagination. Runtime's default maximum is 600 frames per advance; requests are not silently clamped. |
|
||||
| Unknown language or missing reference | Inspect project context and the declared manifest language; use only advertised capabilities/reference IDs. PBS is a creation default, not an unknown-language fallback. |
|
||||
| Returning control reports cleanup failure | Stop the external client's direct editing separately, then retry DEV reclaim after owned-process cleanup. Do not bypass the lock or restore stale editor buffers. |
|
||||
|
||||
Language and SDK references are bundled locally; reading them does not require a
|
||||
compiler checkout or network download. SDK/external-library changes remain outside
|
||||
the game-authoring task, even when a reference exposes a limitation.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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 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.
|
||||
|
||||
To verify the complete HTTP-to-runtime-to-DEV image path, run this separate gate
|
||||
in a desktop environment:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:headlessMcpDesktopTest -PstudioRuntimeInstall=/absolute/path/to/runtime --max-workers=2
|
||||
```
|
||||
|
||||
It opens the real DEV view, grants control, uses an HTTP MCP client to query LSP,
|
||||
edit/build the installed PBS example and execute a fixed input timeline. PNG bytes,
|
||||
frame identities, state and fault are compared with a separate direct-JSONL runtime
|
||||
process; every decoded ImageView pixel and its visible identity/stale label are
|
||||
checked. Reset, fresh-session repetition and rebuild are included. This automated
|
||||
client is not the external coding-agent acceptance gate.
|
||||
|
||||
The same suite also exercises cancellation, disconnect/reconnect, revocation,
|
||||
project/app closure, crash and forced shutdown, corrective builds, and return to
|
||||
the real manual Debug host. These scenarios require a POSIX desktop (validated
|
||||
on macOS ARM64) and free port 7777. Only processes created by the test are killed
|
||||
or suspended. After a forced-shutdown error, an explicit second reclaim can
|
||||
acknowledge completed cleanup; control stays locked until cleanup is confirmed.
|
||||
|
||||
### Follow-ups after the AI-first implementation
|
||||
|
||||
The following findings are recorded for investigation after implementation; they
|
||||
are not considered fixed by the passing integration tests:
|
||||
|
||||
- **PBS/LSP SDK navigation:** the historical probe of the former `Input.pad()`
|
||||
API returned no location; the current input API is `Pad`/`Button` and `Touch`. Project-source navigation and indexed SDK reference
|
||||
reads work. Investigate SDK symbol resolution separately; an empty definition
|
||||
result is not evidence of missing runtime support or permission to edit the SDK.
|
||||
- **Build tooling:** the validation environment's JDK 25 triggers Kotlin's target-24
|
||||
fallback and Java/Kotlin target compatibility warnings in `buildSrc`. The targeted
|
||||
regression passes, but the toolchain/target alignment needs separate review.
|
||||
|
||||
Cross-platform desktop coverage remains a validation boundary, not a confirmed
|
||||
product defect. Baseline HTTP desktop acceptance covers macOS ARM64 and Codex CLI only. The integrated stdio flow completed its separate acceptance gates through automated validation and user-confirmed native-client, graphical-launch and IntelliJ checks; see [LSN-0077](discussion/lessons/DSC-0070-studio-persistent-mcp-connector/LSN-0077-integrated-mcp-stable-setup-and-ephemeral-access.md) for evidence provenance.
|
||||
|
||||
The first real Codex CLI acceptance run exercised editing, LSP, build/pack, input,
|
||||
1,110 frames, native MCP images and explicit release. The developer confirmed the
|
||||
DEV result and successfully ran the edited game using manual Debug Play afterward.
|
||||
Additional follow-ups from that run: clearer errors for oversized
|
||||
reference pages, guidance for sequential headless queries after `BUSY`, and easier
|
||||
discovery of framebuffer dimensions. Capture before the first completed frame
|
||||
correctly returns `NO_FRAME_AVAILABLE`; it is not a runtime defect. Noninteractive
|
||||
clients must also provide an approval path for MCP work calls; the acceptance used
|
||||
Codex's approval review with a project-scoped workspace-write sandbox.
|
||||
|
||||
The completed baseline's architecture, acceptance evidence and post-implementation
|
||||
follow-ups are consolidated in [LSN-0076](discussion/lessons/DSC-0068-studio-headless-runtime-ai-first/LSN-0076-ai-first-studio-through-shared-authority-and-headless-evidence.md).
|
||||
It combines a JavaFX application with compiler integration, asset packing, project
|
||||
services and runtime orchestration in a multi-module Java/Gradle build.
|
||||
|
||||
## Requirements
|
||||
|
||||
- JDK 21 or newer recommended for local development
|
||||
- Gradle wrapper (`./gradlew`) included in the repository
|
||||
- JDK 25 for compilation, tests and the bundled application runtime
|
||||
- The included Gradle wrapper (Gradle 9.3.1)
|
||||
- A desktop environment capable of running JavaFX
|
||||
- A qualified native Prometeu runtime installation for running games
|
||||
|
||||
## Common Commands
|
||||
## Getting Started
|
||||
|
||||
Run the full project graph listing:
|
||||
|
||||
```bash
|
||||
./gradlew projects
|
||||
```
|
||||
|
||||
Run the desktop application:
|
||||
Run these commands from the Studio repository root:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:run
|
||||
```
|
||||
|
||||
Run the test suite:
|
||||
Open an existing project from the project chooser and select a qualified runtime
|
||||
installation. Use Play, Pause, Resume and Stop to run the game inside Studio.
|
||||
Games with saves require an existing development save image or an explicitly
|
||||
disposable session. Close the project before opening another.
|
||||
|
||||
The default frontend is `prometeu-studio-ui-javafx-2`. It provides project opening
|
||||
and integrated Play; editors, Assets/DEV/Shipper workspaces and MCP grant controls
|
||||
are outside its current UI. Play prepares a cartridge directory for execution;
|
||||
distribution/export is a separate concern.
|
||||
|
||||
See the [development guide](docs/development.md) for installation, runtime
|
||||
qualification, IntelliJ setup, MCP integration and integration test commands.
|
||||
The [integrated Play specification](docs/specs/studio/14.%20Integrated%20Play%20Specification.md)
|
||||
defines execution, input and save behavior.
|
||||
|
||||
## Build and Test
|
||||
|
||||
```bash
|
||||
./gradlew build
|
||||
./gradlew test
|
||||
```
|
||||
|
||||
Generate the aggregated coverage report:
|
||||
|
||||
```bash
|
||||
./gradlew jacocoTestReport
|
||||
```
|
||||
|
||||
## Repository Reading Guide
|
||||
`test` runs unit tests and excludes JUnit `@Tag("integration")`. The aggregated
|
||||
JaCoCo report uses unit test results. Process, network and desktop checks have
|
||||
[separate opt-in commands](docs/development.md#integration-checks).
|
||||
|
||||
If you are new to the codebase, this order is usually the fastest path:
|
||||
Stage a complete installation with its bundled Java runtime:
|
||||
|
||||
1. Start at `prometeu-app` to see application bootstrap.
|
||||
2. Read `prometeu-studio-api` and `prometeu-studio-core` for Studio contracts and application services.
|
||||
3. Read `prometeu-studio-ui-javafx` for the current shell, workspaces, and human-facing flows.
|
||||
4. Read `prometeu-app` for Spring composition and provider gateways.
|
||||
5. Read `prometeu-packer` for asset and packaging boundaries.
|
||||
6. Read `prometeu-compiler` when you need compiler or PBS language behavior.
|
||||
```bash
|
||||
./gradlew :prometeu-app:stageStudioInstallation
|
||||
```
|
||||
|
||||
## Specs And Architecture
|
||||
The default installation root is
|
||||
`~/Library/Application Support/Prometeu/Studio`; `current` selects its active
|
||||
version. See [installation and development](docs/development.md#installation-and-intellij-development)
|
||||
for an isolated development installation.
|
||||
|
||||
Important reference surfaces:
|
||||
## Repository Structure
|
||||
|
||||
| Area | Responsibility |
|
||||
| --- | --- |
|
||||
| `prometeu-app` | Spring Boot composition, concrete adapters, packaging and the `p.studio.app.StudioLauncher` entry point |
|
||||
| `prometeu-studio-api` | Toolkit-neutral Studio contracts and operations |
|
||||
| `prometeu-studio-core` | JavaFX-free project, session, asset, shipper and execution services |
|
||||
| `prometeu-studio-ui-javafx-2` | Default frontend and presentation foundation |
|
||||
| `prometeu-studio-ui-javafx` | Previous frontend retained for adapter compatibility checks |
|
||||
| `prometeu-compiler` | Compiler core, build pipeline, frontend APIs and PBS frontend |
|
||||
| `prometeu-packer` | Asset packing APIs and implementation |
|
||||
| `prometeu-infra` | Shared infrastructure |
|
||||
| `test-projects` | Sample projects and integration fixtures |
|
||||
| `docs` | Technical guides, specifications and architecture references |
|
||||
| `discussion/lessons` | Published engineering lessons and their assets |
|
||||
|
||||
Run `./gradlew projects` to list the complete module graph.
|
||||
|
||||
Start with `prometeu-app` for application bootstrap, then read
|
||||
`prometeu-studio-api` and `prometeu-studio-core` for contracts and services.
|
||||
The [JavaFX 2 module guide](prometeu-studio-ui-javafx-2/README.md) covers the current
|
||||
frontend. Follow the compiler and packer modules for their respective pipelines.
|
||||
|
||||
<a id="external-coding-agents-mcp"></a>
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Development guide](docs/development.md): installation, MCP, troubleshooting and integration checks
|
||||
- [Specification guide](docs/specs/README.md): domain ownership and reading order
|
||||
- [General compiler](docs/specs/compiler/README.md): shared compiler specifications
|
||||
- [PBS](docs/specs/compiler-languages/pbs/README.md): language and SDK specifications
|
||||
- [Studio](docs/specs/studio/README.md): shell, workspaces and integration contracts
|
||||
- [Packer](docs/specs/packer/README.md): packer specifications
|
||||
- `docs/vm-arch/`: VM and ISA architecture references
|
||||
- [Studio](docs/specs/studio/README.md): application, services and integration contracts
|
||||
- [Compiler](docs/specs/compiler/README.md): shared compiler contracts
|
||||
- [PBS](docs/specs/compiler-languages/pbs/README.md): language and SDK
|
||||
- [Packer](docs/specs/packer/README.md): asset and packaging contracts
|
||||
- [VM architecture](docs/vm-arch/README.md): VM/ISA references and provenance
|
||||
- [VS Code extension](tools/vscode-extension/README.md): language tooling and external source navigation
|
||||
|
||||
These documents are the long-term normative source for behavior and contracts. When code and docs diverge, fix the divergence explicitly instead of relying on tribal knowledge.
|
||||
Engineering discussions, decisions, plans, build/acceptance results and pending
|
||||
investigations belong to the enclosing
|
||||
[Prometeu Engineering workspace](../README.md) in
|
||||
[AI Engineering](../.ai-engineering/README.md). See [AGENTS.md](AGENTS.md) before
|
||||
contributing.
|
||||
|
||||
+4
-3
@@ -12,18 +12,19 @@ dependencies {
|
||||
|
||||
val jacocoTestReport = tasks.register<JacocoReport>("jacocoTestReport") {
|
||||
group = "Verification"
|
||||
description = "Generates a consolidated JaCoCo report for all subprojects."
|
||||
description = "Generates consolidated unit-test coverage for all subprojects."
|
||||
|
||||
val javaSubprojects = subprojects.filter { subproject ->
|
||||
subproject.subprojects.isEmpty() && subproject.plugins.hasPlugin("java")
|
||||
}
|
||||
|
||||
dependsOn(javaSubprojects.map { it.tasks.withType<JacocoReport>() })
|
||||
dependsOn(javaSubprojects.map { it.tasks.named("jacocoTestReport") })
|
||||
|
||||
additionalSourceDirs.setFrom(javaSubprojects.map { it.layout.projectDirectory.dir("src/main/java") })
|
||||
sourceDirectories.setFrom(javaSubprojects.map { it.layout.projectDirectory.dir("src/main/java") })
|
||||
classDirectories.setFrom(javaSubprojects.map { it.layout.buildDirectory.dir("classes/java/main") })
|
||||
executionData.setFrom(fileTree(projectDir).include("**/build/jacoco/*.exec"))
|
||||
// Opt-in integration tasks must not contribute coverage to the unit gate.
|
||||
executionData.setFrom(javaSubprojects.map { it.layout.buildDirectory.file("jacoco/test.exec") })
|
||||
|
||||
reports {
|
||||
xml.required.set(true)
|
||||
|
||||
@@ -2,6 +2,14 @@ plugins {
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
// Build logic can target Java 21 while the Studio product uses the Java 25 toolchain.
|
||||
// Gradle's embedded Kotlin compiler does not yet emit JVM 25 bytecode.
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) } }
|
||||
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
mavenCentral()
|
||||
|
||||
@@ -29,12 +29,15 @@ dependencies {
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(21)
|
||||
languageVersion = JavaLanguageVersion.of(25)
|
||||
}
|
||||
}
|
||||
|
||||
jacoco { toolVersion = libs.findVersion("jacoco").get().requiredVersion }
|
||||
|
||||
tasks.named<Test>("test") {
|
||||
useJUnitPlatform()
|
||||
description = "Runs unit tests only; integration verification belongs to prometeu-tooling."
|
||||
useJUnitPlatform { excludeTags("integration") }
|
||||
finalizedBy("jacocoTestReport")
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -116,7 +116,7 @@ for runtime evidence. The intrinsic/native catalogue goldens are serialization
|
||||
fixtures and do not claim current PBS catalogue compatibility.
|
||||
|
||||
Reproduce with the commands in
|
||||
[the harness README](../../../tools/pbx-conformance/README.md). The harness
|
||||
[the harness README](../../../../tooling/scripts/pbx-conformance/README.md). The harness
|
||||
creates its Cargo build outside the runtime checkout and saves generated PBX and
|
||||
observed JSON under the build-pipeline build directory.
|
||||
|
||||
@@ -140,6 +140,6 @@ slot-to-type inference to conceal an incomplete handoff.
|
||||
|
||||
- [Typed common Registry/PBX specification](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md)
|
||||
- [Backend conformance matrix](../../../docs/specs/compiler/22.%20Backend%20Spec-to-Test%20Conformance%20Matrix.md)
|
||||
- [Runtime qualification harness](../../../tools/pbx-conformance/README.md)
|
||||
- [Runtime qualification harness](../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
- Runtime sources: registry_v0.rs, program_image.rs, registry_verifier, and
|
||||
devtools/headless-protocol/response.schema.json at the revision above.
|
||||
|
||||
+1
-1
@@ -172,7 +172,7 @@ and behavior together. Roll back that set together if necessary.
|
||||
- [Normative catalog support](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md)
|
||||
- [Typed common Registry/PBX contract](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md)
|
||||
- [VM mirror and provider verification policy](../../../docs/vm-arch/README.md)
|
||||
- [Production runtime harness](../../../tools/pbx-conformance/README.md)
|
||||
- [Production runtime harness](../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
- Runtime sources at the recorded revision: catalog.rs, builtins.rs,
|
||||
input_intrinsics.rs, math_intrinsics.rs, random_intrinsics.rs, random.rs,
|
||||
registry_verifier/{heights,types}.rs and tests/numeric_contract.rs.
|
||||
|
||||
+1
-1
@@ -80,4 +80,4 @@ Frontend negatives cover invalid Button arguments, mixed int/long variables, lit
|
||||
- [Shared runtime catalog contract](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md)
|
||||
- [Typed registry and PBX contract](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md)
|
||||
- [PBS source-to-PBX qualification](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java)
|
||||
- [Actual-runtime harness instructions](../../../tools/pbx-conformance/README.md)
|
||||
- [Actual-runtime harness instructions](../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ The installed knowledge package includes the specification and an executable [ar
|
||||
## Implementation references
|
||||
|
||||
- [Source conformance tests](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStructuredValuesTest.java)
|
||||
- [Runtime harness and reproduction instructions](../../../tools/pbx-conformance/README.md)
|
||||
- [Runtime harness and reproduction instructions](../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
- [Static semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md)
|
||||
- [Dynamic semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md)
|
||||
- [Earlier typed common IR/PBX lesson](../DSC-0074-compiler-pbx-registry-conformance/LSN-0079-typed-common-ir-to-production-pbx.md)
|
||||
|
||||
+1
-1
@@ -109,5 +109,5 @@ Common mistakes to avoid:
|
||||
|
||||
- [Normative function and capture specification](../../../docs/specs/compiler-languages/pbs/15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
|
||||
- [Implementation evidence and reproducible commands](../../evidence/DSC-0080-implementation/README.md).
|
||||
- [Production VM conformance harness](../../../tools/pbx-conformance/README.md).
|
||||
- [Production VM conformance harness](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/closures.pbs).
|
||||
|
||||
+1
-1
@@ -152,7 +152,7 @@ explicitly reported by the full harness; original payloads are preserved.
|
||||
|
||||
- [Service constants and runtime math specification](../../../docs/specs/compiler-languages/pbs/19.%20Service%20Constants%20and%20Runtime%20Math%20Specification.md)
|
||||
- [Runtime catalog policy](../../../docs/specs/compiler/24.%20Runtime%20Catalog%20Support%20Specification.md)
|
||||
- [Production harness](../../../tools/pbx-conformance/README.md)
|
||||
- [Production harness](../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
- [Catalog-port lesson](../DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md)
|
||||
- Historical execution artifacts: DEC-0069 and PLN-0148, removed by CLI housekeeping after completion.
|
||||
|
||||
|
||||
+1
-1
@@ -154,7 +154,7 @@ SDK/spec/example delivery, not execution through an installed runtime process.
|
||||
- [PBS Random specification](../../../docs/specs/compiler-languages/pbs/20.%20Runtime%20Random%20Integration%20Specification.md).
|
||||
- [Typed arrays and optional execution](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md).
|
||||
- [Functions and captures](../../../docs/specs/compiler-languages/pbs/15.%20First-Class%20Functions%20and%20Captures%20Specification.md).
|
||||
- [Conformance commands and boundaries](../../../tools/pbx-conformance/README.md).
|
||||
- [Conformance commands and boundaries](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Provider Random specification](../../../../runtime/docs/specs/runtime/02e-vm-owned-random-core.md).
|
||||
- [Provider qualification](../../../../runtime/docs/vm-arch/RANDOM_QUALIFICATION.md).
|
||||
- Historical accepted DEC-0070 and completed PLN-0149: obligations are preserved
|
||||
|
||||
+1
-1
@@ -155,6 +155,6 @@ remains DSC-0085. Other platforms are not claimed by this evidence.
|
||||
- [PBS lowering](<../../../docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md>).
|
||||
- [Common typed Registry/PBX](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md).
|
||||
- [Source-to-PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsGuestLifecycleTest.java).
|
||||
- [Production VM/foreground harness](../../../tools/pbx-conformance/lifecycle.rs).
|
||||
- [Production VM/foreground harness](../../../../tooling/scripts/pbx-conformance/lifecycle.rs).
|
||||
- [Installed lifecycle guide](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/LIFECYCLE.md).
|
||||
- Runtime [role binding](../../../../runtime/docs/specs/runtime/02c-program-registry-and-pbx-v0.md) and [controlled execution](../../../../runtime/docs/specs/runtime/09a-coroutines-and-cooperative-scheduling.md).
|
||||
|
||||
+1
-1
@@ -192,5 +192,5 @@ Build/Play/UI/MCP deployment remain outside this capacity and belong to DSC-0086
|
||||
- [Project-local state and media selection](<../../../docs/specs/studio/8. Project-Local Studio State Specification.md>).
|
||||
- [DEV and automation](<../../../docs/specs/studio/10. DEV and Automation Specification.md>).
|
||||
- [MCP tool contract](<../../../docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md>).
|
||||
- [Producer/native/process runner](../../../tools/pbx-conformance/README.md).
|
||||
- [Producer/native/process runner](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Independent runtime provider lesson](../../../../runtime/discussion/lessons/DSC-0068-memcard-public-host-persistence/LSN-0073-public-persistence-is-a-process-and-ownership-contract.md).
|
||||
|
||||
+1
-1
@@ -185,7 +185,7 @@ legacy integration cases; production fixtures exercise the required paths.
|
||||
Additional focused cases cover mutual recursion and imported alias navigation.
|
||||
Workflow validation and whitespace checks passed before completion.
|
||||
|
||||
Reproduce with the gates in the [conformance harness documentation](../../../tools/pbx-conformance/README.md).
|
||||
Reproduce with the gates in the [conformance harness documentation](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
The new specification and `contracts.pbs` example are discoverable in installed
|
||||
knowledge, not only in the source checkout.
|
||||
|
||||
|
||||
+1
-1
@@ -248,7 +248,7 @@ production corpus, full regressions and pinned provenance.
|
||||
and [ordinary typed storage](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/collections.rs).
|
||||
- [Source fixture generator](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java),
|
||||
[neutral IR fixtures](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java)
|
||||
and [production harness instructions](../../../tools/pbx-conformance/README.md).
|
||||
and [production harness instructions](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Mutation-phase migration](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md),
|
||||
[generic structs lesson](../DSC-0094-pbs-generic-structs/LSN-0089-concrete-generic-state-and-bodies.md)
|
||||
and [generic contracts lesson](../DSC-0089-pbs-generic-contracts/LSN-0088-concrete-generic-contracts-from-source-to-vm.md).
|
||||
|
||||
+1
-1
@@ -231,7 +231,7 @@ NonFiniteValue, remain explicitly reported with original payloads.
|
||||
- [SDK source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs),
|
||||
[source corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java),
|
||||
[neutral producer](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java)
|
||||
and [production harness instructions](../../../tools/pbx-conformance/README.md).
|
||||
and [production harness instructions](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Current provider typed storage](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/collections.rs),
|
||||
[sequential mutation migration](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md)
|
||||
and [List/Cursor lesson](../DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md).
|
||||
|
||||
+1
-1
@@ -214,5 +214,5 @@ JUnit cases are listed separately from the mandatory runtime corpus.
|
||||
- [Common Registry/PBX specification](../../../docs/specs/compiler/25.%20Typed%20Registry%20and%20PBX%20v0%20Specification.md).
|
||||
- [SDK collection source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs).
|
||||
- [Set source fixtures](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSetTest.java).
|
||||
- [Conformance tooling and reproduction](../../../tools/pbx-conformance/README.md).
|
||||
- [Conformance tooling and reproduction](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Sequential mutation predecessor](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md).
|
||||
|
||||
+1
-1
@@ -189,6 +189,6 @@ evidence and are not counted as new Map conformance.
|
||||
- [Executable installed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/maps.pbs).
|
||||
- [SDK algorithms](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs).
|
||||
- [Source-to-PBX qualification](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsMapKeyvalTest.java).
|
||||
- [Harness reproduction](../../../tools/pbx-conformance/README.md).
|
||||
- [Harness reproduction](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Set/Identity predecessor](../DSC-0092-pbs-sdk-set/LSN-0093-reusable-identity-and-source-set-buckets.md).
|
||||
- [Sequential mutation boundaries](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md).
|
||||
|
||||
+1
-1
@@ -204,7 +204,7 @@ they are not silently relabeled as schema conformance or fixed in runtime here.
|
||||
- [List/Cursor](../../../docs/specs/compiler-languages/pbs/21.%20SDK%20List%20and%20Cursor%20Specification.md),
|
||||
[Linked](../../../docs/specs/compiler-languages/pbs/22.%20SDK%20Linked%20and%20Cursor%20Specification.md) and
|
||||
[Array/optional](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md).
|
||||
- [Conformance commands and coverage](../../../tools/pbx-conformance/README.md).
|
||||
- [Conformance commands and coverage](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Selected provider pin](../../../docs/vm-arch/runtime-catalog.properties).
|
||||
- Original decisions/planning: accepted DEC-0077 and completed PLN-0155 in DSC-0096,
|
||||
consolidated here before their required housekeeping removal.
|
||||
|
||||
+2
-2
@@ -187,7 +187,7 @@ Avoid these maintenance mistakes:
|
||||
[shared Cursor](../../../docs/specs/compiler-languages/pbs/21.%20SDK%20List%20and%20Cursor%20Specification.md).
|
||||
- [SDK algorithms](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs).
|
||||
- [Source/PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java).
|
||||
- [Conformance module](../../../tools/pbx-conformance/stack_queue.rs) and
|
||||
[reproduction instructions](../../../tools/pbx-conformance/README.md).
|
||||
- [Conformance module](../../../../tooling/scripts/pbx-conformance/stack_queue.rs) and
|
||||
[reproduction instructions](../../../../tooling/scripts/pbx-conformance/README.md).
|
||||
- [Sequential mutation lessons](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md).
|
||||
- [Evidence and R1–R9 coverage](evidence/README.md).
|
||||
|
||||
+1
-1
@@ -153,7 +153,7 @@ Normative source: PBS [3 — Core Syntax](../../../docs/specs/compiler-languages
|
||||
[14 — Typed Arrays/Optional](../../../docs/specs/compiler-languages/pbs/14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md)
|
||||
and [Compiler 14 — Resolution/Linking](../../../docs/specs/compiler/14.%20Name%20Resolution%20and%20Module%20Linking%20Specification.md).
|
||||
|
||||
Reproduction: [production corpus runner guide](../../../tools/pbs-production-corpus/README.md),
|
||||
Reproduction: [production corpus runner guide](../../../../tooling/scripts/pbs-production-corpus/README.md),
|
||||
[installed expectations](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/production/cases.json),
|
||||
[installed probe](../../../prometeu-app/src/test/java/p/studio/app/compiler/ProductionContractsInstalledProbe.java)
|
||||
and [quoted-project parser tests](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/parser/PbsQuotedProjectTest.java).
|
||||
|
||||
+1
-1
@@ -93,4 +93,4 @@ Diagnostic ownership, stable detector IDs, source attribution and failure classi
|
||||
|
||||
Normative obligations are propagated to PBS [4 — Static Semantics](../../../docs/specs/compiler-languages/pbs/4.%20Static%20Semantics%20Specification.md), [12 — Diagnostics](../../../docs/specs/compiler-languages/pbs/12.%20Diagnostics%20Specification.md), and [13 — Lowering IRBackend](../../../docs/specs/compiler-languages/pbs/13.%20Lowering%20IRBackend%20Specification.md). Existing PBS [3 — Core Syntax](../../../docs/specs/compiler-languages/pbs/3.%20Core%20Syntax%20Specification.md), [5 — Resolution](../../../docs/specs/compiler-languages/pbs/5.%20Manifest%2C%20Stdlib%2C%20and%20SDK%20Resolution%20Specification.md), and [9 — Dynamic Semantics](../../../docs/specs/compiler-languages/pbs/9.%20Dynamic%20Semantics%20Specification.md) remain authoritative for the unchanged language contracts.
|
||||
|
||||
Durable regressions live in [PbsProductionLoweringRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsProductionLoweringRegressionTest.java), [PbsNominalOwnerRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/lowering/PbsNominalOwnerRegressionTest.java), and the [unchanged corpus resource](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json). The maintained [runner guide](../../../tools/pbs-production-corpus/README.md) describes reproduction. DEC-0088 and PLN-0166 are completed control artifacts consolidated here; their workflow files are removed by CLI housekeeping.
|
||||
Durable regressions live in [PbsProductionLoweringRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PbsProductionLoweringRegressionTest.java), [PbsNominalOwnerRegressionTest](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/lowering/PbsNominalOwnerRegressionTest.java), and the [unchanged corpus resource](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/resources/production-regressions/cases.json). The maintained [runner guide](../../../../tooling/scripts/pbs-production-corpus/README.md) describes reproduction. DEC-0088 and PLN-0166 are completed control artifacts consolidated here; their workflow files are removed by CLI housekeeping.
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
# Studio Development Guide
|
||||
|
||||
Run commands from the Studio repository root unless stated otherwise.
|
||||
This guide covers installation, native runtime qualification, external tooling
|
||||
and opt-in integration checks. See the [project README](../README.md) for the
|
||||
application overview and basic build commands.
|
||||
|
||||
## Native Runtime Installation and Qualification
|
||||
|
||||
Build the native umbrella distribution with `../runtime/scripts/local-dist.sh`.
|
||||
It packages `prometeu`, `prometeu-runtime` (desktop/Studio Play) and
|
||||
`prometeu-headless` (deterministic automation). Select the extracted
|
||||
`../runtime/dist-staging/stable/prometeu-cli-<target>` directory in Studio.
|
||||
An unchanged dispatcher can belong to several releases: Studio selects a profile
|
||||
only when all three executable hashes match the same qualified bundle.
|
||||
|
||||
After changing a native binary, qualify the actual installation before building
|
||||
or launching Studio with its updated catalog:
|
||||
|
||||
```sh
|
||||
make -C ../tooling venv
|
||||
../tooling/.venv/bin/python ../tooling/scripts/qualify.py \
|
||||
--studio . \
|
||||
--runtime ../runtime/dist-staging/stable/prometeu-cli-aarch64-apple-darwin
|
||||
```
|
||||
|
||||
This command executes the native glyph/scene 16/17 boundary test afresh, verifies
|
||||
the evidence and executable identities, then publishes an exact capacity profile
|
||||
under `prometeu-app/src/main/resources/asset-capacity`. Review/include those
|
||||
resources when distributing Studio. It neither builds a replacement runtime nor
|
||||
relaxes the execution guard. A failed qualification publishes no catalog entry.
|
||||
The native build stays independent of the JVM; qualification is an explicit
|
||||
consumer verification step, separate from pressing Play.
|
||||
|
||||
## Installation and IntelliJ Development
|
||||
|
||||
Build and stage the complete distribution, including its Java runtime:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:stageStudioInstallation
|
||||
```
|
||||
|
||||
The macOS default is `~/Library/Application Support/Prometeu/Studio/current`.
|
||||
Staging validates a new version before atomically changing `current`, retaining
|
||||
older versions for rollback and running processes. Native client registration
|
||||
uses absolute paths and argument arrays, independent of shell PATH:
|
||||
|
||||
```text
|
||||
command: <installation>/current/runtime/bin/java
|
||||
args: ["-cp", "<installation>/current/lib/*", "p.studio.app.StudioLauncher", "mcp", "--project", "<absolute-project-root>"]
|
||||
```
|
||||
|
||||
For development, use an isolated installation:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:stageStudioInstallation -PstudioInstallationRoot=/absolute/dev-installation
|
||||
```
|
||||
|
||||
In IntelliJ, run/debug `p.studio.app.StudioLauncher` with the `prometeu-app`
|
||||
runtime classpath and VM option `-Dstudio.installationRoot=/absolute/dev-installation`.
|
||||
The desktop and client-owned connector are separate JVMs. To debug the latter,
|
||||
add the development-only VM argument
|
||||
`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005`
|
||||
before `-cp` in the local MCP entry, restart that MCP process, then use IntelliJ's
|
||||
**Remote JVM Debug** on localhost:5005. Do not commit this local configuration.
|
||||
Because manual edits to the managed entry are protected, restore its original
|
||||
content before using preparation again. Regular registration never enables JDWP.
|
||||
|
||||
## External Coding Agents (MCP)
|
||||
|
||||
The following authorization workflow belongs to the previous DEV adapter. The new
|
||||
Play UI does not yet expose a grant/configuration surface. Headless protocol,
|
||||
task authority, MCP tool schemas and the installed stdio connector retain their
|
||||
existing entry points.
|
||||
|
||||
Studio includes its own `mcp --project <absolute-root>` mode. Configure the native
|
||||
client once; project grants and desktop restarts no longer require copying ports
|
||||
or tokens. The initial integration targets Codex on macOS.
|
||||
|
||||
1. Install/stage Studio with its bundled Java runtime (see installation above).
|
||||
New projects prepare the local client entry during scaffolding. Opening an existing project
|
||||
also prepares its enabled integration automatically; Studio starts the shared
|
||||
MCP server itself. **DEV → Prepare assistant** retries preparation after resolving
|
||||
a reported setup conflict. Opening a project does not grant agent control.
|
||||
2. Open the coding client in the project directory. Trust the project and reload
|
||||
MCP once if the client requests it. Studio does not alter client approval policy.
|
||||
Tools can initialize/list even before the desktop is open or access is granted.
|
||||
3. Open the project in Studio and grant control in DEV (save first if prompted).
|
||||
Active Debug prevents granting. The connector discovers access automatically.
|
||||
4. The agent acquires a task, consults project/language/SDK references, edits saved
|
||||
project files with its native tools and validates through LSP/build. SDK and
|
||||
external libraries remain read-only.
|
||||
5. Recover uncertain operations by operationId/clientRequestId lookup within the
|
||||
same task; never replay build/advance blindly. Explicitly release control when
|
||||
done. Human reclaim also revokes access; stop direct external file edits separately.
|
||||
|
||||
The client invokes the same Studio artifact over stdio. It forwards to Studio's
|
||||
project-scoped loopback service using protected, transient
|
||||
`.studio/mcp/connection.json`. The permanent `.codex/config.toml` entry contains
|
||||
installed Java/classpath/root arguments, not credentials. Both local outputs are
|
||||
ignored by Git. Unrelated client settings are preserved; tracked or conflicting
|
||||
Studio entries require deliberate resolution. `.studio/setup.json` preserves
|
||||
neutral integration intent and existing runtime/editor settings.
|
||||
|
||||
After desktop restart, grant again in DEV. Keep the same client session and
|
||||
configuration; old task identities and operation receipts are not restored.
|
||||
DEV displays connection separately from project authority. No project-local
|
||||
launcher, Python transport script or embedded chat is required.
|
||||
|
||||
### Reading external source code
|
||||
|
||||
VS Code F12 opens SDK/core and admitted libraries as read-only documents, with
|
||||
hover, continued F12 and syntax highlighting. SDK/core stay bundled; no editorial
|
||||
copies are created. After a source revision changes or a session ends, navigate
|
||||
again instead of reusing old positions.
|
||||
|
||||
For MCP, use `studio_language_query` with `operation: "definition"`, then pass a
|
||||
returned `prometeu-source:` URI to `operation: "readExternalSource"`. The response
|
||||
contains `descriptor` and `text`; hover and definition accept the same URI within
|
||||
the owning task. Another task cannot reuse it. MCP does not require VS Code open.
|
||||
External or mixed edit proposals are refused in full. Library installation/cache
|
||||
management is outside this feature. See the [extension guide](../tools/vscode-extension/README.md).
|
||||
|
||||
The production tools cover context, references, task control, LSP,
|
||||
build/pack, operation lookup/cancellation and headless execution.
|
||||
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.
|
||||
|
||||
See the [MCP contract](specs/studio/11.%20MCP%20Tools%20and%20Project%20Knowledge%20Contract.md)
|
||||
for schemas, authorization, limits and delivery boundaries.
|
||||
|
||||
### Troubleshooting automation
|
||||
|
||||
| Symptom | Action |
|
||||
| --- | --- |
|
||||
| Waiting for access / desktop restarted | Open the project and grant again in DEV. Keep the existing client configuration. |
|
||||
| Stale connection / incompatible catalog | Grant fresh access, or update the installed Studio when versions differ. Do not edit transient credentials. |
|
||||
| Preparation conflict | Preserve the existing client settings; resolve a tracked/user-owned/edited Studio table explicitly, then prepare again. |
|
||||
| Acquisition rejected or project busy | Grant control in DEV first; stop manual Debug before granting. Query an existing operation instead of starting another; serialize headless calls. |
|
||||
| `RUNTIME_UNAVAILABLE` or handshake incompatibility | Check the project's configured runtime installation and its packaged headless command. Studio does not download a substitute. |
|
||||
| `NO_FRAME_AVAILABLE` | Advance at least one frame before requesting a capture. |
|
||||
| Advance/page limit rejected | Respect advertised limits and use reference pagination. Runtime's default maximum is 600 frames per advance; requests are not silently clamped. |
|
||||
| Unknown language or missing reference | Inspect project context and the declared manifest language; use only advertised capabilities/reference IDs. PBS is a creation default, not an unknown-language fallback. |
|
||||
| Returning control reports cleanup failure | Stop the external client's direct editing separately, then retry DEV reclaim after owned-process cleanup. Do not bypass the lock or restore stale editor buffers. |
|
||||
|
||||
Language and SDK references are bundled locally; reading them does not require a
|
||||
compiler checkout or network download. SDK/external-library changes remain outside
|
||||
the game-authoring task, even when a reference exposes a limitation.
|
||||
|
||||
## Integration Checks
|
||||
|
||||
Unit tests run through `./gradlew test`. Process, network, desktop and actual
|
||||
application/provider composition checks use separate integration tasks, including
|
||||
fixture subprocesses. These suites remain in Studio; `../tooling` prepares their
|
||||
environment and orchestrates selected commands.
|
||||
Integration checks are excluded from the runtime and Studio pipelines.
|
||||
|
||||
### Installed Studio Connector
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:installedConnectorTest
|
||||
```
|
||||
|
||||
Checks bundled Java, upgrade/rollback, project paths with spaces, minimal
|
||||
environment, scaffolding/preparation and JavaFX startup.
|
||||
|
||||
### Integrated Play
|
||||
|
||||
Requires a desktop environment and an installed native runtime:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:studioPlayProcessTest -PstudioRuntimeInstall=/absolute/runtime-install
|
||||
./gradlew :prometeu-app:studioPlayDesktopTest -PstudioRuntimeInstall=/absolute/runtime-install
|
||||
```
|
||||
|
||||
Add `-PstudioPlayStress=true` for the 30-second presentation/FX-delay/20-cycle
|
||||
check. Fixtures use a disposable copy of `test-projects/pong`. No external port
|
||||
checkout is required. Changed native executables require renewed qualification
|
||||
as described above.
|
||||
|
||||
### Headless Runtime and Application Composition
|
||||
|
||||
Use an extracted runtime distribution:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:headlessProcessTest -PstudioRuntimeInstall=/absolute/path/to/runtime
|
||||
```
|
||||
|
||||
Exercises the real runtime, installed PBS examples, canonical PNGs, reset/reboot,
|
||||
cancellation and process cleanup, plus saved-file LSP/build corrective loops.
|
||||
The task requires the supplied runtime installation.
|
||||
|
||||
### MCP and DEV Desktop Integration
|
||||
|
||||
This check exercises the retained DEV adapter. It requires a POSIX desktop and
|
||||
free port 7777:
|
||||
|
||||
```bash
|
||||
./gradlew :prometeu-app:headlessMcpDesktopTest -PstudioRuntimeInstall=/absolute/path/to/runtime --max-workers=2
|
||||
```
|
||||
|
||||
The HTTP client drives LSP, build and a fixed input timeline; output and visible
|
||||
DEV pixels are compared with a separate direct-JSONL runtime process. Scenarios
|
||||
include reset, cancellation, disconnect/reconnect, revocation, project/app closure,
|
||||
crash, forced shutdown and return to manual Debug. Only test-owned processes are
|
||||
terminated or suspended. After a forced-shutdown error, a second explicit reclaim
|
||||
can acknowledge completed cleanup; control stays locked until cleanup is confirmed.
|
||||
|
||||
These commands describe available checks. Record actual runs, environment,
|
||||
results, acceptance evidence and pending investigations in the owning AIE Work.
|
||||
@@ -22,13 +22,15 @@ The runtime repository owns PBX, ISA, admission and VM execution. Studio's
|
||||
their separate provenance and synchronization policy. [Roadmaps](../roadmaps/)
|
||||
describe cross-domain planning, not an alternative contract source.
|
||||
|
||||
The operational lifecycle is `agenda -> decision -> plan -> implement -> lesson`.
|
||||
Keep its artifacts in `discussion/` and use the local `discussion` CLI for state
|
||||
transitions, validation and housekeeping. See [repository instructions](../../AGENTS.md).
|
||||
Engineering discussions, decisions, plans and execution evidence are maintained
|
||||
in the enclosing workspace's [AI Engineering project](../../../.ai-engineering/README.md).
|
||||
Published lessons and supporting assets remain in `discussion/lessons/`.
|
||||
See [repository instructions](../../AGENTS.md).
|
||||
|
||||
## Navigation verification
|
||||
|
||||
Run `python3 tools/documentation/verify.py` from the repository root to check local
|
||||
Run `../tooling/.venv/bin/python ../tooling/scripts/documentation/verify.py --root .`
|
||||
from the Studio repository root to check local
|
||||
links and anchors. Pass `--runtime ../runtime` to also check provider references
|
||||
against an available read-only runtime checkout. The byte-exact architecture/ISA
|
||||
mirrors retain the link context of their runtime originals; the checker resolves
|
||||
|
||||
+1
-1
@@ -126,4 +126,4 @@ remain separately pending; local results and cross-compilation do not qualify th
|
||||
|
||||
- [Common runtime catalog support](../../compiler/24.%20Runtime%20Catalog%20Support%20Specification.md)
|
||||
- [Runtime numeric contract](../../../../../runtime/docs/specs/runtime/02d-gameplay-math-and-numeric-semantics.md)
|
||||
- [Production conformance harness](../../../../tools/pbx-conformance/README.md)
|
||||
- [Production conformance harness](../../../../../tooling/scripts/pbx-conformance/README.md)
|
||||
|
||||
@@ -903,4 +903,4 @@ Sibling-file callable/global/service surfaces MUST use declaration/signature-lev
|
||||
|
||||
Nominal receiver/method binding MUST retain the originating declaration and lexical scope, including aliases and synthesized receiver types. A private homonym introduced through a dependency cannot replace a local declaration or create an ambiguous executable target merely by sharing spelling. Transient IDs and PBX byte equality across builds are not nominal-identity requirements.
|
||||
|
||||
Conformance: PbsProductionLoweringRegressionTest and PbsNominalOwnerRegressionTest cover the frozen 28-case corpus, contextual overloads, privacy by signature, shared storage/singletons and order-sensitive effects. The maintained source-to-guest matrix is tools/pbs-production-corpus/run.py.
|
||||
Conformance: PbsProductionLoweringRegressionTest and PbsNominalOwnerRegressionTest cover the frozen 28-case corpus, contextual overloads, privacy by signature, shared storage/singletons and order-sensitive effects. The maintained source-to-guest matrix is ../tooling/scripts/pbs-production-corpus/run.py.
|
||||
|
||||
@@ -187,8 +187,8 @@ frontend syntax and lowering remain consumer-owned.
|
||||
| Stable declarations, nominal identity, structural deduplication and cycles | LinkedRegistryTest; IRBackendExecutableContractTest | pass | Common API and linking |
|
||||
| Complete typed signatures, captures, roles and implementations | PbxRegistryConformanceTest; TypedCommonPipelineTest | pass | Common IR through emission |
|
||||
| Exact PBX mandatory tables and multi-slot signatures | Independent 194-byte oracle; fixed vec2 function bytes | pass | Wire format, not a self round-trip |
|
||||
| Runtime final admission and execution | tools/pbx-conformance/run.py | pass | Closure, trait, array, Dynamic, intrinsic, roles, joins, native binding; vec2 load-only |
|
||||
| Invalid structures, references, code and resource refusal | tools/pbx-conformance/main.rs mutation corpus | pass | Production loader, default/lowered limits |
|
||||
| Runtime final admission and execution | ../tooling/scripts/pbx-conformance/run.py | pass | Closure, trait, array, Dynamic, intrinsic, roles, joins, native binding; vec2 load-only |
|
||||
| Invalid structures, references, code and resource refusal | ../tooling/scripts/pbx-conformance/main.rs mutation corpus | pass | Production loader, default/lowered limits |
|
||||
| Structured initialization and binding diagnostics | HeadlessProcessSessionTest; observed runtime JSON fixtures | pass | Preserves full payload through MCP, including null outer PC |
|
||||
| Published schema covers current runtime reasons | Actual LifecycleRole/NonFiniteValue payloads against runtime schema | partial | Runtime enum/schema mismatch recorded in AGD75; no payload rewriting |
|
||||
| PBS migration and integrated delivery | AGD75 and consumer tickets | partial | Existing PBS suite passing is not complete executable lowering evidence |
|
||||
|
||||
@@ -196,7 +196,7 @@ Run the focused common tests, then the production harness:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
../tooling/.venv/bin/python ../tooling/scripts/pbx-conformance/run.py --studio . --runtime ../runtime
|
||||
```
|
||||
|
||||
The Java tests write `build/registry-conformance` inside the build-pipeline
|
||||
|
||||
@@ -41,7 +41,8 @@ are stable and do not imply language-version numbers.
|
||||
Write specs in English with title, status, scope, authority, normative rules,
|
||||
non-goals and conformance/exit criteria. Keep one owner per detailed contract;
|
||||
summaries link to it. Only settled decisions may change normative behavior.
|
||||
Agendas, decisions and plans live in `discussion/`, and completed teaching
|
||||
material lives in `discussion/lessons/`; they are not parallel spec sources.
|
||||
Engineering discussions, decisions and plans live in the enclosing workspace's
|
||||
AI Engineering project. Published teaching material remains in
|
||||
`discussion/lessons/`; neither is a parallel spec source.
|
||||
|
||||
See the [specification guide](../README.md) for other domains.
|
||||
|
||||
@@ -6,6 +6,11 @@ Purpose: Define the normative shell structure of the Studio UI.
|
||||
|
||||
## Authority and Precedence
|
||||
|
||||
This document describes the retained previous frontend. The normal application's
|
||||
replacement shell/project flow is governed by specifications
|
||||
[13](13.%20JavaFX%202%20Foundation%20Specification.md) and
|
||||
[14](14.%20Integrated%20Play%20Specification.md), which take precedence for UI2.
|
||||
|
||||
This specification consolidates the accepted Studio shell decision into normative form. DEC-0060 adds DEV and project-scoped automation authority; its detailed behavior is owned by the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md).
|
||||
|
||||
## Normative Inputs
|
||||
|
||||
@@ -411,7 +411,7 @@ mature gameplay library is not a prerequisite.
|
||||
- Replacing compiler, Packer, LSP, VM or human Debug semantics; a new general-purpose Studio source editor.
|
||||
- Remote MCP, accounts/OAuth and network runtime discovery. Studio-owned stdio and local Codex preparation are the explicit DEC-0061 additions.
|
||||
- Additional language implementation, persistent operation recovery or automatic task resumption.
|
||||
- Integrated discussion-framework agendas/decisions/plans in the product; those are future work, not this runtime/DEV/MCP contract.
|
||||
- Product-integrated engineering workflow management is outside this runtime/DEV/MCP contract.
|
||||
|
||||
## Exit Criteria
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# JavaFX 2 Foundation Specification
|
||||
|
||||
Status: Implemented foundation and default product frontend. Owner: `studio`.
|
||||
|
||||
## Scope and precedence
|
||||
|
||||
This document governs `prometeu-studio-ui-javafx-2`, an independent replacement frontend foundation. It defines the minimal shell, presentation components, themes, localization and typography. It does not redefine Studio API/Core, MCP, asset banks or runtime contracts.
|
||||
|
||||
The normal application now uses this frontend, with project/Play integration owned
|
||||
by the [Integrated Play Specification](14.%20Integrated%20Play%20Specification.md).
|
||||
The previous module is retained for consultation and adapter qualification.
|
||||
Specifications 1–4 describe its shell/components/workspaces; they are not a visual
|
||||
template for JavaFX 2. Later capabilities must extend the foundation through their
|
||||
own explicit contracts.
|
||||
|
||||
## Shell
|
||||
|
||||
The standalone foundation launch MUST show a native-decorated window with Studio
|
||||
identity, presentation selectors and an empty working area. The product mounts its
|
||||
chooser/Play view there. Minimum outer size is 680×480; the foundation initial scene
|
||||
is 1200×800, and the integrated product starts at 1200×850. Toolbar content MUST
|
||||
wrap/reflow instead of requiring horizontal scrolling at the minimum width.
|
||||
|
||||
The shell component and standalone demonstrations MUST NOT initialize a project,
|
||||
backend graph, runtime or agent. Product services are injected into a separate
|
||||
coordinator by the app. There MUST be no fictitious editor tabs or domain panels.
|
||||
The component gallery is a separate developer launch, not a product workspace.
|
||||
|
||||
## Presentation ownership
|
||||
|
||||
An `AppearanceContext` owns presentation state and subscriptions for one window and MUST be closed when that window is hidden. A closed context MUST NOT accept updates. Reopening MUST construct a new context. Components MUST retain normal JavaFX semantics for keyboard, focus, editing and accessibility, while exposing Studio appearance and small APIs.
|
||||
|
||||
Reusable families are text/title, decorative pixel icon, button, toggle, text field, non-editable selector, panel and message/progress feedback. Error appearance MUST have explanatory text. Text meaning MUST NOT depend on color alone. Custom geometry MUST NOT replace native interaction with a rasterized whole-window surface.
|
||||
|
||||
## Themes and geometry
|
||||
|
||||
The dark and light themes MUST provide matching semantic color tokens for background/workspace/surface/field, text/muted text, border, highlight/shadow, accent/on-accent, focus and error. Shared state styles MUST use those tokens. Theme changes MUST update active controls and selector popups in place without losing entered text.
|
||||
|
||||
Stepped corners and layered relief are the foundation's visual direction. Region outlines MUST be recomputed at actual layout dimensions so corner steps do not grow with panel width. Main text MUST remain vector-rendered and independently scalable. Palette and geometry refinements MUST preserve legibility, interaction and the agreed identity.
|
||||
|
||||
Normal text contrast targets are at least 4.5:1, large text 3:1, and necessary control/focus indicators 3:1. These are design/verification references, not an accessibility certification.
|
||||
|
||||
## Fonts and configuration
|
||||
|
||||
Departure Mono MUST be the default interior family; Roboto Mono MUST be available locally as an alternative. Both MUST ship with full SIL OFL 1.1 copyright and license notices. Loading MUST NOT require network access or preinstalled fonts. Font failure MUST diagnose and use a readable fallback.
|
||||
|
||||
Family and text scale MUST be configurable through presentation settings, not hardcoded in consumers. Supported text scale is 75–200%, default 100%. The developer gallery exposes these choices and comparable editable text. This contract does not require a full preferences window or system-font manager. Native window decoration remains platform-owned.
|
||||
|
||||
## Localization and persistence
|
||||
|
||||
The UI MUST support pt-BR and English, including runtime labels, accessible names and feedback. English is the fallback bundle. A missing translation MUST diagnose and fall back; an unknown key MUST remain identifiable as `[key]`. Bundles MUST have matching key sets in verification. Formatting MUST use the active locale. Changing locale MUST preserve user-authored text.
|
||||
|
||||
First launch MUST select dark, Departure Mono and 100% scale. A supported system locale selects pt-BR; otherwise English. Explicit choices MUST restore without a game project. Invalid individual preference values MUST fall back independently. Persistence MUST remain local presentation state, execute outside the FX thread and flush the latest selection on orderly close. It MUST NOT migrate or mutate the previous frontend's project-local state.
|
||||
|
||||
## Verification and non-goals
|
||||
|
||||
The foundation MUST have display-free tests of its own locale/preferences/resources/contracts and opt-in real desktop qualification. Desktop checks MUST identify environment/output scale, include normal/minimum sizes and inspect both themes, locales and fonts. Tests MUST exercise active popup appearance, focus/Tab, clipboard, state retention and close/reopen. Performance evidence MUST identify the measured operation; a CSS/layout measurement MUST NOT be presented as total frame latency.
|
||||
|
||||
Initial qualification is on available macOS. Windows/Linux, assistive-technology walkthroughs and native IME composition require their own evidence. Logical scene snapshots MUST NOT be presented as proof of physical pixel alignment at every HiDPI scale.
|
||||
|
||||
Project navigation and integrated Play are specified separately by specification
|
||||
14. Document host, free docking, ACP, asset workflows, code/LSP editor, scene/entity
|
||||
authoring, pixels/audio editing and shipping remain outside this foundation
|
||||
contract. Backend integrations MUST use existing application services; domain logic
|
||||
MUST NOT be duplicated here.
|
||||
@@ -0,0 +1,157 @@
|
||||
# Integrated Play Specification
|
||||
|
||||
Status: Implemented first interactive slice. Owner: `studio`.
|
||||
|
||||
## Product and scope
|
||||
|
||||
The normal `prometeu-app` launcher and managed installation MUST use
|
||||
`prometeu-studio-ui-javafx-2`. The standalone foundation shell and gallery remain
|
||||
development entry points. The previous frontend is retained for existing adapter
|
||||
qualification; its workspaces are not mounted in the new product.
|
||||
|
||||
Startup MUST show known projects and an action to open an existing project
|
||||
directory. A project MUST be closed before another can open. Closing returns to
|
||||
the chooser. Startup MUST NOT automatically restore the previous project.
|
||||
|
||||
This slice exposes Play, Pause, Resume, Stop, a game viewport, and bounded logs.
|
||||
It MUST NOT initialize an AI client or editor/LSP infrastructure when opening for
|
||||
Play. Existing headless, MCP, evidence, tests and agent contracts remain available
|
||||
through their existing entry points and services. Their preservation takes
|
||||
precedence over interactive convenience.
|
||||
|
||||
Project creation UI, editors, workspaces, AI prompts, tuning during Play,
|
||||
breakpoints, hot reload, PMC builds and distribution/export are outside this
|
||||
slice. Future packaging belongs in Studio as a separate action; Play MUST NOT
|
||||
implicitly package a PMC or a distributable runtime.
|
||||
|
||||
## Preparation, process and authority
|
||||
|
||||
Play MUST reuse the compiler/Packer/Shipper preparation pipeline to produce the
|
||||
cartridge directory. Managed asset capacity, input revision and artifact identity
|
||||
guards MUST remain enforced against the selected runtime installation. A changed
|
||||
runtime requires a newly qualified capacity profile; the consumer MUST NOT infer
|
||||
equivalence from its version string or bypass the guard.
|
||||
|
||||
Core owns execution orchestration and an exclusive project lease. The lease MUST
|
||||
cover preparation, connection, running, paused and stopping phases until actual
|
||||
preparation termination and native process/worker cleanup. Other project writes
|
||||
MUST be rejected at service admission, including writes initiated outside the UI.
|
||||
Preparation by the execution owner has a scoped admission path; it MUST NOT grant
|
||||
an arbitrary caller permission to edit. The frontend MUST disable configuration
|
||||
through the same ownership interval. A state label alone MUST NOT release ownership.
|
||||
|
||||
The application adapter MUST start a direct, owned `prometeu-runtime` child in
|
||||
interactive `--studio` mode, without a native game window. This does not compile
|
||||
Rust for the JVM or load native VM code into Java. Wire and process mechanics
|
||||
belong to `prometeu-app`, behind neutral API/Core ports. UI2 MUST depend only on
|
||||
Studio API and its presentation toolkit, never Core, concrete providers or the
|
||||
previous frontend.
|
||||
|
||||
Process/control/video/log workers MUST use a per-connection executor independent
|
||||
of the bounded operation pool. FX code MUST NOT wait for compilation, sockets,
|
||||
native process exit or worker joins. Native process completion and worker cleanup
|
||||
are prerequisites for returning project authority. Failed/stale attempts MUST NOT
|
||||
change a replacement execution's lifecycle.
|
||||
|
||||
## Lifecycle and focus
|
||||
|
||||
Play prepares, connects, waits for READY, and issues START. Pause freezes logical
|
||||
game advancement and audio without replacing the machine. Resume continues that
|
||||
same session. Pause requested during preparation/connection MUST arm a paused
|
||||
startup; START alone MUST NOT undo it. Stop cancels/waits for preparation or asks
|
||||
the native host to stop and confirms teardown.
|
||||
|
||||
Minimizing or switching focus to another application MUST pause. Returning focus
|
||||
or restoring the window MUST NOT automatically resume. Windows/popups owned by
|
||||
Studio MUST be treated as part of Studio. A focus loss during an asynchronous
|
||||
Resume MUST still result in pause once the runtime becomes running.
|
||||
|
||||
Closing a project or Studio MUST stop its game before closing the project session.
|
||||
A normal Stop or close that is refused by save protection MUST retain the paused
|
||||
session and its lease, explain the refusal in logs, and allow manual Resume.
|
||||
|
||||
Required IPC failure MUST close channels, terminate the owned native process,
|
||||
retain bounded diagnostics and restore controls after cleanup. There MUST be no
|
||||
automatic reconnect/restart, process-name-based termination or loss of headless
|
||||
capabilities as a recovery mechanism. A new Play requires a new explicit action.
|
||||
|
||||
## Save media
|
||||
|
||||
For a game declaring save slots, the human MUST select an existing development
|
||||
save image or explicitly select a disposable session. The frontend MUST NOT
|
||||
silently create, overwrite or discard persistent media. The disposable choice is
|
||||
per Play and MUST NOT be silently restored as a persistent project preference.
|
||||
Existing agent/indentation setup fields MUST be preserved when runtime/save paths
|
||||
are saved.
|
||||
|
||||
Normal Stop MUST wait for pending IO or refuse if it cannot finish safely, and
|
||||
MUST refuse uncommitted persistent data. Disposable Stop may discard only because
|
||||
that session was explicitly selected. IPC failure is the bounded forced-teardown
|
||||
exception; it MUST be reported rather than represented as a successful save.
|
||||
|
||||
## Presentation and input
|
||||
|
||||
The binary [Studio Play protocol](../../../../runtime/docs/specs/runtime/11b-studio-play-protocol.md)
|
||||
uses independent control/input and video channels, bounded messages, session and
|
||||
epoch correlation, and one video credit returned after full reception. The native
|
||||
tick MUST NOT wait for FX or socket writes. Unsent presentation frames may be
|
||||
replaced by the latest complete publication; partial wire messages MUST finish or
|
||||
fail. Control messages MUST NOT be dropped as a presentation optimization.
|
||||
|
||||
Java reception converts RGBA8 to premultiplied BGRA on an IO worker. Three CPU
|
||||
buffers have explicit free, receiving, pending and presentation ownership, with
|
||||
at most one presentation lease. A leased image MUST remain stable until close.
|
||||
FX polls the latest complete frame on a pulse, copies it to an FX-owned
|
||||
`WritableImage`, and releases the lease. Reception MUST NOT enqueue one FX task
|
||||
per frame. Logs and frontend projections MUST remain bounded.
|
||||
|
||||
Zoom choices MUST be x1, x2 and x4 with nearest-neighbor presentation. At x1 a
|
||||
640×360 game occupies 640×360 logical pixels, respecting OS scale; it does not mean
|
||||
one physical display pixel. Oversized images MUST retain zoom and scroll. The UI
|
||||
MUST NOT silently fit the image or change zoom.
|
||||
|
||||
Input MUST invert the image's scene transform and selected logical zoom. Touch
|
||||
outside the image MUST release/reject touch rather than clamp to an edge. Keyboard
|
||||
input belongs to the focused viewport, with modifiers reserved for application
|
||||
shortcuts. Pad keys are arrows, A/D/W/S for A/B/X/Y, Q/E for L/R, Z for Start and
|
||||
Shift for Select. Focus loss and lifecycle changes MUST neutralize held input;
|
||||
native epochs reject input from older execution phases.
|
||||
|
||||
The only native machine output is 640×360 RGBA8888 at 60 Hz. The new JavaFX 2
|
||||
viewport obtains dimensions from complete runtime publications; it MUST NOT keep
|
||||
an independent fallback resolution. Leaving the image cancels an active contact;
|
||||
dragging back while still held MUST NOT recapture without a new press inside.
|
||||
Zoom and scroll continue to operate in JavaFX logical coordinates, with scene
|
||||
transforms accounting for host display scaling. These frontend changes apply to
|
||||
the new UI only; the old UI is outside the current graphics migration scope.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
The product baseline is Java 25, retaining JavaFX 23.0.2. The bundled image uses an
|
||||
explicit JDK `jmods` module path for jlink. Build logic may target Java 21 bytecode;
|
||||
that is not the Studio application baseline.
|
||||
|
||||
Qualification MUST cover actual installed startup, existing-game image/input,
|
||||
pause/resume and focus, project close, dirty-save refusal and cross-mode readback,
|
||||
broken channels, slow presentation/receiver, bounded buffers, repeated sessions,
|
||||
and preserved headless/MCP/evidence/tests. Codec fixtures alone are insufficient.
|
||||
|
||||
`studioPlayDesktopTest` is an opt-in desktop gate. `-PstudioPlayStress=true` adds a
|
||||
30-second idle-host measurement, deliberate FX suspension and twenty cycles.
|
||||
Receive-to-copy latency uses `System.nanoTime` in the same JVM; it MUST NOT be
|
||||
called end-to-end input latency or physical scanout latency. CPU/heap observations
|
||||
and hardware/OS/build flavor MUST accompany performance claims. A heap-used sample
|
||||
does not prove retained-memory bounds; ownership and resource tests do.
|
||||
|
||||
Executed functional qualification includes macOS ARM64 with Java 25 and the release
|
||||
umbrella distribution produced by `runtime/scripts/local-dist.sh`, including real
|
||||
Pong Play and the deterministic headless process. Capacity qualification identifies
|
||||
the dispatcher and both native backends as one exact bundle; multiple releases may
|
||||
share an unchanged dispatcher. The explicit qualification command is documented in
|
||||
the [development guide](../../development.md#native-runtime-installation-and-qualification).
|
||||
|
||||
Earlier presentation performance measurements used debug native binaries.
|
||||
Windows/Linux, release performance, physical HiDPI pixel alignment, and human
|
||||
listening/IME/accessibility walkthroughs require separate evidence. Diagnostic runs
|
||||
and failures remain in Work evidence; a later passing run does not establish their
|
||||
unobserved cause.
|
||||
@@ -20,6 +20,13 @@ Define the normative contract for Studio project-local persistence under `.studi
|
||||
|
||||
## Authority and Precedence
|
||||
|
||||
The new Play frontend preserves stored workspace state but does not mount or
|
||||
restore previous workspaces and never automatically opens the last project.
|
||||
Runtime/save path updates preserve indentation and agent intent. Presentation
|
||||
preferences remain separate from `.studio/state.json`; disposable save selection
|
||||
is an explicit per-Play choice. See specification
|
||||
[14](14.%20Integrated%20Play%20Specification.md).
|
||||
|
||||
This specification implements the accepted decision for project-local Studio state under `.studio/`.
|
||||
|
||||
It extends:
|
||||
|
||||
@@ -9,6 +9,7 @@ Active
|
||||
- `prometeu-studio-api`
|
||||
- `prometeu-studio-core`
|
||||
- `prometeu-studio-ui-javafx`
|
||||
- `prometeu-studio-ui-javafx-2`
|
||||
- `prometeu-app`
|
||||
- integrations with compiler, Packer, LSP, and the runtime
|
||||
|
||||
@@ -47,6 +48,15 @@ JavaFX is the human adapter; DEV is its authorization and observation workspace.
|
||||
|
||||
Gradle is the physical classpath boundary. Spring Modulith verifies the functional modules rooted exclusively at `p.studio.core`; it does not replace the Gradle modules.
|
||||
|
||||
The normal app composes UI2 through neutral API services; the previous adapter
|
||||
remains for compatibility qualification. Interactive execution adds neutral
|
||||
pause/resume, input, stable frame leases and ownership queries. Core owns exclusive
|
||||
admission through preparation and confirmed teardown. Binary TCP framing, native
|
||||
process ownership and IO workers belong to the app adapter, independently of the
|
||||
deterministic headless gateway. `openForPlay` defers editor/agent infrastructure;
|
||||
the existing session path and automation contracts remain. See specification
|
||||
[14](14.%20Integrated%20Play%20Specification.md).
|
||||
|
||||
The legacy mixed `prometeu-studio` module and the static `p.studio.Container` service locator MUST NOT exist in the final architecture.
|
||||
|
||||
## API Neutrality
|
||||
|
||||
@@ -4,6 +4,19 @@ Owner: `studio`. Canonical source: `docs/specs/studio`.
|
||||
|
||||
This directory contains the normative Studio specification set.
|
||||
|
||||
## Default JavaFX 2 frontend
|
||||
|
||||
[`13. JavaFX 2 Foundation Specification.md`](13.%20JavaFX%202%20Foundation%20Specification.md)
|
||||
defines the `prometeu-studio-ui-javafx-2` foundation and reusable shell.
|
||||
Its [module guide](../../../prometeu-studio-ui-javafx-2/README.md) documents execution,
|
||||
component ownership, themes, locales, bundled fonts and verification. The previous
|
||||
frontend is retained for adapter qualification; specifications 1–4 describe its behavior and
|
||||
do not impose its visual structure on the new implementation. Backend contracts
|
||||
remain shared. The normal/installed app uses the new chooser and Play frontend;
|
||||
[`14. Integrated Play Specification.md`](14.%20Integrated%20Play%20Specification.md)
|
||||
owns project flow, execution authority, transport/presentation, input, saves and
|
||||
qualification boundaries.
|
||||
|
||||
## Purpose
|
||||
|
||||
Specs define the official Studio contract.
|
||||
|
||||
@@ -43,7 +43,7 @@ architecture mirrors are synchronized or that all PBS facades are implemented.
|
||||
Run the explicit source/exporter verification from the Studio root:
|
||||
|
||||
```sh
|
||||
python3 tools/runtime-catalog/verify.py --runtime ../runtime
|
||||
../tooling/.venv/bin/python ../tooling/scripts/runtime-catalog/verify.py --studio . --runtime ../runtime
|
||||
```
|
||||
|
||||
This command requires a clean checkout of the recorded provider revision, compares
|
||||
|
||||
Vendored
+12
-3
@@ -1,6 +1,10 @@
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
tools {
|
||||
jdk 'JDK25'
|
||||
}
|
||||
|
||||
environment {
|
||||
GRADLE_USER_HOME = '/var/jenkins_home/.gradle'
|
||||
GRADLE_OPTS = '-Dorg.gradle.parallel=true -Dorg.gradle.caching=true'
|
||||
@@ -24,6 +28,7 @@ pipeline {
|
||||
script { env.TESTS_STARTED = 'true' }
|
||||
withChecks(name: 'Test', includeStage: true) {
|
||||
withGradle {
|
||||
// test excludes the integration tag; tooling owns integration execution.
|
||||
// --continue finishes independent tests/reports but retains a nonzero exit on failure.
|
||||
sh './gradlew test jacocoTestReport --continue --parallel --max-workers=2 --build-cache --no-daemon --console=plain'
|
||||
}
|
||||
@@ -40,9 +45,10 @@ pipeline {
|
||||
// Isolate publishers so a failed publisher does not suppress the other diagnostics.
|
||||
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
|
||||
junit testResults: '**/build/test-results/test/TEST-*.xml',
|
||||
checksName: 'Test / Tests and coverage',
|
||||
allowEmptyResults: env.VERIFICATION_SUCCEEDED != 'true'
|
||||
if (env.VERIFICATION_SUCCEEDED == 'true' && !fileExists('prometeu-packer/prometeu-packer-v1/build/test-results/test/TEST-p.packer.services.PackerAssetContractTest.xml')) {
|
||||
error 'Successful verification is missing the packer contract test report.'
|
||||
if (env.VERIFICATION_SUCCEEDED == 'true' && !fileExists('prometeu-packer/prometeu-packer-v1/build/test-results/test/TEST-p.packer.services.PackerAssetDeclarationParserTest.xml')) {
|
||||
error 'Successful verification is missing the packer unit test report.'
|
||||
}
|
||||
}
|
||||
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
|
||||
@@ -52,6 +58,8 @@ pipeline {
|
||||
id: 'jacoco',
|
||||
name: 'JaCoCo Coverage',
|
||||
checksName: 'JaCoCo Coverage',
|
||||
enabledForFailure: true,
|
||||
failOnError: true,
|
||||
sourceDirectories: [[path: 'glob:**/src/main/java']],
|
||||
sourceCodeEncoding: 'UTF-8',
|
||||
sourceCodeRetention: 'EVERY_BUILD',
|
||||
@@ -79,7 +87,8 @@ pipeline {
|
||||
])
|
||||
}
|
||||
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
|
||||
archiveArtifacts artifacts: '**/build/test-results/test/**, **/build/reports/tests/test/**, **/build/reports/jacoco/**',
|
||||
// Keep raw coverage data even when report generation fails.
|
||||
archiveArtifacts artifacts: '**/build/test-results/test/**, **/build/reports/tests/test/**, **/build/reports/jacoco/**, **/build/jacoco/*.exec',
|
||||
allowEmptyArchive: env.VERIFICATION_SUCCEEDED != 'true',
|
||||
onlyIfSuccessful: false
|
||||
}
|
||||
|
||||
+42
-11
@@ -2,16 +2,17 @@
|
||||
|
||||
`Jenkinsfile` uses the checked-in Gradle wrapper (currently 9.3.1). A compatible
|
||||
Java installation must be available to launch Gradle; project conventions select
|
||||
Java 21 for compilation/tests. The pipeline retains its existing Gradle cache
|
||||
Java 25 for compilation/tests and the product runtime. Build logic targets Java 21
|
||||
bytecode independently. The pipeline retains its existing Gradle cache
|
||||
location, worker limit and installed Jenkins report plugins. It does not require
|
||||
a named Jenkins Gradle installation.
|
||||
|
||||
The build runs on a Unix agent with Java and dependency/cache access. It sets
|
||||
`JAVA_TOOL_OPTIONS=-Djava.awt.headless=true` for Gradle and test JVMs. No display,
|
||||
runtime binary, sibling runtime checkout, runtime download/build, or new Jenkins
|
||||
plugin is required by the packer contract suite.
|
||||
plugin is required by the unit suite.
|
||||
|
||||
## Commands
|
||||
## Unit pipeline commands
|
||||
|
||||
```sh
|
||||
export JAVA_TOOL_OPTIONS=-Djava.awt.headless=true
|
||||
@@ -22,8 +23,18 @@ export JAVA_TOOL_OPTIONS=-Djava.awt.headless=true
|
||||
Clean is a separate stage: when it fails, old reports must not be published as a
|
||||
new test run. Gradle `--continue` lets independent tasks and reports finish after
|
||||
a test failure; it does not turn a failing command into success. Runtime/desktop
|
||||
opt-in test tasks are not invoked. The ordinary packer `test` task includes
|
||||
`PackerAssetContractTest` without skips or a runtime fallback.
|
||||
opt-in test tasks are not invoked. All ordinary `test` tasks exclude the JUnit
|
||||
`integration` tag. Tests involving real process, network, desktop, application
|
||||
composition or cross-provider pipelines are tagged explicitly, including fixture
|
||||
subprocesses. This exclusion applies even when optional environment variables are
|
||||
set. Existing integration suites remain in this repository; `../tooling` prepares
|
||||
their environment and orchestrates selected integration commands and builds.
|
||||
No integration suite is executed by the repository pipeline.
|
||||
|
||||
The required packer unit report is `PackerAssetDeclarationParserTest`.
|
||||
`PackerAssetContractTest` is integration-tagged and is not a prerequisite of this
|
||||
unit-only pipeline. Consolidated coverage consumes only `build/jacoco/test.exec`
|
||||
from each Java subproject; opt-in integration `.exec` files cannot inflate it.
|
||||
|
||||
## Failure reporting
|
||||
|
||||
@@ -32,9 +43,25 @@ HTML and archived test/coverage reports after a failed verification command.
|
||||
Each publisher is isolated so one publisher error does not prevent the others
|
||||
from being attempted. The build console retains compilation/setup diagnostics.
|
||||
|
||||
JUnit explicitly completes the `Test / Tests and coverage` check from the post
|
||||
block. Its name must match the check required by Gitea, independently of the
|
||||
publisher's stage context. The separate coverage check remains `JaCoCo Coverage`.
|
||||
|
||||
Coverage recording is enabled for failed builds so available coverage can still
|
||||
be inspected after test failures. Coverage processing errors fail publication;
|
||||
the isolated HTML and artifact publishers are still attempted. Archiving runs
|
||||
even for failed or unstable builds and retains the original JUnit XML/binary
|
||||
results, test HTML, coverage XML/HTML, and raw `**/build/jacoco/*.exec` files.
|
||||
JUnit XML includes test failure details and captured output; the raw JaCoCo data
|
||||
is retained even if consolidated XML/HTML generation fails. If no coverage data
|
||||
was produced, there is no coverage artifact to recover; inspect the build console
|
||||
and any available test results. Artifacts follow the Jenkins job's build/artifact
|
||||
retention policy.
|
||||
|
||||
An otherwise successful verification must produce JUnit results, the packer
|
||||
contract suite report, consolidated JaCoCo XML and HTML. Missing successful-build
|
||||
evidence fails publication. A failed compilation may have no reports: the
|
||||
unit suite report, consolidated JaCoCo XML and HTML. Missing successful-build
|
||||
evidence fails publication. The required packer report is the unit parser suite.
|
||||
A failed compilation may have no reports: the
|
||||
original build failure remains authoritative and available diagnostics are still
|
||||
preserved. A failed clean does not publish potentially stale artifacts.
|
||||
|
||||
@@ -45,13 +72,17 @@ test runs are useful diagnostics, not a passing quality gate.
|
||||
## Contract and manual verification boundary
|
||||
|
||||
See the packer fixture [provenance and coverage](../../prometeu-packer/prometeu-packer-v1/src/test/resources/fixtures/contracts/README.md).
|
||||
The automated suite checks producer bytes and metadata against independent
|
||||
expectations. Runtime gameplay remains manual with existing games, not a local
|
||||
or CI automated test. Record manual outcomes only after execution.
|
||||
The retained integration contract suite checks producer bytes and metadata against
|
||||
independent expectations. It is excluded from this unit pipeline. Runtime gameplay
|
||||
and installed-process verification remain separate integration/desktop checks for
|
||||
the tooling repository; record their outcomes only after explicit execution.
|
||||
|
||||
Local Gradle checks and Groovy parsing cannot certify controller plugin behavior.
|
||||
A Jenkins run is needed to observe actual report publication and coverage checks;
|
||||
report any unavailable controller validation explicitly.
|
||||
|
||||
Jenkins behavior references: [post conditions](https://www.jenkins.io/doc/book/pipeline/syntax/#post)
|
||||
and [catchError](https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#catcherror-catch-error-and-set-build-result-to-failure).
|
||||
and [catchError](https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#catcherror-catch-error-and-set-build-result-to-failure),
|
||||
[JUnit check names](https://www.jenkins.io/doc/pipeline/steps/junit/),
|
||||
[coverage recording on failed builds](https://www.jenkins.io/doc/pipeline/steps/coverage/),
|
||||
and [artifact archiving](https://www.jenkins.io/doc/pipeline/steps/core/#archiveartifacts-archive-the-artifacts).
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
javafx = "23.0.2"
|
||||
richtextfx = "0.11.2"
|
||||
jackson = "2.18.2"
|
||||
jacoco = "0.8.12"
|
||||
lombok = "1.18.32"
|
||||
jacoco = "0.8.14"
|
||||
lombok = "1.18.42"
|
||||
junit-jupiter = "5.12.1"
|
||||
archunit = "1.4.2"
|
||||
slf4j = "2.0.7"
|
||||
|
||||
@@ -3,6 +3,9 @@ plugins {
|
||||
alias(libs.plugins.javafx)
|
||||
}
|
||||
|
||||
// Configure the application-capable UI module before lazy classpath queries configure it.
|
||||
evaluationDependsOn(":prometeu-studio-ui-javafx-2")
|
||||
|
||||
dependencies {
|
||||
implementation(libs.tomlj)
|
||||
implementation(project(":prometeu-infra"))
|
||||
@@ -17,6 +20,7 @@ dependencies {
|
||||
implementation(project(":prometeu-studio-api"))
|
||||
implementation(project(":prometeu-studio-core"))
|
||||
implementation(project(":prometeu-studio-ui-javafx"))
|
||||
implementation(project(":prometeu-studio-ui-javafx-2"))
|
||||
implementation(libs.spring.boot)
|
||||
implementation(libs.lsp4j)
|
||||
implementation(libs.javafx.controls)
|
||||
@@ -25,9 +29,10 @@ dependencies {
|
||||
|
||||
application {
|
||||
mainClass = "p.studio.app.StudioLauncher"
|
||||
applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED")
|
||||
}
|
||||
|
||||
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) }
|
||||
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
|
||||
val studioRuntime = layout.buildDirectory.dir("studio-runtime")
|
||||
val assembleStudioRuntime by tasks.registering(Exec::class) {
|
||||
val jdk = studioJava.get().metadata.installationPath.asFile
|
||||
@@ -40,11 +45,16 @@ val assembleStudioRuntime by tasks.registering(Exec::class) {
|
||||
check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" }
|
||||
}
|
||||
}
|
||||
commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
|
||||
commandLine(jdk.resolve("bin/jlink"), "--module-path", jdk.resolve("jmods"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
|
||||
"--no-man-pages", "--output", studioRuntime.get().asFile)
|
||||
}
|
||||
distributions {
|
||||
main { contents { from(assembleStudioRuntime) { into("runtime") } } }
|
||||
main { contents {
|
||||
from(assembleStudioRuntime) { into("runtime") }
|
||||
from(project(":prometeu-studio-ui-javafx-2").file("src/main/resources/p/studio/ui/javafx2/fonts")) {
|
||||
include("*-LICENSE.txt");into("licenses")
|
||||
}
|
||||
} }
|
||||
}
|
||||
tasks.register<JavaExec>("stageStudioInstallation") {
|
||||
group = "application"
|
||||
@@ -121,6 +131,7 @@ tasks.register<Test>("headlessProcessTest") {
|
||||
project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath)
|
||||
include("**/HeadlessTaskIntegrationTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath)
|
||||
}
|
||||
|
||||
tasks.register<Test>("memcardProcessTest") {
|
||||
@@ -149,8 +160,40 @@ tasks.register<Test>("headlessMcpDesktopTest") {
|
||||
// Subprocess tests exercise the actual Studio main and OS ownership boundaries.
|
||||
tasks.withType<Test>().configureEach {
|
||||
systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath)
|
||||
systemProperty("studio.test.studioHost", providers.gradleProperty("studioPlayHost").getOrElse(
|
||||
rootProject.file("../runtime/target/debug/prometeu-host-desktop-winit" + if (System.getProperty("os.name").startsWith("Windows")) ".exe" else "").absolutePath))
|
||||
systemProperty("studio.test.studioCartridge", rootProject.file("../runtime/test-cartridges/dummy-boy").absolutePath)
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayProcessTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayDesktopTest.class") }
|
||||
tasks.register<Test>("studioPlayDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies the default Play frontend with an installed native runtime and a desktop."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/StudioPlayDesktopTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath)
|
||||
systemProperty("studio.test.playStress", providers.gradleProperty("studioPlayStress").getOrElse("false"))
|
||||
systemProperty("java.awt.headless", "false")
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
tasks.register<Test>("studioPlayProcessTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies real interactive binary IPC (requires the Studio host binary, no display)."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/StudioPlayProcessTest.class")
|
||||
include("**/StudioPlayInstalledRuntimeTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayInstalledRuntimeTest.class") }
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/InstalledConnectorTest.class") }
|
||||
tasks.register<Test>("installedConnectorTest") {
|
||||
group = "verification"
|
||||
@@ -191,6 +234,9 @@ tasks.named<Test>("test") { exclude("**/AssetCapacityInstalledRuntimeTest.class"
|
||||
tasks.register<Test>("assetCapacityProcessTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies glyph/scene 16/17 boundaries against the exact installed runtime."
|
||||
// The selected installation is external and can be rebuilt at the same path.
|
||||
outputs.upToDateWhen { false }
|
||||
outputs.doNotCacheIf("Qualification must observe the currently installed native binaries") { true }
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
|
||||
@@ -5,11 +5,11 @@ import javafx.stage.Stage;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import p.studio.ui.javafx.window.StudioWindowCoordinator;
|
||||
import p.studio.ui.javafx2.window.StudioWindowCoordinator2;
|
||||
|
||||
public class App extends Application {
|
||||
private ConfigurableApplicationContext applicationContext;
|
||||
private StudioWindowCoordinator studioWindowCoordinator;
|
||||
private StudioWindowCoordinator2 studioWindowCoordinator;
|
||||
|
||||
@Override
|
||||
public void init() throws Exception {
|
||||
@@ -18,11 +18,12 @@ public class App extends Application {
|
||||
.web(WebApplicationType.NONE)
|
||||
.headless(false)
|
||||
.run();
|
||||
applicationContext.getBean(StudioUiFactory.class).prepareInteractive();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) {
|
||||
studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).create(stage);
|
||||
studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).createInteractive(stage);
|
||||
studioWindowCoordinator.showLauncher();
|
||||
}
|
||||
|
||||
|
||||
@@ -323,7 +323,9 @@ public class StudioApplicationConfiguration {
|
||||
TiledAssetService tiledAssetService,
|
||||
SceneBankWorkflow sceneBankWorkflow,
|
||||
WindowStateStore windowStateStore,
|
||||
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) {
|
||||
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide,
|
||||
p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations,
|
||||
p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore) {
|
||||
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
|
||||
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
@@ -331,6 +333,9 @@ public class StudioApplicationConfiguration {
|
||||
tiledAssetService, sceneBankWorkflow, windowStateStore,
|
||||
activityHistoryStore, connectionGuide);
|
||||
factory.setAnimationService(animationService);
|
||||
factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper,
|
||||
new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access),
|
||||
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}});
|
||||
return factory;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,19 @@ import p.studio.ui.javafx.utilities.i18n.I18nService;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
|
||||
public final class StudioUiFactory {
|
||||
private ExecutionControllerFactory interactiveExecutions;
|
||||
private java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> setupSaver;
|
||||
private p.studio.ui.javafx2.window.WindowResources interactiveResources;
|
||||
public void enableInteractive(ExecutionControllerFactory factory,
|
||||
java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> saver) {
|
||||
interactiveExecutions=Objects.requireNonNull(factory);setupSaver=Objects.requireNonNull(saver);
|
||||
}
|
||||
public void prepareInteractive(){interactiveResources=new p.studio.ui.javafx2.window.WindowResources();}
|
||||
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
|
||||
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
|
||||
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources);
|
||||
}
|
||||
private final ProjectCatalog projectCatalog;
|
||||
private final KnownProjects knownProjects;
|
||||
private final ProjectLanguageCatalog languageCatalog;
|
||||
|
||||
@@ -5,35 +5,55 @@ import p.studio.api.assets.AssetBudgets.*;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.io.InputStream;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Installed resource profiles only. Ordinary builds never inspect a sibling runtime checkout. */
|
||||
public final class AssetCapacityProfiles {
|
||||
public record Bundle(Profile profile,Map<String,String> executables){}
|
||||
public record Catalog(int schemaVersion,List<Bundle> profiles){}
|
||||
private final ObjectMapper json;
|
||||
public AssetCapacityProfiles(ObjectMapper json){this.json=json;}
|
||||
private static final Set<String> EXECUTABLES = Set.of("prometeu", "prometeu-headless", "prometeu-runtime");
|
||||
private final Function<String, InputStream> resources;
|
||||
public AssetCapacityProfiles(ObjectMapper json){this(json, name -> AssetCapacityProfiles.class.getClassLoader().getResourceAsStream(name));}
|
||||
AssetCapacityProfiles(ObjectMapper json, Function<String, InputStream> resources){this.json=json;this.resources=resources;}
|
||||
public ProfileSelection select(ProjectLocalStudioSetup setup) {
|
||||
if(setup==null||setup.prometeuRuntimePath()==null)return ProfileSelection.unknown(null,"No runtime installation selected");
|
||||
String selected=null;
|
||||
try {
|
||||
Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=System.getProperty("os.name").startsWith("Windows")?"prometeu.exe":"prometeu";
|
||||
Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=executable("prometeu");
|
||||
selected=AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(dispatcher)));
|
||||
try(var stream=getClass().getResourceAsStream("/asset-capacity/catalog.json")) {
|
||||
var actual = new HashMap<String, String>();
|
||||
actual.put("prometeu", selected);
|
||||
String mismatch = null;
|
||||
try(var stream=resources.apply("asset-capacity/catalog.json")) {
|
||||
if(stream==null)return ProfileSelection.unknown(selected,"No distributed capacity profiles");
|
||||
var catalog=json.readValue(stream,Catalog.class);if(catalog.schemaVersion()!=1)throw new IllegalArgumentException("Unsupported profile catalog");
|
||||
for(var bundle:catalog.profiles())if(bundle.profile().executableSha256().equals(selected)) {
|
||||
if(!bundle.executables().keySet().containsAll(Set.of("prometeu","prometeu-headless","prometeu-runtime")))throw new IllegalArgumentException("Incomplete executable identity");
|
||||
if(!bundle.executables().keySet().equals(EXECUTABLES))throw new IllegalArgumentException("Incomplete or unsupported executable identity");
|
||||
String changed = null;
|
||||
for(var entry:bundle.executables().entrySet()) {
|
||||
if(!Set.of("prometeu","prometeu-headless","prometeu-runtime").contains(entry.getKey()))throw new IllegalArgumentException("Unsupported executable identity");
|
||||
if(!AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(entry.getKey()))).equals(entry.getValue()))return ProfileSelection.unknown(selected,"Runtime component changed: "+entry.getKey());
|
||||
String hash = actual.get(entry.getKey());
|
||||
if(hash == null) {
|
||||
hash = AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(executable(entry.getKey()))));
|
||||
actual.put(entry.getKey(), hash);
|
||||
}
|
||||
if(!hash.equals(entry.getValue())) { changed = entry.getKey(); break; }
|
||||
}
|
||||
for(var evidence:bundle.profile().evidence())try(var record=getClass().getClassLoader().getResourceAsStream(evidence.evidencePath())) {
|
||||
// Several qualified releases may legitimately share an unchanged dispatcher.
|
||||
// Never combine backend identities from separate catalog entries.
|
||||
if(changed != null) { mismatch = "Runtime component changed: " + changed + "; no complete qualified bundle matched"; continue; }
|
||||
for(var evidence:bundle.profile().evidence())try(var record=resources.apply(evidence.evidencePath())) {
|
||||
if(record==null||!AssetWorkspaceFiles.hash(record.readAllBytes()).equals(evidence.evidenceSha256()))throw new IllegalArgumentException("Capacity evidence integrity mismatch");
|
||||
}
|
||||
return new ProfileSelection(QualificationState.known,selected,bundle.profile(),"Exact qualified dispatcher and runtime components match");
|
||||
}
|
||||
}
|
||||
if(mismatch != null)return ProfileSelection.unknown(selected,mismatch);
|
||||
return ProfileSelection.unknown(selected,"Selected executable has no qualified capacity profile");
|
||||
}catch(Exception invalid){return ProfileSelection.unknown(selected,"Capacity profile unavailable or invalid: "+Objects.requireNonNullElse(invalid.getMessage(),invalid.getClass().getSimpleName()));}
|
||||
}
|
||||
private static String executable(String name) {
|
||||
return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import p.studio.api.execution.ExecutionFrame;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayDeque;
|
||||
|
||||
/** Three CPU buffers; at most one presentation lease, independent of reception. */
|
||||
final class LatestFramePool implements AutoCloseable {
|
||||
private final int width,height;
|
||||
private final ArrayDeque<byte[]> free=new ArrayDeque<>(3);
|
||||
private Pending pending;
|
||||
private boolean leased,closed;
|
||||
private record Pending(byte[] pixels,long id,long epoch,long receivedAt) { }
|
||||
LatestFramePool(int width,int height)throws IOException {
|
||||
this.width=width;this.height=height;
|
||||
int size=StudioWire.frameBytes(width,height,width);
|
||||
for(int i=0;i<3;i++)free.add(new byte[size]);
|
||||
}
|
||||
synchronized byte[] receive()throws IOException {
|
||||
if(closed)throw new IOException("Video pool closed");
|
||||
byte[] pixels=free.poll();
|
||||
if(pixels==null)throw new IOException("Video ownership exhausted");
|
||||
return pixels;
|
||||
}
|
||||
synchronized void recycle(byte[] pixels){if(!closed)free.add(pixels);}
|
||||
synchronized void publish(byte[] pixels,long id,long epoch){
|
||||
publish(pixels,id,epoch,System.nanoTime());
|
||||
}
|
||||
synchronized void publish(byte[] pixels,long id,long epoch,long receivedAt){
|
||||
if(closed)return;
|
||||
if(pending!=null)free.add(pending.pixels());
|
||||
pending=new Pending(pixels,id,epoch,receivedAt);
|
||||
}
|
||||
synchronized ExecutionFrame acquire(){
|
||||
if(closed||leased||pending==null)return null;
|
||||
Pending owned=pending;pending=null;leased=true;
|
||||
return new ExecutionFrame(width,height,owned.id(),owned.epoch(),owned.pixels(),owned.receivedAt(),()->{
|
||||
synchronized(this){leased=false;if(!closed)free.add(owned.pixels());}
|
||||
});
|
||||
}
|
||||
@Override public synchronized void close(){closed=true;pending=null;free.clear();}
|
||||
static void rgbaToBgraPre(byte[] pixels){
|
||||
for(int i=0;i<pixels.length;i+=4){
|
||||
int r=pixels[i]&255,g=pixels[i+1]&255,b=pixels[i+2]&255,a=pixels[i+3]&255;
|
||||
pixels[i]=(byte)((b*a+127)/255);pixels[i+1]=(byte)((g*a+127)/255);pixels[i+2]=(byte)((r*a+127)/255);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import p.studio.api.execution.*;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
import p.studio.core.runtime.*;
|
||||
import java.io.*;
|
||||
import java.net.Socket;
|
||||
import java.nio.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.function.Consumer;
|
||||
import static p.studio.app.runtime.studio.StudioWire.*;
|
||||
import p.studio.app.runtime.studio.StudioWire.Reader;
|
||||
import p.studio.app.runtime.studio.StudioWire.Writer;
|
||||
|
||||
final class StudioRuntimeConnection implements RuntimeConnection {
|
||||
private final Process process;
|
||||
private final Socket control,video;
|
||||
private final Reader controlReader,videoReader;
|
||||
private final Writer writer;
|
||||
private final byte[] session;
|
||||
private final int width,height;
|
||||
private final LatestFramePool frames;
|
||||
private final Consumer<RuntimeLogEntry> logs;
|
||||
private final Executor executor;
|
||||
private final CompletableFuture<Integer> completion=new CompletableFuture<>();
|
||||
private final CompletableFuture<Void> stopped=new CompletableFuture<>();
|
||||
private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{
|
||||
Thread t=new Thread(r,"studio-play-heartbeat");t.setDaemon(true);return t;
|
||||
});
|
||||
private final ArrayBlockingQueue<Packet> outgoing=new ArrayBlockingQueue<>(256);
|
||||
private final ConcurrentMap<Long,Pending> pending=new ConcurrentHashMap<>();
|
||||
private final AtomicBoolean closing=new AtomicBoolean(),failed=new AtomicBoolean();
|
||||
private final AtomicLong epoch=new AtomicLong(1);
|
||||
private final AtomicInteger state=new AtomicInteger();
|
||||
private final List<CompletableFuture<Void>> workers=new ArrayList<>();
|
||||
private volatile long lastControl=System.nanoTime();
|
||||
private volatile Throwable failure;
|
||||
private volatile boolean expectedEnd;
|
||||
private long nextRequest;
|
||||
private volatile long stopRequest;
|
||||
private CompletableFuture<Void> stopResult;
|
||||
private record Packet(int kind,long request,byte[] payload) { }
|
||||
private record Pending(int kind,long deadline,CompletableFuture<Void> result) { }
|
||||
|
||||
StudioRuntimeConnection(Process process,Socket control,Socket video,Reader controlReader,Reader videoReader,
|
||||
byte[] session,int width,int height,Consumer<RuntimeLogEntry> logs,Executor executor,
|
||||
CompletableFuture<Void> stdout,CompletableFuture<Void> stderr)throws IOException {
|
||||
this.process=process;this.control=control;this.video=video;this.controlReader=controlReader;this.videoReader=videoReader;
|
||||
this.session=session.clone();this.width=width;this.height=height;this.logs=logs;this.executor=executor;
|
||||
writer=new Writer(control.getOutputStream());frames=new LatestFramePool(width,height);
|
||||
workers.add(CompletableFuture.runAsync(this::writeLoop,executor));
|
||||
workers.add(CompletableFuture.runAsync(this::controlLoop,executor));
|
||||
workers.add(CompletableFuture.runAsync(this::videoLoop,executor));
|
||||
timer.scheduleAtFixedRate(this::heartbeat,1,1,TimeUnit.SECONDS);
|
||||
executor.execute(()->{
|
||||
try{
|
||||
int code=process.waitFor();
|
||||
// Drain the terminal control message before closing the other channel.
|
||||
// TCP ordering is per channel; video EOF can race STOPPED on control.
|
||||
if(code==0&&stopRequest!=0&&!failed.get()){
|
||||
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception missing){fail(new IOException("Runtime exited without STOPPED",missing));}
|
||||
}
|
||||
closing.set(true);state.set(4);timer.shutdownNow();closeSockets();frames.close();
|
||||
for(Pending p:pending.values())p.result().completeExceptionally(new IOException("Runtime exited"));pending.clear();
|
||||
for(var worker:workers)await(worker);await(stdout);await(stderr);
|
||||
logs.accept(code==0?RuntimeLogEntry.info("Runtime stopped."):RuntimeLogEntry.error("Runtime exit code "+code));
|
||||
Throwable why=failure;
|
||||
if(why==null)completion.complete(code);else completion.completeExceptionally(why);
|
||||
if(!stopped.isDone())stopped.completeExceptionally(why==null?new IOException("Runtime exited before STOPPED"):why);
|
||||
}catch(InterruptedException interrupted){Thread.currentThread().interrupt();fail(interrupted);completion.completeExceptionally(interrupted);}
|
||||
});
|
||||
}
|
||||
@Override public CompletableFuture<Integer> completion(){return completion;}
|
||||
@Override public CompletableFuture<Void> startExecution(){return command(START);}
|
||||
@Override public CompletableFuture<Void> pause(){return command(PAUSE);}
|
||||
@Override public CompletableFuture<Void> resume(){return command(RESUME);}
|
||||
@Override public synchronized CompletableFuture<Void> stopAsync(){
|
||||
if(completion.isDone())return completion.thenApply(code->{if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return null;});
|
||||
if(stopResult!=null)return stopResult;
|
||||
CompletableFuture<Void> accepted=command(STOP);
|
||||
stopResult=accepted.thenCompose(v->stopped).thenCompose(v->completion).thenApply(code->{
|
||||
if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return (Void)null;
|
||||
}).orTimeout(5,TimeUnit.SECONDS);
|
||||
CompletableFuture<Void> result=stopResult;
|
||||
result.whenComplete((v,e)->{
|
||||
Throwable why=root(e);
|
||||
if(why instanceof RuntimeStopRefusedException){synchronized(this){if(stopResult==result)stopResult=null;}}
|
||||
else if(e!=null)fail(why);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@Override public void close(){try{stopAsync().join();}catch(CompletionException e){
|
||||
if(root(e) instanceof RuntimeException runtime)throw runtime;throw e;}}
|
||||
@Override public ExecutionFrame acquireLatestFrame(){return frames.acquire();}
|
||||
@Override public void input(ExecutionInput input){
|
||||
if(state.get()!=1||closing.get()||failed.get())return;
|
||||
if((input.buttons()&4096)!=0&&(input.touchX()<0||input.touchY()<0||input.touchX()>=width||input.touchY()>=height))
|
||||
throw new IllegalArgumentException("Touch outside game image");
|
||||
enqueue(new Packet(INPUT,0,little(20).putLong(epoch.get()).putShort((short)input.buttons()).putShort((short)0)
|
||||
.putInt(input.touchX()).putInt(input.touchY()).array()));
|
||||
}
|
||||
private synchronized CompletableFuture<Void> command(int kind){
|
||||
if(closing.get()||failed.get())return CompletableFuture.failedFuture(new IOException("Runtime connection closed"));
|
||||
long id=++nextRequest;
|
||||
if(kind==STOP)stopRequest=id;
|
||||
var future=new CompletableFuture<Void>();
|
||||
pending.put(id,new Pending(kind,System.nanoTime()+TimeUnit.SECONDS.toNanos(5),future));
|
||||
enqueue(new Packet(kind,id,new byte[0]));return future;
|
||||
}
|
||||
private void enqueue(Packet packet){if(!outgoing.offer(packet))fail(new IOException("Runtime control queue saturated"));}
|
||||
private void writeLoop(){
|
||||
try{while(!closing.get()&&!failed.get()){
|
||||
Packet p=outgoing.poll(100,TimeUnit.MILLISECONDS);if(p!=null)writer.send(p.kind(),p.request(),p.payload());
|
||||
}}catch(InterruptedException e){Thread.currentThread().interrupt();if(!closing.get())fail(e);}
|
||||
catch(IOException e){if(!closing.get()&&!expectedEnd)fail(e);}
|
||||
}
|
||||
private void controlLoop(){
|
||||
try{while(!closing.get()){
|
||||
Message m=controlReader.receive();lastControl=System.nanoTime();
|
||||
switch(m.header().kind()){
|
||||
case RESULT->result(m);
|
||||
case PONG->{
|
||||
if(m.payload().length!=20||m.header().request()!=0)throw new IOException("Invalid PONG");
|
||||
var p=ByteBuffer.wrap(m.payload()).order(ByteOrder.LITTLE_ENDIAN);
|
||||
long e=p.getLong();p.getLong();int s=p.getInt();
|
||||
if(e==0||s<0||s>2)throw new IOException("Invalid PONG state");
|
||||
}
|
||||
case ERROR->{String text=text(m.payload(),0);logs.accept(RuntimeLogEntry.error(text));fail(new IOException(text));return;}
|
||||
case STOPPED->{if(m.payload().length!=0||m.header().request()!=stopRequest||stopRequest==0)
|
||||
throw new IOException("Unexpected STOPPED");expectedEnd=true;stopped.complete(null);return;}
|
||||
default->throw new IOException("Unexpected runtime control message");
|
||||
}
|
||||
}}catch(IOException|RuntimeException e){if(!closing.get()&&!expectedEnd)fail(e);}
|
||||
}
|
||||
private void result(Message message)throws IOException {
|
||||
byte[] p=message.payload();if(p.length<20)throw new IOException("Invalid command result");
|
||||
var b=ByteBuffer.wrap(p).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int kind=Short.toUnsignedInt(b.getShort()),status=Short.toUnsignedInt(b.getShort());
|
||||
long nextEpoch=b.getLong();b.getLong();String text=text(p,20);
|
||||
Pending request=pending.remove(message.header().request());
|
||||
if(request==null||request.kind()!=kind||status>2||nextEpoch==0)throw new IOException("Uncorrelated runtime result");
|
||||
epoch.set(nextEpoch);
|
||||
if(status==0){switch(kind){
|
||||
case START->state.compareAndSet(0,1);case RESUME->state.set(1);case PAUSE,STOP->state.set(2);default->{}}
|
||||
request.result().complete(null);
|
||||
}else if(status==2&&kind==STOP){state.set(2);stopRequest=0;request.result().completeExceptionally(new RuntimeStopRefusedException(text));}
|
||||
else request.result().completeExceptionally(new IllegalStateException(text));
|
||||
}
|
||||
private void videoLoop(){
|
||||
byte[] metadata=new byte[FRAME_METADATA_BYTES];
|
||||
try{while(!closing.get()){
|
||||
Header h=videoReader.nextHeader();
|
||||
if(h.kind()!=FRAME||h.length()<FRAME_METADATA_BYTES||h.request()!=0)throw new IOException("Invalid frame envelope");
|
||||
videoReader.readFully(metadata,0,metadata.length);
|
||||
if(!Arrays.equals(session,Arrays.copyOfRange(metadata,0,16)))throw new IOException("Frame belongs to another session");
|
||||
var b=ByteBuffer.wrap(metadata).order(ByteOrder.LITTLE_ENDIAN);b.position(16);
|
||||
long frameEpoch=b.getLong(),id=b.getLong();int w=b.getInt(),height=b.getInt(),stride=b.getInt(),format=b.getInt();
|
||||
int bytes=frameBytes(w,height,stride);
|
||||
if(w!=width||height!=this.height||format!=RGBA8||frameEpoch==0||bytes+FRAME_METADATA_BYTES!=h.length())
|
||||
throw new IOException("Frame metadata changed or mismatches payload");
|
||||
byte[] pixels=frames.receive();boolean published=false;
|
||||
try{
|
||||
videoReader.readFully(pixels,0,pixels.length);
|
||||
long receivedAt=System.nanoTime();
|
||||
if(Long.compareUnsigned(frameEpoch,epoch.get())>=0){
|
||||
LatestFramePool.rgbaToBgraPre(pixels);frames.publish(pixels,id,frameEpoch,receivedAt);published=true;
|
||||
}
|
||||
enqueue(new Packet(FRAME_RECEIVED,0,little(16).putLong(frameEpoch).putLong(id).array()));
|
||||
}finally{if(!published)frames.recycle(pixels);}
|
||||
}}catch(IOException|RuntimeException e){
|
||||
if(!closing.get()&&!expectedEnd){
|
||||
if(stopRequest!=0){
|
||||
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception incomplete){if(!closing.get()&&!expectedEnd)fail(e);}
|
||||
}else fail(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
private void heartbeat(){
|
||||
if(closing.get()||failed.get())return;
|
||||
long now=System.nanoTime();
|
||||
if(now-lastControl>TimeUnit.SECONDS.toNanos(5)){fail(new IOException("Runtime control heartbeat expired"));return;}
|
||||
for(Pending p:pending.values())if(now-p.deadline()>0){fail(new IOException("Runtime command timed out"));return;}
|
||||
enqueue(new Packet(PING,0,new byte[0]));
|
||||
}
|
||||
private void fail(Throwable why){
|
||||
if(closing.get()||!failed.compareAndSet(false,true))return;
|
||||
failure=why;state.set(4);logs.accept(RuntimeLogEntry.error("Runtime connection failed: "+why.getMessage()));
|
||||
for(Pending p:pending.values())p.result().completeExceptionally(why);pending.clear();
|
||||
stopped.completeExceptionally(why);closeSockets();frames.close();timer.shutdownNow();
|
||||
// Process identity is owned by this connection; never search or kill by executable name.
|
||||
executor.execute(()->{
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();
|
||||
try{if(!process.waitFor(2,TimeUnit.SECONDS)){
|
||||
process.destroyForcibly();if(!process.waitFor(2,TimeUnit.SECONDS))logs.accept(RuntimeLogEntry.error("Runtime termination is not confirmed"));
|
||||
}}catch(InterruptedException e){Thread.currentThread().interrupt();}
|
||||
});
|
||||
}
|
||||
private void closeSockets(){StudioRuntimeGateway.close(control);StudioRuntimeGateway.close(video);}
|
||||
private static void await(CompletableFuture<Void> work){try{work.join();}catch(CompletionException|CancellationException ignored){}}
|
||||
private static Throwable root(Throwable failure){
|
||||
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();return failure;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.execution.PlayOptions;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
import p.studio.core.runtime.*;
|
||||
import p.studio.core.project.ProjectCartridgeConfiguration;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.nio.file.*;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
import static p.studio.app.runtime.studio.StudioWire.*;
|
||||
import p.studio.app.runtime.studio.StudioWire.Reader;
|
||||
import p.studio.app.runtime.studio.StudioWire.Writer;
|
||||
|
||||
/** Owns a direct child runtime and two private loopback channels. */
|
||||
public final class StudioRuntimeGateway implements RuntimeGateway {
|
||||
private final ObjectMapper mapper;
|
||||
public StudioRuntimeGateway(ObjectMapper mapper){this.mapper=Objects.requireNonNull(mapper);}
|
||||
@Override public boolean interactive(){return true;}
|
||||
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,Consumer<RuntimeLogEntry> logs)throws Exception {
|
||||
return start(project,setup,logs,PlayOptions.PERSISTENT);
|
||||
}
|
||||
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,
|
||||
Consumer<RuntimeLogEntry> logs,PlayOptions options)throws Exception {
|
||||
new p.studio.app.assets.ManagedAssetGuard(mapper).require(project.rootPath(),project.rootPath().resolve("build"),setup);
|
||||
Path executable=executable(setup);
|
||||
List<String> command=new ArrayList<>(List.of(executable.toString(),"--studio","--run",project.rootPath().resolve("build").toString()));
|
||||
if(project.memcardSlots()!=null&&!options.disposableSave()){
|
||||
Path image=ProjectCartridgeConfiguration.selectedImage(project,setup);
|
||||
if(!Files.isRegularFile(image))throw new IOException("Select an existing development save or an explicitly disposable session");
|
||||
command.add("--memcard");command.add(image.toString());
|
||||
}
|
||||
InetAddress loopback=InetAddress.getByName("127.0.0.1");
|
||||
byte[] session=new byte[16],token=new byte[32];SecureRandom random=new SecureRandom();random.nextBytes(session);random.nextBytes(token);
|
||||
Process process=null;Socket control=null,video=null;
|
||||
ExecutorService io=Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("studio-play-io-",0).factory());
|
||||
try(ServerSocket controls=new ServerSocket(0,4,loopback);ServerSocket videos=new ServerSocket(0,4,loopback)){
|
||||
process=new ProcessBuilder(command).directory(project.rootPath().toFile()).start();
|
||||
CompletableFuture<Void> stdout=drain(process.getInputStream(),false,logs,io);
|
||||
CompletableFuture<Void> stderr=drain(process.getErrorStream(),true,logs,io);
|
||||
byte[] bootstrap=little(53).put(session).put(token).putShort((short)controls.getLocalPort())
|
||||
.putShort((short)videos.getLocalPort()).put((byte)(options.disposableSave()?1:0)).array();
|
||||
try(OutputStream input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,bootstrap);}
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);
|
||||
Accepted c=accept(controls,session,token,1,process,deadline);control=c.socket();
|
||||
Accepted v=accept(videos,session,token,2,process,deadline);video=v.socket();
|
||||
control.setSoTimeout(remaining(deadline));
|
||||
Message ready=c.reader().receive();
|
||||
if(ready.header().kind()!=READY||ready.header().request()!=0||ready.payload().length<16)throw new IOException("Interactive runtime did not become ready");
|
||||
var fields=java.nio.ByteBuffer.wrap(ready.payload()).order(java.nio.ByteOrder.LITTLE_ENDIAN);
|
||||
int width=fields.getInt(),height=fields.getInt(),fps=fields.getInt(),format=fields.getInt();
|
||||
frameBytes(width,height,width);
|
||||
if(fps!=60||format!=RGBA8)throw new IOException("Unsupported interactive display format");
|
||||
String version=text(ready.payload(),16);
|
||||
logs.accept(RuntimeLogEntry.info("Studio Play protocol 1.0; runtime "+version));
|
||||
control.setSoTimeout(0);video.setSoTimeout(0);
|
||||
var connection=new StudioRuntimeConnection(process,control,video,c.reader(),v.reader(),session,width,height,logs,io,stdout,stderr);
|
||||
connection.completion().whenComplete((code,failure)->io.shutdown());
|
||||
return connection;
|
||||
}catch(Throwable failure){
|
||||
close(control);close(video);
|
||||
if(process!=null){process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();process.waitFor(2,TimeUnit.SECONDS);}
|
||||
io.shutdownNow();
|
||||
throw failure;
|
||||
}finally{Arrays.fill(token,(byte)0);}
|
||||
}
|
||||
private static Path executable(ProjectLocalStudioSetup setup)throws IOException {
|
||||
if(setup.prometeuRuntimePath()==null)throw new IOException("Select a runtime installation");
|
||||
String name=System.getProperty("os.name").startsWith("Windows")?"prometeu-runtime.exe":"prometeu-runtime";
|
||||
Path path=Path.of(setup.prometeuRuntimePath()).resolve(name).toAbsolutePath().normalize();
|
||||
if(!Files.isRegularFile(path)||!Files.isExecutable(path))throw new IOException("Interactive runtime not found: "+path);
|
||||
return path;
|
||||
}
|
||||
private record Accepted(Socket socket,Reader reader){ }
|
||||
private static Accepted accept(ServerSocket listener,byte[] session,byte[] token,int role,Process process,long deadline)throws IOException {
|
||||
listener.setSoTimeout(100);
|
||||
while(System.nanoTime()<deadline){
|
||||
if(Thread.currentThread().isInterrupted())throw new InterruptedIOException("Runtime startup cancelled");
|
||||
if(!process.isAlive())throw new IOException("Runtime exited during startup with code "+process.exitValue());
|
||||
Socket socket;
|
||||
try{socket=listener.accept();}catch(SocketTimeoutException wait){continue;}
|
||||
boolean admitted=false;
|
||||
try{
|
||||
socket.setSoTimeout(Math.min(1000,remaining(deadline)));socket.setTcpNoDelay(true);
|
||||
Reader reader=new Reader(socket.getInputStream());Message hello=reader.receive();
|
||||
byte[] p=hello.payload();
|
||||
if(hello.header().kind()!=HELLO||hello.header().request()!=0||p.length!=49||p[48]!=(byte)role
|
||||
||!Arrays.equals(session,Arrays.copyOfRange(p,0,16))
|
||||
||!java.security.MessageDigest.isEqual(token,Arrays.copyOfRange(p,16,48)))continue;
|
||||
admitted=true;return new Accepted(socket,reader);
|
||||
}catch(IOException invalid){/* Reject an unrelated/malformed peer within the startup deadline. */}
|
||||
finally{if(!admitted)close(socket);}
|
||||
}
|
||||
throw new SocketTimeoutException("Interactive runtime handshake timed out");
|
||||
}
|
||||
private static int remaining(long deadline)throws SocketTimeoutException {
|
||||
long ms=TimeUnit.NANOSECONDS.toMillis(deadline-System.nanoTime());
|
||||
if(ms<=0)throw new SocketTimeoutException("Interactive runtime handshake timed out");return (int)Math.min(ms,Integer.MAX_VALUE);
|
||||
}
|
||||
static void close(Socket socket){if(socket!=null)try{socket.close();}catch(IOException ignored){}}
|
||||
static CompletableFuture<Void> drain(InputStream source,boolean error,Consumer<RuntimeLogEntry> logs,Executor executor){
|
||||
return CompletableFuture.runAsync(()->{
|
||||
try(var reader=new InputStreamReader(source,java.nio.charset.StandardCharsets.UTF_8)){
|
||||
StringBuilder line=new StringBuilder();boolean truncated=false;char[] chars=new char[2048];int count;
|
||||
while((count=reader.read(chars))!=-1){for(int i=0;i<count;i++){
|
||||
char ch=chars[i];
|
||||
if(ch=='\n'){
|
||||
String text=line+(truncated?"…":"");if(!text.isBlank())logs.accept(error?RuntimeLogEntry.error(text):RuntimeLogEntry.info(text));
|
||||
line.setLength(0);truncated=false;
|
||||
}else if(ch!='\r'){if(line.length()<8192)line.append(ch);else truncated=true;}
|
||||
}}
|
||||
if(!line.toString().isBlank())logs.accept(error?RuntimeLogEntry.error(line.toString()):RuntimeLogEntry.info(line.toString()));
|
||||
}catch(IOException ignored){/* Process completion owns status; preserve the already drained prefix. */}
|
||||
},executor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.*;
|
||||
import java.nio.charset.*;
|
||||
|
||||
/** Studio Play v1. No JavaFX, object serialization or platform-native transport. */
|
||||
public final class StudioWire {
|
||||
private StudioWire() { }
|
||||
public static final int HEADER_BYTES = 32, CONTROL_LIMIT = 65536, FRAME_LIMIT = 16 * 1024 * 1024;
|
||||
public static final int FRAME_METADATA_BYTES = 48, RGBA8 = 1;
|
||||
public static final int HELLO=1, READY=2, START=3, PAUSE=4, RESUME=5, STOP=6, RESULT=7,
|
||||
INPUT=8, FRAME=9, FRAME_RECEIVED=10, PING=11, PONG=12, ERROR=13, STOPPED=14, BOOTSTRAP=15;
|
||||
public static ByteBuffer little(int length) { return ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); }
|
||||
public record Header(int kind, int length, long sequence, long request) {
|
||||
public Header {
|
||||
if (kind < HELLO || kind > BOOTSTRAP || sequence == 0 || length < 0
|
||||
|| length > (kind == FRAME ? FRAME_LIMIT : CONTROL_LIMIT))
|
||||
throw new IllegalArgumentException("Invalid Studio message type, sequence or payload length");
|
||||
}
|
||||
public byte[] encode() {
|
||||
return little(HEADER_BYTES).putInt(0x31545350).putShort((short)1).putShort((short)0)
|
||||
.putShort((short)kind).putShort((short)0).putInt(length).putLong(sequence).putLong(request).array();
|
||||
}
|
||||
public static Header decode(byte[] bytes) throws IOException {
|
||||
if (bytes.length != HEADER_BYTES) throw new IOException("Truncated Studio header");
|
||||
var b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
||||
if (b.getInt()!=0x31545350 || b.getShort()!=1 || b.getShort()!=0)
|
||||
throw new IOException("Incompatible Studio protocol magic/version");
|
||||
int kind = Short.toUnsignedInt(b.getShort());
|
||||
if (b.getShort()!=0) throw new IOException("Unknown Studio protocol flags");
|
||||
long length = Integer.toUnsignedLong(b.getInt()), seq=b.getLong(), request=b.getLong();
|
||||
if (length > FRAME_LIMIT) throw new IOException("Studio payload exceeds limit");
|
||||
try { return new Header(kind, (int)length, seq, request); }
|
||||
catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); }
|
||||
}
|
||||
}
|
||||
public record Message(Header header, byte[] payload) { }
|
||||
public static final class Reader {
|
||||
private final DataInputStream input;
|
||||
private final byte[] header = new byte[HEADER_BYTES];
|
||||
private long sequence;
|
||||
public Reader(InputStream input) { this.input = new DataInputStream(input); }
|
||||
public Header nextHeader() throws IOException {
|
||||
input.readFully(header);
|
||||
Header result = Header.decode(header);
|
||||
if (Long.compareUnsigned(result.sequence(),sequence) <= 0)
|
||||
throw new IOException("Non-monotonic Studio sequence");
|
||||
sequence = result.sequence(); return result;
|
||||
}
|
||||
public void readFully(byte[] into, int offset, int length) throws IOException { input.readFully(into,offset,length); }
|
||||
public Message receive() throws IOException {
|
||||
Header h = nextHeader();
|
||||
if (h.kind()==FRAME) throw new IOException("Video must use the bounded frame pool");
|
||||
byte[] bytes = new byte[h.length()]; input.readFully(bytes); return new Message(h,bytes);
|
||||
}
|
||||
}
|
||||
public static final class Writer {
|
||||
private final OutputStream output;
|
||||
private long sequence;
|
||||
public Writer(OutputStream output) { this.output=output; }
|
||||
public synchronized void send(int kind,long request,byte[] bytes) throws IOException {
|
||||
if (++sequence==0) throw new IOException("Studio sequence exhausted");
|
||||
try { output.write(new Header(kind,bytes.length,sequence,request).encode()); }
|
||||
catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); }
|
||||
output.write(bytes); output.flush();
|
||||
}
|
||||
}
|
||||
public static int frameBytes(int width,int height,int stride) throws IOException {
|
||||
if (width <= 0 || height <= 0 || stride != width) throw new IOException("Invalid Studio frame dimensions/stride");
|
||||
final long bytes;
|
||||
try { bytes = Math.multiplyExact(Math.multiplyExact((long)width,height),4); }
|
||||
catch (ArithmeticException e) { throw new IOException("Studio frame dimensions overflow",e); }
|
||||
if (bytes > FRAME_LIMIT-FRAME_METADATA_BYTES) throw new IOException("Studio frame exceeds limit");
|
||||
return (int)bytes;
|
||||
}
|
||||
public static String text(byte[] bytes,int offset) throws IOException {
|
||||
try { return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes,offset,bytes.length-offset)).toString(); }
|
||||
catch (CharacterCodingException e) { throw new IOException("Invalid Studio UTF-8",e); }
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,204 @@
|
||||
"prometeu-headless": "18423f798ab28bbd38c12a7ee46459f3ef3d08876cc64327952f57be041fc5df",
|
||||
"prometeu-runtime": "ee00a587eb48030d1455d3c9bedd784ab620309a09877b50fe3641ae502635df"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "macos-arm64-studio-play-v1-b377b99e40b7",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json",
|
||||
"evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json",
|
||||
"evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a",
|
||||
"prometeu-headless": "3ace82881012fbdb83834055cf9f9fb759256da6d95260bce80de045f978ece5",
|
||||
"prometeu-runtime": "b56341fd45011871ef192a7788eeef2fb15edb8b4fd4fbd03e2d03a378cfd8a0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json",
|
||||
"evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json",
|
||||
"evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"prometeu-headless": "a1662aaae81794a0f1eedfdbe386a52601ca133cf1634845d82c882fa130c942",
|
||||
"prometeu-runtime": "918ff7a8eccf3e7263cbfb265a27fd2d015a317d5bb0dcb25a801a04a7c969f6"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-43069a2a4e9c94dfaae0c6a681461f2f5810ff6dc38be45da22987febfe5c371",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-43069a2a4e9c94dfaae0c6a681461f2f5810ff6dc38be45da22987febfe5c371.json",
|
||||
"evidenceSha256": "612d7b9c53d327748ae2a98f0b20e71ddbffae21a621f8ab3e2c8e2e7f00b44d"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-43069a2a4e9c94dfaae0c6a681461f2f5810ff6dc38be45da22987febfe5c371.json",
|
||||
"evidenceSha256": "612d7b9c53d327748ae2a98f0b20e71ddbffae21a621f8ab3e2c8e2e7f00b44d"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"prometeu-headless": "61a879c044097087b15fd6e4088ad8f93cb547c71cf2f7e05cf3ae586d78fada",
|
||||
"prometeu-runtime": "8259e3f707f1a006349fd1756979245f7a71668ac04fc896269084045d14a4e2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-f1f8224d1adeafea62bbf388c3c083361a145e52f084d6c48ccbb4c6060b97e2",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-f1f8224d1adeafea62bbf388c3c083361a145e52f084d6c48ccbb4c6060b97e2.json",
|
||||
"evidenceSha256": "f909a77726f9d3c132f8ec8f172347021cf9b7d91a6424df905330c34f85b197"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-f1f8224d1adeafea62bbf388c3c083361a145e52f084d6c48ccbb4c6060b97e2.json",
|
||||
"evidenceSha256": "f909a77726f9d3c132f8ec8f172347021cf9b7d91a6424df905330c34f85b197"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"prometeu-headless": "61a879c044097087b15fd6e4088ad8f93cb547c71cf2f7e05cf3ae586d78fada",
|
||||
"prometeu-runtime": "8e0e005de4b11b649088b77ed9fdfb4e97e851f3604fd4a09c2abadd272e231d"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-2cb9ab9296f9395fad196f7dd0b899f9e1c01ccc2e48cfe3b8dff37e628d419b",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-2cb9ab9296f9395fad196f7dd0b899f9e1c01ccc2e48cfe3b8dff37e628d419b.json",
|
||||
"evidenceSha256": "deffbb51c56aa7958c53b83674ffa486364e7965f7ec629d74951b5889aec9ea"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-2cb9ab9296f9395fad196f7dd0b899f9e1c01ccc2e48cfe3b8dff37e628d419b.json",
|
||||
"evidenceSha256": "deffbb51c56aa7958c53b83674ffa486364e7965f7ec629d74951b5889aec9ea"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"prometeu-headless": "61a879c044097087b15fd6e4088ad8f93cb547c71cf2f7e05cf3ae586d78fada",
|
||||
"prometeu-runtime": "02a7008a2efa2213fb34dd7de3057bec9c6a99c25656f9ab47ddd9338808234b"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-64979a224cd9c4f664b0a070285e4179df0b2ab4ac65d0637f4e843dcb677d70",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-64979a224cd9c4f664b0a070285e4179df0b2ab4ac65d0637f4e843dcb677d70.json",
|
||||
"evidenceSha256": "f794f9802ba60925f595f302522cdd45f8a875add6cd73f0305da997a36b0bfd"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-64979a224cd9c4f664b0a070285e4179df0b2ab4ac65d0637f4e843dcb677d70.json",
|
||||
"evidenceSha256": "f794f9802ba60925f595f302522cdd45f8a875add6cd73f0305da997a36b0bfd"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "ff1f910a0fa2f88828f03985767bb55c9364ec3ece25e46cf5965cd3faf1ceff",
|
||||
"prometeu-headless": "16aa375c2f79884f45d4a54f62bcaa25d62949ff96295422bc4a8e41d10e66a0",
|
||||
"prometeu-runtime": "2ba89830c9588e2854ee9feed0dea92506f22b08224523cea66d5701f66e0046"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
@@ -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,236 @@
|
||||
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(2560,image.getFitWidth());assertFalse(image.isSmooth());
|
||||
zoom.setValue(2);assertEquals(1280,image.getFitWidth());zoom.setValue(1);assertEquals(640,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_DRAGGED,6,6);assertEquals(0,input.get().buttons(),"Reentry while held must not recapture");
|
||||
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 {
|
||||
|
||||
+1
@@ -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;
|
||||
@@ -92,6 +93,70 @@ class HeadlessTaskIntegrationTest {
|
||||
}
|
||||
void authorityRetained() { assertEquals(ControlState.AGENT_WORKING, project.automation().snapshot().state()); }
|
||||
|
||||
@org.junit.jupiter.params.ParameterizedTest
|
||||
@org.junit.jupiter.params.provider.ValueSource(strings={"pong","fragments","main"})
|
||||
void maintainedGraphicsExamplesBuildAndPublishNativeFrames(String name) throws Exception {
|
||||
project.close();
|
||||
Path examples=Path.of("../test-projects").toAbsolutePath().normalize();
|
||||
if(!Files.isDirectory(examples))examples=Path.of("test-projects").toAbsolutePath().normalize();
|
||||
Path example=examples.resolve(name);
|
||||
for(String directory:List.of("src","assets")){
|
||||
Path from=example.resolve(directory);
|
||||
if(!Files.isDirectory(from))continue;
|
||||
try(var files=Files.walk(from)){
|
||||
for(Path file:files.toList()){
|
||||
Path target=root.resolve(directory).resolve(from.relativize(file));
|
||||
if(Files.isDirectory(file))Files.createDirectories(target);
|
||||
else Files.copy(file,target,StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
}
|
||||
Files.copy(example.resolve("prometeu.json"),root.resolve("prometeu.json"),StandardCopyOption.REPLACE_EXISTING);
|
||||
var reference=app.getBean(ProjectCatalog.class).openProject(root);
|
||||
project=app.getBean(ProjectSessionFactory.class).open(reference);
|
||||
assertTrue(project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS).success());
|
||||
task=tasks.acquire(root).task().value();
|
||||
call(TaskTools.HeadlessAction.BOOT,successfulBuild("graphics-"+name));
|
||||
var result=advance("graphics-frames-"+name);
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED,result.kind(),String.valueOf(result));
|
||||
var png=result.capture().png();
|
||||
var pixels=new p.studio.app.evidence.PngEvidenceCodec().decode(png);
|
||||
assertEquals(640,pixels.width());assertEquals(360,pixels.height());
|
||||
assertNull(call(TaskTools.HeadlessAction.FAULT,null).values().get("fault"));
|
||||
Path output=Path.of("build/graphics-examples");Files.createDirectories(output);
|
||||
Files.write(output.resolve(name+".png"),png);
|
||||
if(name.equals("pong")) {
|
||||
tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",true));
|
||||
advance("pong-native-start");
|
||||
tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",false,"a",true));
|
||||
advance("pong-native-serve");
|
||||
tasks.headless(root,task,TaskTools.HeadlessAction.CLEAR_INPUT,null,Map.of());
|
||||
int previous=-1;boolean rightPaddleBounce=false;
|
||||
for(int i=0;i<80&&!rightPaddleBounce;i++) {
|
||||
String request="pong-native-contact-"+i;
|
||||
tasks.advance(root,task,request,1);
|
||||
var frame=finished(request);assertNull(frame.failure());
|
||||
assertEquals(AutomationOutcome.Kind.SUCCEEDED,frame.runtimeResult().kind());
|
||||
var image=new p.studio.app.evidence.PngEvidenceCodec().decode(frame.runtimeResult().capture().png());
|
||||
byte[] rgba=image.rgba();int left=640,right=-1;
|
||||
// Independent observation of the white ball/flash in the arena;
|
||||
// HUD is above it, and neither paddle has this color.
|
||||
for(int y=72;y<328;y++)for(int x=60;x<615;x++) {
|
||||
int offset=(y*640+x)*4;
|
||||
if(Byte.toUnsignedInt(rgba[offset])==236&&Byte.toUnsignedInt(rgba[offset+1])==244
|
||||
&&Byte.toUnsignedInt(rgba[offset+2])==250) {left=Math.min(left,x);right=Math.max(right,x);}
|
||||
}
|
||||
assertTrue(right>=left,"Playing ball must remain observable before right contact");
|
||||
int center=(left+right)/2;
|
||||
// A scored point would teleport to the center; require a local
|
||||
// reversal near the new right paddle at x=590 instead.
|
||||
rightPaddleBounce=previous>570&¢er<previous&¢er>500;
|
||||
previous=center;
|
||||
}
|
||||
assertTrue(rightPaddleBounce,"Actual guest ball must bounce off the paddle in the expanded arena");
|
||||
}
|
||||
}
|
||||
|
||||
@Test void originalCaptureEvidenceSurvivesLaterFramesRebuildReleaseAndReopen() throws Exception {
|
||||
call(TaskTools.HeadlessAction.BOOT,successfulBuild("evidence-build"));
|
||||
tasks.advance(root,task,"evidence-frame",1);var original=finished("evidence-frame");
|
||||
@@ -120,12 +185,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 +202,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(193,159,1,80),new Evidence.Rect(317,197,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 +226,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[640*360*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(640,360,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 +245,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 +268,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(640,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,62 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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(String name) throws IOException {
|
||||
try (InputStream resource = StudioWireTest.class.getResourceAsStream("/studio-protocol/fixtures/" + name)) {
|
||||
assertNotNull(resource, "Missing protocol fixture: " + name);
|
||||
String hex = new String(resource.readAllBytes(), StandardCharsets.US_ASCII);
|
||||
return HexFormat.of().parseHex(hex.replaceAll("\\s+", ""));
|
||||
}
|
||||
}
|
||||
@Test void headerMatchesSharedRustFixture() throws Exception {
|
||||
assertArrayEquals(fixture("pause.hex"),new Header(PAUSE,0,1,42).encode());
|
||||
assertEquals(42,Header.decode(fixture("pause.hex")).request());
|
||||
}
|
||||
@Test void fragmentedReadsWorkButTruncationAndReplayFail() throws Exception {
|
||||
byte[] bytes=fixture("pause.hex");
|
||||
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("pause.hex");bad[offset]=(byte)255;
|
||||
assertThrows(IOException.class,()->Header.decode(bad));}
|
||||
byte[] huge=fixture("pause.hex");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(640,360,641));
|
||||
assertEquals(921600,frameBytes(640,360,640));
|
||||
assertThrows(IOException.class,()->text(new byte[]{(byte)0xff},0));
|
||||
}
|
||||
@Test void rgbaPayloadMatchesSharedFixture() throws Exception {
|
||||
byte[] bytes=fixture("rgba.hex");
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Studio protocol test vectors
|
||||
|
||||
These protocol 1.0 vectors mirror `devtools/studio-protocol/fixtures` in
|
||||
`prometeu-runtime`. Keep both copies identical when changing the protocol.
|
||||
|
||||
`pause.hex` checks the control header; `rgba.hex` checks frame metadata and pixels.
|
||||
They are fixed reference bytes, independent of the Java encoder under test.
|
||||
Studio unit tests load these resources from the classpath so a standalone checkout
|
||||
does not need a sibling runtime repository. Cross-repository qualification belongs
|
||||
to `prometeu-tooling`.
|
||||
@@ -0,0 +1,2 @@
|
||||
50 53 54 31 01 00 00 00 04 00 00 00 00 00 00 00
|
||||
01 00 00 00 00 00 00 00 2a 00 00 00 00 00 00 00
|
||||
@@ -0,0 +1,6 @@
|
||||
50 53 54 31 01 00 00 00 09 00 00 00 38 00 00 00
|
||||
01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
|
||||
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
|
||||
01 00 00 00 00 00 00 00 07 00 00 00 00 00 00 00
|
||||
02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00
|
||||
ff 00 00 ff 00 00 ff 80
|
||||
@@ -19,6 +19,7 @@ dependencies {
|
||||
testImplementation(project(":prometeu-studio-api"))
|
||||
testImplementation(project(":prometeu-studio-core"))
|
||||
testImplementation(project(":prometeu-studio-ui-javafx"))
|
||||
testImplementation(project(":prometeu-studio-ui-javafx-2"))
|
||||
testImplementation(project(":prometeu-app"))
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -70,7 +70,7 @@ class StudioBoundaryArchTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule javaFxAdapterDoesNotDependOnCoreOrProviderImplementations = noClasses()
|
||||
.that().resideInAPackage("p.studio.ui.javafx..")
|
||||
.that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..")
|
||||
.should().dependOnClassesThat().resideInAnyPackage(
|
||||
"p.studio.core..",
|
||||
"p.packer..",
|
||||
@@ -81,13 +81,13 @@ class StudioBoundaryArchTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule javaFxAdapterDoesNotOrchestrateTheFileSystem = noClasses()
|
||||
.that().resideInAPackage("p.studio.ui.javafx..")
|
||||
.that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..")
|
||||
.should().dependOnClassesThat().haveFullyQualifiedName("java.nio.file.Files")
|
||||
.because("DEC-0059 keeps filesystem orchestration behind neutral Studio services");
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule javaFxAdapterDoesNotOwnSerialization = noClasses()
|
||||
.that().resideInAPackage("p.studio.ui.javafx..")
|
||||
.that().resideInAnyPackage("p.studio.ui.javafx..", "p.studio.ui.javafx2..")
|
||||
.should().dependOnClassesThat().resideInAPackage("com.fasterxml.jackson..")
|
||||
.because("DEC-0059 keeps serialization in core or application adapters, not visual controls");
|
||||
|
||||
|
||||
+1
@@ -6,6 +6,7 @@ import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class PbsClosuresTest {
|
||||
@Test void namedAndAnonymousFunctionsShareSignature() throws Exception {
|
||||
PbsStructuredValuesTest.compile("closure-functions", """
|
||||
|
||||
+1
@@ -13,6 +13,7 @@ import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class PbsGenericContractsTest {
|
||||
private static final String ECHO = "declare contract Echo<T> { fn echo(value: T) -> T; } declare service Strategy {}\n";
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user