diff --git a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md index d73e6496..2aaf24e7 100644 --- a/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md +++ b/docs/specs/studio/1. Studio Shell and Workspace Layout Specification.md @@ -6,7 +6,7 @@ Purpose: Define the normative shell structure of the Studio UI. ## Authority and Precedence -This specification consolidates the accepted Studio shell decision into normative form. +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 @@ -46,10 +46,13 @@ The baseline workspace set includes: - Asset Management; - Debugger/Profiler; +- DEV, for granting/reclaiming project control and observing external-agent automation; - Shipper, temporarily represented by the current `BuilderWorkspace`. `BuilderWorkspace` is transitional and must not be treated as a long-term architectural reference for the final shipping surface. +DEV MUST remain separate from human Debug and MUST NOT offer chat or manual Play/input for the headless session. Selecting, hiding or switching away from DEV MUST NOT grant or release project authority. The shell's always-visible run surface remains visible, but conflicting manual actions MUST be unavailable while project control is ceded, including while waiting for an agent. Services MUST enforce the same exclusion; shell bindings alone are insufficient. + ## Workspace Architecture Model The shell-level workspace host exists to mount independently authored workspaces under one Studio contract. diff --git a/docs/specs/studio/10. DEV and Automation Specification.md b/docs/specs/studio/10. DEV and Automation Specification.md new file mode 100644 index 00000000..a256fdb8 --- /dev/null +++ b/docs/specs/studio/10. DEV and Automation Specification.md @@ -0,0 +1,357 @@ +# DEV and Automation Specification + +## Status + +Active normative baseline; implementation is delivered in ordered phases. +This status does not claim that the DEV workspace, MCP endpoint or integrated +agent loop is already available in an installed Studio. + +## Scope and Ownership + +Owner: **studio**, including neutral API/Core services, the JavaFX DEV workspace +and application/infrastructure adapters. Runtime owns execution and its external +headless protocol. Compiler, language/SDK references, LSP and Packer retain their +existing domain ownership. + +## Purpose + +Allow a developer to grant control of an open project to an external coding +agent, observe managed operations and canonical runtime images, and explicitly +reclaim control. Studio provides specialized project services through MCP, not +an embedded agent or a second editor. + +## Authority and Normative Inputs + +This specification implements accepted **DEC-0060**, including D1–D7 and B1–B9. +PLN-0139 sequences its implementation; it does not redefine this contract. + +- [Core and Adapter Architecture](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md): dependency direction, composition and shared operations. +- [Shell and Workspace Layout](1.%20Studio%20Shell%20and%20Workspace%20Layout%20Specification.md): workspace mounting and project lifetime. +- [Project-Local State](8.%20Project-Local%20Studio%20State%20Specification.md): configuration and restoration exclusions. +- [Runtime Headless Automation Protocol](../../../../runtime/docs/specs/runtime/11a-headless-automation-protocol.md): runtime-owned wire, commands, framing, limits and execution meanings. + +MUST, MUST NOT and MAY express requirements, prohibitions and permissions. +Implementation MUST NOT weaken this accepted baseline; substantive ambiguity +requires explicit decision review rather than a guessed implementation rule. + +## 1. Shared Services and Protocol Boundaries + +JavaFX and MCP MUST consume the same neutral API/Core authority, sessions, +operations and orchestration. Neither adapter MAY simulate UI actions or +implement a parallel permission/build/pack/execution system. + +| Boundary | Owner and responsibility | +| --- | --- | +| Studio API | Plain-Java contracts, identities, snapshots, typed outcomes, diagnostics and ports; no toolkit, framework or concrete wire DTOs | +| Studio Core | Project/session authority, guards, operations, build/pack/runtime coordination and ordered cleanup; testable without JavaFX or Spring | +| JavaFX DEV | Human grant/reclaim actions, presentation, localization, canvas, subscriptions and FX-thread projection | +| Application/infrastructure | MCP HTTP transport, process supervision, runtime JSONL translation, existing project LSP client, lifecycle and packaging | +| Runtime | Firmware/VM execution, input sampling, logical frames, ticks, rendering, watchdogs and faults | +| External coding client | Agent/chat, model/provider credentials, native file editing, budget, iterations and simple task stopping criteria | + +MCP Streamable HTTP, runtime JSONL/stdio, and human Debug/DevTools MUST remain +distinct protocols with distinct lifecycles. A native Rust/Java binding is not +the chosen runtime boundary. Compiler, LSP, Packer and runtime semantics MUST +NOT be reimplemented in Studio. + +The functional dependency graph in spec 9 MUST remain unchanged. Services +requiring guards MUST receive shared authority through neutral contracts and +composition, not depend on concrete session implementations or UI state. + +## 2. Project Authority and Control States + +Authority MUST belong to an open project session, not a tab, focused window, +HTTP connection or UI component. The agent MUST supply a project root; Studio +MUST validate it against an open project and use explicit project identity. +Window focus MUST NOT implicitly select a call's target. + +Connection authentication, human project grant and task control identity MUST +be separate checks. At most one task MAY own a project's grant. Acquisition +without a prior human grant MUST fail. A task identity MUST be required for +authorized work and MUST NOT be reusable for another project or revoked task. + +| State | Admission and permitted behavior | Exit | +| --- | --- | --- | +| Manual control | Human editing/Debug; grant only with no active Debug or conflicting managed work, and successful document handoff | Human grant enters waiting | +| Waiting for agent | Grant already blocks conflicting manual work; authenticated agent can acquire; human can reclaim without an agent connection | Acquisition enters working; reclaim enters returning | +| Agent working | One acquired task uses its valid identity; developer can inspect, navigate and reclaim | Explicit task release or human revoke enters returning | +| Returning control | Prior authority is invalid; stop managed work and refresh documents; manual conflicting actions remain blocked | Manual control only after cleanup/handoff | + +Grant and acquisition MUST be enforced atomically with conflicting operation +admission. Concurrent acquisition MUST NOT create two owners. Project-local +authority MUST NOT become a global Studio lock. + +Human Debug active MUST prevent grant. From grant onward, including waiting +and silence, Studio MUST prevent manual editing, Debug, build and other +conflicting project mutation. Guards MUST apply at service entry points as +well as UI bindings. Navigation, inspection and monitoring remain available. + +An operation finishing, failing compilation, raising a guest fault or losing +its runtime session MUST NOT release task authority. Silence, client +disconnection and waiting MUST NOT cause expiration or automatic resumption. +There is no heartbeat or silence timeout in this baseline. + +## 3. Grant and Saved-Document Handoff + +Grant MUST cover Studio-owned unsaved buffers/drafts, including dirty asset +editing surfaces; it MUST NOT assume that source files are the only editable +project content. + +If such content is dirty, DEV MUST offer **Save all and grant** or **Cancel**. +Grant MUST follow successful saves; user cancellation or save failure MUST NOT +cede control. Clean projects do not require a code snapshot, clean Git tree or +commit. Document participants MUST use neutral handoff contracts without moving +presentation buffers or JavaFX types into Core. + +The agent edits the actual project folder with native external tools. Build +MUST use saved files, and the existing project LSP client MUST synchronize +saved content before semantic queries. Studio MUST NOT claim to save external +unsaved buffers or protect against concurrent external writes. + +On authority return, Studio MUST refresh open documents from disk and MUST NOT +reapply stale buffers over agent changes. Revocation/cancellation MUST preserve +edits already made. There is no later Apply/merge step or Studio-owned code +rollback. Review, integrity, Git commits and recovery remain developer duties. + +SDK/external libraries MUST be consultable but MUST NOT be edited by the +game-authoring task. Editable local libraries MUST be inside project scope. +Unsupported capabilities or required SDK changes MUST be reported as limitations, +not silently implemented outside that scope. This does not prohibit the runtime +engineering delivery that prepared this integration. + +## 4. Return, Revocation and Closure + +Explicit release and human reclaim MUST follow this order: + +1. Invalidate task authority and reject new or delayed calls under the old identity. +2. Cancel/stop managed work and shut down owned runtime processes. +3. Refresh open documents from saved project content, without stale writeback. +4. Release conflicting manual operations and present manual control. + +Late completions MUST NOT resurrect a revoked task or restore its authority. +Cleanup MUST NOT advertise manual control before managed work is stopped and +document refresh is complete. Diagnostics MUST distinguish cleanup failure from +a successful return; operation outcome and authorization state are not the same. + +Reclaim MUST also work while waiting for an agent or after an operation failure. +Another task MUST require a new human grant. Closing/hiding/switching DEV MUST +NOT release control. Closing the project or Studio MUST revoke authority and +stop managed processes before teardown of their providers/executors. Reopening +MUST start in manual control, even when restoring DEV as the selected workspace. + +Studio cannot stop direct writes by the external coding client. The UI and +connection instructions MUST tell the developer to stop that client separately; +reclaim is not an operating-system filesystem lock or a rollback guarantee. + +## 5. DEV Workspace Contract + +DEV MUST expose: + +- **Grant control to AI** (`Ceder controle à IA`) and **Interrupt and reclaim control** (`Interromper e retomar controle`); +- the four control states, project identity, current managed operation and diagnostics; +- a canonical-image canvas with session/build/logical-frame/render-frame identity and stale status; +- a short history of Studio calls, not an independent code history; +- **Copy MCP configuration**, plus short connection/use instructions when the real MCP composition is available. + +Actions MUST reflect shared service authority. DEV MUST NOT own a duplicate +lock or release authority when disposing visual subscriptions. Presentation +updates MUST follow the existing FX-thread, theme, localization and workspace +lifecycle rules. + +DEV MUST NOT contain chat, provider settings, manual headless Play/input or +concurrent human control of the agent's execution. Human play/testing remains +in Debug with its existing host/protocol/lifecycle, subject to symmetric guards. +“Agent working” means the task has been acquired; it is not a claim to observe +all external edits, reasoning or conversation. + +Without a real composed MCP endpoint, configuration copy MUST be unavailable +rather than produce a fabricated endpoint or token. Test doubles MAY supply +operations/captures to isolated tests, never masquerade as product execution. + +## 6. Operations and Lost Responses + +Automation MUST reuse the neutral operation executor/handle boundary: stable +operation identity, observable snapshots/progress, cancellation, asynchronous +completion and typed results. Build/pack diagnostics MUST be preserved. +Success, lifecycle termination, guest fault, infrastructure/host failure and +cancellation MUST remain distinguishable, including known partial progress. + +Build and advance starts MUST return `operationId` promptly. Each start MUST +accept `clientRequestId` and allow authorized lookup by that identity if the +initial response is lost. Within the task: + +- same identifier and same parameters MUST return the existing operation without reexecution; +- same identifier with different parameters MUST fail; +- deduplication and lookup MUST still validate project/task authority; +- the registry MUST stay in memory only, without restart recovery or replay. + +Runtime `requestId` correlates a wire call; it is not Studio operation +deduplication. Neither transport error nor lost response authorizes blindly +retrying an advance. A runtime crash requires an explicit new session, not +restoration/replay; task authority remains governed by section 2. + +## 7. Runtime Supervision and Canonical Capture + +Studio MUST resolve `prometeu headless --stdio` from the configured runtime +installation. It MUST NOT discover/download another runtime over the network. +Missing or incompatible installations MUST fail explicitly. Each process owns +one session; each task MUST have at most one active headless session. + +The gateway MUST validate the runtime's protocol major/minor, real version, +required capabilities and effective limits. Incompatible major or missing +mandatory capability MUST block the session; compatible minor additions are +permitted. It MUST obey complete UTF-8 JSONL framing and separate protocol +stdout from stderr diagnostics. Invalid input/schema MUST not disappear silently. + +The runtime-owned surface covers boot/reset, set/clear normalized input, +advance, capture, state/fault, cancel and shutdown. Conflicting execution work +MUST NOT execute concurrently or be silently queued. Advance MUST preserve +requested/completed counts and stop reasons. Cancellation is observed between +frames; the current frame retains its deterministic watchdog, not a wall-clock +guest deadline. No background realtime game loop is introduced for automation. + +| Configurable, handshake-advertised limit | Default | +| --- | --- | +| Frames per advance | 600 | +| Command message | 64 KiB | +| Complete response including image/envelope | 32 MiB | +| Handshake wait | 5 s | +| Headless-call timeout | 60 s | +| Cancel/shutdown grace before process termination | 5 s | + +Oversized requests MUST fail, not be silently clamped. Responses MUST respect +their complete serialized limit. Studio MUST supervise external-process +deadlines and terminate only its owned process tree if cancellation/shutdown +does not respond within the configured grace. Report infrastructure failure +and only known progress. EOF closes the headless process; it never resumes it. + +Screenshot means the runtime's canonical **RGBA8888 framebuffer bitmap**. +Capture MUST use lossless PNG/base64 with dimensions, original stride/layout, +runtime session, `logical_frame_index` and `FrameId`. These two frame identities +MUST NOT be assumed numerically equal. Studio MUST attach build correlation. +Hashes MAY supplement but MUST NOT replace pixels. No desktop/window screenshot, +temporary-image-file transport or continuous video is permitted. + +Agent and DEV MUST receive the same capture and correlation for requested +advances. DEV MUST identify images from an older build/session as stale during +edits/rebuilds. The previous execution MUST stop before rebuilding artifacts +that it uses. Capture/build correlation MUST NOT introduce code snapshots. + +## 8. Local MCP Admission and Functional Surface + +The app MUST host Streamable HTTP at `127.0.0.1:/mcp` while +Studio is open. It MUST generate a random token per Studio start, require it +on connections, validate Origin and reject unexpected origins. No remote +binding, accounts, OAuth or stdio MCP bridge is part of this baseline. + +Copied configuration MUST contain the actual endpoint/token and MUST NOT be +written to versioned files. Instructions MUST explain that restart requires +refreshing client configuration. Copying configuration and authenticating +MUST NOT grant control. + +| Tool group | Required capabilities | Required authority | +| --- | --- | --- | +| Context/references | Project identity, languages, versions, capabilities and paginated references | Authenticated connection; no grant required | +| Control | Acquire task and release control | Prior human grant for acquisition; valid task identity for release | +| Language | Existing LSP diagnostics/navigation and supported capabilities | Valid project/task identity | +| Build | Compile and pack | Valid project/task identity | +| Headless | Boot/reset, input, advance, capture, state/fault and shutdown | Valid project/task identity | +| Operations | Query, lookup by client request identity and cancel | Valid project/task identity | + +MCP capture responses MUST expose image content plus structured metadata; +clients MUST NOT need to parse logs or fetch a temporary file to obtain pixels. +Generic shell, generic file editing, Git, publication and out-of-project changes +MUST NOT be exposed as shortcuts around these specialized services. Studio +grant does not override the external client's own permission policy or require +a new human confirmation for every authorized Studio operation. + +## 9. Project Language Context and References + +The project manifest MUST be authoritative for primary language and dependencies; +there is no parallel AI-only language configuration. PBS is the project-creation +default, not a fallback for an unknown declared language. Installed compiler/LSP +integrations MUST advertise their actual capabilities; unknown versions or +capabilities MUST be reported as unknown, not invented. + +Context MUST include: + +- explicit project identity/root; +- language list and primary designation, with separately identified known language/compiler/SDK versions; +- source extensions/scope and actual LSP/build capabilities; +- references, examples, libraries and editable versus read-only roots. + +A one-entry PBS list is valid; extensibility does not require another language +or a multilingual compiler. LSP MUST use the existing project server and support +project/library navigation through the diagnostics, definitions, references, +symbols and other queries/refactorings it actually supports. It MUST NOT +advertise nonexistent features or apply edits outside authorized scope. + +The matching language/SDK distribution MUST ship indexed local quickstart, +syntax, semantics, examples and SDK reference material. Consultation MUST work +without Studio/compiler checkouts. MCP MUST read references by identifier with +pagination, not arbitrary paths. Documentation ownership remains with its +language/SDK/library owner; packaging does not create parallel language semantics. + +Connection guidance MUST describe: connect → consult current project/languages/ +references → acquire after human grant → work using saved files and validate +through LSP/build → release. The agent need not know PBS in advance. Missing +documentation or unsupported language MUST appear as explicit limitations; +static copied instructions MUST NOT substitute for current project context. + +## 10. Delivery Phases and Conformance Gates + +The accepted slicing is runtime → DEV/shared services → MCP → integration. +No intermediate phase constitutes complete delivery of this specification. + +| Phase / plan steps | Required gate and limit | +| --- | --- | +| Runtime, 01–07 | Independent process client proves external contract, deterministic execution, canonical pixels, limits/failures and installed CLI; no Studio/AI dependency | +| DEV/shared services, 08–14 | Neutral authority/operations and document handoff first, then DEV; test grant/reclaim, Debug exclusion, dirty buffers, revocation/closure, late calls and FX lifecycle; desktop navigation smoke; doubles only in tests, no fake product endpoint | +| MCP, 15–21 | Automated MCP client proves authenticated discovery, real configuration, unauthorized rejection, exclusive acquisition, context/references, operations/deduplication, revocation and image contracts; no model required for this gate | +| Integration, 22–28 | Real runtime/LSP/build and an external coding client prove edit → build/pack → boot/input/advance → matching agent/DEV image → release; corrective loops and cleanup preserve manual Debug | + +Cross-phase conformance MUST prove API/Core neutrality, the unchanged Modulith +dependency graph, application startup/shutdown, installed/offline references, +packaging and desktop behavior. Real-client tool/image compatibility MUST be +verified with the selected client, not promised uniformly across providers. +The vertical slice MAY use a simple existing PBS program; a complete game or +mature gameplay library is not a prerequisite. + +### Decision Traceability + +| Accepted requirement | Normative location | +| --- | --- | +| D1 architecture | Section 1 and spec 9 | +| D2 runtime; B1–B3 entry/wire/order | Sections 6–7 and runtime-owned protocol | +| D3 capture; B4 capture/limits | Sections 5 and 7 | +| D4 DEV/authority | Sections 2–5; shell spec and state-restoration exclusions | +| D5 files/LSP/write scope | Sections 3 and 9 | +| D6 MCP/operations; B5–B7 | Sections 6 and 8; spec 9's HTTP exception | +| D7 languages/onboarding; B8–B9 | Sections 8–9 | +| Ordered slicing and acceptance | Section 10 | +| Accepted exclusions | Section 11 | + +## 11. Non-Goals + +- Embedded agent, chat, provider adapter, provider credentials or cost/budget accounting. +- Mirroring external conversation, reasoning or all filesystem activity. +- Pixel-art generation, full-game libraries, audio capture or deep guest introspection. +- Shared editing, isolated worktrees, code snapshots/journals/checkpoints, merge/apply, divergence recovery, undo/rollback or automatic commits/clean-tree gates. +- Replacing compiler, Packer, LSP, VM or human Debug semantics; a new general-purpose Studio source editor. +- Remote MCP, accounts/OAuth, stdio MCP bridge, network runtime discovery or provider-specific connection wizard. +- 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. + +## Exit Criteria + +Implementation is conformant only when all phase gates hold and: + +1. Human grant, task acquisition, operation outcome and authority return are distinct and tested. +2. Service-level guards prevent conflicting manual work from grant through cleanup without blocking read-only navigation globally. +3. Save failure prevents grant; successful return refreshes documents without overwriting agent edits. +4. Revoke invalidates old calls first, works while waiting and preserves edits; project/application closure cleans owned processes and never restores authority. +5. DEV and the agent see the same canonical image with explicit build/session/frame correlation and stale labeling. +6. Local transport authentication does not bypass project/task authorization or scope restrictions. +7. Lost operation responses cannot duplicate execution; runtime crash cannot trigger replay or implicit authority release. +8. Language context and indexed local references reflect real installed support and work without source checkouts. +9. Manual Debug, architecture boundaries, packaging and real-client integration pass their regression gates. diff --git a/docs/specs/studio/8. Project-Local Studio State Specification.md b/docs/specs/studio/8. Project-Local Studio State Specification.md index db6d3f2a..df5125dc 100644 --- a/docs/specs/studio/8. Project-Local Studio State Specification.md +++ b/docs/specs/studio/8. Project-Local Studio State Specification.md @@ -79,6 +79,8 @@ The main session-restoration store MUST NOT include: - heavy operational output; - recomputable results that do not represent session restoration state. +Under DEC-0060, automation grants, task/control identities, active runtime sessions and the task-local operation/deduplication registry MUST NOT be persisted or restored through `.studio/state.json` or `.studio/setup.json`. Reopening a project MUST start under manual control. Restoring DEV as the selected workspace is presentation restoration, not permission to resume work. MCP connection credentials MUST NOT be stored in versioned files; they are regenerated on Studio restart. See the [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md). + `Project-local activity` and project-local setup may still live under `.studio/`, but they are separate persistence concerns and not part of the main session-restoration store defined here. ## Ownership Rules diff --git a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md index d8a6f806..aabb8d0e 100644 --- a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +++ b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md @@ -18,14 +18,16 @@ Define the physical and functional boundary that makes the Studio consumable by ## Authority and Precedence -This specification implements `DEC-0059` and is the normative architecture reference for the Studio split. More specific domain specs may refine behavior, but they MUST preserve the dependency direction defined here. +This specification implements `DEC-0059` and the accepted `DEC-0060` AI-first baseline. It is the normative architecture reference for the Studio split. DEC-0060 adds shared automation services and the narrowly scoped local MCP server exception below; it does not replace the module boundaries or dependency direction. + +The [DEV and Automation Specification](10.%20DEV%20and%20Automation%20Specification.md) defines project authority, document handoff, operations, captures and delivery gates. More specific domain specs MUST preserve the dependency direction defined here. Normative requirements describe the target contract, not a claim that every delivery phase is already implemented. ## Architectural Model The Studio is a set of project and tooling services consumed by adapters: ```text -JavaFX UI ──> Studio API <── future non-visual adapters +JavaFX UI ──> Studio API <── local MCP adapter <── external coding agent │ ▼ Studio Core @@ -34,7 +36,7 @@ JavaFX UI ──> Studio API <── future non-visual adapters application/infrastructure adapters ``` -JavaFX is the current human adapter. A future agent surface is not part of this specification, but MUST be able to consume the same neutral services instead of simulating UI interaction. +JavaFX is the human adapter; DEV is its authorization and observation workspace. The local MCP adapter exposes the same neutral services to an external coding agent. Neither adapter MAY simulate the other adapter's UI or duplicate project authority, build/pack or execution orchestration. The external client owns the agent, chat, model/provider credentials and coding loop. ## Physical Modules @@ -53,7 +55,8 @@ The public Studio API MUST be plain Java and MUST NOT depend on: - JavaFX; - Spring Framework, Spring Boot, or Spring Modulith; -- AI, MCP, or provider SDKs; +- HTTP, AI, MCP, or provider SDKs; +- concrete runtime-wire or MCP transport DTOs; - concrete compiler, Packer, LSP, or runtime implementations; - `p.studio.core` or `p.studio.ui.javafx` internals. @@ -68,6 +71,7 @@ Core classes MUST be POJOs with constructor injection and MUST remain testable w The core module MUST NOT: - depend on JavaFX or UI packages; +- depend on HTTP/MCP SDKs, Spring, or concrete external protocol DTOs; - call `Platform.runLater`; - perform navigation or workspace selection; - use presentation severity or visual state as domain semantics; @@ -76,11 +80,11 @@ The core module MUST NOT: The functional core modules are: - `project`: project identity, catalog, creation, paths, setup, and restoration state; -- `session`: open-project lifecycle, ordered cleanup, execution ownership, and the LSP lifecycle port; +- `session`: open-project lifecycle, project-scoped automation authority, document handoff, ordered cleanup, execution ownership, and the LSP lifecycle port; - `assets`: Studio-owned asset projections, metadata, policies, non-visual sessions, validation, and workflow orchestration; - `shipper`: build/pack coordination, manifest generation, artifacts, and neutral logs/results; -- `runtime`: runtime settings, handshake, process/client lifecycle, and technical logs; -- `execution`: play/stop state, cancellation, shutdown, and orchestration of shipper and runtime. +- `runtime`: runtime settings, handshake, process/client lifecycle, canonical capture contracts, and technical logs; human Debug and headless automation retain distinct protocol/lifecycle boundaries; +- `execution`: play/stop and automation operation state, cancellation, shutdown, and orchestration of shipper and runtime. The functional dependency direction MUST remain: @@ -92,6 +96,10 @@ execution --> project, shipper, runtime session --> project, execution, LSP port ``` +Session-owned authority lifetime MUST NOT introduce reverse functional dependencies from `assets`, `shipper`, `runtime` or `execution` to the concrete `session` module. Service entry points MUST receive the shared authority through neutral contracts and composition, not reach into JavaFX or concrete session implementations. Document-handoff participants likewise use neutral contracts; their presentation buffers remain adapter-owned. + +Manual Debug and project mutation MUST enforce the same project authority as automation. Disabled UI buttons alone are not authorization. Grant, acquisition, operation completion and authority return MUST remain distinct lifecycle facts. + ## JavaFX Adapter Rules The JavaFX module MUST depend on Studio API contracts rather than core or provider implementations. It owns visual state, UI events, navigation, FX-thread transitions, CSS, fonts, locale bindings, and lifecycle of visual objects. @@ -104,7 +112,11 @@ The JavaFX module MUST NOT directly invoke compiler implementations, `p.packer`, ## Spring Composition -Spring Boot MUST be used only by `prometeu-app` as a non-web composition and lifecycle mechanism. The application MUST start with `WebApplicationType.NONE` or an equivalent guarantee and MUST NOT introduce Spring Web, WebFlux, Data, AI, durable events, or a web server without a later accepted decision. +Spring Boot MUST be used only by `prometeu-app` for desktop composition and lifecycle. `WebApplicationType.NONE` remains a valid composition mode with an explicitly managed local HTTP adapter. Conformance MUST NOT impose an unconditional absence of a web server that would forbid the DEC-0060 MCP exception. + +The sole accepted HTTP-server use is an in-process MCP Streamable HTTP endpoint at `127.0.0.1:/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a random per-Studio-start token, validate Origin and reject unexpected origins, and stop with Studio. Connection authentication MUST NOT grant project/task authority. The token MUST NOT be stored in versioned files, and restart requires refreshed client configuration. + +This exception does not authorize a web UI, remote binding, general-purpose web application, accounts, OAuth, or a stdio MCP bridge. HTTP/MCP dependencies MUST NOT enter API/Core or the JavaFX adapter. Spring Data, Spring AI and durable event infrastructure remain outside the accepted architecture. Spring configuration MAY create core services, infrastructure adapters, and a JavaFX composition factory. It MUST NOT use field injection, context lookup, broad service bags, or a replacement static container. @@ -125,6 +137,9 @@ A narrow consumer-owned gateway MUST be used when the available integration is c | `session` | LSP | Neutral session-owned lifecycle port | | `runtime` | external runtime/process | Narrow runtime-owned gateway | | JavaFX UI | Studio | Studio API only | +| MCP adapter | Studio | Studio API only; transport DTO translation belongs to infrastructure | + +The headless gateway MUST start `prometeu headless --stdio` from the configured runtime installation and map the runtime-owned JSONL contract to neutral results. It MUST NOT reuse the human DevTools connection, introduce a native Rust/Java binding, search/download another runtime, or redefine firmware/VM semantics. Runtime process supervision and the existing project LSP client belong to application/infrastructure adapters, not UI controls. `p.packer` remains an autonomous domain and MUST NOT depend on any `p.studio` package. Studio MUST NOT copy or assume ownership of Packer semantics. @@ -138,21 +153,27 @@ Long-running build, pack, runtime, and execution work MUST expose a neutral oper Core services MUST submit such work through the neutral `OperationExecutor` port. `prometeu-app` owns the executor-backed implementation and its thread lifecycle; JavaFX consumes `OperationHandle` completion and snapshots and performs only the required FX-thread projection. +Automation MUST reuse this operation boundary. Task authority is separate from operation success, guest fault, infrastructure failure or cancellation. Revocation MUST invalidate task authority before stopping managed work, refreshing open documents and releasing manual control. Closing the project or application MUST perform that cleanup; changing the active workspace MUST NOT. + +Build and advance admission MUST return a promptly queryable operation identity. Task-scoped, in-memory `clientRequestId` deduplication MUST live behind the shared services, not in a second MCP orchestrator. Runtime `requestId` is wire correlation and MUST NOT be treated as that deduplication mechanism. Late calls/results MUST NOT restore revoked authority. + ## Conformance Gates The architecture is conformant only when all of the following hold together: -- API and core compile without JavaFX or Spring dependencies; +- API and core compile without JavaFX, Spring, HTTP/MCP SDKs or concrete transport DTO dependencies; - UI has no dependency on core or concrete external providers; - `ApplicationModules.verify()` succeeds for the exclusive `p.studio.core` root; -- the application boots and shuts down in non-web mode; +- the desktop application boots and shuts down with no web exposure other than the authorized loopback MCP endpoint, whose transport is lifecycle-managed by the app; +- MCP and JavaFX consume shared authorization and operations; grant/Debug exclusion and cleanup are enforced in services; - `Container`, `AppContainer`, compatibility allowlists, and the mixed module are absent; - unit, integration, architecture, packaging, and desktop smoke tests pass; - no service locator or context lookup replaces the removed static container. ## Non-Goals -- creating an agent or MCP module; +- embedding an agent, chat or provider adapter; +- adding a second orchestration/authorization implementation inside MCP; - replacing JavaFX with a web UI; - migrating the Studio to Rust, Electron, Tauri, or a parallel rewrite; - redesigning compiler, Packer, LSP, or runtime semantics; diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index d3b02240..1d8ad82b 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -56,6 +56,7 @@ The current Studio core corpus is: 4. [`4. Assets Workspace Specification.md`](4.%20Assets%20Workspace%20Specification.md) 5. [`8. Project-Local Studio State Specification.md`](8.%20Project-Local%20Studio%20State%20Specification.md) 6. [`9. Studio Core and Adapter Architecture Specification.md`](9.%20Studio%20Core%20and%20Adapter%20Architecture%20Specification.md) +7. [`10. DEV and Automation Specification.md`](10.%20DEV%20and%20Automation%20Specification.md) ## Reading Order @@ -66,7 +67,8 @@ Recommended order: 3. components module policy; 4. assets workspace behavior; 5. project-local Studio state behavior; -6. Studio Core, adapter, composition, and external integration boundaries. +6. Studio Core, adapter, composition, and external integration boundaries; +7. DEV authority, document handoff, automation operations/captures and phased integration gates. ## Current Wave Notes @@ -74,9 +76,9 @@ The embedded Studio code-editor stack was removed by `DEC-0031`. Normative reminders: -- the active Studio workspace corpus is `Assets`, `Debug`, and `Shipper`; +- the accepted Studio workspace corpus is `Assets`, `Debug`, `Shipper`, and `DEV`; the DEV implementation follows DEC-0060's phased delivery; - project-local Studio session state remains normative and is owned by `StudioProjectSession`; -- any future external-editor backend or replacement language-service architecture requires a new accepted decision before new Studio specs are introduced. -- the Studio backend is exposed through neutral API contracts shared by the JavaFX adapter and future non-visual adapters; -- Spring Boot is a non-web composition root, while Spring Modulith verifies the JavaFX-free `p.studio.core` boundary; +- DEC-0060 authorizes an external coding agent using native file tools and the existing project LSP through MCP; it does not reinstate the embedded editor or authorize a replacement language-service architecture; +- the Studio backend is exposed through neutral API contracts shared by JavaFX and the local MCP adapter, without duplicated authority or orchestration; +- Spring Boot remains the desktop composition root with the narrow DEC-0060 local MCP HTTP exception; Spring Modulith still verifies the JavaFX-free `p.studio.core` boundary; - `p.studio.Container`, `AppContainer`, and the mixed `prometeu-studio` module are not valid final architecture. diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 56dde4e9..1c17f60e 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -28,3 +28,15 @@ javafx { version = libs.versions.javafx.get() modules("javafx.controls", "javafx.fxml") } + +// Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. +tasks.named("test") { exclude("**/DevDesktopTest.class") } +tasks.register("devDesktopTest") { + group = "verification" + description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/DevDesktopTest.class") + systemProperty("java.awt.headless", "false") +} diff --git a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java index ccf134b8..36a39a5a 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -101,18 +101,18 @@ public class StudioApplicationConfiguration { } @Bean - AssetCatalog assetCatalog(PackerWorkspaceService packer) { - return new PackerAssetCatalog(packer); + AssetCatalog assetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetCatalog(packer, access); } @Bean - AssetCommands assetCommands(PackerWorkspaceService packer) { - return new PackerAssetCommands(packer); + AssetCommands assetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetCommands(packer, access); } @Bean - AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations) { - return new PackerAssetPacking(packer, operations); + AssetPacking assetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new PackerAssetPacking(packer, operations, access); } @Bean @@ -126,8 +126,8 @@ public class StudioApplicationConfiguration { } @Bean - AssetWorkspaceStorage assetWorkspaceStorage() { - return new FileSystemAssetWorkspaceStorage(); + AssetWorkspaceStorage assetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) { + return new FileSystemAssetWorkspaceStorage(access); } @Bean @@ -146,18 +146,18 @@ public class StudioApplicationConfiguration { } @Bean - AssetMetadataService assetMetadataService(ObjectMapper mapper) { - return new AssetStudioMetadataService(mapper); + AssetMetadataService assetMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + return new AssetStudioMetadataService(mapper, access); } @Bean - SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper) { - return new SceneBankWorkflowService(assetCatalog, mapper); + SceneBankWorkflow sceneBankWorkflow(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + return new SceneBankWorkflowService(assetCatalog, mapper, access); } @Bean - TiledAssetService tiledAssetService(AssetMetadataService metadataService) { - return new TiledAssetGenerationService(metadataService); + TiledAssetService tiledAssetService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) { + return new TiledAssetGenerationService(metadataService, access); } @Bean @@ -177,8 +177,8 @@ public class StudioApplicationConfiguration { @Bean Shipper shipper(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, - OperationExecutor operations) { - return new StudioShipperService(compiler, packer, mapper, operations); + OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new StudioShipperService(compiler, packer, mapper, operations, access); } @Bean(destroyMethod = "shutdown") @@ -198,8 +198,8 @@ public class StudioApplicationConfiguration { @Bean ExecutionControllerFactory executionControllerFactory(Shipper shipper, RuntimeGateway runtime, - OperationExecutor operations) { - return new DefaultExecutionControllerFactory(shipper, runtime, operations); + OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + return new DefaultExecutionControllerFactory(shipper, runtime, operations, access); } @Bean @@ -222,10 +222,16 @@ public class StudioApplicationConfiguration { return new LspLifecycleAdapter(lifecycle); } + @Bean + p.studio.core.project.ProjectAccessRegistry projectAccessRegistry() { + return new p.studio.core.project.ProjectAccessRegistry(); + } + @Bean ProjectSessionFactory projectSessionFactory(ProjectLocalStudioStateStore stateStore, - ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) { - return new DefaultProjectSessionFactory(stateStore, setupStore, lsp); + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, OperationExecutor operations) { + return new DefaultProjectSessionFactory(stateStore, setupStore, lsp, access, operations); } @Bean diff --git a/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java b/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java index b128c030..65f3b5ef 100644 --- a/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java +++ b/prometeu-app/src/main/java/p/studio/app/operation/ExecutorOperationExecutor.java @@ -39,6 +39,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor { private final String summary; private final Callable operation; private final CompletableFuture completion = new CompletableFuture<>(); + private final CompletableFuture termination = new CompletableFuture<>(); + private final Object workerLifecycle = new Object(); + private boolean started; private final CopyOnWriteArrayList> subscribers = new CopyOnWriteArrayList<>(); private final AtomicReference snapshot; private volatile Future task; @@ -62,12 +65,19 @@ public final class ExecutorOperationExecutor implements OperationExecutor { } } return null; - }); + }) { + @Override public void run() { + synchronized (workerLifecycle) { started = true; } + try { super.run(); } + finally { termination.complete(null); } + } + }; task = submitted; try { transition(OperationState.RUNNING, summary); executor.execute(submitted); } catch (RuntimeException failure) { + termination.complete(null); if (transitionTerminal(OperationState.FAILED, failureSummary(failure))) { completion.completeExceptionally(failure); } @@ -89,6 +99,8 @@ public final class ExecutorOperationExecutor implements OperationExecutor { return completion; } + @Override public CompletionStage termination() { return termination; } + @Override public boolean cancel() { while (true) { @@ -99,8 +111,9 @@ public final class ExecutorOperationExecutor implements OperationExecutor { final OperationSnapshot cancelled = new OperationSnapshot(id, OperationState.CANCELLED, Instant.now(), summary); if (snapshot.compareAndSet(current, cancelled)) { final Future submitted = task; - if (submitted != null) { - submitted.cancel(true); + synchronized (workerLifecycle) { + if (submitted != null) submitted.cancel(true); + if (!started) termination.complete(null); } completion.cancel(false); publish(cancelled); diff --git a/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java new file mode 100644 index 00000000..a44980ea --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/DevDesktopTest.java @@ -0,0 +1,146 @@ +package p.studio.app; + +import javafx.application.Platform; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.api.operation.OperationSubscription; +import p.studio.api.project.*; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.core.execution.DefaultExecutionSession; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.ui.javafx.controls.forms.*; +import p.studio.ui.javafx.events.StudioEventBus; +import p.studio.ui.javafx.utilities.i18n.I18nService; +import p.studio.ui.javafx.workspaces.*; +import p.studio.ui.javafx.workspaces.debug.DebugWorkspace; +import p.studio.ui.javafx.workspaces.dev.*; +import java.nio.file.*; +import java.util.List; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.*; + +/** Uses the actual desktop toolkit; runtime, operation and document inputs are test consumers only. */ +class DevDesktopTest { + @TempDir Path root; + @BeforeAll static void toolkit() throws Exception { + var ready = new CompletableFuture(); + Platform.startup(() -> { Platform.setImplicitExit(false); ready.complete(null); }); + ready.get(10, TimeUnit.SECONDS); + } + @AfterAll static void stopToolkit() { Platform.exit(); } + static void fx(Runnable work) throws Exception { + var completed = new CompletableFuture(); + Platform.runLater(() -> { try { work.run(); completed.complete(null); } catch (Throwable failure) { completed.completeExceptionally(failure); } }); + completed.get(10, TimeUnit.SECONDS); + } + + @Test void devDebugNavigationBackgroundProjectionAndDisposal() throws Exception { + var pool = Executors.newSingleThreadExecutor(); + var authority = new DefaultAutomationSession(root, new ExecutorOperationExecutor(pool)); + var subscriptions = new AtomicInteger(); + var observed = (AutomationSession) java.lang.reflect.Proxy.newProxyInstance(getClass().getClassLoader(), + new Class[]{AutomationSession.class}, (proxy, method, args) -> { + var result = method.invoke(authority, args); + if (method.getName().equals("subscribe")) { + subscriptions.incrementAndGet(); + return (OperationSubscription) () -> { ((OperationSubscription) result).unsubscribe(); subscriptions.decrementAndGet(); }; + } + return result; + }); + var stage = new Stage[1]; var host = new WorkspaceHost[1]; var dev = new DevWorkspace[1]; + var locale = new I18nService(); + try { + fx(() -> { + var project = new ProjectReference("DEV smoke", "1", "pbs", 1, ProjectTarget.Game, root); + var events = new StudioEventBus(); + host[0] = new WorkspaceHost(); + dev[0] = new DevWorkspace(project, observed, locale, events); + host[0].register(dev[0]); + host[0].register(new DebugWorkspace(project, new DefaultExecutionSession(), locale, events)); + stage[0] = new Stage(); stage[0].setTitle("DEV/Debug desktop verification"); + stage[0].setScene(new Scene(host[0], 1050, 800)); stage[0].show(); host[0].change(WorkspaceId.DEV); + }); + fx(() -> { + assertEquals(1, subscriptions.get()); + assertTrue(((Button) dev[0].rootNode().lookup("#dev-mcp-config")).isDisabled()); + ((Button) dev[0].rootNode().lookup("#dev-grant")).fire(); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + host[0].change(WorkspaceId.DEBUG); assertEquals(0, subscriptions.get()); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + host[0].change(WorkspaceId.DEV); + }); + fx(() -> assertEquals(1, subscriptions.get())); + var task = authority.acquire(); // Intentionally outside the FX thread. + authority.attachRuntime(task.task(), new ManagedHeadlessSession() { + public String sessionId() { return "smoke-session"; } + public void cancel() { } + public CompletionStage shutdown() { return CompletableFuture.completedFuture(null); } + }); + // Real 1x1 PNG, supplied by the test runtime. Product never fabricates captures. + var png = java.util.Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9l0AAAAASUVORK5CYII="); + authority.submit(task.task(), "capture", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 4, 4, List.of(), + new CanonicalCapture("smoke-session", "smoke-build", 4, 1, 1, 1, 1, png))).termination().toCompletableFuture().get(5, TimeUnit.SECONDS); + fx(() -> { + assertTrue(((Button) dev[0].rootNode().lookup("#dev-grant")).isDisabled()); + assertTrue(dev[0].rootNode().lookupAll(".label").stream().filter(n -> n instanceof Label) + .map(n -> ((Label) n).getText()).anyMatch(t -> t.contains("logical=4") && t.contains("FrameId=1"))); + ((Button) dev[0].rootNode().lookup("#dev-reclaim")).fire(); + assertEquals(ControlState.MANUAL, authority.snapshot().state()); + assertTrue(authority.snapshot().stale()); + locale.setLocale(java.util.Locale.forLanguageTag("pt-BR")); + host[0].deactivateCurrentWorkspace(); assertEquals(0, subscriptions.get()); + authority.grant(false); locale.setLocale(java.util.Locale.ENGLISH); + assertEquals(ControlState.WAITING_FOR_AGENT, authority.snapshot().state()); + }); + } finally { + fx(() -> { if (host[0] != null) host[0].deactivateCurrentWorkspace(); if (stage[0] != null) stage[0].close(); }); + authority.closeAsync().toCompletableFuture().get(5, TimeUnit.SECONDS); pool.shutdownNow(); + } + } + + @Test void formsSaveFailurePreservesDraftAndReturnReadsExternalContent() throws Exception { + var file = root.resolve("document.txt"); Files.writeString(file, "initial"); + fx(() -> { + var form = new TestForm(); form.draft = "edited"; form.dirty = true; + form.fail = true; + assertThrows(CompletionException.class, () -> form.saveForHandoff().toCompletableFuture().join()); + assertTrue(form.hasUnsavedDraft()); assertEquals("edited", form.draft); + form.fail = false; form.saveForHandoff().toCompletableFuture().join(); assertFalse(form.hasUnsavedDraft()); + form.draft = "stale presentation"; + try { Files.writeString(file, "external agent edit"); } catch (Exception failure) { throw new RuntimeException(failure); } + form.discardDraftForHandoff(); + try { form.draft = Files.readString(file); } catch (Exception failure) { throw new RuntimeException(failure); } + assertEquals("external agent edit", form.draft); + }); + } + + @Test void lockedUiBlocksMutationActionsButNotReadOnlyActions() throws Exception { + fx(() -> { + var root = new VBox(); var mutate = new Button("write"); var inspect = new Button("inspect"); + inspect.getProperties().put(ManualProjectUiGuard.READ_ONLY_ACTION, true); + var writes = new AtomicInteger(); var reads = new AtomicInteger(); + mutate.setOnAction(e -> writes.incrementAndGet()); inspect.setOnAction(e -> reads.incrementAndGet()); + root.getChildren().addAll(mutate, inspect); ManualProjectUiGuard.install(root, () -> false); + mutate.fire(); inspect.fire(); assertEquals(0, writes.get()); assertEquals(1, reads.get()); + }); + } + static class TestForm extends StudioFormSection { + boolean dirty, fail; String draft = ""; + TestForm() { super(new I18nService()); } + protected String formSectionId() { return "test"; } + protected String sectionTitle() { return "test"; } + protected StudioFormMode formMode() { return StudioFormMode.EDITING; } + protected boolean isDirty() { return dirty; } + protected void renderSection() { } + protected void beginEdit() { } + protected void apply() { if (!fail) dirty = false; finishHandoffSave(!fail, "save failure"); } + protected void reset() { } + protected void cancel() { dirty = false; draft = ""; } + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java b/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java index 61ad1075..bf1cfa26 100644 --- a/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java +++ b/prometeu-app/src/test/java/p/studio/app/operation/ExecutorOperationExecutorTest.java @@ -12,6 +12,39 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; final class ExecutorOperationExecutorTest { + @Test + void cancellationDoesNotPretendAnUncooperativeWorkerHasStopped() throws Exception { + final var executor = Executors.newSingleThreadExecutor(); + final var started = new CountDownLatch(1); + final var finish = new CountDownLatch(1); + try { + var handle = new ExecutorOperationExecutor(executor).submit("stubborn worker", () -> { + started.countDown(); + boolean done = false; + while (!done) try { finish.await(); done = true; } catch (InterruptedException ignored) { } + return 42; + }); + assertTrue(started.await(2, TimeUnit.SECONDS)); + handle.cancel(); + assertTrue(handle.completion().toCompletableFuture().isCancelled()); + org.junit.jupiter.api.Assertions.assertFalse(handle.termination().toCompletableFuture().isDone()); + finish.countDown(); + handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS); + } finally { finish.countDown(); executor.shutdownNow(); } + } + + @Test + void cancellingQueuedWorkCompletesTerminationWithoutRunningItsBody() throws Exception { + final var executor = Executors.newSingleThreadExecutor(); + final var finish = new CountDownLatch(1); + try { + executor.submit(() -> { try { finish.await(); } catch (InterruptedException ignored) { } }); + var handle = new ExecutorOperationExecutor(executor).submit("queued", () -> { throw new AssertionError("must not execute"); }); + handle.cancel(); + handle.termination().toCompletableFuture().get(2, TimeUnit.SECONDS); + } finally { finish.countDown(); executor.shutdownNow(); } + } + @Test void completesWithTypedResultAndTerminalSnapshot() throws Exception { final var executor = Executors.newSingleThreadExecutor(); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java new file mode 100644 index 00000000..099ac920 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationOutcome.java @@ -0,0 +1,7 @@ +package p.studio.api.automation; +import java.util.List; +public record AutomationOutcome(Kind kind, long requestedFrames, long completedFrames, + List diagnostics, CanonicalCapture capture) { + public enum Kind { SUCCEEDED, TERMINATED, GUEST_FAULT, INFRASTRUCTURE_FAILURE, CANCELLED } + public AutomationOutcome { diagnostics = List.copyOf(diagnostics); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java new file mode 100644 index 00000000..dc46493b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSession.java @@ -0,0 +1,20 @@ +package p.studio.api.automation; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; +import p.studio.api.operation.OperationHandle; +import p.studio.api.operation.OperationSubscription; +public interface AutomationSession { + AutomationSnapshot snapshot(); + OperationSubscription subscribe(Consumer listener); + OperationSubscription registerDocuments(DocumentHandoff documents); + CompletionStage grant(boolean saveUnsavedDocuments); + ControlResult acquire(); + CompletionStage release(TaskIdentity task); + CompletionStage reclaim(); + CompletionStage closeAsync(); + /** Internal specialized service work, not a generic MCP shell/tool endpoint. */ + OperationHandle submit(TaskIdentity task, String summary, Callable work); + void attachRuntime(TaskIdentity task, ManagedHeadlessSession runtime); + void markCaptureStale(); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java new file mode 100644 index 00000000..7b3fba5b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationSnapshot.java @@ -0,0 +1,12 @@ +package p.studio.api.automation; +import java.nio.file.Path; +import java.util.List; +import p.studio.api.operation.OperationSnapshot; +public record AutomationSnapshot(Path projectRoot, ControlState state, boolean handoffPending, + boolean closed, int manualOperations, TaskIdentity task, OperationSnapshot operation, + CanonicalCapture capture, boolean stale, List diagnostics, List calls) { + public AutomationSnapshot { diagnostics = List.copyOf(diagnostics); calls = List.copyOf(calls); } + public boolean manualAllowed() { return !closed && !handoffPending && state == ControlState.MANUAL; } + public boolean canGrant() { return manualAllowed() && manualOperations == 0; } + public boolean canReclaim() { return !closed && state != ControlState.MANUAL; } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java new file mode 100644 index 00000000..582bdf0c --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/CanonicalCapture.java @@ -0,0 +1,12 @@ +package p.studio.api.automation; +import java.util.Objects; +/** Lossless PNG bytes; stride describes the original RGBA8888 buffer, not PNG padding. */ +public record CanonicalCapture(String sessionId, String buildId, long logicalFrameIndex, + long frameId, int width, int height, int stridePixels, byte[] png) { + public CanonicalCapture { + Objects.requireNonNull(sessionId); Objects.requireNonNull(buildId); Objects.requireNonNull(png); + if (width <= 0 || height <= 0 || stridePixels < width) throw new IllegalArgumentException("invalid frame layout"); + png = png.clone(); + } + @Override public byte[] png() { return png.clone(); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java new file mode 100644 index 00000000..461dc8d8 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlDeniedException.java @@ -0,0 +1,10 @@ +package p.studio.api.automation; +/** A typed admission failure; adapters must preserve the domain status. */ +public final class ControlDeniedException extends IllegalStateException { + private final ControlResult.Status status; + public ControlDeniedException(ControlResult.Status status) { + super("Project control: " + status); + this.status = status; + } + public ControlResult.Status status() { return status; } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java new file mode 100644 index 00000000..a8544e28 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlResult.java @@ -0,0 +1,6 @@ +package p.studio.api.automation; +public record ControlResult(Status status, TaskIdentity task, String diagnostic) { + public enum Status { GRANTED, ACQUIRED, RETURNED, BUSY, DIRTY_DOCUMENTS, SAVE_FAILED, NOT_GRANTED, INVALID_TASK, CLOSED, CLEANUP_FAILED } + public boolean success() { return status == Status.GRANTED || status == Status.ACQUIRED || status == Status.RETURNED; } + public static ControlResult of(Status status, String message) { return new ControlResult(status, null, message); } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java new file mode 100644 index 00000000..ceab85a4 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ControlState.java @@ -0,0 +1,2 @@ +package p.studio.api.automation; +public enum ControlState { MANUAL, WAITING_FOR_AGENT, AGENT_WORKING, RETURNING_CONTROL } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java new file mode 100644 index 00000000..f1cd77c8 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/DocumentHandoff.java @@ -0,0 +1,10 @@ +package p.studio.api.automation; +import java.util.concurrent.CompletionStage; +/** A participant must complete only after saves/refreshes, not when they are scheduled. */ +public interface DocumentHandoff extends AutoCloseable { + CompletionStage hasUnsavedChanges(); + CompletionStage saveAll(); + CompletionStage refreshFromDisk(); + /** Disposes presentation work on project closure; must not write buffered content. */ + @Override default void close() { } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java new file mode 100644 index 00000000..0b8f9b71 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManagedHeadlessSession.java @@ -0,0 +1,8 @@ +package p.studio.api.automation; +import java.util.concurrent.CompletionStage; +/** Lifecycle port implemented by the process adapter, never by JavaFX. */ +public interface ManagedHeadlessSession { + String sessionId(); + void cancel(); + CompletionStage shutdown(); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java new file mode 100644 index 00000000..437e1848 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ManualLease.java @@ -0,0 +1,7 @@ +package p.studio.api.automation; +/** Keeps grant admission closed until the actual manual work has finished. */ +@FunctionalInterface +public interface ManualLease extends AutoCloseable { + @Override void close(); + default void onProjectClose(Runnable cancellation) { } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java new file mode 100644 index 00000000..56b1a63b --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/ProjectAccess.java @@ -0,0 +1,17 @@ +package p.studio.api.automation; +import java.nio.file.Path; +/** Shared service guard. Paths may be project roots or contained asset paths. */ +public interface ProjectAccess { + ManualLease enterManual(Path path); + + default p.studio.api.operation.OperationHandle submitManual(Path path, + p.studio.api.operation.OperationExecutor executor, String summary, java.util.concurrent.Callable work) { + ManualLease lease = enterManual(path); + try { + var operation = executor.submit(summary, work); + lease.onProjectClose(operation::cancel); + operation.termination().whenComplete((result, failure) -> lease.close()); + return operation; + } catch (RuntimeException failure) { lease.close(); throw failure; } + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java new file mode 100644 index 00000000..d4084cc3 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/TaskIdentity.java @@ -0,0 +1,9 @@ +package p.studio.api.automation; +import java.nio.file.Path; +import java.util.Objects; +public record TaskIdentity(Path projectRoot, String value) { + public TaskIdentity { + projectRoot = Objects.requireNonNull(projectRoot).toAbsolutePath().normalize(); + if (Objects.requireNonNull(value).isBlank()) throw new IllegalArgumentException("empty task identity"); + } +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java b/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java index 56edd2c3..fc5bd03f 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/operation/OperationHandle.java @@ -10,6 +10,11 @@ public interface OperationHandle { CompletionStage completion(); + /** Completes only when the worker has stopped, even if cancellation was acknowledged earlier. */ + default CompletionStage termination() { + return completion().handle((result, failure) -> null); + } + boolean cancel(); OperationSubscription subscribe(Consumer subscriber); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java index 6210746e..687ae501 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/session/ProjectSession.java @@ -14,6 +14,8 @@ public interface ProjectSession extends AutoCloseable { ExecutionSession executionSession(); + p.studio.api.automation.AutomationSession automation(); + void replaceProjectLocalStudioState(ProjectLocalStudioState state); void saveProjectLocalStudioState(); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java index c7c13cff..afdeb4e7 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/FileSystemAssetWorkspaceStorage.java @@ -10,6 +10,13 @@ import java.nio.file.Path; import java.util.Objects; public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStorage { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public FileSystemAssetWorkspaceStorage() { } + public FileSystemAssetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) { + this(); + this.access = java.util.Objects.requireNonNull(access); + } + @Override public Path assetsRoot(ProjectReference projectReference) { return Objects.requireNonNull(projectReference, "projectReference") @@ -21,12 +28,14 @@ public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStor @Override public AssetWorkspacePreparation prepare(ProjectReference projectReference) { - final Path root = assetsRoot(projectReference); - try { - Files.createDirectories(root); - return new AssetWorkspacePreparation(true, root, ""); - } catch (IOException exception) { - return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory.")); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(projectReference.rootPath())) { + final Path root = assetsRoot(projectReference); + try { + Files.createDirectories(root); + return new AssetWorkspacePreparation(true, root, ""); + } catch (IOException exception) { + return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory.")); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java index 4345f9c1..dc9ff473 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java @@ -14,6 +14,12 @@ import java.util.List; import java.util.Objects; public final class PackerAssetCatalog implements AssetCatalog { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + this(packer); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; public PackerAssetCatalog(PackerWorkspaceService packer) { @@ -22,20 +28,22 @@ public final class PackerAssetCatalog implements AssetCatalog { @Override public List list(ProjectReference projectReference, boolean deepSync) { - final var context = new p.packer.messages.PackerProjectContext( - projectReference.name(), - projectReference.rootPath()); - return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream() - .map(summary -> new AssetSummary( - AssetReference.of(summary.assetReference().value()), - summary.identity().assetName(), - AssetRegistrationState.valueOf(summary.state().name()), - AssetBuildParticipation.valueOf(summary.buildParticipation().name()), - summary.identity().assetId(), - AssetFamily.valueOf(summary.assetFamily().name()), - summary.identity().assetRoot(), - summary.preloadEnabled(), - summary.hasDiagnostics())) - .toList(); + try (p.studio.api.automation.ManualLease accessLease = deepSync ? access.enterManual(projectReference.rootPath()) : () -> {}) { + final var context = new p.packer.messages.PackerProjectContext( + projectReference.name(), + projectReference.rootPath()); + return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream() + .map(summary -> new AssetSummary( + AssetReference.of(summary.assetReference().value()), + summary.identity().assetName(), + AssetRegistrationState.valueOf(summary.state().name()), + AssetBuildParticipation.valueOf(summary.buildParticipation().name()), + summary.identity().assetId(), + AssetFamily.valueOf(summary.assetFamily().name()), + summary.identity().assetRoot(), + summary.preloadEnabled(), + summary.hasDiagnostics())) + .toList(); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java index a79552cc..1e629840 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCommands.java @@ -14,6 +14,12 @@ import java.util.Map; import java.util.Objects; public final class PackerAssetCommands implements AssetCommands { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) { + this(packer); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; public PackerAssetCommands(PackerWorkspaceService packer) { @@ -23,64 +29,80 @@ public final class PackerAssetCommands implements AssetCommands { @Override public AssetMutationResult create(ProjectReference project, String assetRoot, String assetName, AssetFamily assetFamily, String outputFormat, String outputCodec, boolean preloadEnabled) { - final var result = packer.createAsset(new CreateAssetRequest( - context(project), assetRoot, assetName, - AssetFamilyCatalog.valueOf(assetFamily.name()), - OutputFormatCatalog.valueOf(outputFormat), - OutputCodecCatalog.valueOf(outputCodec), - preloadEnabled)); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.createAsset(new CreateAssetRequest( + context(project), assetRoot, assetName, + AssetFamilyCatalog.valueOf(assetFamily.name()), + OutputFormatCatalog.valueOf(outputFormat), + OutputCodecCatalog.valueOf(outputCodec), + preloadEnabled)); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult move(ProjectReference project, AssetReference assetReference, String targetRoot) { - final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot)); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot)); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult register(ProjectReference project, AssetReference assetReference) { - final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference))); - return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference))); + return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult delete(ProjectReference project, AssetReference assetReference) { - final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference))); - return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference))); + return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath()); + } } @Override public AssetMutationResult updateBuildParticipation(ProjectReference project, AssetReference assetReference, boolean includeInBuild) { - final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest( - context(project), reference(assetReference), includeInBuild)); - return mutation(result.status(), result.summary(), result.assetReference(), null, null); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest( + context(project), reference(assetReference), includeInBuild)); + return mutation(result.status(), result.summary(), result.assetReference(), null, null); + } } @Override public AssetUpdateResult updateContract(ProjectReference project, AssetReference assetReference, boolean preload, String outputCodec, Map codecFieldValues, Map metadataFieldValues) { - final var result = packer.updateAssetContract(new UpdateAssetContractRequest( - context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec), - codecFieldValues, metadataFieldValues)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.updateAssetContract(new UpdateAssetContractRequest( + context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec), + codecFieldValues, metadataFieldValues)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } @Override public AssetUpdateResult applyBankComposition(ProjectReference project, AssetReference assetReference, List selectedPaths) { - final var result = packer.applyBankComposition(new ApplyBankCompositionRequest( - context(project), reference(assetReference), selectedPaths)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.applyBankComposition(new ApplyBankCompositionRequest( + context(project), reference(assetReference), selectedPaths)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } @Override public AssetUpdateResult applyPaletteOverhauling(ProjectReference project, AssetReference assetReference, List> selectedPalettes) { - final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest( - context(project), reference(assetReference), selectedPalettes)); - return new AssetUpdateResult(result.success(), result.errorMessage()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) { + final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest( + context(project), reference(assetReference), selectedPalettes)); + return new AssetUpdateResult(result.success(), result.errorMessage()); + } } private static PackerProjectContext context(ProjectReference project) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java index f9918794..58a45740 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetPacking.java @@ -10,6 +10,12 @@ import p.studio.api.operation.OperationHandle; import java.util.Objects; public final class PackerAssetPacking implements AssetPacking { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public PackerAssetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + this(packer, operations); + this.access = java.util.Objects.requireNonNull(access); + } + private final PackerWorkspaceService packer; private final OperationExecutor operations; @@ -20,7 +26,7 @@ public final class PackerAssetPacking implements AssetPacking { @Override public OperationHandle deepSync(ProjectReference project) { - return operations.submit("Synchronize project assets", () -> deepSyncNow(project)); + return access.submitManual(project.rootPath(), operations, "Synchronize project assets", () -> deepSyncNow(project)); } private AssetSyncResult deepSyncNow(ProjectReference project) { @@ -63,7 +69,7 @@ public final class PackerAssetPacking implements AssetPacking { @Override public OperationHandle pack(ProjectReference project) { - return operations.submit("Pack project assets", () -> packNow(project)); + return access.submitManual(project.rootPath(), operations, "Pack project assets", () -> packNow(project)); } private AssetPackExecution packNow(ProjectReference project) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java index 421f98c1..3f736e47 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/metadata/AssetStudioMetadataService.java @@ -18,6 +18,12 @@ import java.util.Objects; import java.util.Set; public final class AssetStudioMetadataService implements AssetMetadataService { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public AssetStudioMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + this(mapper); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String STUDIO_ASSET_METADATA_FILE = "studio.asset.json"; public static final String SCENE_BANK_SUPPORT_FILE = "scene-bank.studio.json"; public static final String GLYPH_MATERIAL_SUPPORT_FILE = "glyph-material.json"; @@ -43,11 +49,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeSceneBankMetadata(Path assetRoot, AssetStudioSceneBankMetadata metadata) { - try { - writeSceneBankMetadataFile(assetRoot, metadata); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeSceneBankMetadataFile(assetRoot, metadata); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception)); + } } } @@ -91,11 +99,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeGlyphSpecialization(Path assetRoot, AssetStudioGlyphSpecialization specialization) { - try { - writeGlyphSpecializationFile(assetRoot, specialization); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeGlyphSpecializationFile(assetRoot, specialization); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception)); + } } } @@ -119,11 +129,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService { @Override public AssetMetadataWriteResult writeGlyphMaterialMetadata(Path assetRoot, AssetStudioGlyphMaterialMetadata metadata) { - try { - writeGlyphMaterialMetadataFile(assetRoot, metadata); - return AssetMetadataWriteResult.success(); - } catch (IOException exception) { - return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception)); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) { + try { + writeGlyphMaterialMetadataFile(assetRoot, metadata); + return AssetMetadataWriteResult.success(); + } catch (IOException exception) { + return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception)); + } } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java index 790a28ae..29507e47 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/scene/SceneBankWorkflowService.java @@ -23,6 +23,12 @@ import java.util.List; import java.util.Objects; public final class SceneBankWorkflowService implements SceneBankWorkflow { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public SceneBankWorkflowService(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) { + this(assetCatalog, mapper); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String ACCEPTED_REQUEST_FILE = "scene-bank.pack-request.json"; private final ObjectMapper mapper; @@ -60,10 +66,12 @@ public final class SceneBankWorkflowService implements SceneBankWorkflow { } final List diagnostics = new ArrayList<>(validateDiagnostics(projectReference, details)); if (diagnostics.stream().noneMatch(AssetDiagnostic::blocking)) { - try { + try (var accessLease = access.enterManual(projectReference.rootPath())) { writeAcceptedRequest( details.summary().assetRoot().resolve(ACCEPTED_REQUEST_FILE), buildCanonicalRequest(projectReference, details)); + } catch (p.studio.api.automation.ControlDeniedException locked) { + // Inspection remains available while ceded; do not persist derived requests. } catch (IOException | IllegalArgumentException exception) { diagnostics.add(error( "Unable to persist canonical scene-pack request: " + exception.getMessage(), diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java index 4283c146..a3cac290 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/tiled/TiledAssetGenerationService.java @@ -25,6 +25,12 @@ import java.util.Map; import java.util.Objects; public final class TiledAssetGenerationService implements TiledAssetService { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public TiledAssetGenerationService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) { + this(metadataService); + this.access = java.util.Objects.requireNonNull(access); + } + public static final String GENERATED_TSX_FILE = "tileset.tsx"; private static final long FLIP_HORIZONTAL_FLAG = 0x80000000L; @@ -49,61 +55,71 @@ public final class TiledAssetGenerationService implements TiledAssetService { } public TiledAssetGenerationResult generateTilesetTsx(AssetWorkspaceAssetDetails details) { - return exportTilesetTsx(details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportTilesetTsx(details); + } } @Override public TiledAssetGenerationResult exportTilesetTsx(AssetWorkspaceAssetDetails details) { - if (details == null - || details.summary().assetFamily() != AssetFamily.GLYPH_BANK - || details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) { - return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of()); - } - final List selectedFiles = details.bankComposition().selectedFiles(); - if (selectedFiles.isEmpty()) { - return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of()); - } - final int tileSize = parseTileSize(details.metadataFields()); - final List tiles = new ArrayList<>(); - for (int index = 0; index < selectedFiles.size(); index += 1) { - final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index); - tiles.add(new TiledTilesetTile( - index, - file.path(), + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null + || details.summary().assetFamily() != AssetFamily.GLYPH_BANK + || details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) { + return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of()); + } + final List selectedFiles = details.bankComposition().selectedFiles(); + if (selectedFiles.isEmpty()) { + return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of()); + } + final int tileSize = parseTileSize(details.metadataFields()); + final List tiles = new ArrayList<>(); + for (int index = 0; index < selectedFiles.size(); index += 1) { + final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index); + tiles.add(new TiledTilesetTile( + index, + file.path(), + tileSize, + tileSize, + List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))), + null)); + } + final TiledTilesetDocument document = new TiledTilesetDocument( + "1.10", + "1.12.1", + details.summary().assetName(), tileSize, tileSize, - List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))), - null)); - } - final TiledTilesetDocument document = new TiledTilesetDocument( - "1.10", - "1.12.1", - details.summary().assetName(), - tileSize, - tileSize, - tiles.size(), - 0, - List.of(), - tiles); - final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE); - try { - codec.writeTileset(outputPath, document); - return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath)); - } catch (IOException exception) { - return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of()); + tiles.size(), + 0, + List.of(), + tiles); + final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE); + try { + codec.writeTileset(outputPath, document); + return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath)); + } catch (IOException exception) { + return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of()); + } } } public TiledAssetGenerationResult generateSceneBankTilemaps(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - return exportSceneBankTmx(projectReference, details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details); + } } public TiledAssetGenerationResult generateSceneBankTilemap(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) { - return exportSceneBankTmx(projectReference, details); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details); + } } public TiledAssetGenerationResult exportSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE); + } } @Override @@ -111,221 +127,225 @@ public final class TiledAssetGenerationService implements TiledAssetService { ProjectReference projectReference, AssetWorkspaceAssetDetails details, SceneTmxExportDisposition disposition) { - if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { - return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of()); - } - final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); - if (metadata == null) { - return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); - } - final List enabledLayers = metadata.layerBindings().stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .toList(); - if (enabledLayers.isEmpty()) { - return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of()); - } - final String sceneTilemap = resolveSceneTilemap(metadata); - if (sceneTilemap == null) { - return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); - } - try { - final ExportContext context = buildExportContext(projectReference, details, enabledLayers); - final List tileLayers = new ArrayList<>(); - int nextLayerId = 1; - for (AssetStudioSceneLayerBinding binding : enabledLayers) { - final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot()); - final List gids = new ArrayList<>(binding.tiles().size()); - for (AssetStudioSceneTile tile : binding.tiles()) { - if (!tile.active()) { - gids.add(0L); - continue; + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { + return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of()); + } + final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); + if (metadata == null) { + return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); + } + final List enabledLayers = metadata.layerBindings().stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .toList(); + if (enabledLayers.isEmpty()) { + return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of()); + } + final String sceneTilemap = resolveSceneTilemap(metadata); + if (sceneTilemap == null) { + return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); + } + try { + final ExportContext context = buildExportContext(projectReference, details, enabledLayers); + final List tileLayers = new ArrayList<>(); + int nextLayerId = 1; + for (AssetStudioSceneLayerBinding binding : enabledLayers) { + final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot()); + final List gids = new ArrayList<>(binding.tiles().size()); + for (AssetStudioSceneTile tile : binding.tiles()) { + if (!tile.active()) { + gids.add(0L); + continue; + } + if (tile.glyphId() >= ref.tileCount()) { + return new TiledAssetGenerationResult( + false, + "Layer " + binding.index() + " references glyph_id outside the exported TSX range.", + List.of(), + List.of()); + } + long gid = ref.firstGid() + tile.glyphId(); + if (tile.flipX()) { + gid |= FLIP_HORIZONTAL_FLAG; + } + if (tile.flipY()) { + gid |= FLIP_VERTICAL_FLAG; + } + gids.add(gid); } - if (tile.glyphId() >= ref.tileCount()) { - return new TiledAssetGenerationResult( - false, - "Layer " + binding.index() + " references glyph_id outside the exported TSX range.", - List.of(), - List.of()); - } - long gid = ref.firstGid() + tile.glyphId(); - if (tile.flipX()) { - gid |= FLIP_HORIZONTAL_FLAG; - } - if (tile.flipY()) { - gid |= FLIP_VERTICAL_FLAG; - } - gids.add(gid); + tileLayers.add(new TiledTileLayer( + nextLayerId, + binding.layerName(), + binding.width(), + binding.height(), + gids, + List.of())); + nextLayerId += 1; } - tileLayers.add(new TiledTileLayer( + final TiledMapDocument document = new TiledMapDocument( + "1.10", + "1.12.1", + "orthogonal", + "right-down", + enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1), + enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1), + context.tileSize(), + context.tileSize(), nextLayerId, - binding.layerName(), - binding.width(), - binding.height(), - gids, - List.of())); - nextLayerId += 1; + 1, + List.of(), + context.tilesetRefs(), + tileLayers, + List.of()); + final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap); + final ArrayList writtenFiles = new ArrayList<>(); + if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) { + final Path backupPath = nextSceneTmxBackupPath(outputPath); + Files.copy(outputPath, backupPath); + writtenFiles.add(backupPath); + } + codec.writeMap(outputPath, document); + writtenFiles.add(outputPath); + return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles)); + } catch (IOException | TiledUnsupportedFeatureException exception) { + return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of()); } - final TiledMapDocument document = new TiledMapDocument( - "1.10", - "1.12.1", - "orthogonal", - "right-down", - enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1), - enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1), - context.tileSize(), - context.tileSize(), - nextLayerId, - 1, - List.of(), - context.tilesetRefs(), - tileLayers, - List.of()); - final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap); - final ArrayList writtenFiles = new ArrayList<>(); - if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) { - final Path backupPath = nextSceneTmxBackupPath(outputPath); - Files.copy(outputPath, backupPath); - writtenFiles.add(backupPath); - } - codec.writeMap(outputPath, document); - writtenFiles.add(outputPath); - return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles)); - } catch (IOException | TiledUnsupportedFeatureException exception) { - return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of()); } } @Override public TiledAssetGenerationResult importSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) { - if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { - return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of()); - } - final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); - if (metadata == null) { - return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); - } - final String sceneTilemap = resolveSceneTilemap(metadata); - if (sceneTilemap == null) { - return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); - } - final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap); - if (!Files.isRegularFile(inputPath)) { - return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of()); - } - try { - final List enabledLayers = metadata.layerBindings().stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .toList(); - final ExportContext context = buildExportContext(projectReference, details, enabledLayers); - final TiledMapDocument map = codec.readMap(inputPath); - if (map.tileLayers().isEmpty()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of()); + try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) { + if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) { + return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of()); } - if (map.tileLayers().size() > metadata.layerCount()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of()); + final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata(); + if (metadata == null) { + return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of()); } - if (map.tilesets().size() != context.tilesetRefs().size()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of()); + final String sceneTilemap = resolveSceneTilemap(metadata); + if (sceneTilemap == null) { + return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of()); } - for (int index = 0; index < context.tilesetRefs().size(); index += 1) { - if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) { - return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of()); + final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap); + if (!Files.isRegularFile(inputPath)) { + return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of()); + } + try { + final List enabledLayers = metadata.layerBindings().stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .toList(); + final ExportContext context = buildExportContext(projectReference, details, enabledLayers); + final TiledMapDocument map = codec.readMap(inputPath); + if (map.tileLayers().isEmpty()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of()); + } + if (map.tileLayers().size() > metadata.layerCount()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of()); + } + if (map.tilesets().size() != context.tilesetRefs().size()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of()); + } + for (int index = 0; index < context.tilesetRefs().size(); index += 1) { + if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) { + return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of()); + } } - } - final List updatedBindings = new ArrayList<>(); - for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) { - final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex); - if (bindingIndex >= map.tileLayers().size()) { + final List updatedBindings = new ArrayList<>(); + for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) { + final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex); + if (bindingIndex >= map.tileLayers().size()) { + updatedBindings.add(new AssetStudioSceneLayerBinding( + false, + binding.index(), + binding.layerName(), + binding.width(), + binding.height(), + binding.tilemap(), + binding.tilesetAssetRoot(), + binding.parallaxFactorX(), + binding.parallaxFactorY(), + binding.defaultPaletteId(), + binding.tiles())); + continue; + } + final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex); + if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of()); + } + final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context); + if (ref == null) { + return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of()); + } + final List importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height()); + for (long rawGid : importedLayer.gids()) { + if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) { + return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of()); + } + final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L; + final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L; + final long gid = rawGid & GID_MASK; + if (gid == 0L) { + importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId())); + continue; + } + if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) { + return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of()); + } + final int tilesetTileId = (int) (gid - ref.firstGid()); + final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId); + if (glyphId == null) { + return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of()); + } + importedTiles.add(new AssetStudioSceneTile( + true, + glyphId, + binding.defaultPaletteId(), + flipX, + flipY)); + } updatedBindings.add(new AssetStudioSceneLayerBinding( - false, + true, binding.index(), binding.layerName(), - binding.width(), - binding.height(), + importedLayer.width(), + importedLayer.height(), binding.tilemap(), - binding.tilesetAssetRoot(), + ref.assetRoot(), binding.parallaxFactorX(), binding.parallaxFactorY(), binding.defaultPaletteId(), - binding.tiles())); - continue; + importedTiles)); } - final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex); - if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of()); + final int mapWidth = Math.max(map.width(), updatedBindings.stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .mapToInt(AssetStudioSceneLayerBinding::width) + .max() + .orElse(metadata.mapWidth())); + final int mapHeight = Math.max(map.height(), updatedBindings.stream() + .filter(AssetStudioSceneLayerBinding::enabled) + .mapToInt(AssetStudioSceneLayerBinding::height) + .max() + .orElse(metadata.mapHeight())); + final var metadataWrite = metadataService.writeSceneBankMetadata( + details.summary().assetRoot(), new AssetStudioSceneBankMetadata( + mapWidth, + mapHeight, + metadata.layerCount(), + updatedBindings, + metadata.supportFile())); + if (!metadataWrite.successful()) { + return new TiledAssetGenerationResult( + false, + "Unable to import TMX: " + metadataWrite.message(), + List.of(), + List.of()); } - final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context); - if (ref == null) { - return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of()); - } - final List importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height()); - for (long rawGid : importedLayer.gids()) { - if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) { - return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of()); - } - final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L; - final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L; - final long gid = rawGid & GID_MASK; - if (gid == 0L) { - importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId())); - continue; - } - if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) { - return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of()); - } - final int tilesetTileId = (int) (gid - ref.firstGid()); - final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId); - if (glyphId == null) { - return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of()); - } - importedTiles.add(new AssetStudioSceneTile( - true, - glyphId, - binding.defaultPaletteId(), - flipX, - flipY)); - } - updatedBindings.add(new AssetStudioSceneLayerBinding( - true, - binding.index(), - binding.layerName(), - importedLayer.width(), - importedLayer.height(), - binding.tilemap(), - ref.assetRoot(), - binding.parallaxFactorX(), - binding.parallaxFactorY(), - binding.defaultPaletteId(), - importedTiles)); + return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile())); + } catch (IOException | TiledUnsupportedFeatureException exception) { + return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of()); } - final int mapWidth = Math.max(map.width(), updatedBindings.stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .mapToInt(AssetStudioSceneLayerBinding::width) - .max() - .orElse(metadata.mapWidth())); - final int mapHeight = Math.max(map.height(), updatedBindings.stream() - .filter(AssetStudioSceneLayerBinding::enabled) - .mapToInt(AssetStudioSceneLayerBinding::height) - .max() - .orElse(metadata.mapHeight())); - final var metadataWrite = metadataService.writeSceneBankMetadata( - details.summary().assetRoot(), new AssetStudioSceneBankMetadata( - mapWidth, - mapHeight, - metadata.layerCount(), - updatedBindings, - metadata.supportFile())); - if (!metadataWrite.successful()) { - return new TiledAssetGenerationResult( - false, - "Unable to import TMX: " + metadataWrite.message(), - List.of(), - List.of()); - } - return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile())); - } catch (IOException | TiledUnsupportedFeatureException exception) { - return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of()); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java index 4daf71a7..c837946f 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/DefaultExecutionControllerFactory.java @@ -15,15 +15,18 @@ public final class DefaultExecutionControllerFactory implements ExecutionControl private final Shipper shipper; private final RuntimeGateway runtime; private final OperationExecutor operations; + private final p.studio.api.automation.ProjectAccess access; - public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) { + public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations, + p.studio.api.automation.ProjectAccess access) { this.shipper = Objects.requireNonNull(shipper, "shipper"); this.runtime = Objects.requireNonNull(runtime, "runtime"); this.operations = Objects.requireNonNull(operations, "operations"); + this.access = Objects.requireNonNull(access); } @Override public ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session) { - return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations); + return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations, access); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java index a05ac817..3248b0fa 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/execution/PlayStopExecutionController.java @@ -30,15 +30,24 @@ final class PlayStopExecutionController implements ExecutionController { private OperationHandle activeOperation; private OperationHandle preparationOperation; private boolean stopRequested; + private final p.studio.api.automation.ProjectAccess access; + private p.studio.api.automation.ManualLease manualLease; PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) { + this(project, setup, session, shipper, runtime, operations, new p.studio.core.project.ProjectAccessRegistry()); + } + + PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup, + ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations, + p.studio.api.automation.ProjectAccess access) { this.project = Objects.requireNonNull(project, "project"); this.setup = Objects.requireNonNull(setup, "setup"); this.session = Objects.requireNonNull(session, "session"); this.shipper = Objects.requireNonNull(shipper, "shipper"); this.runtime = Objects.requireNonNull(runtime, "runtime"); this.operations = Objects.requireNonNull(operations, "operations"); + this.access = Objects.requireNonNull(access); } @Override @@ -47,9 +56,17 @@ final class PlayStopExecutionController implements ExecutionController { if (isBusy(session.snapshot().state()) && activeOperation != null) { return activeOperation; } + if (manualLease != null) throw new p.studio.api.automation.ControlDeniedException( + p.studio.api.automation.ControlResult.Status.BUSY); + manualLease = access.enterManual(project.rootPath()); + manualLease.onProjectClose(this::stop); stopRequested = false; session.beginPreparationCycle(); - activeOperation = operations.submit("Run " + project.name(), this::runPlay); + try { activeOperation = operations.submit("Run " + project.name(), this::runPlay); } + catch (RuntimeException failure) { releaseManual(); throw failure; } + activeOperation.termination().whenComplete((v, f) -> { + synchronized (monitor) { if (!isBusy(session.snapshot().state()) || stopRequested) releaseManual(); } + }); return activeOperation; } } @@ -74,6 +91,7 @@ final class PlayStopExecutionController implements ExecutionController { if (state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING) { session.transitionToStopped(); } + if (execution == null || execution.termination().toCompletableFuture().isDone()) releaseManual(); } @Override @@ -141,8 +159,10 @@ final class PlayStopExecutionController implements ExecutionController { private void handleExit(RuntimeConnection started, Integer exitCode, Throwable failure) { final boolean stopped; synchronized (monitor) { - if (connection == started) connection = null; + if (connection != started) return; + connection = null; stopped = stopRequested; + releaseManual(); } if (stopped || session.snapshot().state() == ExecutionState.STOPPED) return; if (failure == null && exitCode != null && exitCode == 0) { @@ -159,6 +179,12 @@ final class PlayStopExecutionController implements ExecutionController { return state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING; } + private void releaseManual() { + synchronized (monitor) { + if (manualLease != null) { manualLease.close(); manualLease = null; } + } + } + private static String message(Throwable failure) { return failure.getMessage() == null || failure.getMessage().isBlank() ? failure.getClass().getSimpleName() : failure.getMessage(); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java new file mode 100644 index 00000000..4b5748a9 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/project/ProjectAccessRegistry.java @@ -0,0 +1,42 @@ +package p.studio.core.project; + +import p.studio.api.automation.ManualLease; +import p.studio.api.automation.ProjectAccess; +import p.studio.api.operation.OperationSubscription; +import java.nio.file.Path; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +/** Application-composed routing only; authority is owned by each project session. */ +public final class ProjectAccessRegistry implements ProjectAccess { + private final Map> projects = new HashMap<>(); + + public synchronized OperationSubscription register(Path root, Supplier authority) { + Path key = canonical(root); + if (projects.putIfAbsent(key, authority) != null) throw new IllegalStateException("Project already open: " + key); + return () -> { synchronized (this) { projects.remove(key, authority); } }; + } + + @Override public ManualLease enterManual(Path path) { + Supplier authority; + synchronized (this) { + Path key = canonical(path); + authority = projects.entrySet().stream().filter(e -> key.startsWith(e.getKey())) + .max(java.util.Comparator.comparingInt(e -> e.getKey().getNameCount())) + .map(Map.Entry::getValue).orElse(null); + } + // Project creation/setup before opening a session is still a manual workflow. + return authority == null ? () -> {} : authority.get(); + } + + private static Path canonical(Path path) { + Path normalized = path.toAbsolutePath().normalize(); + try { return normalized.toRealPath(); } + catch (IOException ignored) { + Path parent = normalized.getParent(); + return parent == null ? normalized : canonical(parent).resolve(normalized.getFileName()); + } + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java new file mode 100644 index 00000000..9b1a3544 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultAutomationSession.java @@ -0,0 +1,243 @@ +package p.studio.core.session; + +import p.studio.api.automation.*; +import p.studio.api.operation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.Consumer; + +/** Project authority is independent of any UI, transport connection or operation result. */ +public final class DefaultAutomationSession implements AutomationSession { + private final Path root; + private final OperationExecutor executor; + private final List> listeners = new CopyOnWriteArrayList<>(); + private final List documents = new CopyOnWriteArrayList<>(); + private final Deque calls = new ArrayDeque<>(); + private ControlState state = ControlState.MANUAL; + private TaskIdentity task; + private int manualOperations; + private boolean handoffPending, closed, busy, stale; + private long generation; + private OperationHandle active; + private ManagedHeadlessSession runtime; + private CanonicalCapture capture; + private List diagnostics = List.of(); + private CompletableFuture returning; + private final List manualCancellation = new ArrayList<>(); + private CompletableFuture manualIdle = CompletableFuture.completedFuture(null); + + public DefaultAutomationSession(Path root, OperationExecutor executor) { + this.root = root.toAbsolutePath().normalize(); + this.executor = Objects.requireNonNull(executor); + } + + public synchronized ManualLease enterManual() { + if (closed) throw new ControlDeniedException(ControlResult.Status.CLOSED); + if (state != ControlState.MANUAL) throw new ControlDeniedException(ControlResult.Status.BUSY); + if (manualOperations++ == 0) manualIdle = new CompletableFuture<>(); + stale = capture != null; + publish(); + return new ManualLease() { + private boolean released; + private Runnable cancellation; + @Override public void onProjectClose(Runnable action) { + boolean cancel; + synchronized (DefaultAutomationSession.this) { + if (released) return; + cancellation = action; + manualCancellation.add(action); + cancel = closed; + } + if (cancel) action.run(); + } + @Override public void close() { + synchronized (DefaultAutomationSession.this) { + if (!released) { + released = true; manualCancellation.remove(cancellation); + if (--manualOperations == 0) manualIdle.complete(null); + publish(); + } + } + } + }; + } + + @Override public synchronized AutomationSnapshot snapshot() { + return new AutomationSnapshot(root, state, handoffPending, closed, manualOperations, task, + active == null ? null : active.snapshot(), capture, stale, diagnostics, List.copyOf(calls)); + } + + @Override public OperationSubscription subscribe(Consumer listener) { + listeners.add(listener); notifyListener(listener, snapshot()); + return () -> listeners.remove(listener); + } + + @Override public OperationSubscription registerDocuments(DocumentHandoff participant) { + documents.add(Objects.requireNonNull(participant)); + return () -> { if (documents.remove(participant)) participant.close(); }; + } + + @Override public CompletionStage grant(boolean save) { + final long attempt; + final List participants; + synchronized (this) { + if (closed) return result(ControlResult.Status.CLOSED, "Project closed"); + if (state != ControlState.MANUAL || handoffPending || manualOperations != 0) + return result(ControlResult.Status.BUSY, "Manual work or another control transition is active"); + handoffPending = true; attempt = ++generation; + participants = List.copyOf(documents); publish(); + } + CompletableFuture dirty = CompletableFuture.completedFuture(false); + for (var participant : participants) + dirty = dirty.thenCompose(found -> participant.hasUnsavedChanges().thenApply(next -> found || next)).toCompletableFuture(); + return dirty.thenCompose(found -> { + if (found && !save) return result(ControlResult.Status.DIRTY_DOCUMENTS, "Save all and grant, or cancel"); + CompletionStage saved = CompletableFuture.completedFuture(null); + if (found) for (var participant : participants) saved = saved.thenCompose(v -> participant.saveAll()); + return saved.thenCompose(v -> verifySaved(participants)).thenApply(v -> { + synchronized (this) { + if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active"); + state = ControlState.WAITING_FOR_AGENT; + record("grant"); + return ControlResult.of(ControlResult.Status.GRANTED, ""); + } + }); + }).exceptionally(f -> ControlResult.of(ControlResult.Status.SAVE_FAILED, message(f))) + .thenApply(outcome -> { + synchronized (this) { + if (generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated"); + handoffPending = false; + diagnostics = outcome.success() ? List.of() : List.of(outcome.diagnostic()); + publish(); return outcome; + } + }); + } + + private CompletionStage verifySaved(List participants) { + CompletionStage check = CompletableFuture.completedFuture(null); + for (var p : participants) check = check.thenCompose(v -> p.hasUnsavedChanges().thenAccept(dirty -> { + if (dirty) throw new IllegalStateException("Document save did not finish successfully"); + })); + return check; + } + + @Override public synchronized ControlResult acquire() { + if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed"); + if (state != ControlState.WAITING_FOR_AGENT) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required"); + task = new TaskIdentity(root, UUID.randomUUID().toString()); + state = ControlState.AGENT_WORKING; record("acquire"); publish(); + return new ControlResult(ControlResult.Status.ACQUIRED, task, ""); + } + + @Override public CompletionStage release(TaskIdentity identity) { + return beginReturn(false, identity, true); + } + @Override public CompletionStage reclaim() { return beginReturn(false, null, false); } + @Override public CompletionStage closeAsync() { + var cleanup = beginReturn(true, null, false); + for (var participant : List.copyOf(documents)) { + if (documents.remove(participant)) participant.close(); + } + return cleanup; + } + + private CompletionStage beginReturn(boolean closing, TaskIdentity identity, boolean requireIdentity) { + final CompletableFuture result; + final OperationHandle operation; + final ManagedHeadlessSession ownedRuntime; + final List cancellations; + final List participants; + final CompletableFuture idle; + synchronized (this) { + if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current"); + if (closing) closed = true; + if (returning != null && !returning.isDone()) return returning; + if (!closing && state == ControlState.MANUAL) return result(ControlResult.Status.RETURNED, ""); + state = ControlState.RETURNING_CONTROL; task = null; generation++; handoffPending = false; + record(closing ? "close" : "reclaim"); stale = capture != null; + result = returning = new CompletableFuture<>(); + operation = active; ownedRuntime = runtime; idle = manualIdle; + cancellations = closing ? List.copyOf(manualCancellation) : List.of(); + participants = closing ? List.of() : List.copyOf(documents); + publish(); + } + // Never call another service while holding the authority monitor: Debug owns its own lock. + CompletionStage cleanup; + try { + for (var cancellation : cancellations) cancellation.run(); + if (operation != null) operation.cancel(); + CompletionStage stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination(); + CompletionStage shutdown = CompletableFuture.completedFuture(null); + if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); } + cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle); + // Closing disposes documents; an explicit return must refresh them before unlocking. + for (var p : participants) cleanup = cleanup.thenCompose(v -> { + synchronized (this) { if (closed) return CompletableFuture.completedFuture(null); } + return p.refreshFromDisk(); + }); + } catch (RuntimeException failure) { cleanup = CompletableFuture.failedFuture(failure); } + cleanup.whenComplete((v, failure) -> { + synchronized (this) { + if (failure == null) { + runtime = null; busy = false; state = ControlState.MANUAL; + diagnostics = List.of(); publish(); + result.complete(ControlResult.of(ControlResult.Status.RETURNED, "")); + } else { + diagnostics = List.of(message(failure)); publish(); + result.complete(ControlResult.of(ControlResult.Status.CLEANUP_FAILED, message(failure))); + } + } + }); + return result; + } + + @Override public synchronized OperationHandle submit(TaskIdentity identity, String summary, + Callable work) { + requireTask(identity); + if (busy) throw new ControlDeniedException(ControlResult.Status.BUSY); + busy = true; record(summary); + try { active = executor.submit(summary, work); } + catch (RuntimeException failure) { busy = false; throw failure; } + var operation = active; + var subscription = operation.subscribe(s -> { synchronized (this) { if (active == operation) publish(); } }); + operation.completion().whenComplete((outcome, failure) -> { + synchronized (this) { + if (!valid(identity) || active != operation) return; + diagnostics = failure != null ? List.of(message(failure)) : outcome.diagnostics(); + if (outcome != null && outcome.capture() != null && runtime != null + && runtime.sessionId().equals(outcome.capture().sessionId())) { + capture = outcome.capture(); stale = false; + } + publish(); + } + }); + operation.termination().whenComplete((v, f) -> { + subscription.unsubscribe(); + synchronized (this) { if (active == operation) { busy = false; publish(); } } + }); + publish(); return operation; + } + + @Override public synchronized void attachRuntime(TaskIdentity identity, ManagedHeadlessSession next) { + requireTask(identity); + if (runtime != null) throw new ControlDeniedException(ControlResult.Status.BUSY); + runtime = Objects.requireNonNull(next); stale = capture != null; record("runtime " + next.sessionId()); publish(); + } + @Override public synchronized void markCaptureStale() { stale = capture != null; publish(); } + private boolean valid(TaskIdentity identity) { return !closed && state == ControlState.AGENT_WORKING && task != null && task.equals(identity); } + private void requireTask(TaskIdentity identity) { if (!valid(identity)) throw new ControlDeniedException(ControlResult.Status.INVALID_TASK); } + private void record(String call) { calls.addLast(Objects.requireNonNullElse(call, "")); while (calls.size() > 50) calls.removeFirst(); } + private void publish() { var value = snapshot(); listeners.forEach(l -> notifyListener(l, value)); } + private static void notifyListener(Consumer listener, AutomationSnapshot value) { + try { listener.accept(value); } catch (RuntimeException ignored) { /* Observation cannot change authority. */ } + } + private static CompletionStage result(ControlResult.Status status, String text) { + return CompletableFuture.completedFuture(ControlResult.of(status, text)); + } + private static String message(Throwable failure) { + while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause(); + return Objects.requireNonNullElse(failure.getMessage(), failure.getClass().getSimpleName()); + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java index 976ac425..930e1175 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSession.java @@ -17,30 +17,39 @@ public final class DefaultProjectSession implements ProjectSession { private final LspLifecyclePort lsp; private ProjectLocalStudioState state; private boolean closed; + private final DefaultAutomationSession automation; + private final p.studio.api.operation.OperationSubscription accessRegistration; DefaultProjectSession(ProjectReference project, ProjectLocalStudioStateStore stateStore, ProjectLocalStudioSetup setup, ExecutionSession execution, LspLifecyclePort lsp, - ProjectLocalStudioState state) { + ProjectLocalStudioState state, DefaultAutomationSession automation, + p.studio.api.operation.OperationSubscription accessRegistration) { this.project = Objects.requireNonNull(project, "project"); this.stateStore = Objects.requireNonNull(stateStore, "stateStore"); this.setup = Objects.requireNonNull(setup, "setup"); this.execution = Objects.requireNonNull(execution, "execution"); this.lsp = Objects.requireNonNull(lsp, "lsp"); this.state = Objects.requireNonNull(state, "state"); + this.automation = Objects.requireNonNull(automation); + this.accessRegistration = Objects.requireNonNull(accessRegistration); } @Override public ProjectReference projectReference() { return project; } @Override public ProjectLocalStudioState projectLocalStudioState() { return state; } @Override public ProjectLocalStudioSetup projectLocalStudioSetup() { return setup; } @Override public ExecutionSession executionSession() { return execution; } + @Override public p.studio.api.automation.AutomationSession automation() { return automation; } @Override public void replaceProjectLocalStudioState(ProjectLocalStudioState next) { state = Objects.requireNonNull(next, "state"); } @Override public void saveProjectLocalStudioState() { stateStore.save(project, state); } @Override public synchronized void close() { if (closed) return; + var cleanup = automation.closeAsync().toCompletableFuture().join(); + if (!cleanup.success()) throw new IllegalStateException(cleanup.diagnostic()); closed = true; - RuntimeException failure = attempt(this::saveProjectLocalStudioState, null); + RuntimeException failure = attempt(accessRegistration::unsubscribe, null); + failure = attempt(this::saveProjectLocalStudioState, failure); failure = attempt(execution::close, failure); failure = attempt(() -> lsp.shutdown(project), failure); if (failure != null) throw failure; diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java index db6ffba6..627337b3 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/DefaultProjectSessionFactory.java @@ -13,12 +13,17 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory private final ProjectLocalStudioStateStore stateStore; private final ProjectLocalStudioSetupStore setupStore; private final LspLifecyclePort lsp; + private final p.studio.core.project.ProjectAccessRegistry access; + private final p.studio.api.operation.OperationExecutor operations; public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore, - ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) { + ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp, + p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations) { this.stateStore = Objects.requireNonNull(stateStore, "stateStore"); this.setupStore = Objects.requireNonNull(setupStore, "setupStore"); this.lsp = Objects.requireNonNull(lsp, "lsp"); + this.access = Objects.requireNonNull(access); + this.operations = Objects.requireNonNull(operations); } @Override @@ -26,7 +31,10 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference"); final var setup = setupStore.load(project); final var state = stateStore.load(project); - lsp.boot(project); - return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state); + var automation = new DefaultAutomationSession(project.rootPath(), operations); + var registration = access.register(project.rootPath(), automation::enterManual); + try { lsp.boot(project); } + catch (RuntimeException failure) { registration.unsubscribe(); throw failure; } + return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java b/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java index 08ddcd9b..f44d6570 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/shipper/StudioShipperService.java @@ -28,6 +28,12 @@ import java.util.Objects; import java.util.function.Consumer; public final class StudioShipperService implements Shipper { + private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry(); + public StudioShipperService(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) { + this(compiler, packer, mapper, operations); + this.access = java.util.Objects.requireNonNull(access); + } + private final CompilerBuildGateway compiler; private final PackerWorkspaceService packer; private final ObjectMapper mapper; @@ -45,7 +51,7 @@ public final class StudioShipperService implements Shipper { public OperationHandle prepare(ProjectReference project, Consumer sink) { Objects.requireNonNull(project, "project"); Objects.requireNonNull(sink, "sink"); - return operations.submit("Build and pack " + project.name(), () -> prepareNow(project, sink)); + return access.submitManual(project.rootPath(), operations, "Build and pack " + project.name(), () -> prepareNow(project, sink)); } private ShipperPrepareResult prepareNow(ProjectReference project, Consumer sink) { diff --git a/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java b/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java new file mode 100644 index 00000000..5c7efde3 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/assets/AssetAuthorityTest.java @@ -0,0 +1,51 @@ +package p.studio.core.assets; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.packer.PackerWorkspaceService; +import p.studio.api.assets.*; +import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.core.assets.metadata.AssetStudioMetadataService; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.session.DefaultAutomationSession; +import p.studio.core.support.ControlledOperations; +import java.nio.file.*; +import static org.junit.jupiter.api.Assertions.*; + +class AssetAuthorityTest { + @TempDir Path root; + @Test void actualMutatorsRejectDirectCallsButInspectionRemainsAvailable() { + var access = new ProjectAccessRegistry(); + var automation = new DefaultAutomationSession(root, new ControlledOperations()); + access.register(root, automation::enterManual); + var project = new ProjectReference("Test", "1", "pbs", 1, ProjectTarget.Game, root); + var packer = (PackerWorkspaceService) java.lang.reflect.Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[]{PackerWorkspaceService.class}, + (proxy, method, args) -> { throw new AssertionError("Rejected call reached packer: " + method); }); + var commands = new PackerAssetCommands(packer, access); + var packing = new PackerAssetPacking(packer, new ControlledOperations(), access); + var shipper = new p.studio.core.shipper.StudioShipperService((p, log) -> { throw new AssertionError("must not compile"); }, + packer, new ObjectMapper(), new ControlledOperations(), access); + var storage = new FileSystemAssetWorkspaceStorage(access); + var metadata = new AssetStudioMetadataService(new ObjectMapper(), access); + automation.grant(false).toCompletableFuture().join(); + for (int state = 0; state < 2; state++) { + assertThrows(ControlDeniedException.class, () -> commands.delete(project, AssetReference.of("test"))); + assertThrows(ControlDeniedException.class, () -> commands.register(project, AssetReference.of("test"))); + assertThrows(ControlDeniedException.class, () -> storage.prepare(project)); + assertThrows(ControlDeniedException.class, () -> packing.pack(project)); + assertThrows(ControlDeniedException.class, () -> packing.deepSync(project)); + assertThrows(ControlDeniedException.class, () -> shipper.prepare(project, log -> {})); + assertThrows(ControlDeniedException.class, () -> metadata.writeGlyphSpecialization(root, AssetStudioGlyphSpecialization.NONE)); + assertFalse(storage.assetManifestExists(project, "missing")); + assertNotNull(metadata.read(root, AssetFamily.GLYPH_BANK)); + automation.acquire(); + } + assertFalse(Files.exists(root.resolve("assets"))); + automation.reclaim().toCompletableFuture().join(); + assertTrue(storage.prepare(project).success()); + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java b/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java index 8e098589..5a2e49a1 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/execution/PlayStopExecutionControllerTest.java @@ -39,6 +39,38 @@ import static org.junit.jupiter.api.Assertions.assertTrue; final class PlayStopExecutionControllerTest { private static final OperationExecutor OPERATIONS = new ImmediateOperationExecutor(); + @Test + void debugAndAutomationAreMutuallyExclusiveAndLateExitCannotUnlockNewDebug() { + var authority = new p.studio.core.session.DefaultAutomationSession(project().rootPath(), OPERATIONS); + var access = new p.studio.core.project.ProjectAccessRegistry(); + access.register(project().rootPath(), authority::enterManual); + var session = new DefaultExecutionSession(); + var exits = new java.util.ArrayList>(); + RuntimeGateway runtime = (project, setup, logs) -> { + var exit = new CompletableFuture(); exits.add(exit); + return new RuntimeConnection() { + public CompletableFuture completion() { return exit; } + public void close() { } // Exit notification can arrive after close returned. + }; + }; + var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(), + session, successfulShipper(), runtime, OPERATIONS, access); + controller.play(); + assertEquals(p.studio.api.automation.ControlResult.Status.BUSY, authority.grant(false).toCompletableFuture().join().status()); + controller.stop(); controller.play(); exits.getFirst().complete(0); + assertEquals(ExecutionState.RUNNING, session.snapshot().state()); + assertEquals(1, authority.snapshot().manualOperations()); + controller.stop(); + assertEquals(p.studio.api.automation.ControlResult.Status.GRANTED, authority.grant(false).toCompletableFuture().join().status()); + org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play); + authority.acquire(); + org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play); + authority.reclaim().toCompletableFuture().join(); + controller.play(); + authority.closeAsync().toCompletableFuture().join(); + assertEquals(ExecutionState.STOPPED, session.snapshot().state()); + } + @Test void successfulPreparationStartsRuntimeAndProjectsExit() { final var session = new DefaultExecutionSession(); diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java new file mode 100644 index 00000000..b1533bc1 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultAutomationSessionTest.java @@ -0,0 +1,185 @@ +package p.studio.core.session; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import p.studio.api.automation.*; +import p.studio.core.project.ProjectAccessRegistry; +import p.studio.core.support.ControlledOperations; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.*; +import static org.junit.jupiter.api.Assertions.*; +import static p.studio.api.automation.ControlResult.Status.*; + +class DefaultAutomationSessionTest { + @TempDir Path root; + final ControlledOperations operations = new ControlledOperations(); + DefaultAutomationSession session() { return new DefaultAutomationSession(root, operations); } + ControlResult await(CompletionStage result) { return result.toCompletableFuture().join(); } + TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); } + + @Test void explicitGrantAndProjectScopedIdentityAreRequired() { + var s = session(); + assertEquals(NOT_GRANTED, s.acquire().status()); + var task = start(s); + assertEquals(NOT_GRANTED, s.acquire().status()); + assertEquals(INVALID_TASK, await(s.release(new TaskIdentity(root.resolve("other"), task.value()))).status()); + assertThrows(ControlDeniedException.class, s::enterManual); + assertEquals(RETURNED, await(s.release(task)).status()); + var next = start(s); + assertNotEquals(task, next); + assertEquals(INVALID_TASK, await(s.release(task)).status()); + assertEquals(ControlState.AGENT_WORKING, s.snapshot().state()); + } + + @Test void racingClientsCannotBothAcquireAndWaitingGrantCanBeReclaimed() throws Exception { + var s = session(); s.grant(false).toCompletableFuture().join(); + assertEquals(RETURNED, await(s.reclaim()).status()); assertEquals(NOT_GRANTED, s.acquire().status()); + s.grant(false).toCompletableFuture().join(); + var pool = Executors.newFixedThreadPool(2); + try { + var a = pool.submit(s::acquire); var b = pool.submit(s::acquire); + assertEquals(1, java.util.stream.Stream.of(a.get(), b.get()).filter(r -> r.status() == ACQUIRED).count()); + } finally { pool.shutdownNow(); } + } + + @Test void captureFromWrongRuntimeIsNotPublished() { + var s = session(); var task = start(s); s.attachRuntime(task, new Runtime()); + s.submit(task, "wrong frame", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), + new CanonicalCapture("other-session", "build", 0, 0, 1, 1, 1, new byte[]{1}))); + operations.last.finish(); assertNull(s.snapshot().capture()); + } + + @Test void closureDisposesPendingRefreshWithoutWaitingForPresentationThread() { + var s = session(); var docs = new Documents() { + @Override public void close() { refresh.complete(null); } + }; + docs.refresh = new CompletableFuture<>(); + var registration = s.registerDocuments(docs); start(s); + var returned = s.reclaim().toCompletableFuture(); assertFalse(returned.isDone()); + assertEquals(RETURNED, await(s.closeAsync()).status()); + registration.unsubscribe(); + assertEquals(RETURNED, returned.join().status()); assertFalse(s.snapshot().manualAllowed()); + } + + @Test void manualAndAgentAcquisitionRaceHasOnlyOneWinner() throws Exception { + for (int n = 0; n < 100; n++) { + var s = session(); + var gate = new CountDownLatch(1); + var workers = Executors.newFixedThreadPool(2); + try { + var manual = workers.submit(() -> { gate.await(); try { return s.enterManual(); } catch (ControlDeniedException denied) { return null; } }); + var grant = workers.submit(() -> { gate.await(); return await(s.grant(false)); }); + gate.countDown(); + var lease = manual.get(2, TimeUnit.SECONDS); + var granted = grant.get(2, TimeUnit.SECONDS).status() == GRANTED; + assertNotEquals(lease != null, granted); + if (lease != null) lease.close(); + } finally { workers.shutdownNow(); } + } + } + + @Test void dirtyDocumentsRequireSuccessfulSaveAndRefreshBeforeManualReturn() { + var s = session(); var docs = new Documents(); docs.dirty = true; + s.registerDocuments(docs); + assertEquals(DIRTY_DOCUMENTS, await(s.grant(false)).status()); + assertTrue(s.snapshot().manualAllowed()); assertEquals(0, docs.saves); + docs.failSave = true; + assertEquals(SAVE_FAILED, await(s.grant(true)).status()); + assertTrue(docs.dirty); assertTrue(s.snapshot().manualAllowed()); + docs.failSave = false; + assertEquals(GRANTED, await(s.grant(true)).status()); + assertFalse(docs.dirty); + docs.refresh = new CompletableFuture<>(); + var returned = s.reclaim().toCompletableFuture(); + assertEquals(ControlState.RETURNING_CONTROL, s.snapshot().state()); + assertFalse(returned.isDone()); assertFalse(s.snapshot().manualAllowed()); + docs.refresh.complete(null); + assertEquals(RETURNED, returned.join().status()); assertTrue(s.snapshot().manualAllowed()); + } + + @Test void revocationInvalidatesFirstAndWaitsForWorkerAndRuntimeBeforeRefresh() { + var s = session(); var docs = new Documents(); s.registerDocuments(docs); + var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime); + var capture = new CanonicalCapture("session", "build", 20, 7, 2, 2, 2, new byte[]{1}); + s.submit(task, "advance", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 20, 20, List.of(), capture)); + assertThrows(ControlDeniedException.class, () -> s.submit(task, "overlap", () -> null)); + var returned = s.reclaim().toCompletableFuture(); + assertNull(s.snapshot().task()); assertTrue(operations.last.cancelled); assertTrue(runtime.cancelled); + assertThrows(ControlDeniedException.class, () -> s.submit(task, "late", () -> null)); + assertEquals(0, docs.refreshes); + operations.last.finish(); // A late successful completion must not publish a frame. + assertNull(s.snapshot().capture()); assertFalse(returned.isDone()); + runtime.stopped.complete(null); + assertEquals(RETURNED, returned.join().status()); assertEquals(1, docs.refreshes); + } + + @Test void guestFaultAndCancellationDoNotRevokeAuthorityAndCaptureIsImmutable() { + var s = session(); var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime); + byte[] bytes = {1, 2}; var frame = new CanonicalCapture("session", "build", 9, 4, 2, 2, 2, bytes); + bytes[0] = 8; frame.png()[0] = 9; + assertEquals(1, frame.png()[0]); + s.submit(task, "fault", () -> new AutomationOutcome(AutomationOutcome.Kind.GUEST_FAULT, 10, 9, List.of("fault"), frame)); + operations.last.finish(); + assertEquals(ControlState.AGENT_WORKING, s.snapshot().state()); assertEquals(frame, s.snapshot().capture()); + assertEquals(List.of("fault"), s.snapshot().diagnostics()); + s.markCaptureStale(); assertTrue(s.snapshot().stale()); + s.submit(task, "cancel", () -> new AutomationOutcome(AutomationOutcome.Kind.CANCELLED, 10, 0, List.of(), null)).cancel(); + operations.last.finish(); assertEquals(task, s.snapshot().task()); + } + + @Test void failedCleanupKeepsGuardAndHumanCanRetry() { + var s = session(); var docs = new Documents(); s.registerDocuments(docs); start(s); + docs.refresh = CompletableFuture.failedFuture(new IllegalStateException("disk unavailable")); + assertEquals(CLEANUP_FAILED, await(s.reclaim()).status()); + assertThrows(ControlDeniedException.class, s::enterManual); + docs.refresh = CompletableFuture.completedFuture(null); + assertEquals(RETURNED, await(s.reclaim()).status()); assertTrue(s.snapshot().manualAllowed()); + } + + @Test void registryIsPerProjectAndClosedAuthorityCannotBeReused() { + var registry = new ProjectAccessRegistry(); var s = session(); + var registration = registry.register(root, s::enterManual); start(s); + assertThrows(ControlDeniedException.class, () -> registry.enterManual(root.resolve("assets/new"))); + try (var unrelated = registry.enterManual(root.resolveSibling("unrelated"))) { assertNotNull(unrelated); } + await(s.closeAsync()); assertEquals(CLOSED, s.acquire().status()); + assertThrows(ControlDeniedException.class, () -> registry.enterManual(root)); + registration.unsubscribe(); var reopened = session(); registry.register(root, reopened::enterManual); + try (var manual = registry.enterManual(root)) { assertEquals(1, reopened.snapshot().manualOperations()); } + } + + @Test void closeCancelsManualWorkWithoutCallingItUnderAuthorityLock() throws Exception { + var s = session(); var lease = s.enterManual(); + lease.onProjectClose(() -> { + var worker = CompletableFuture.runAsync(() -> { s.snapshot(); lease.close(); }); + assertDoesNotThrow(() -> worker.get(2, TimeUnit.SECONDS)); + }); + assertEquals(RETURNED, await(s.closeAsync()).status()); assertTrue(s.snapshot().closed()); + assertFalse(s.snapshot().manualAllowed()); + } + + @Test void closeDuringSaveCannotGrantAfterProjectHasClosed() { + var s = session(); var docs = new Documents(); docs.dirty = true; docs.save = new CompletableFuture<>(); + s.registerDocuments(docs); var grant = s.grant(true); + assertTrue(s.snapshot().handoffPending()); await(s.closeAsync()); docs.save.complete(null); + assertEquals(CLOSED, await(grant).status()); assertTrue(s.snapshot().closed()); + } + + static class Documents implements DocumentHandoff { + boolean dirty, failSave; int saves, refreshes; + CompletableFuture save = CompletableFuture.completedFuture(null), refresh = CompletableFuture.completedFuture(null); + public CompletionStage hasUnsavedChanges() { return CompletableFuture.completedFuture(dirty); } + public CompletionStage saveAll() { + saves++; + if (failSave) return CompletableFuture.failedFuture(new IllegalStateException("save failed")); + return save.thenRun(() -> dirty = false); + } + public CompletionStage refreshFromDisk() { refreshes++; return refresh; } + } + static class Runtime implements ManagedHeadlessSession { + final CompletableFuture stopped = new CompletableFuture<>(); boolean cancelled; + public String sessionId() { return "session"; } + public void cancel() { cancelled = true; } + public CompletionStage shutdown() { return stopped; } + } +} diff --git a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java index 712008bb..f80b95d0 100644 --- a/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java +++ b/prometeu-studio-core/src/test/java/p/studio/core/session/DefaultProjectSessionTest.java @@ -22,7 +22,8 @@ final class DefaultProjectSessionTest { final var stateStore = new ProjectLocalStudioStateStore(mapper); final var setupStore = new ProjectLocalStudioSetupStore(mapper); final var lsp = new RecordingLsp(); - final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp); + final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp, + new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()); final var project = project(); final var session = factory.open(project); @@ -44,7 +45,8 @@ final class DefaultProjectSessionTest { lsp.failShutdown = true; final var session = new DefaultProjectSessionFactory( new ProjectLocalStudioStateStore(mapper), - new ProjectLocalStudioSetupStore(mapper), lsp).open(project()); + new ProjectLocalStudioSetupStore(mapper), lsp, + new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()).open(project()); final var failure = assertThrows(IllegalStateException.class, session::close); assertEquals("lsp shutdown", failure.getMessage()); } diff --git a/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java b/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java new file mode 100644 index 00000000..be3447f8 --- /dev/null +++ b/prometeu-studio-core/src/test/java/p/studio/core/support/ControlledOperations.java @@ -0,0 +1,37 @@ +package p.studio.core.support; + +import p.studio.api.operation.*; +import java.time.Instant; +import java.util.concurrent.*; +import java.util.function.Consumer; + +/** Cancellation acknowledgement and worker termination are deliberately independent. */ +public final class ControlledOperations implements OperationExecutor { + public Handle last; + @Override public OperationHandle submit(String summary, Callable work) { + Handle handle = new Handle<>(summary, work); + last = handle; + return handle; + } + public static final class Handle implements OperationHandle { + public final CompletableFuture completed = new CompletableFuture<>(); + public final CompletableFuture stopped = new CompletableFuture<>(); + public boolean cancelled; + private final Callable work; + private final String summary; + private final OperationId id = new OperationId(java.util.UUID.randomUUID().toString()); + Handle(String summary, Callable work) { this.summary = summary; this.work = work; } + public void finish() { + try { completed.complete(work.call()); } catch (Exception failure) { completed.completeExceptionally(failure); } + stopped.complete(null); + } + @Override public OperationId id() { return id; } + @Override public OperationSnapshot snapshot() { + return new OperationSnapshot(id, cancelled ? OperationState.CANCELLED : completed.isDone() ? OperationState.SUCCEEDED : OperationState.RUNNING, Instant.now(), summary); + } + @Override public CompletionStage completion() { return completed; } + @Override public CompletionStage termination() { return stopped; } + @Override public boolean cancel() { cancelled = true; return true; } + @Override public OperationSubscription subscribe(Consumer observer) { observer.accept(snapshot()); return () -> {}; } + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java index 26a8172c..e92a0721 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/controls/forms/StudioFormSection.java @@ -16,6 +16,22 @@ public abstract class StudioFormSection extends StudioSection { private final VBox contentHost = new VBox(); private boolean editAllowed = true; private VBox mountedSection; + private java.util.concurrent.CompletableFuture handoffSave; + + public final boolean hasUnsavedDraft() { return isDirty(); } + public final java.util.concurrent.CompletionStage saveForHandoff() { + if (!isDirty()) return java.util.concurrent.CompletableFuture.completedFuture(null); + if (handoffSave != null && !handoffSave.isDone()) return handoffSave; + handoffSave = new java.util.concurrent.CompletableFuture<>(); + try { apply(); } catch (RuntimeException failure) { handoffSave.completeExceptionally(failure); } + return handoffSave; + } + protected final void finishHandoffSave(boolean success, String message) { + if (handoffSave == null) return; + if (success) handoffSave.complete(null); + else handoffSave.completeExceptionally(new IllegalStateException(Objects.requireNonNullElse(message, "Save failed"))); + } + public final void discardDraftForHandoff() { cancel(); renderSection(); } protected StudioFormSection(I18nService i18n) { super(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java index a067142e..b6926533 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/utilities/i18n/I18n.java @@ -3,6 +3,13 @@ package p.studio.ui.javafx.utilities.i18n; import lombok.Getter; public enum I18n { + WORKSPACE_DEV("workspace.dev"), + DEV_GRANT("dev.grant"), DEV_RECLAIM("dev.reclaim"), DEV_COPY_CONFIG("dev.copyConfig"), + DEV_MCP_UNAVAILABLE("dev.mcpUnavailable"), DEV_EXTERNAL_WARNING("dev.externalWarning"), + DEV_MANUAL("dev.manual"), DEV_WAITING("dev.waiting"), DEV_WORKING("dev.working"), DEV_RETURNING("dev.returning"), + DEV_SAVE_GRANT("dev.saveGrant"), DEV_UNSAVED("dev.unsaved"), + DEV_DIAGNOSTICS("dev.diagnostics"), DEV_HISTORY("dev.history"), + DEV_NO_FRAME("dev.noFrame"), DEV_STALE_FRAME("dev.staleFrame"), DEV_CURRENT_FRAME("dev.currentFrame"), APP_TITLE("app.title"), APP_PROJECT_TITLE("app.projectTitle"), SHIELD_LOADING_PROJECT("shield.loadingProject"), diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java index f4f3780e..9600f564 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java @@ -44,6 +44,9 @@ public final class MainView extends BorderPane { private final ExecutionController playStopCoordinator; private boolean initializing; private boolean workspaceLifecycleInitialized; + private p.studio.api.operation.OperationSubscription controlSubscription; + private p.studio.api.operation.OperationSubscription documentRegistration; + private boolean closed; public MainView(final ProjectSession projectSession, final Shipper shipper, final ExecutionControllerFactory executionControllerFactory, @@ -93,12 +96,29 @@ public final class MainView extends BorderPane { assetWorkspace.restoreProjectLocalState(persistedState); assetWorkspace.setStateChangedAction(this::persistProjectLocalState); host.register(new DebugWorkspace(projectReference, projectSession.executionSession(), i18n, eventBus)); - host.register(new ShipperWorkspace(projectReference, shipper, i18n, eventBus)); + final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus); + host.register(shipperWorkspace); + host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus)); + documentRegistration = projectSession.automation().registerDocuments(assetWorkspace.documentHandoff()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(assetWorkspace.rootNode(), + () -> projectSession.automation().snapshot().manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(shipperWorkspace.rootNode(), + () -> projectSession.automation().snapshot().manualAllowed()); + controlSubscription = projectSession.automation().subscribe(snapshot -> { + Runnable update = () -> { + if (closed) return; + runSurface.setDisable(!snapshot.manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(assetWorkspace.rootNode(), snapshot.manualAllowed()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(shipperWorkspace.rootNode(), snapshot.manualAllowed()); + }; + if (javafx.application.Platform.isFxApplicationThread()) update.run(); else javafx.application.Platform.runLater(update); + }); workspaceRail = new StudioWorkspaceRailControl<>( List.of( new StudioWorkspaceRailItem<>(WorkspaceId.ASSETS, "📦", i18n.bind(I18n.WORKSPACE_ASSETS)), new StudioWorkspaceRailItem<>(WorkspaceId.DEBUG, "🎮", i18n.bind(I18n.WORKSPACE_DEBUG)), + new StudioWorkspaceRailItem<>(WorkspaceId.DEV, "◇", i18n.bind(I18n.WORKSPACE_DEV)), new StudioWorkspaceRailItem<>(WorkspaceId.SHIPPER, "⚙️", i18n.bind(I18n.WORKSPACE_SHIPPER)) ), this::loadWorkspace); @@ -141,6 +161,10 @@ public final class MainView extends BorderPane { } public void close() { + if (closed) return; + closed = true; + controlSubscription.unsubscribe(); + documentRegistration.unsubscribe(); playStopCoordinator.shutdown(); persistProjectLocalState(); host.deactivateCurrentWorkspace(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java index 58383dad..b1896e25 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/StudioWorkspaceLifecycleSupport.java @@ -11,15 +11,18 @@ import java.util.List; import java.util.Objects; public final class StudioWorkspaceLifecycleSupport { + private static final Object ACTIVATION = new Object(); private StudioWorkspaceLifecycleSupport() { } public static void activate(Workspace workspace) { final Workspace target = Objects.requireNonNull(workspace, "workspace"); final Node rootNode = target.rootNode(); + final Object activation = new Object(); + rootNode.getProperties().put(ACTIVATION, activation); final Scene scene = rootNode.getScene(); if (scene != null) { - activateNow(target); + activateNow(target, activation); return; } @@ -33,13 +36,14 @@ public final class StudioWorkspaceLifecycleSupport { return; } rootNode.sceneProperty().removeListener(this); - activateNow(target); + activateNow(target, activation); } }); } public static void deactivate(Workspace workspace) { final Workspace target = Objects.requireNonNull(workspace, "workspace"); + target.rootNode().getProperties().remove(ACTIVATION); target.unLoad(); final List participants = target.lifecycleParticipants(); for (int index = participants.size() - 1; index >= 0; index--) { @@ -47,8 +51,9 @@ public final class StudioWorkspaceLifecycleSupport { } } - private static void activateNow(Workspace workspace) { + private static void activateNow(Workspace workspace, Object activation) { Platform.runLater(() -> { + if (workspace.rootNode().getProperties().get(ACTIVATION) != activation) return; final List participants = workspace.lifecycleParticipants(); for (StudioControlLifecycle participant : participants) { participant.subscribe(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java index 3d346af8..7a2337fd 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/WorkspaceId.java @@ -3,5 +3,6 @@ package p.studio.ui.javafx.workspaces; public enum WorkspaceId { ASSETS, SHIPPER, - DEBUG + DEBUG, + DEV } diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java index 02f742bf..d4d8cb3b 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java @@ -126,6 +126,8 @@ public final class AssetWorkspace extends Workspace { this.stateChangedAction = java.util.Objects.requireNonNull(stateChangedAction, "stateChangedAction"); } + public p.studio.api.automation.DocumentHandoff documentHandoff() { return detailsControl.documentHandoff(); } + public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) { pendingAssetsLayoutState = projectLocalStudioState.shellLayout().assetsLayout(); reapplyPendingLayoutState(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java index e4fb5dae..533fff0d 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java @@ -85,6 +85,63 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware private boolean actionRunning; private String actionFeedbackMessage; + public p.studio.api.automation.DocumentHandoff documentHandoff() { + return new p.studio.api.automation.DocumentHandoff() { + private volatile boolean disposed; + private final java.util.Set> pending = java.util.concurrent.ConcurrentHashMap.newKeySet(); + @Override public void close() { + disposed = true; + pending.forEach(future -> future.complete(null)); + pending.clear(); + } + @Override public java.util.concurrent.CompletionStage hasUnsavedChanges() { + return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft)); + } + @Override public java.util.concurrent.CompletionStage saveAll() { + return onFx(() -> { + java.util.concurrent.CompletionStage saved = java.util.concurrent.CompletableFuture.completedFuture(null); + for (var form : handoffForms()) saved = saved.thenCompose(v -> form.saveForHandoff()); + return saved; + }).thenCompose(saved -> saved); + } + @Override public java.util.concurrent.CompletionStage refreshFromDisk() { + var refreshed = new java.util.concurrent.CompletableFuture(); + pending.add(refreshed); + refreshed.whenComplete((v, f) -> pending.remove(refreshed)); + if (disposed) { refreshed.complete(null); return refreshed; } + onFx(() -> { + if (disposed) { refreshed.complete(null); return null; } + handoffForms().forEach(p.studio.ui.javafx.controls.forms.StudioFormSection::discardDraftForHandoff); + var selected = viewState.selectedAssetReference(); + if (selected == null) { refreshed.complete(null); return refreshed; } + long generation = loadGeneration.incrementAndGet(); + executor.execute(() -> { + try { + var details = mapDetails(assetDetails.get(projectReference, selected)); + Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); refreshed.complete(null); }); + } catch (RuntimeException failure) { + Platform.runLater(() -> { if (!disposed) applyLoadFailure(generation, selected, failure); refreshed.completeExceptionally(failure); }); + } + }); + return refreshed; + }).whenComplete((v, failure) -> { if (failure != null) refreshed.completeExceptionally(failure); }); + return refreshed; + } + }; + } + + private java.util.List handoffForms() { + var forms = new java.util.ArrayList<>(contractControl.handoffForms()); + forms.add(bankCompositionControl); forms.add(colorSchemaGroupsControl); forms.add(paletteOverhaulingControl); + return forms; + } + private static java.util.concurrent.CompletableFuture onFx(java.util.function.Supplier action) { + var result = new java.util.concurrent.CompletableFuture(); + Runnable run = () -> { try { result.complete(action.get()); } catch (RuntimeException f) { result.completeExceptionally(f); } }; + if (Platform.isFxApplicationThread()) run.run(); else Platform.runLater(run); + return result; + } + public AssetDetailsControl( ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus, @@ -382,6 +439,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware AssetDetailsUiSupport.applyActionTone(analyseButton, "studio-button-warning"); analyseButton.setDisable(actionRunning || viewState.selectedAssetDetails().diagnostics().isEmpty()); analyseButton.setOnAction(ignored -> openDiagnosticsDialog()); + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(analyseButton); nodes.add(analyseButton); if (canGenerateTsx()) { final Button exportTsxButton = AssetDetailsUiSupport.createActionButton(i18n.text(I18n.ASSETS_ACTION_EXPORT_TSX)); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java index 97866226..7504b2b0 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/bank/AssetDetailsBankCompositionControl.java @@ -212,16 +212,20 @@ public final class AssetDetailsBankCompositionControl extends StudioFormSection final var response = assetCommands.applyBankComposition(projectReference, assetReference, selectedPaths); Platform.runLater(() -> { if (response.success()) { + coordinator.apply(); publishEditScope(workspaceBus, currentScopeKey(), null); + finishHandoffSave(true, ""); workspaceBus.publish(new StudioAssetBankCompositionAppliedEvent(assetReference)); executor.execute(() -> publishAppliedBankComposition(assetReference)); } else { + finishHandoffSave(false, response.errorMessage()); workspaceBus.publish(new StudioAssetBankCompositionApplyFailedEvent( assetReference, response.errorMessage())); } }); } catch (Exception exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetBankCompositionApplyFailedEvent( assetReference, "Unable to apply bank composition."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java index 86f0372a..fb7a4a9a 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/contract/AssetDetailsContractControl.java @@ -48,6 +48,8 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private AssetWorkspaceDetailsViewState viewState; + public java.util.List handoffForms() { return java.util.List.of(runtimeSection, codecSection); } + public AssetDetailsContractControl(ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus, p.studio.ui.javafx.utilities.i18n.I18nService i18n, java.util.concurrent.Executor executor, AssetCommands assetCommands) { @@ -283,14 +285,15 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private void handleApplyResponse(boolean success, String errorMessage) { if (success) { formSession().apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); logContractEvent("Runtime contract updated"); requestRefresh(); renderSection(); return; } + finishHandoffSave(false, errorMessage); logContractEvent(errorMessage); - cancel(); renderSection(); } @@ -447,14 +450,15 @@ public final class AssetDetailsContractControl extends HBox implements StudioCon private void handleApplyResponse(boolean success, String errorMessage) { if (success) { formSession().apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); logContractEvent("Codec updated"); requestRefresh(); renderSection(); return; } + finishHandoffSave(false, errorMessage); logContractEvent(errorMessage); - cancel(); renderSection(); } diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java index b5aeeb15..1bd8bcc9 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/palette/AssetDetailsPaletteOverhaulingControl.java @@ -223,6 +223,7 @@ public final class AssetDetailsPaletteOverhaulingControl extends StudioFormSecti .filter(Objects::nonNull) .toList(); if (selectedPalettes.isEmpty()) { + finishHandoffSave(false, "No palette selected"); workspaceBus.publish(new StudioAssetLogEvent("palette-overhauling", "Apply failed: no palette was selected.")); workspaceBus.publish(new StudioPackerOperationEvent( UUID.randomUUID().toString(), @@ -240,15 +241,18 @@ public final class AssetDetailsPaletteOverhaulingControl extends StudioFormSecti Platform.runLater(() -> { if (response.success()) { coordinator.apply(); + finishHandoffSave(true, ""); publishEditScope(workspaceBus, currentScopeKey(), null); renderSection(); workspaceBus.publish(new StudioAssetsWorkspaceSelectionRequestedEvent(assetReference, true)); } else { + finishHandoffSave(false, response.errorMessage()); workspaceBus.publish(new StudioAssetLogEvent("palette-overhauling", "Apply failed: " + Objects.requireNonNullElse(response.errorMessage(), "unknown error"))); } }); } catch (Exception exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "palette-overhauling", "Apply failed due to an unexpected error."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java index 05e2042d..799eac40 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/schema/AssetDetailsColorSchemaGroupsControl.java @@ -181,16 +181,19 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio } final AssetColorSchemaState draft = coordinator.state(); if (!draft.selected()) { + finishHandoffSave(false, "Select or create a schema first"); workspaceBus.publish(new StudioAssetLogEvent("color-schema-groups", "Apply failed: select or create a schema first.")); return; } if (!draft.removeRequested()) { final List orderedColors = draft.orderedColors(); if (draft.assignedTiles().isEmpty() || orderedColors.isEmpty()) { + finishHandoffSave(false, "Schema requires at least one tile"); workspaceBus.publish(new StudioAssetLogEvent("color-schema-groups", "Apply failed: schema must contain at least one tile.")); return; } if (orderedColors.size() > 16) { + finishHandoffSave(false, "Schema exceeds palette capacity"); workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", i18n.text(I18n.ASSETS_COLOR_SCHEMA_DIALOG_TOO_MANY_COLORS))); @@ -207,6 +210,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio : coordinator.upsertSchema(draft.schemaId(), draft.assignedTiles(), draft.orderedColors()); final var writeResult = metadataService.writeGlyphMaterialMetadata(assetDetails.summary().assetRoot(), metadata); if (!writeResult.successful()) { + Platform.runLater(() -> finishHandoffSave(false, writeResult.message())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", "Unable to save schema: " + writeResult.message()))); @@ -214,6 +218,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio } Platform.runLater(() -> { coordinator.apply(); + finishHandoffSave(true, ""); selectedSchemaId = draft.removeRequested() ? null : draft.schemaId(); publishEditScope(workspaceBus, currentScopeKey(), null); workspaceBus.publish(new StudioAssetLogEvent( @@ -223,6 +228,7 @@ public final class AssetDetailsColorSchemaGroupsControl extends StudioFormSectio renderSection(); }); } catch (RuntimeException exception) { + Platform.runLater(() -> finishHandoffSave(false, exception.getMessage())); Platform.runLater(() -> workspaceBus.publish(new StudioAssetLogEvent( "color-schema-groups", "Unable to save schema."))); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java index 7d03ad22..d474cbc7 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/list/AssetListControl.java @@ -98,6 +98,7 @@ public final class AssetListControl extends VBox implements StudioEventAware { } private TextField createSearchField() { + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(searchField); searchField.setPromptText(i18n.text(I18n.ASSETS_SEARCH_PROMPT)); searchField.getStyleClass().add("assets-workspace-search"); return searchField; @@ -117,6 +118,7 @@ public final class AssetListControl extends VBox implements StudioEventAware { } private ToggleButton configureFilterButton(ToggleButton button, I18n i18n) { + p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(button); button.textProperty().bind(this.i18n.bind(i18n)); button.getStyleClass().addAll("studio-button", "studio-button-secondary", "studio-button-pill", "studio-button-toggle"); return button; diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java new file mode 100644 index 00000000..05810691 --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspace.java @@ -0,0 +1,108 @@ +package p.studio.ui.javafx.workspaces.dev; + +import javafx.application.Platform; +import javafx.geometry.Insets; +import javafx.scene.Node; +import javafx.scene.control.*; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.*; +import p.studio.api.automation.*; +import p.studio.api.operation.OperationSubscription; +import p.studio.api.project.ProjectReference; +import p.studio.ui.javafx.events.StudioEventBus; +import p.studio.ui.javafx.utilities.i18n.*; +import p.studio.ui.javafx.workspaces.*; +import java.io.ByteArrayInputStream; + +/** Human authorization and observation only; never an embedded agent or a fake runtime. */ +public final class DevWorkspace extends Workspace { + private final VBox root = new VBox(12); + private final ScrollPane scroll = new ScrollPane(root); + private final AutomationSession automation; + private final I18nService i18n; + private final Label state = new Label(), identity = new Label(), operation = new Label(), imageStatus = new Label(); + private final TextArea diagnostics = new TextArea(), history = new TextArea(); + private final ImageView canvas = new ImageView(); + private final Button grant = new Button(), reclaim = new Button(); + private OperationSubscription subscription; + private long generation; + private CanonicalCapture rendered; + private final javafx.beans.value.ChangeListener localeListener; + + public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) { + super(project, events); this.automation = automation; this.i18n = i18n; + localeListener = (o, before, after) -> apply(this.automation.snapshot()); + scroll.setFitToWidth(true); + root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace"); + grant.setId("dev-grant"); reclaim.setId("dev-reclaim"); + grant.textProperty().bind(i18n.bind(I18n.DEV_GRANT)); + reclaim.textProperty().bind(i18n.bind(I18n.DEV_RECLAIM)); + grant.setOnAction(e -> grant(false)); + reclaim.setOnAction(e -> automation.reclaim()); + Button configuration = new Button(); configuration.setId("dev-mcp-config"); + configuration.textProperty().bind(i18n.bind(I18n.DEV_COPY_CONFIG)); configuration.setDisable(true); + Label availability = new Label(); availability.textProperty().bind(i18n.bind(I18n.DEV_MCP_UNAVAILABLE)); + Label warning = new Label(); warning.setWrapText(true); + warning.textProperty().bind(i18n.bind(I18n.DEV_EXTERNAL_WARNING)); + canvas.setPreserveRatio(true); canvas.setSmooth(false); canvas.setFitWidth(640); canvas.setFitHeight(360); + StackPane imagePane = new StackPane(canvas); imagePane.setMinHeight(200); imagePane.getStyleClass().add("dev-canvas"); + diagnostics.setEditable(false); diagnostics.setPrefRowCount(3); + history.setEditable(false); history.setPrefRowCount(5); + root.getChildren().addAll(new Label(project.name() + " — " + project.rootPath()), + state, new HBox(10, grant, reclaim, configuration), availability, warning, + operation, imageStatus, imagePane, identity, + pane(I18n.DEV_DIAGNOSTICS, diagnostics), pane(I18n.DEV_HISTORY, history)); + apply(automation.snapshot()); + } + + private TitledPane pane(I18n key, Node content) { + TitledPane pane = new TitledPane(); pane.textProperty().bind(i18n.bind(key)); + pane.setContent(content); pane.setCollapsible(false); return pane; + } + @Override public WorkspaceId workspaceId() { return WorkspaceId.DEV; } + @Override public I18n title() { return I18n.WORKSPACE_DEV; } + @Override public Node rootNode() { return scroll; } + @Override public void load() { + if (subscription != null) return; + i18n.localeProperty().addListener(localeListener); + long subscribed = ++generation; + subscription = automation.subscribe(snapshot -> { + Runnable update = () -> { if (generation == subscribed) apply(snapshot); }; + if (Platform.isFxApplicationThread()) update.run(); else Platform.runLater(update); + }); + } + @Override public void unLoad() { + generation++; + i18n.localeProperty().removeListener(localeListener); + if (subscription != null) { subscription.unsubscribe(); subscription = null; } + } + private void grant(boolean save) { + automation.grant(save).whenComplete((result, failure) -> Platform.runLater(() -> { + if (failure != null) { diagnostics.setText(failure.getMessage()); return; } + if (result.status() == ControlResult.Status.DIRTY_DOCUMENTS) { + ButtonType confirm = new ButtonType(i18n.text(I18n.DEV_SAVE_GRANT), ButtonBar.ButtonData.OK_DONE); + Alert dialog = new Alert(Alert.AlertType.CONFIRMATION, i18n.text(I18n.DEV_UNSAVED), confirm, ButtonType.CANCEL); + if (root.getScene() != null) dialog.initOwner(root.getScene().getWindow()); + if (dialog.showAndWait().orElse(ButtonType.CANCEL) == confirm) grant(true); + } + })); + } + private void apply(AutomationSnapshot snapshot) { + var view = DevWorkspaceProjection.from(snapshot); + state.setText(i18n.text(switch (view.state()) { + case MANUAL -> I18n.DEV_MANUAL; + case WAITING_FOR_AGENT -> I18n.DEV_WAITING; + case AGENT_WORKING -> I18n.DEV_WORKING; + case RETURNING_CONTROL -> I18n.DEV_RETURNING; + })); + grant.setDisable(!view.grantEnabled()); reclaim.setDisable(!view.reclaimEnabled()); + identity.setText(view.identity()); operation.setText(view.operation()); + diagnostics.setText(view.diagnostics()); history.setText(view.calls()); + imageStatus.setText(i18n.text(view.capture() == null ? I18n.DEV_NO_FRAME : view.stale() ? I18n.DEV_STALE_FRAME : I18n.DEV_CURRENT_FRAME)); + if (rendered != view.capture()) { + rendered = view.capture(); + canvas.setImage(rendered == null ? null : new Image(new ByteArrayInputStream(rendered.png()))); + } + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java new file mode 100644 index 00000000..b4c149cf --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjection.java @@ -0,0 +1,16 @@ +package p.studio.ui.javafx.workspaces.dev; + +import p.studio.api.automation.*; + +public record DevWorkspaceProjection(ControlState state, boolean grantEnabled, boolean reclaimEnabled, + boolean stale, CanonicalCapture capture, String identity, String operation, String diagnostics, String calls) { + public static DevWorkspaceProjection from(AutomationSnapshot s) { + var frame = s.capture(); + String identity = frame == null ? "" : "session=" + frame.sessionId() + " | build=" + frame.buildId() + + " | logical=" + frame.logicalFrameIndex() + " | FrameId=" + frame.frameId() + + " | " + frame.width() + "×" + frame.height() + " | stride=" + frame.stridePixels(); + return new DevWorkspaceProjection(s.state(), s.canGrant(), s.canReclaim(), s.stale(), frame, identity, + s.operation() == null ? "" : s.operation().id().value() + " | " + s.operation().state() + " | " + s.operation().summary(), + String.join("\n", s.diagnostics()), String.join("\n", s.calls())); + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java new file mode 100644 index 00000000..669e6d9f --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/dev/ManualProjectUiGuard.java @@ -0,0 +1,48 @@ +package p.studio.ui.javafx.workspaces.dev; + +import javafx.event.ActionEvent; +import javafx.scene.Node; +import javafx.scene.control.ButtonBase; +import javafx.scene.control.TextInputControl; +import javafx.scene.input.KeyEvent; +import javafx.scene.input.MouseEvent; +import javafx.css.PseudoClass; +import java.util.function.BooleanSupplier; + +/** Presentation guard only. Core service admission remains authoritative. */ +public final class ManualProjectUiGuard { + public static final String READ_ONLY_ACTION = "studio.readOnlyAction"; + private ManualProjectUiGuard() { } + public static void allowReadOnly(Node node) { + node.getProperties().put(READ_ONLY_ACTION, true); + node.getStyleClass().add("studio-read-only-action"); + } + public static void install(Node root, BooleanSupplier manualAllowed) { + root.addEventFilter(ActionEvent.ACTION, event -> { + if (!manualAllowed.getAsBoolean() && event.getTarget() instanceof Node target + && !Boolean.TRUE.equals(target.getProperties().get(READ_ONLY_ACTION))) event.consume(); + }); + root.addEventFilter(KeyEvent.KEY_TYPED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + root.addEventFilter(MouseEvent.MOUSE_PRESSED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + root.addEventFilter(KeyEvent.KEY_PRESSED, event -> { + if (!manualAllowed.getAsBoolean() && mutationTarget(event.getTarget())) event.consume(); + }); + } + public static void project(Node root, boolean manualAllowed) { + root.pseudoClassStateChanged(PseudoClass.getPseudoClass("automation-locked"), !manualAllowed); + } + private static boolean mutationTarget(Object target) { + Node node = target instanceof Node value ? value : null; + while (node != null) { + if (Boolean.TRUE.equals(node.getProperties().get(READ_ONLY_ACTION))) return false; + if (node instanceof ButtonBase || node instanceof javafx.scene.control.ComboBoxBase + || node instanceof TextInputControl text && text.isEditable()) return true; + node = node.getParent(); + } + return false; + } +} diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties index 7184af4a..6ee9a196 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages.properties @@ -357,3 +357,20 @@ assets.packWizard.error.deepSync=Unable to complete deep sync for the current wo assets.packWizard.error.validation=Unable to validate the current pack set. assets.packWizard.error.pack=Unable to pack the current build set. workspace.debug=Debug +workspace.dev=DEV +dev.grant=Grant control to AI +dev.reclaim=Interrupt and reclaim control +dev.copyConfig=Copy MCP configuration +dev.mcpUnavailable=MCP connection is not available yet. This stage provides project control and observation. +dev.externalWarning=Reclaiming control stops Studio-managed work, not direct writes by your external agent. Stop that client separately. Existing edits are preserved. +dev.manual=Manual control +dev.waiting=Waiting for agent — project control granted +dev.working=Agent working — task acquired +dev.returning=Returning control — stopping work and refreshing documents +dev.saveGrant=Save all and grant +dev.unsaved=Studio has unsaved changes. Save all before granting project control? +dev.diagnostics=Diagnostics +dev.history=Recent Studio calls +dev.noFrame=No runtime capture +dev.staleFrame=Stale capture — previous build or execution +dev.currentFrame=Canonical runtime capture diff --git a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties index 5e00b3ed..ff673d74 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx/src/main/resources/i18n/messages_pt_BR.properties @@ -28,3 +28,20 @@ workspace.debug.status.connecting=Conectando workspace.debug.status.running=Executando workspace.debug.status.runtimeFailed=Runtime falhou workspace.debug.status.stopped=Parado +workspace.dev=DEV +dev.grant=Ceder controle à IA +dev.reclaim=Interromper e retomar controle +dev.copyConfig=Copiar configuração MCP +dev.mcpUnavailable=A conexão MCP ainda não está disponível. Esta etapa oferece controle do projeto e acompanhamento. +dev.externalWarning=Retomar controle encerra o trabalho gerenciado pelo Studio, não as escritas diretas do agente externo. Pare esse cliente separadamente. As alterações existentes são preservadas. +dev.manual=Controle manual +dev.waiting=Aguardando agente — controle do projeto cedido +dev.working=Agente trabalhando — tarefa adquirida +dev.returning=Retomando controle — encerrando trabalho e atualizando documentos +dev.saveGrant=Salvar tudo e ceder +dev.unsaved=Existem alterações não salvas no Studio. Salvar tudo antes de ceder o controle? +dev.diagnostics=Diagnósticos +dev.history=Chamadas recentes ao Studio +dev.noFrame=Nenhuma captura do runtime +dev.staleFrame=Captura desatualizada — build ou execução anterior +dev.currentFrame=Captura canônica do runtime diff --git a/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css b/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css index c98780ff..f5c479ad 100644 --- a/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css +++ b/prometeu-studio-ui-javafx/src/main/resources/themes/default-prometeu.css @@ -1583,3 +1583,8 @@ -fx-text-fill: #b9cae0; -fx-font-size: 12px; } +.dev-canvas { -fx-background-color: #16191f; -fx-padding: 12; } +.automation-locked { -fx-opacity: 0.95; } +.assets-workspace:automation-locked .button, +.shipper-workspace:automation-locked .button { -fx-opacity: 0.45; } +.assets-workspace:automation-locked .studio-read-only-action { -fx-opacity: 1; } diff --git a/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java new file mode 100644 index 00000000..cf26fa4c --- /dev/null +++ b/prometeu-studio-ui-javafx/src/test/java/p/studio/ui/javafx/workspaces/dev/DevWorkspaceProjectionTest.java @@ -0,0 +1,31 @@ +package p.studio.ui.javafx.workspaces.dev; + +import org.junit.jupiter.api.Test; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class DevWorkspaceProjectionTest { + @Test void actionMappingUsesAuthorityAndNeverInventsAnEndpointOrFrame() { + for (var state : ControlState.values()) { + var view = DevWorkspaceProjection.from(snapshot(state, null, false, false)); + assertEquals(state == ControlState.MANUAL, view.grantEnabled()); + assertEquals(state != ControlState.MANUAL, view.reclaimEnabled()); + assertNull(view.capture()); assertEquals("", view.identity()); + } + var closed = DevWorkspaceProjection.from(snapshot(ControlState.MANUAL, null, false, true)); + assertFalse(closed.grantEnabled()); assertFalse(closed.reclaimEnabled()); + } + @Test void captureIdentityRetainsIndependentLogicalAndRenderCountersAndStaleness() { + var frame = new CanonicalCapture("session-A", "build-B", 99, 7, 320, 180, 320, new byte[]{1}); + var view = DevWorkspaceProjection.from(snapshot(ControlState.AGENT_WORKING, frame, true, false)); + assertSame(frame, view.capture()); assertTrue(view.stale()); + assertTrue(view.identity().contains("logical=99")); assertTrue(view.identity().contains("FrameId=7")); + assertTrue(view.identity().contains("session-A")); assertTrue(view.identity().contains("build-B")); + assertEquals("diagnostic", view.diagnostics()); assertEquals("call", view.calls()); + } + private AutomationSnapshot snapshot(ControlState state, CanonicalCapture frame, boolean stale, boolean closed) { + return new AutomationSnapshot(Path.of("."), state, false, closed, 0, null, null, frame, stale, List.of("diagnostic"), List.of("call")); + } +}