feat(studio): coordinate integrated AI activity and internal language services
Start project-owned language and authenticated MCP services when opening a project, reusing the embedded LSP backend without a desktop TCP listener. Keep editor overlays separate from saved-file MCP queries. Reserve conflicting editing before ACP prompt delivery and retain protection through native/tool termination, runtime cleanup and document refresh. Preserve drafts on rejected admission, provide cleanup/preparation recovery, distinguish terminal outcomes and redact permission previews. Add lifecycle, language parity, activity, composition and UI regressions and update the canonical Studio contracts. Keep distribution update alignment as the separate WRK-002A follow-up. Validation: complete make -C tooling verify PASSED in 20261127T035822Z-ec5d9266 (1172 unit, 131 compiler fixture, 31 headless tests). Opt-in real-model and native AI-view qualification are outside that gate. Work: WRK-0029; decision: DEC-0001.
This commit is contained in:
@@ -165,5 +165,6 @@ port as scaffold and DEV retry. Desktop composition MUST start the shared loopba
|
||||
server before project sessions become available; no external command or separate
|
||||
per-project desktop Run is required. Explicitly disabled integration MUST remain
|
||||
disabled. Preparation failure MUST remain visible in DEV readiness without blocking
|
||||
project use. Opening MUST NOT publish credentials or grant/acquire agent control.
|
||||
project use. Opening MUST publish authenticated project MCP access without granting task
|
||||
authority or reserving editing. Integrated activity admission follows specs 10 and 16.
|
||||
The coding client continues to own its configured stdio process and initial trust.
|
||||
|
||||
@@ -15,15 +15,18 @@ 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.
|
||||
Coordinate the integrated AI conversation with project editing, specialized MCP
|
||||
services and managed runtime work. Opening a project starts its internal language
|
||||
workspace and authenticated MCP access. Their availability does not reserve assets.
|
||||
Studio reserves conflicting editing only for the admitted AI activity and its
|
||||
actual finalization. Legacy external DEV grant/reclaim remains an explicit,
|
||||
separate compatibility flow.
|
||||
|
||||
## 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.
|
||||
The shared operation/runtime contracts remain applicable to both integrated AI
|
||||
and the legacy external DEV workflow. Integrated activity admission below defines
|
||||
the current desktop flow; manual grant buttons belong only to the legacy flow.
|
||||
|
||||
- [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.
|
||||
@@ -44,8 +47,8 @@ implement a parallel permission/build/pack/execution system.
|
||||
| --- | --- |
|
||||
| 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 |
|
||||
| JavaFX | Integrated conversation and activity projection; legacy DEV grant/reclaim; localization and subscriptions |
|
||||
| Application/infrastructure | MCP HTTP transport, process supervision, runtime JSONL translation, internal language workspace, 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 |
|
||||
|
||||
@@ -65,17 +68,19 @@ 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.
|
||||
Connection authentication, activity admission and task identity MUST be separate
|
||||
checks. The project-owned ACP coordinator MUST reserve the Core editing lane
|
||||
before submitting a prompt. `studio_control_acquire` returns the admitted task
|
||||
idempotently during that activity. Outside an integrated activity, external
|
||||
acquisition still requires an explicit human DEV grant. A task MUST NOT be reused
|
||||
across projects, activities or project generations.
|
||||
|
||||
| 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 |
|
||||
| Manual control | Editing and Play are available; AI admission refuses dirty documents, active manual work or Play, without saving/discarding/stopping them | Integrated admission enters working; legacy grant enters waiting |
|
||||
| Waiting for agent | Legacy external grant already blocks conflicting editing | Legacy acquisition enters working; reclaim enters returning |
|
||||
| Agent working | Integrated activity protects assets through prompt, permission waits and tool work; chat selection, writing drafts and cancel remain available | Coordinator finalization enters returning; integrated model release alone retains protection |
|
||||
| Returning control | Prior task is invalid; wait for workers/runtime shutdown and refresh documents | Manual control only after successful cleanup; failure retains protection and explicit retry |
|
||||
|
||||
Grant and acquisition MUST be enforced atomically with conflicting operation
|
||||
admission. Concurrent acquisition MUST NOT create two owners. Project-local
|
||||
@@ -84,7 +89,8 @@ 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.
|
||||
well as UI bindings. The integrated shell MUST stay in the AI area while activity
|
||||
is admitted/finalizing. Conversation inspection and cancellation remain available.
|
||||
|
||||
An operation finishing, failing compilation, raising a guest fault or losing
|
||||
its runtime session MUST NOT release task authority. Silence, client
|
||||
@@ -97,15 +103,18 @@ 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**.
|
||||
Integrated admission MUST refuse dirty content and preserve it, requiring an
|
||||
explicit save or discard in its owning editor before retrying Send. It MUST NOT
|
||||
silently save or discard it. In the legacy external flow only, 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
|
||||
MUST use saved files. MCP language queries MUST use a saved-file view distinct
|
||||
from editor overlays, while sharing the existing language engine internally. 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
|
||||
@@ -121,7 +130,13 @@ engineering delivery that prepared this integration.
|
||||
|
||||
## 4. Return, Revocation and Closure
|
||||
|
||||
Explicit release and human reclaim MUST follow this order:
|
||||
Integrated normal completion MUST await the active operation's actual termination
|
||||
before return. Cancellation, transport failure and project close MUST cancel
|
||||
managed work and await termination. An ACP response, model release, completed
|
||||
response Future or cancellation acknowledgement alone MUST NOT unlock editing.
|
||||
An integrated model release acknowledges completion intent without revoking the
|
||||
coordinator-owned reservation. The coordinator's return, or legacy explicit
|
||||
release/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.
|
||||
@@ -134,7 +149,7 @@ 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
|
||||
Another task MUST require a newly admitted integrated activity or a fresh explicit legacy external 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.
|
||||
@@ -313,17 +328,17 @@ specified in [MCP Tools and Project Knowledge Contract](11.%20MCP%20Tools%20and%
|
||||
|
||||
The desktop MUST host Streamable HTTP at `127.0.0.1:<OS-assigned-port>/mcp`.
|
||||
DEC-0061 adds Studio-owned stdio discovery and one-time preparation as specified
|
||||
in spec 11. Each human grant publishes a fresh project-scoped credential through
|
||||
in spec 11. Each project opening publishes a fresh project-scoped credential through
|
||||
the required lifecycle participant in spec 8. Authentication, project scope and
|
||||
task identity remain separate checks. There is no global credential bypass.
|
||||
Restart invalidates old access and requires a fresh human grant, while the native
|
||||
Restart invalidates old access and requires fresh project access and activity admission, while the native
|
||||
client's command/configuration remains unchanged. No remote binding, accounts or
|
||||
OAuth are introduced. Preparation never grants editing authority.
|
||||
|
||||
| Tool group | Required capabilities | Required authority |
|
||||
| --- | --- | --- |
|
||||
| Context/references | Project identity, languages, versions, capabilities and paginated references | Project credential; no acquired task required |
|
||||
| Control | Acquire task and release control | Prior human grant for acquisition; valid task identity for release |
|
||||
| Control | Acquire task and release control | Admitted integrated activity or prior legacy human grant; 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 |
|
||||
@@ -364,7 +379,7 @@ 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
|
||||
references → obtain the admitted integrated task (or acquire after a legacy 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.
|
||||
|
||||
@@ -23,7 +23,7 @@ initialization exchange negotiates that supported revision; no compatibility
|
||||
with other revisions or deprecated HTTP+SSE transport is claimed. An offered
|
||||
unsupported revision receives the supported revision in `InitializeResult`.
|
||||
|
||||
Each desktop start generates a new instance identity. Each human project grant
|
||||
Each desktop start generates a new instance identity. Each successful project opening
|
||||
publishes a fresh 256-bit bearer credential scoped to that canonical project root.
|
||||
Every HTTP request MUST include `Authorization: Bearer <credential>`; missing,
|
||||
wrong or revoked credentials return 401. Initialized HTTP sessions MUST be bound
|
||||
@@ -113,7 +113,7 @@ file/permissions, stale credentials/instance, catalog incompatibility and transp
|
||||
reconnection. Calls cannot wait indefinitely for a grant. No reconnect path may
|
||||
resubmit a tool call. An uncertain response MUST retain available clientRequestId
|
||||
correlation and instruct receipt lookup within the same authorized task. A new
|
||||
desktop/task has no old receipt registry and requires a fresh human grant.
|
||||
desktop/task has no old receipt registry and requires a fresh integrated activity or explicit legacy external grant.
|
||||
Connector-generated uncertain-outcome errors carry that correlation in
|
||||
`error.details.clientRequestId`, within the advertised output schema; the text
|
||||
content block MUST serialize the identical structured envelope.
|
||||
@@ -180,9 +180,9 @@ prove authorization.
|
||||
The authority levels in the packaged catalog are:
|
||||
|
||||
- `authenticated`: connection authentication only; project/context/reference reads
|
||||
need no acquired task. HTTP access still requires the project credential published by human grant. Offline catalog discovery returns no task token.
|
||||
- `granted`: acquisition validates the prior human grant and atomically creates
|
||||
the sole task identity. The transport session ID is not that identity.
|
||||
need no acquired task. HTTP access still requires the credential published for the open project. Offline catalog discovery returns no task token.
|
||||
- `granted`: acquisition returns the existing admitted integrated task, or validates
|
||||
a prior human external grant and atomically creates the sole external task identity. The transport session ID is not that identity.
|
||||
- `task`: `projectRoot` and `taskId` must identify the current acquired task.
|
||||
Revalidate before admission, lookup and deduplication, including read-only LSP.
|
||||
|
||||
@@ -241,8 +241,11 @@ SDK/library scope. No query applies filesystem edits.
|
||||
|
||||
### 3.1 Language Query Operations
|
||||
|
||||
`studio_language_query` uses the existing project's LSP server via a real client,
|
||||
not a parallel language implementation or a direct call into compiler semantics.
|
||||
`studio_language_query` uses the project-owned internal language workspace and
|
||||
existing embedded LSP implementation. It MUST NOT require a TCP endpoint,
|
||||
`.studio/lsp.json`, JSON-RPC launcher or parallel compiler implementation in the
|
||||
integrated desktop. Editor clients consume a neutral typed language port; LSP4j
|
||||
and compiler classes remain application/provider details.
|
||||
Its successful value is `{operation, result, limitations}`. `result` is the JSON
|
||||
projection of the existing LSP response (including null or an empty list when
|
||||
appropriate); LSP union wrappers are unwrapped. Provider classes remain inside
|
||||
@@ -306,26 +309,29 @@ with `prepareCallHierarchy(uri, position)`, then use a returned opaque `itemId`
|
||||
`incomingCalls` or `outgoingCalls`. Returned hierarchy items may supply new `itemId`
|
||||
values for further traversal. Item IDs cannot be invented from symbol names or URIs.
|
||||
|
||||
The application lifecycle supplies each open project's bound loopback LSP
|
||||
endpoint. Studio uses OS-assigned ports so different open projects do not compete
|
||||
for one fixed port. The public LSP configuration default remains unchanged for
|
||||
other hosts. A manifest language change requires reopening that project's server;
|
||||
the adapter MUST NOT send queries to a server bound to another language/root.
|
||||
Opening any desktop project, including the Play shell, MUST start its internal
|
||||
language workspace; close MUST stop it. A manifest language change requires
|
||||
reopening; root/language and generation MUST be checked before dispatch and
|
||||
publication. Closing/reopening or switching projects MUST fence late results and
|
||||
expire task/source/hierarchy handles. A standalone TCP host MAY retain its own
|
||||
transport; it is not part of the integrated composition.
|
||||
|
||||
Each query uses a short-lived client connection. For physical document requests, the
|
||||
adapter opens exactly the saved UTF-8 text and waits for that connection's
|
||||
published diagnostics before issuing the semantic query. Other dependency files
|
||||
are read from disk by the existing compiler bridge. A fresh connection prevents
|
||||
reuse of stale overlays from previous requests or the human editor. Unsaved or
|
||||
concurrent external writes remain the developer's responsibility.
|
||||
Each MCP request uses the saved UTF-8 document and dependencies. Editor queries
|
||||
use a separate snapshot of open versioned overlays, including imported documents;
|
||||
MCP task release MUST NOT clear editor buffers. Conflicting/obsolete versions and
|
||||
results from superseded editor snapshots MUST be rejected. Refactoring returns
|
||||
proposals without applying edits. Saved primary-file revision changes during a
|
||||
query MUST invalidate its result. No long-lived compiler cache is required;
|
||||
assets, dependency/configuration and saved-file changes are read by fresh analysis.
|
||||
|
||||
Queries require the current task, share the project's work admission/cancellation
|
||||
and DEV operation observation, and do not silently queue behind conflicting work.
|
||||
Return/reclaim invalidates the task immediately, waits for worker termination,
|
||||
then clears task-local hierarchy items before manual control is restored. Item
|
||||
IDs from another task or project cannot be used. Client sockets/listeners close
|
||||
on success, failure, timeout or cancellation; project-server shutdown closes its
|
||||
accepted sockets and executor. A lost client does not independently grant control.
|
||||
Queries require the current task, share the project's admission/cancellation and
|
||||
operation observation, and do not silently queue behind conflicting task work.
|
||||
Internal compiler execution MUST run outside FX, serialize per project and use
|
||||
bounded queues, execution and cleanup response budgets. A timeout/cancel response
|
||||
MUST NOT be interpreted as worker termination. Return waits for actual termination,
|
||||
then clears task-local hierarchy/source handles. Project close cancels requests,
|
||||
rejects queued work and retains incomplete cleanup for retry. Editor and saved
|
||||
views MUST NOT share mutable document maps or task authority.
|
||||
|
||||
The adapter bounds connect time to 2 seconds within the shared 10-second admission-relative execution budget, followed by a 2-second cleanup response window;
|
||||
Core bounds the request worker wait to 12 seconds. Documents are limited to 4 MiB
|
||||
@@ -424,7 +430,10 @@ the registry, replays an advance or recovers authorization.
|
||||
`TaskTools` is the neutral service surface; MCP only validates schemas and projects
|
||||
its results. The Core implementation admits work through `AutomationSession.submit`
|
||||
and the existing operation executor, sharing DEV's busy state and cancellation.
|
||||
Acquisition requires the prior human grant. Release reports `MANUAL` only after
|
||||
Integrated acquisition returns the coordinator-admitted task; external acquisition
|
||||
requires the prior human DEV grant. Integrated release does not independently
|
||||
unlock editing; the activity coordinator owns finalization. Legacy release reports
|
||||
`MANUAL` only after
|
||||
managed cleanup and document refresh succeed; cleanup failures remain explicit.
|
||||
|
||||
Admission and request registration are atomic per project. Deduplication uses the
|
||||
@@ -549,7 +558,7 @@ reference provider, not a Studio-maintained language specification.
|
||||
|
||||
`studio_project_context` resolves an exact, canonical root registered by an open
|
||||
project session. It does not use the focused window, accept a source-directory
|
||||
path as a project root, acquire a manual lease, or acquire task authority. The HTTP boundary separately requires the grant-published project credential. A session
|
||||
path as a project root, acquire a manual lease, or acquire task authority. The HTTP boundary separately requires the open-project credential. A session
|
||||
is discoverable only after successful opening and until closure begins.
|
||||
Unregistered/closed roots return `PROJECT_NOT_OPEN`.
|
||||
|
||||
@@ -620,7 +629,7 @@ IDs or hashes when created, modified or removed. Regeneration MUST remove
|
||||
previously copied transient resources. The installed example MUST remain
|
||||
compilable and packable outside the source checkout without a preexisting cache.
|
||||
|
||||
`studio_reference_read` is authenticated but does not require an acquired task; the transport still requires a grant-published project credential. It resolves the explicit open root and its current saved manifest selection
|
||||
`studio_reference_read` is authenticated but does not require an acquired task; the transport still requires a open-project credential. It resolves the explicit open root and its current saved manifest selection
|
||||
on every read. Changing SDK/target can invalidate previously advertised IDs.
|
||||
Only IDs in that project's installed index can be read, including when other
|
||||
languages/providers are installed globally. SDK and external-library texts remain
|
||||
@@ -739,7 +748,9 @@ port as scaffold and DEV retry. Desktop composition MUST start the shared loopba
|
||||
server before project sessions become available; no external command or separate
|
||||
per-project desktop Run is required. Explicitly disabled integration MUST remain
|
||||
disabled. Preparation failure MUST remain visible in DEV readiness without blocking
|
||||
project use. Opening MUST NOT publish credentials or grant/acquire agent control.
|
||||
project use. Opening MUST publish project-scoped MCP access independently of task authority.
|
||||
It MUST NOT reserve assets or start an AI task. Preparation/connection failure MUST
|
||||
remain observable and retryable without claiming ACP login implies tool readiness.
|
||||
The coding client continues to own its configured stdio process and initial trust.
|
||||
|
||||
|
||||
|
||||
@@ -89,14 +89,16 @@ controls MUST remain outside that split. Adjusting it MUST NOT change execution
|
||||
state or restart the runtime. The split is retained for the open view; it does not
|
||||
introduce persisted project settings or a restoration contract across reopening.
|
||||
|
||||
It MUST NOT initialize an AI client or editor/LSP infrastructure when opening for
|
||||
Opening MUST initialize project-owned internal language and MCP services. The
|
||||
integrated AI connection follows specification 16. This does not mount an editor
|
||||
or add compiler work to FX when opening for
|
||||
Play. Existing headless, MCP, evidence, tests and agent contracts remain available
|
||||
through their existing entry points and services. Their preservation takes
|
||||
precedence over interactive convenience.
|
||||
|
||||
Editors, functional agent integration, tuning during Play,
|
||||
breakpoints, hot reload, PMC builds and distribution/export are outside this
|
||||
slice. Future packaging belongs in Studio as a separate action; Play MUST NOT
|
||||
A full editor, tuning during Play, breakpoints, hot reload, PMC builds and
|
||||
distribution/export are outside this interactive slice. Integrated AI follows
|
||||
specifications 15–16. Future packaging belongs in Studio as a separate action; Play MUST NOT
|
||||
implicitly package a PMC or a distributable runtime.
|
||||
|
||||
## Project selection, creation and loading
|
||||
@@ -354,8 +356,8 @@ available for attribution, with concise visual forms permitted.
|
||||
|
||||
The UI uses static presentation controls with existing themes, text scale,
|
||||
English/Portuguese localization and accessible labels. It MUST NOT instantiate
|
||||
an editor, full-document view, edit/save actions, editorial LSP or unused future
|
||||
editor infrastructure. The legacy JavaFX frontend is not modified by this feature;
|
||||
an editor, full-document view or edit/save actions. Project-owned internal language
|
||||
services still start at project open, independently of this diagnostic view. The legacy JavaFX frontend is not modified by this feature;
|
||||
neutral API constructors remain compatible with its compilation.
|
||||
|
||||
## Verification and limits
|
||||
@@ -394,3 +396,12 @@ Windows/Linux, release performance, physical HiDPI pixel alignment, and human
|
||||
listening/IME/accessibility walkthroughs require separate evidence. Diagnostic runs
|
||||
and failures remain in Work evidence; a later passing run does not establish their
|
||||
unobserved cause.
|
||||
|
||||
|
||||
## AI activity exclusion
|
||||
|
||||
Play admission MUST use the shared Core editing/execution guard. Active or
|
||||
finalizing AI activity MUST disable conflicting Play/settings/navigation actions
|
||||
and keep the AI workspace selected. A running Play session MUST cause AI admission
|
||||
to refuse without stopping Play or discarding game data. Closing requires confirmed
|
||||
agent and managed worker/runtime cleanup before releasing project resources.
|
||||
|
||||
@@ -152,3 +152,25 @@ Codex connection, sending, streaming, explicit permissions and cancellation foll
|
||||
[specification 16](16.%20Codex%20ACP%20Integration%20Specification.md). Asset attachment
|
||||
and persisted chat resumption remain future capabilities. Integration MUST preserve
|
||||
shared-composer ownership, independent drafts and the project lifetime boundary.
|
||||
|
||||
|
||||
## Project activity and readiness
|
||||
|
||||
Send MUST require ACP readiness and current project tool preparation. Authentication
|
||||
success alone MUST NOT imply MCP readiness. Preparation failures MUST remain
|
||||
visible, preserve drafts and offer an explicit retry. Activity admission and cleanup
|
||||
MUST run off FX through the shared Core guard. Admission refuses unsaved project
|
||||
buffers and conflicting manual/Play work without silent saving or stopping.
|
||||
|
||||
During admitted/finalizing AI work, the shell MUST stay in the AI area and disable
|
||||
conflicting project editing/Play/settings entry points. Chat selection, independent
|
||||
conversation drafts, reading, explicit permissions and Cancel remain usable. Model
|
||||
completion MUST wait for actual tool workers/runtime cleanup and document refresh
|
||||
before editing becomes available. Cleanup failure MUST retain protection, show the
|
||||
failure and provide an explicit cleanup retry. Cancel acknowledgement is not proof
|
||||
of termination.
|
||||
|
||||
Terminal presentation MUST distinguish `end_turn`, `cancelled`, `max_tokens`,
|
||||
`max_turn_requests`, `refusal`, transport failure and unknown interruption. Limited,
|
||||
refused and interrupted turns MUST NOT be shown as successful completion. Preserve
|
||||
the supplied stop reason without inventing missing tool outcomes.
|
||||
|
||||
@@ -7,8 +7,8 @@ Status: Implemented initial conversation slice. Owner: `studio`.
|
||||
The Studio JavaFX 2 project shell MUST consume an asynchronous, JavaFX-free
|
||||
`AgentConnection` port in Studio API. The application MUST own the process adapter
|
||||
and composition. UI MUST NOT launch processes or parse ACP; Core MUST NOT depend
|
||||
on JavaFX. This extends specifications 8 and 15 and does not change runtime or MCP
|
||||
authority. Assets, model selection, persistent chat indexing and history resumption
|
||||
on JavaFX. This extends specifications 8 and 15; integrated MCP editing authority follows
|
||||
specification 10 and is coordinated by the project-owned agent decorator. Assets, model selection, persistent chat indexing and history resumption
|
||||
are outside this slice.
|
||||
|
||||
## Project connection and authentication
|
||||
@@ -106,7 +106,9 @@ NOT silently create a replacement session pretending to retain conversation cont
|
||||
|
||||
Each `session/request_permission` MUST require an explicit choice from its offered
|
||||
options. The owned, nonblocking dialog MUST identify the chat and requested action,
|
||||
with a bounded scrollable action preview when supplied. Closing/cancelling MUST
|
||||
with a bounded scrollable action preview when supplied. Known credential patterns
|
||||
MUST be masked in permission titles/previews with the same policy as tool output;
|
||||
permission correlation and option IDs MUST remain intact. Closing/cancelling MUST
|
||||
return cancelled; unknown options MUST NOT authorize. Cancellation, turn completion
|
||||
and project close MUST dismiss stale permission dialogs. UI callbacks MUST run on FX;
|
||||
protocol IO and process waits MUST run off FX.
|
||||
@@ -143,3 +145,21 @@ the actual settings, prompt, chat routing, permissions and project lifetime with
|
||||
controlled backend. The opt-in live smoke MUST use a disposable project and an
|
||||
existing ChatGPT login, request no tools or file changes, and await full shutdown.
|
||||
Live smoke MUST NOT run as part of ordinary unit tests.
|
||||
|
||||
|
||||
## Integrated activity qualification
|
||||
|
||||
Before the native prompt is submitted, Core MUST admit exactly one activity for
|
||||
that project. Dirty editor/asset buffers, manual work and Play MUST refuse admission
|
||||
without modifying them. The reservation MUST outlive model `studio_control_release`
|
||||
and the ACP prompt response until managed work terminates and refresh succeeds.
|
||||
Cancel, crash, close and late callbacks MUST preserve this ordering. A stale
|
||||
completion MUST NOT cancel or release a subsequent activity.
|
||||
|
||||
Controlled peers MUST qualify ACP/tool/context/return sequencing separately from
|
||||
a real-model run. Full-path live qualification MUST use a disposable project,
|
||||
existing allowed authentication and actual MCP discovery, context/reference and
|
||||
tool queries; it MUST NOT copy credentials into the project or engineering memory,
|
||||
start browser login automatically, or treat a controlled fixture/environmental
|
||||
refusal as real-model success. The existing no-tools live conversation smoke remains
|
||||
an independent narrower check.
|
||||
|
||||
@@ -124,7 +124,7 @@ The JavaFX module MUST NOT directly invoke compiler implementations, `p.packer`,
|
||||
|
||||
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:<OS-assigned-port>/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a fresh grant-published project credential, validate project/session scope and Origin, and stop with Studio. Connection authentication MUST NOT grant project/task authority. Credentials MUST NOT be stored in versioned files. Restart requires a fresh human grant, while the stable client configuration remains unchanged.
|
||||
The sole accepted HTTP-server use is an in-process MCP Streamable HTTP endpoint at `127.0.0.1:<OS-assigned-port>/mcp`. The application/infrastructure adapter MUST own its transport dependencies and lifecycle. It MUST require a fresh open-project credential, validate project/session scope and Origin, and stop with Studio. Connection authentication MUST NOT grant project/task authority. Credentials MUST NOT be stored in versioned files. Restart requires fresh project access and a newly admitted activity, while the stable client configuration remains unchanged.
|
||||
|
||||
This exception does not authorize a web UI, remote binding, general-purpose web application, accounts or OAuth. DEC-0061 explicitly adds the Studio-owned stdio mode and local client preparation. 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.
|
||||
|
||||
@@ -149,7 +149,7 @@ A narrow consumer-owned gateway MUST be used when the available integration is c
|
||||
| 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.
|
||||
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 project-owned internal language workspace 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.
|
||||
|
||||
@@ -367,3 +367,21 @@ Encoded guest messages MUST fit 256 UTF-8 bytes and stay within the unchanged
|
||||
runner drains every pending native page before another bounded advance. Native
|
||||
continuity alone cannot detect events dropped before ring insertion. No new guest
|
||||
ABI, formatting facility or increased execution/logging budget is introduced.
|
||||
|
||||
|
||||
## Internal project language and integrated activity
|
||||
|
||||
The application MUST compose one language workspace per open project, using the
|
||||
existing compiler bridge and embedded LSP services without a TCP listener. API
|
||||
exposes versioned document requests and JSON-compatible results; Core owns its
|
||||
lifecycle and editor document handoff through neutral ports. Editor overlays and
|
||||
MCP saved-file requests share the engine while keeping separate document views.
|
||||
Backend execution and bounded admission MUST remain outside FX. Project generation
|
||||
and document revisions fence results; shutdown waits for actual workers.
|
||||
|
||||
Core MUST reserve conflicting project editing before ACP prompt submission. A
|
||||
project-owned agent decorator coordinates admission, model completion, cancellation,
|
||||
managed worker/runtime finalization and refresh. MCP authentication is available
|
||||
at project open and never implies task authority. UI bindings project this guard;
|
||||
they MUST NOT be its authority. An integrated model release alone MUST NOT unlock
|
||||
editing. Failed cleanup retains the reservation and exposes an explicit retry.
|
||||
|
||||
@@ -284,3 +284,18 @@ tasks.register<Test>("studioControlsDesktopTest") {
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
|
||||
|
||||
// Explicit full-path real-model qualification; excluded from ordinary unit tests by integration tag.
|
||||
tasks.register<Test>("integratedAiLiveTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies integrated ACP discovery, project MCP references and internal language with an existing login."
|
||||
dependsOn(tasks.named("installDist"))
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/IntegratedAiLiveTest.class")
|
||||
systemProperty("studio.test.distribution", layout.buildDirectory.dir("install/prometeu-app").get().asFile.absolutePath)
|
||||
systemProperty("studio.test.codexAcp", providers.gradleProperty("studioCodexAcp").getOrElse(""))
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
|
||||
@@ -43,11 +43,8 @@ import p.studio.core.project.ProjectLocalStudioStateStore;
|
||||
import p.studio.api.project.ProjectWorkspaceInitializer;
|
||||
import p.studio.core.project.PackerProjectWorkspaceInitializer;
|
||||
import p.studio.api.session.ProjectSessionFactory;
|
||||
import p.studio.app.lsp.LspLifecycleAdapter;
|
||||
import p.studio.core.session.DefaultProjectSessionFactory;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
import p.studio.lsp.api.LspServerLifecycle;
|
||||
import p.studio.lsp.services.LspServerLifecycleImpl;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
import p.studio.ui.javafx.utilities.ThemeService;
|
||||
import p.studio.ui.javafx.utilities.i18n.I18nService;
|
||||
@@ -258,13 +255,10 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
LspServerLifecycle lspServerLifecycle(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events) {
|
||||
return new LspServerLifecycleImpl(layouts,(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)));
|
||||
}
|
||||
|
||||
@Bean
|
||||
LspLifecyclePort lspLifecyclePort(LspServerLifecycle lifecycle) {
|
||||
return new LspLifecycleAdapter(lifecycle);
|
||||
p.studio.app.lsp.InProcessLanguageWorkspace projectLanguageWorkspace(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events,
|
||||
ProjectCatalog catalog,p.studio.api.automation.ProjectKnowledge knowledge,ObjectMapper mapper) {
|
||||
return new p.studio.app.lsp.InProcessLanguageWorkspace(layouts,
|
||||
(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer)),catalog,knowledge,mapper);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -337,7 +331,8 @@ public class StudioApplicationConfiguration {
|
||||
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide,
|
||||
p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations,
|
||||
p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore,
|
||||
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings) {
|
||||
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
|
||||
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
@@ -347,7 +342,12 @@ public class StudioApplicationConfiguration {
|
||||
factory.setAnimationService(animationService);
|
||||
factory.setRuntimeSettings(runtimeSettings);
|
||||
factory.setAgentSettings(agentSettings);
|
||||
factory.setAgentConnections(root->new p.studio.app.acp.CodexAcpConnection(root,mapper));
|
||||
factory.setAgentConnections(root->new p.studio.core.session.ProjectAgentConnection(
|
||||
new p.studio.app.acp.CodexAcpConnection(root,mapper),access.requireAutomation(root),
|
||||
()->setupStore.load(projectCatalog.openProject(root)).agentIntegration().enabled()?preparation.status(root):
|
||||
new p.studio.api.automation.AgentIntegrationPreparation.Result(false,"Project assistant integration is disabled"),
|
||||
()->setupStore.load(projectCatalog.openProject(root)).agentIntegration().enabled()?preparation.prepare(root):
|
||||
new p.studio.api.automation.AgentIntegrationPreparation.Result(false,"Project assistant integration is disabled"),studioExecutor));
|
||||
factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper,
|
||||
new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access),
|
||||
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}});
|
||||
@@ -366,9 +366,8 @@ public class StudioApplicationConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
p.studio.core.language.LanguageQueryPort automationLanguagePort(LspServerLifecycle lifecycle, ProjectCatalog catalog,
|
||||
p.studio.api.automation.ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
return new p.studio.app.lsp.AutomationLspQueries(lifecycle, catalog, knowledge, mapper);
|
||||
p.studio.core.language.LanguageQueryPort automationLanguagePort(p.studio.app.lsp.InProcessLanguageWorkspace workspace) {
|
||||
return workspace.savedQueries();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -80,7 +80,9 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
if(!chatGptLogin)throw new IOException("Agent does not offer ChatGPT authentication");
|
||||
if(!closing){state(State.CONNECTED,"");queryAuth().join();}
|
||||
}catch(Throwable failure){
|
||||
terminate(owned.get());fail(epoch,failure);throw new CompletionException(failure);
|
||||
fail(epoch,failure);
|
||||
try{terminate(owned.get());}catch(Throwable cleanup){failure.addSuppressed(cleanup);}
|
||||
throw new CompletionException(failure);
|
||||
}
|
||||
},workers);
|
||||
}
|
||||
@@ -124,7 +126,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
var params=json.createObjectNode().put("sessionId",id);params.putArray("prompt").addObject().put("type","text").put("text",text);
|
||||
request("session/prompt",params,1800).whenComplete((result,failure)->{
|
||||
turns.remove(id);accepted.remove(id);cancelling.remove(id);cancelPermissions(id);
|
||||
if(failure==null){acknowledgement.complete(null);done.complete(result.path("stopReason").asText("end_turn"));}
|
||||
if(failure==null){acknowledgement.complete(null);done.complete(result.path("stopReason").asText("unknown"));}
|
||||
else{
|
||||
if(failure instanceof TimeoutException)state(State.FAILED,"Agent request timed out");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);
|
||||
@@ -231,9 +233,9 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
var choices=new ArrayList<Choice>();for(var o:params.path("options"))choices.add(new Choice(o.path("optionId").asText(),o.path("name").asText(),o.path("kind").asText()));
|
||||
ObjectNode request=json.createObjectNode().set("id",message.get("id"));request.put("sessionId",session);permissionRequests.put(key,request);
|
||||
if(!turns.containsKey(session)||cancelling.contains(session)||closing){replyPermission(key,null);return;}
|
||||
String details=params.path("toolCall").toPrettyString();
|
||||
String details=message(params.path("toolCall").toPrettyString());
|
||||
if(details.length()>16_000)details=details.substring(0,16_000)+"\n…";
|
||||
try{permissions.apply(new Permission(session,params.path("toolCall").path("title").asText("Agent action"),details,List.copyOf(choices)))
|
||||
try{permissions.apply(new Permission(session,boundedToolText(params.path("toolCall").path("title").asText("Agent action")),details,List.copyOf(choices)))
|
||||
.whenComplete((choice,failure)->replyPermission(key,failure==null&&choices.stream().anyMatch(c->c.id().equals(choice))?choice:null));}
|
||||
catch(RuntimeException failure){replyPermission(key,null);}
|
||||
}
|
||||
@@ -254,6 +256,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
if(!closing)state(State.FAILED,message(failure));
|
||||
for(var f:requests)f.completeExceptionally(failure);
|
||||
}
|
||||
@Override public CompletionStage<Void> awaitQuiescence(){return CompletableFuture.runAsync(this::terminate,workers);}
|
||||
public synchronized CompletionStage<Void> closeAsync(){
|
||||
if(shutdown!=null)return shutdown;
|
||||
var stopping=new ArrayList<CompletableFuture<Void>>();for(String id:turns.keySet())stopping.add(cancel(id).toCompletableFuture().exceptionally(f->null));
|
||||
@@ -274,7 +277,8 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
private void terminate(){terminate(process);}
|
||||
private void terminate(Process owned){synchronized(terminationLock){
|
||||
if(owned==null||owned!=process)return;
|
||||
owned.descendants().forEach(ownedProcesses::add);
|
||||
RuntimeException discoveryFailure=null;
|
||||
try{owned.descendants().forEach(ownedProcesses::add);}catch(RuntimeException denied){discoveryFailure=denied;}
|
||||
var tree=ownedProcesses.stream().filter(p->p.pid()!=owned.pid()).toList();
|
||||
tree.forEach(ProcessHandle::destroy);owned.toHandle().destroy();
|
||||
try{if(!owned.waitFor(2,TimeUnit.SECONDS))owned.toHandle().destroyForcibly();}catch(InterruptedException e){Thread.currentThread().interrupt();owned.toHandle().destroyForcibly();}
|
||||
@@ -283,6 +287,7 @@ public final class CodexAcpConnection implements AgentConnection {
|
||||
try{owned.waitFor(3,TimeUnit.SECONDS);for(var child:tree)if(child.isAlive())child.onExit().get(Math.max(1,deadline-System.nanoTime()),TimeUnit.NANOSECONDS);}
|
||||
catch(Exception e){throw new CompletionException(e);}
|
||||
if(owned.isAlive()||tree.stream().anyMatch(ProcessHandle::isAlive))throw new IllegalStateException("Agent process did not terminate");
|
||||
if(discoveryFailure!=null)throw new IllegalStateException("Agent parent stopped; descendant cleanup could not be verified",discoveryFailure);
|
||||
process=null;output=null;ownedProcesses.clear();
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.lsp4j.*;
|
||||
import org.eclipse.lsp4j.jsonrpc.json.MessageJsonHandler;
|
||||
import org.eclipse.lsp4j.jsonrpc.messages.Either;
|
||||
import org.eclipse.lsp4j.launch.LSPLauncher;
|
||||
import org.eclipse.lsp4j.services.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.ProjectCatalog;
|
||||
@@ -20,9 +19,10 @@ import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** A real client of the already-running project LSP. Each query owns and closes its connection. */
|
||||
/** Reuses the project language protocol internally, with a standalone TCP compatibility adapter. */
|
||||
public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
private final LspServerLifecycle lifecycle;
|
||||
private final InProcessLanguageWorkspace internal;
|
||||
private final ProjectCatalog projects;
|
||||
private final ProjectKnowledge knowledge;
|
||||
private final ObjectMapper mapper;
|
||||
@@ -34,7 +34,18 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
private static final Set<String> EDITS = Set.of("completion", "prepareRename", "rename", "codeActions", "formatting");
|
||||
|
||||
public AutomationLspQueries(LspServerLifecycle lifecycle, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
this.lifecycle = lifecycle; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper;
|
||||
this.lifecycle = lifecycle; this.internal=null; this.projects = projects; this.knowledge = knowledge; this.mapper = mapper;
|
||||
}
|
||||
|
||||
public AutomationLspQueries(InProcessLanguageWorkspace internal, ProjectCatalog projects, ProjectKnowledge knowledge, ObjectMapper mapper) {
|
||||
this.lifecycle=null; this.internal=internal; this.projects=projects; this.knowledge=knowledge; this.mapper=mapper;
|
||||
}
|
||||
|
||||
Map<String,Object> queryEditor(TaskIdentity editor, p.studio.api.session.ProjectLanguageService.Request request,Map<Path,String> overlays) throws Exception {
|
||||
var parameters=new LinkedHashMap<>(request.parameters());
|
||||
if(request.document()!=null)parameters.put("uri",request.document().uri());
|
||||
var execution=new LanguageQueryExecution(request.operation(),10_000,2_000);
|
||||
return performQuery(editor,request.operation(),parameters,execution,request.document(),overlays);
|
||||
}
|
||||
|
||||
private record ExternalTask(String consumer, p.studio.lsp.messages.LspServerEndpoint endpoint,
|
||||
@@ -45,6 +56,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
items.remove(task);
|
||||
final var state = externalTasks.get(task);
|
||||
if (state == null) return;
|
||||
if(internal!=null){internal.endTask(task,state.consumer());externalTasks.remove(task,state);return;}
|
||||
final var workers = Executors.newCachedThreadPool();
|
||||
try (var socket = new Socket()) {
|
||||
socket.connect(new InetSocketAddress(state.endpoint().host(), state.endpoint().port()), 2000);
|
||||
@@ -88,7 +100,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
@Override public Map<String, Object> query(TaskIdentity task, String operation, Map<String, Object> parameters,
|
||||
LanguageQueryExecution execution) throws Exception {
|
||||
try {
|
||||
var result = performQuery(task, operation, parameters, execution);
|
||||
var result = performQuery(task, operation, parameters, execution, null,Map.of());
|
||||
if (execution.hasFailure()) throw execution.exception(AutomationFailure.Code.LANGUAGE_QUERY_CLEANUP_FAILED, "Language query cleanup failed", true);
|
||||
return result;
|
||||
} catch (IllegalArgumentException | ControlDeniedException failure) { throw failure; }
|
||||
@@ -99,7 +111,7 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
}
|
||||
|
||||
private Map<String, Object> performQuery(TaskIdentity task, String operation, Map<String, Object> parameters,
|
||||
LanguageQueryExecution execution) throws Exception {
|
||||
LanguageQueryExecution execution, p.studio.api.session.ProjectLanguageService.Document overlay,Map<Path,String> overlays) throws Exception {
|
||||
if (!OPERATIONS.contains(operation)) throw failure(AutomationFailure.Code.UNSUPPORTED_CAPABILITY, "Unsupported language operation: " + operation);
|
||||
var context = knowledge.context(task.projectRoot());
|
||||
var primary = context.languages().stream().filter(ProjectKnowledge.Language::primary).findFirst().orElseThrow();
|
||||
@@ -107,7 +119,8 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
throw failure(AutomationFailure.Code.UNSUPPORTED_LANGUAGE, "Project language has no available LSP");
|
||||
var project = projects.openProject(context.projectRoot());
|
||||
var binding = LspLifecycleAdapter.context(project);
|
||||
var endpoint = lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP is not running; reopen the project if its language changed"));
|
||||
var endpoint = internal==null?lifecycle.endpoint(binding).orElseThrow(() -> failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP is not running; reopen the project if its language changed")):null;
|
||||
if(internal!=null&&!internal.available(binding))throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project language service is not running");
|
||||
var params = mapper.valueToTree(parameters);
|
||||
CallHierarchyItem item = null;
|
||||
String uri = null;
|
||||
@@ -137,15 +150,15 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
source = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
|
||||
}
|
||||
uri = document.toUri().toString();
|
||||
if(overlay!=null){
|
||||
if(overlay.text().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>4*1024*1024)
|
||||
throw failure(AutomationFailure.Code.LIMIT_EXCEEDED,"Editor source exceeds 4 MiB");
|
||||
source=overlay.text();
|
||||
}
|
||||
}
|
||||
int documentVersion=overlay==null?1:overlay.version();
|
||||
long deadline = execution.deadlineNanos();
|
||||
if (System.nanoTime() >= deadline) throw new TimeoutException("Language query admission budget expired");
|
||||
var workers = Executors.newCachedThreadPool(r -> { var thread = new Thread(r, "studio-automation-lsp"); thread.setDaemon(true); return thread; });
|
||||
try (var socket = new Socket()) {
|
||||
execution.own(() -> { try { socket.close(); } catch (java.io.IOException ignored) {} });
|
||||
execution.own(workers::shutdownNow);
|
||||
if (!InetAddress.getByName(endpoint.host()).isLoopbackAddress()) throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE, "Project LSP endpoint is not local");
|
||||
socket.connect(new InetSocketAddress(endpoint.host(), endpoint.port()), (int)Math.max(1, Math.min(2000, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()))));
|
||||
var diagnostics = new CompletableFuture<List<Diagnostic>>();
|
||||
String expectedUri = uri;
|
||||
LanguageClient client = new LanguageClient() {
|
||||
@@ -158,12 +171,8 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
return CompletableFuture.completedFuture(new ApplyWorkspaceEditResponse(false));
|
||||
}
|
||||
};
|
||||
var launcher = new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
|
||||
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream())
|
||||
.setOutput(socket.getOutputStream()).setExecutorService(workers).create();
|
||||
var listening = launcher.startListening();
|
||||
execution.own(() -> listening.cancel(true));
|
||||
final var server = launcher.getRemoteProxy();
|
||||
try(var connection=connect(binding,endpoint,client,execution,overlays)) {
|
||||
final var server=connection.server;
|
||||
final var acquired = new HashSet<String>();
|
||||
boolean succeeded = false;
|
||||
try {
|
||||
@@ -193,11 +202,11 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
String digest = source == null ? null : sha256(source);
|
||||
if (document != null) {
|
||||
// Fresh client overlay contains exactly the saved UTF-8 file. Wait for analysis before querying.
|
||||
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), 1, source)));
|
||||
server.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(new TextDocumentItem(uri, primary.id(), documentVersion, source)));
|
||||
if (richAnalysis) {
|
||||
execution.method("prometeu/documentAnalysis");
|
||||
var retained = await(server.documentAnalysis(new ExternalSourceLanguageServer.DiagnosticAnalysisRequest(
|
||||
new VersionedTextDocumentIdentifier(uri, 1), digest)), deadline, execution);
|
||||
new VersionedTextDocumentIdentifier(uri, documentVersion), digest)), deadline, execution);
|
||||
analysis = mapper.convertValue(mapper.readTree(gson.toJson(retained)), Map.class);
|
||||
}
|
||||
currentDiagnostics = await(diagnostics, deadline, execution);
|
||||
@@ -283,9 +292,12 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
output.put("analysis", analysis);
|
||||
output.put("context", ImmutableJson.fields("projectRoot", context.projectRoot().toString(),
|
||||
"taskId", task.value(), "clientRequestId", null, "buildId", null, "queryId", execution.queryId(), "analysisId", analysis.get("analysisId"),
|
||||
"document", document == null ? null : ImmutableJson.fields("uri", uri, "version", 1, "sha256", digest),
|
||||
"document", document == null ? null : ImmutableJson.fields("uri", uri, "version", documentVersion, "sha256", digest),
|
||||
"inputs", analysis.getOrDefault("inputs", List.of()), "externalRevision", externalRevision,
|
||||
"inputCoverage", "partial", "configuration", analysis.getOrDefault("configuration", Map.of())));
|
||||
if(internal!=null)internal.verify(connection.embedded);
|
||||
if(document!=null&&overlay==null&&!sha256(Files.readString(document)).equals(digest))
|
||||
throw failure(AutomationFailure.Code.LANGUAGE_QUERY_REVISION_MISMATCH,"Saved source changed during language query");
|
||||
succeeded = true;
|
||||
return Collections.unmodifiableMap(output);
|
||||
} catch (Exception failure) {
|
||||
@@ -305,9 +317,37 @@ public final class AutomationLspQueries implements LanguageQueryPort {
|
||||
execution.record(AutomationFailure.Code.LANGUAGE_QUERY_CLEANUP_FAILED, "Could not release query external sources", Map.of());
|
||||
} finally { if (interrupted) Thread.currentThread().interrupt(); }
|
||||
}
|
||||
listening.cancel(true);
|
||||
}
|
||||
} finally { execution.finishWorkers(workers); }
|
||||
}
|
||||
}
|
||||
|
||||
private final class Connection implements AutoCloseable {
|
||||
final ExternalSourceLanguageServer server;
|
||||
final InProcessLanguageWorkspace.Connection embedded;
|
||||
final Socket socket; final ExecutorService workers; final Future<?> listening;
|
||||
final LanguageQueryExecution execution;
|
||||
Connection(ExternalSourceLanguageServer server,InProcessLanguageWorkspace.Connection embedded,Socket socket,
|
||||
ExecutorService workers,Future<?> listening,LanguageQueryExecution execution) {
|
||||
this.server=server;this.embedded=embedded;this.socket=socket;this.workers=workers;this.listening=listening;this.execution=execution;
|
||||
}
|
||||
public void close() throws Exception {
|
||||
if(embedded!=null){embedded.close();return;}
|
||||
try{listening.cancel(true);socket.close();}finally{execution.finishWorkers(workers);}
|
||||
}
|
||||
}
|
||||
private Connection connect(p.studio.lsp.messages.LspProjectContext binding,p.studio.lsp.messages.LspServerEndpoint endpoint,
|
||||
LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) throws Exception {
|
||||
if(internal!=null){var embedded=internal.connect(binding,client,execution,overlays);return new Connection(embedded.server,embedded,null,null,null,execution);}
|
||||
var workers=Executors.newCachedThreadPool();var socket=new Socket();
|
||||
try {
|
||||
execution.own(()->{try{socket.close();}catch(java.io.IOException ignored){}});execution.own(workers::shutdownNow);
|
||||
if(!InetAddress.getByName(endpoint.host()).isLoopbackAddress())throw failure(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project LSP endpoint is not local");
|
||||
socket.connect(new InetSocketAddress(endpoint.host(),endpoint.port()),2000);
|
||||
var launcher=new Launcher.Builder<ExternalSourceLanguageServer>().setLocalService(client)
|
||||
.setRemoteInterface(ExternalSourceLanguageServer.class).setInput(socket.getInputStream()).setOutput(socket.getOutputStream()).setExecutorService(workers).create();
|
||||
var listening=launcher.startListening();execution.own(()->listening.cancel(true));
|
||||
return new Connection(launcher.getRemoteProxy(),null,socket,workers,listening,execution);
|
||||
}catch(Exception failure){socket.close();execution.finishWorkers(workers);throw failure;}
|
||||
}
|
||||
|
||||
private static String sha256(String text) throws java.security.NoSuchAlgorithmException {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package p.studio.app.lsp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.eclipse.lsp4j.services.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.ProjectLanguageService;
|
||||
import p.studio.core.language.LanguageQueryExecution;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
import p.studio.lsp.messages.LspProjectContext;
|
||||
import p.studio.lsp.services.compiler.*;
|
||||
import p.studio.lsp.services.protocol.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
/** Project-owned language engine. No sockets, launchers, discovery files, or UI types. */
|
||||
public final class InProcessLanguageWorkspace implements LspLifecyclePort, AutoCloseable {
|
||||
private final Map<Path,Workspace> projects=new ConcurrentHashMap<>();
|
||||
private final CompilerLanguageServiceBridge bridge;
|
||||
private final AutomationLspQueries queries;
|
||||
private volatile boolean closed;
|
||||
private static final class Workspace {
|
||||
final ExternalSourceRegistry sources=new ExternalSourceRegistry();
|
||||
final Semaphore admission=new Semaphore(1,true);
|
||||
final Set<Connection> connections=ConcurrentHashMap.newKeySet();
|
||||
final Map<String,ProjectLanguageService.Document> editorVersions=new ConcurrentHashMap<>();
|
||||
final Set<CompletableFuture<?>> pending=ConcurrentHashMap.newKeySet();
|
||||
final TaskIdentity editor;
|
||||
final ProjectReference project;
|
||||
final ThreadPoolExecutor requests=executor("studio-editor-language",16);
|
||||
volatile boolean closing;
|
||||
volatile java.util.function.Supplier<ManualLease> editing;
|
||||
Workspace(ProjectReference project){this.project=project;editor=new TaskIdentity(key(project.rootPath()),UUID.randomUUID().toString());}
|
||||
}
|
||||
public InProcessLanguageWorkspace(p.animation.GlyphBankLayoutSource layouts,
|
||||
p.animation.AnimationOriginNavigation navigation,ProjectCatalog catalog,ProjectKnowledge knowledge,ObjectMapper mapper) {
|
||||
bridge=new CompilerLanguageServiceBridge(layouts,navigation);
|
||||
queries=new AutomationLspQueries(this,catalog,knowledge,mapper);
|
||||
}
|
||||
public AutomationLspQueries savedQueries(){return queries;}
|
||||
private static ThreadPoolExecutor executor(String name,int capacity) {
|
||||
return new ThreadPoolExecutor(1,1,0,TimeUnit.SECONDS,new ArrayBlockingQueue<>(capacity),
|
||||
Thread.ofPlatform().daemon().name(name+"-",0).factory(),new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
private static Path key(Path root){try{return root.toRealPath();}catch(java.io.IOException failure){throw new IllegalStateException("Project root is unavailable",failure);}}
|
||||
@Override public synchronized void boot(ProjectReference project) {
|
||||
if(closed)throw new IllegalStateException("Language services are closing");
|
||||
Path root=key(project.rootPath());
|
||||
if(projects.putIfAbsent(root,new Workspace(project))!=null)throw new IllegalStateException("Project language service already open");
|
||||
}
|
||||
public boolean available(LspProjectContext context){var w=projects.get(key(context.projectRoot()));return w!=null&&!w.closing&&w.project.languageId().equals(context.languageId());}
|
||||
private Workspace require(LspProjectContext context) {
|
||||
var workspace=projects.get(key(context.projectRoot()));
|
||||
if(workspace==null||workspace.closing||!workspace.project.languageId().equals(context.languageId()))throw new AutomationException(AutomationFailure.Code.LANGUAGE_SERVER_UNAVAILABLE,"Project language service is not running");
|
||||
return workspace;
|
||||
}
|
||||
public void verify(Connection connection) {
|
||||
if(connection.workspace.closing||projects.get(connection.root)!=connection.workspace)
|
||||
throw new AutomationException(AutomationFailure.Code.CLOSED,"Project language session was closed");
|
||||
}
|
||||
Connection connect(LspProjectContext context,LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) throws Exception {
|
||||
var workspace=require(context);
|
||||
if(!workspace.admission.tryAcquire(Math.max(1,execution.deadlineNanos()-System.nanoTime()),TimeUnit.NANOSECONDS))
|
||||
throw new TimeoutException("Language admission budget expired");
|
||||
try {
|
||||
if(workspace.closing)throw new IllegalStateException("Project language service is closing");
|
||||
var connection=new Connection(key(context.projectRoot()),workspace,context,client,execution,overlays);
|
||||
workspace.connections.add(connection);return connection;
|
||||
}catch(Throwable failure){workspace.admission.release();throw failure;}
|
||||
}
|
||||
void endTask(TaskIdentity task,String consumer) {
|
||||
var workspace=projects.get(key(task.projectRoot()));
|
||||
if(workspace==null||workspace.closing)return;
|
||||
workspace.sources.connect(consumer,true);workspace.sources.release(consumer,null);
|
||||
}
|
||||
@Override public ProjectLanguageService language(ProjectReference project) {
|
||||
var context=LspLifecycleAdapter.context(project);var workspace=require(context);
|
||||
return new ProjectLanguageService() {
|
||||
@Override public void closeDocument(String uri) {
|
||||
try(var lease=workspace.editing.get()){workspace.editorVersions.remove(uri);}
|
||||
}
|
||||
@Override public CompletionStage<Result> query(Request request) {
|
||||
var response=new CompletableFuture<ProjectLanguageService.Result>();
|
||||
if(workspace.closing){response.completeExceptionally(new IllegalStateException("Project language service is closing"));return response;}
|
||||
var document=request.document();
|
||||
if(document!=null) {
|
||||
try {
|
||||
if(!Objects.equals(workspace.editorVersions.get(document.uri()),document)) {
|
||||
if(workspace.editing==null)throw new IllegalStateException("Editor admission is not bound");
|
||||
try(var lease=workspace.editing.get()) {
|
||||
Path path=Path.of(java.net.URI.create(document.uri())).toRealPath();
|
||||
if(!path.startsWith(key(project.rootPath())))throw new IllegalArgumentException("Overlay is outside the project");
|
||||
if(document.text().getBytes(java.nio.charset.StandardCharsets.UTF_8).length>4*1024*1024)
|
||||
throw new IllegalArgumentException("Editor document exceeds 4 MiB");
|
||||
var prior=workspace.editorVersions.compute(document.uri(),(uri,value)->value==null||document.version()>value.version()?document:value);
|
||||
if(!prior.equals(document))throw new IllegalArgumentException("Obsolete or conflicting editor document version");
|
||||
}
|
||||
}
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
var snapshot=Map.copyOf(workspace.editorVersions);
|
||||
var overlays=new HashMap<Path,String>();
|
||||
snapshot.values().forEach(d->overlays.put(Path.of(java.net.URI.create(d.uri())).toAbsolutePath().normalize(),d.text()));
|
||||
workspace.pending.add(response);response.whenComplete((v,f)->workspace.pending.remove(response));
|
||||
try {
|
||||
var work=workspace.requests.submit(()->{
|
||||
try {
|
||||
if(workspace.closing||response.isCancelled())throw new CancellationException("Project language request cancelled");
|
||||
var value=queries.queryEditor(workspace.editor,request,overlays);
|
||||
if(workspace.closing||projects.get(key(project.rootPath()))!=workspace
|
||||
||!workspace.editorVersions.equals(snapshot))
|
||||
throw new AutomationException(AutomationFailure.Code.LANGUAGE_QUERY_REVISION_MISMATCH,"Editor revision was superseded");
|
||||
response.complete(new ProjectLanguageService.Result(value));
|
||||
}catch(Throwable failure){response.completeExceptionally(failure);}
|
||||
});
|
||||
response.whenComplete((v,f)->{if(response.isCancelled())work.cancel(true);});
|
||||
}catch(RejectedExecutionException full){response.completeExceptionally(new IllegalStateException("Project language queue is full or closing",full));}
|
||||
return response;
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override public DocumentHandoff documents(ProjectReference project,java.util.function.Supplier<ManualLease> editing) {
|
||||
var workspace=require(LspLifecycleAdapter.context(project));workspace.editing=Objects.requireNonNull(editing);
|
||||
return new DocumentHandoff() {
|
||||
public CompletionStage<Boolean> hasUnsavedChanges() {
|
||||
try {
|
||||
for(var document:workspace.editorVersions.values())
|
||||
if(!java.nio.file.Files.readString(Path.of(java.net.URI.create(document.uri()))).equals(document.text()))
|
||||
return CompletableFuture.completedFuture(true);
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
public CompletionStage<Void> saveAll() {
|
||||
// Persistence belongs to the editor. Admission must never silently write drafts.
|
||||
return hasUnsavedChanges().thenAccept(dirty->{if(dirty)throw new IllegalStateException("Save the editor documents explicitly");});
|
||||
}
|
||||
public CompletionStage<Void> refreshFromDisk() {
|
||||
try {
|
||||
var refreshed=new HashMap<String,ProjectLanguageService.Document>();
|
||||
for(var document:workspace.editorVersions.values()) {
|
||||
Path path=Path.of(java.net.URI.create(document.uri()));
|
||||
if(java.nio.file.Files.isRegularFile(path))refreshed.put(document.uri(),new ProjectLanguageService.Document(
|
||||
document.uri(),Math.addExact(document.version(),1),java.nio.file.Files.readString(path)));
|
||||
}
|
||||
workspace.editorVersions.clear();workspace.editorVersions.putAll(refreshed);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}catch(Exception failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
};
|
||||
}
|
||||
@Override public void shutdown(ProjectReference project) {
|
||||
Path root=key(project.rootPath());var workspace=projects.get(root);if(workspace==null)return;
|
||||
workspace.closing=true;workspace.requests.shutdownNow();workspace.connections.forEach(Connection::cancel);
|
||||
workspace.pending.forEach(f->f.completeExceptionally(new IllegalStateException("Project language service closed")));
|
||||
boolean interrupted=Thread.interrupted();
|
||||
try {
|
||||
if(!workspace.requests.awaitTermination(2,TimeUnit.SECONDS)||workspace.connections.stream().anyMatch(c->!c.workers.isTerminated()))
|
||||
throw new IllegalStateException("Project language workers have not terminated; retry cleanup");
|
||||
queries.endTask(workspace.editor);workspace.sources.close();projects.remove(root,workspace);
|
||||
}catch(InterruptedException stop){interrupted=true;throw new IllegalStateException("Language cleanup interrupted",stop);}
|
||||
finally{if(interrupted)Thread.currentThread().interrupt();}
|
||||
}
|
||||
@Override public void close(){closed=true;for(var workspace:List.copyOf(projects.values()))shutdown(workspace.project);}
|
||||
|
||||
final class Connection implements AutoCloseable {
|
||||
final Path root;final Workspace workspace;
|
||||
final ThreadPoolExecutor workers=executor("studio-internal-language",32);
|
||||
final PrometeuLanguageServer implementation;
|
||||
final ExternalSourceLanguageServer server;
|
||||
final LanguageQueryExecution execution;
|
||||
final AtomicReference<Throwable> failure=new AtomicReference<>();
|
||||
final AtomicBoolean disposed=new AtomicBoolean();
|
||||
Connection(Path root,Workspace workspace,LspProjectContext context,LanguageClient client,LanguageQueryExecution execution,Map<Path,String> overlays) {
|
||||
this.root=root;this.workspace=workspace;this.execution=execution;
|
||||
implementation=new PrometeuLanguageServer(context,bridge.withOverlays(overlays),workspace.sources);implementation.connect(client);
|
||||
server=proxy(ExternalSourceLanguageServer.class,implementation);
|
||||
execution.own(this::cancel);
|
||||
}
|
||||
void cancel(){workers.shutdownNow();}
|
||||
@SuppressWarnings("unchecked") <T>T proxy(Class<T> type,Object target) {
|
||||
return (T)Proxy.newProxyInstance(type.getClassLoader(),new Class<?>[]{type},(self,method,args)->{
|
||||
if(method.getDeclaringClass()==Object.class)return method.invoke(target,args);
|
||||
if(method.getName().equals("getTextDocumentService"))return proxy(TextDocumentService.class,implementation.getTextDocumentService());
|
||||
if(method.getName().equals("getWorkspaceService"))return proxy(WorkspaceService.class,implementation.getWorkspaceService());
|
||||
var result=new CompletableFuture<Object>();
|
||||
try {workers.execute(()->{
|
||||
try {
|
||||
verify(this);if(failure.get()!=null)throw new CompletionException(failure.get());
|
||||
Object value=method.invoke(target,args);
|
||||
if(value instanceof CompletableFuture<?> pending) {
|
||||
execution.own(()->pending.cancel(true));
|
||||
pending.whenComplete((v,f)->{if(f==null)result.complete(v);else result.completeExceptionally(f);});
|
||||
}else result.complete(value);
|
||||
}catch(Throwable problem){Throwable cause=problem instanceof InvocationTargetException invoked?invoked.getCause():problem;failure.compareAndSet(null,cause);result.completeExceptionally(cause);}
|
||||
});}catch(RejectedExecutionException rejected){result.completeExceptionally(rejected);}
|
||||
return method.getReturnType()==void.class?null:result;
|
||||
});
|
||||
}
|
||||
@Override public void close() {
|
||||
if(!disposed.compareAndSet(false,true))return;
|
||||
execution.finishWorkers(workers);
|
||||
try{implementation.disconnected();}finally{workspace.connections.remove(this);workspace.admission.release();}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,14 @@ import java.util.Optional;
|
||||
/** Projects connection liveness and permanent setup independently of task authority. */
|
||||
public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
public static final String INSTRUCTIONS = """
|
||||
Use the Studio tools for this project. Wait for the developer to grant access in DEV, then acquire control.
|
||||
Use the Studio tools for this open project. In an integrated Studio conversation, activity admission is owned by Studio.
|
||||
The installed Studio connector discovers the connection automatically; do not write transport scripts or copy tokens.
|
||||
Connect and list available tools. Read studio_project_context for the explicit projectRoot and consult
|
||||
studio_reference_read for the declared languages, SDK and libraries before editing as needed.
|
||||
Do not assume PBS or another language when support/documentation is missing; report the limitation.
|
||||
Wait for the developer to grant control in DEV, then call studio_control_acquire. Copying or connecting
|
||||
does not grant permission. Use the returned taskId for all work and operate only on this project.
|
||||
Call studio_control_acquire to obtain the current integrated activity taskId. Connection authentication
|
||||
does not create editing authority. If no integrated activity is active, an external client requires an
|
||||
explicit human grant in the legacy DEV interface. Use the returned taskId only for this project/activity.
|
||||
Edit saved project files with your native tools; SDK and external libraries are read-only.
|
||||
Discover language operations and required parameters in studio_language_query.inputSchema or
|
||||
studio_project_context.languageQuery. languages[].capabilities describes provider support, not
|
||||
@@ -50,8 +51,8 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
explicit studio_tests_shutdown policy; do not infer consent to discard pending/unsaved data.
|
||||
Release errors retain final authority and cleanup in details.control: taskRevoked means the old task
|
||||
cannot be reused even when cleanup failed. The authenticated studio_project_context exposes current
|
||||
control/runtime observations when the connection is available; otherwise inspect DEV and obtain a
|
||||
fresh human grant. Never treat the need to inspect cleanup as permission to reuse a revoked identity.
|
||||
control/runtime observations when the connection is available; otherwise inspect Studio and start a
|
||||
fresh activity (or obtain an explicit legacy external grant). Never treat the need to inspect cleanup as permission to reuse a revoked identity.
|
||||
For asset authoring, inspect studio_assets_catalog, studio_assets_artifacts, studio_assets_inspect,
|
||||
studio_assets_dependencies and studio_assets_budget. Freeze studio_assets_revision before
|
||||
studio_assets_preview. Review changed files/hashes, producer diagnostics and affected references;
|
||||
@@ -69,13 +70,14 @@ public final class McpConnectionGuide implements AgentConnectionGuide {
|
||||
are exact. Read the verdict, metrics, normalized ROI/masks, hashes and expected/actual/diff IDs.
|
||||
Use studio_evidence_image for direct PNG content and studio_evidence_read for bounded bytes.
|
||||
Recover a lost publication response via studio_evidence_list requestId or identical request parameters;
|
||||
never replay guest work. Evidence survives release/rebuild/reopen, but a fresh task grant is required.
|
||||
never replay guest work. Evidence survives release/rebuild/reopen, but a fresh activity task is required.
|
||||
Quota refusal includes used/required/limit; deletion is explicit and reference-aware. Baseline approval
|
||||
is a human manual-control action in the DEV inspector; never promote a failed comparison automatically.
|
||||
Observe headless images/state when those tools are available, and explicitly studio_control_release
|
||||
when finished. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
when finished. In integrated mode, release is an acknowledgement; Studio retains editing protection
|
||||
until the prompt, tools and cleanup actually finish. On revocation stop external edits too: Studio cannot stop your native file writes.
|
||||
Existing edits are preserved. Git/review/recovery remain the developer's responsibility.
|
||||
After Studio restart, wait for a fresh human grant. The connector reconnects automatically; old task identities are invalid.
|
||||
After Studio restart, wait for a fresh integrated activity or explicit legacy external grant. The connector reconnects automatically; old task identities are invalid.
|
||||
""";
|
||||
private final LocalMcpServer server;
|
||||
private final ProjectAccessRegistry projects;
|
||||
|
||||
@@ -62,7 +62,7 @@ public final class StudioAgentPreparation implements AgentIntegrationPreparation
|
||||
try { Files.writeString(temporary, setupText); Files.move(temporary, setup, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
finally { Files.deleteIfExists(temporary); }
|
||||
}
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Then grant access in DEV; no token copying or restart reconfiguration is needed.");
|
||||
return new Result(true, "Assistant prepared. Trust this project in your client and reload MCP once if requested. Studio reserves editing before each integrated prompt; no token copying or restart reconfiguration is needed.");
|
||||
} catch (ManagedStudioInstallation.MissingInstallation missing) { return new Result(false, missing.getMessage()); }
|
||||
catch (Conflict conflict) { return new Result(false, conflict.getMessage()); }
|
||||
catch (Exception failure) { return new Result(false, "Preparation incomplete. Check the Studio installation and project/configuration permissions; existing client settings were not deliberately replaced."); }
|
||||
|
||||
@@ -267,7 +267,7 @@
|
||||
{
|
||||
"name": "studio_control_acquire",
|
||||
"authority": "granted",
|
||||
"description": "Acquire the task after explicit human grant in DEV. Authentication alone is insufficient.",
|
||||
"description": "Obtain the task admitted for the integrated Studio activity, or acquire after an explicit legacy external human grant. Authentication alone is insufficient.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -381,7 +381,7 @@
|
||||
{
|
||||
"name": "studio_control_release",
|
||||
"authority": "task",
|
||||
"description": "Invalidate this task, stop managed work and refresh documents before manual return. Return and cleanup are independent; errors retain authority/cleanup in details.control and native cause when available.",
|
||||
"description": "In integrated mode acknowledge release intent while Studio retains editing protection until activity finalization. In legacy external mode invalidate this task, stop managed work and refresh before manual return. Return and cleanup are independent; errors retain authority/cleanup in details.control and native cause when available.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -393,7 +393,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -513,7 +513,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"operation": {
|
||||
"type": "string",
|
||||
@@ -1210,7 +1210,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"clientRequestId": {
|
||||
"type": "string",
|
||||
@@ -1330,7 +1330,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"buildId": {
|
||||
"type": "string",
|
||||
@@ -1491,7 +1491,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"discardUnsaved": {
|
||||
"type": "boolean",
|
||||
@@ -1621,7 +1621,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1741,7 +1741,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1870,7 +1870,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -1990,7 +1990,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -2110,7 +2110,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"discardUnsaved": {
|
||||
"type": "boolean",
|
||||
@@ -2240,7 +2240,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"input": {
|
||||
"type": "object",
|
||||
@@ -2437,7 +2437,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"clientRequestId": {
|
||||
"type": "string",
|
||||
@@ -2558,7 +2558,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"operationId": {
|
||||
"type": "string",
|
||||
@@ -2874,7 +2874,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"operationId": {
|
||||
"type": "string",
|
||||
@@ -2988,7 +2988,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -3108,7 +3108,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
@@ -3249,7 +3249,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -3369,7 +3369,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -3489,7 +3489,7 @@
|
||||
"taskId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Current task identity obtained after human grant."
|
||||
"description": "Current task identity obtained for the admitted activity or legacy external human grant."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -24,6 +24,12 @@ class StudioApplicationConfigurationTest {
|
||||
final ExecutorService executor = context.getBean(ExecutorService.class);
|
||||
final var mcp = context.getBean(p.studio.app.mcp.LocalMcpServer.class);
|
||||
try (context) {
|
||||
org.junit.jupiter.api.Assertions.assertEquals(1,
|
||||
context.getBeansOfType(p.studio.core.session.LspLifecyclePort.class).size());
|
||||
org.junit.jupiter.api.Assertions.assertSame(
|
||||
context.getBean(p.studio.app.lsp.InProcessLanguageWorkspace.class),
|
||||
context.getBean(p.studio.core.session.LspLifecyclePort.class));
|
||||
assertNotNull(context.getBean(p.studio.api.session.ProjectSessionFactory.class));
|
||||
assertNotNull(context.getBean(StudioUiFactory.class));
|
||||
assertNotNull(context.getBean(PackerWorkspaceService.class));
|
||||
assertNotNull(context.getBean(OperationExecutor.class));
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package p.studio.app;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** Checks the real application bean definitions without starting transports or JavaFX. */
|
||||
class StudioLanguageCompositionTest {
|
||||
@Test void projectLanguageLifecycleHasOneAutowireCandidate() {
|
||||
try (var context = new AnnotationConfigApplicationContext()) {
|
||||
context.register(StudioApplicationConfiguration.class);
|
||||
var beans = context.getDefaultListableBeanFactory();
|
||||
new ConfigurationClassPostProcessor().postProcessBeanDefinitionRegistry(beans);
|
||||
assertEquals(1, beans.getBeanNamesForType(LspLifecyclePort.class, false, false).length,
|
||||
"Project session lifecycle must resolve without name-based injection or qualifiers");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ public final class AcpFixture {
|
||||
if(text.equals("permission")){
|
||||
pendingPrompt=id;
|
||||
var request=JSON.createObjectNode().put("jsonrpc","2.0").put("method","session/request_permission").put("id","permit");
|
||||
var params=request.putObject("params").put("sessionId",session);params.putObject("toolCall").put("title","Run fixture action");
|
||||
var params=request.putObject("params").put("sessionId",session);params.putObject("toolCall").put("title","Run fixture action sk-ARTIFICIAL_SENTINEL").put("rawInput","Bearer ARTIFICIAL_SENTINEL");
|
||||
params.putArray("options").addObject().put("optionId","yes").put("name","Allow once").put("kind","allow_once");send(request);break;
|
||||
}
|
||||
if(text.equals("tools")){
|
||||
|
||||
@@ -44,7 +44,7 @@ class CodexAcpConnectionTest {
|
||||
}
|
||||
@Test void permissionIsNeverGrantedWithoutAnExplicitChoice()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());
|
||||
var choice=new CompletableFuture<String>();c.permissions(p->{assertEquals(id,p.sessionId());return choice;});
|
||||
var choice=new CompletableFuture<String>();c.permissions(p->{assertEquals(id,p.sessionId());assertFalse(p.title().contains("ARTIFICIAL_SENTINEL"));assertFalse(p.details().contains("ARTIFICIAL_SENTINEL"));assertTrue(p.details().contains("[redacted]"));return choice;});
|
||||
var turn=c.prompt(id,"permission");assertFalse(turn.completion().toCompletableFuture().isDone());
|
||||
choice.complete("invalid-option");await(turn.completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("cancelled"));
|
||||
|
||||
@@ -40,10 +40,17 @@ class AutomationLspQueriesTest {
|
||||
Files.writeString(source.resolveSibling("mod.barrel"), "pub fn helper() -> int;\npub fn main() -> int;\n");
|
||||
var setup = new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog = new ProjectCatalogService(temporary, mapper, setup);
|
||||
session = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup,
|
||||
new LspLifecycleAdapter(lifecycle), access, new ExecutorOperationExecutor(workers)).open(catalog.openProject(root));
|
||||
knowledge = new CompilerProjectKnowledge(access, catalog, mapper);
|
||||
queries = new TaskLanguageQueries(access, new AutomationLspQueries(lifecycle, catalog, knowledge, mapper));
|
||||
session = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup,
|
||||
languageLifecycle(catalog), access, new ExecutorOperationExecutor(workers)).open(catalog.openProject(root));
|
||||
queries = new TaskLanguageQueries(access, languageQueries(catalog));
|
||||
}
|
||||
p.studio.core.session.LspLifecyclePort languageLifecycle(ProjectCatalogService catalog){return new LspLifecycleAdapter(lifecycle);}
|
||||
p.studio.core.language.LanguageQueryPort languageQueries(ProjectCatalogService catalog){return new AutomationLspQueries(lifecycle,catalog,knowledge,mapper);}
|
||||
void closeLanguageAndAssertUnavailable(p.studio.lsp.messages.LspProjectContext context) throws Exception {
|
||||
var endpoint=lifecycle.endpoint(context).orElseThrow();session.close();session=null;
|
||||
assertTrue(lifecycle.endpoint(context).isEmpty());
|
||||
assertThrows(java.io.IOException.class,()->new java.net.Socket(endpoint.host(),endpoint.port()));
|
||||
}
|
||||
@AfterEach void close() { if (session != null) session.close(); workers.shutdownNow(); }
|
||||
void acquire() {
|
||||
@@ -254,10 +261,7 @@ class AutomationLspQueriesTest {
|
||||
() -> query("diagnostics", Map.of("uri", outside.toUri().toString()))).failure().code());
|
||||
assertThrows(IllegalArgumentException.class, () -> query("definition", at(999, 0)));
|
||||
var context = LspLifecycleAdapter.context(session.projectReference());
|
||||
var endpoint = lifecycle.endpoint(context).orElseThrow();
|
||||
session.close(); session = null;
|
||||
assertTrue(lifecycle.endpoint(context).isEmpty());
|
||||
assertThrows(java.io.IOException.class, () -> new java.net.Socket(endpoint.host(), endpoint.port()));
|
||||
closeLanguageAndAssertUnavailable(context);
|
||||
assertEquals(AutomationFailure.Code.PROJECT_NOT_OPEN, assertThrows(AutomationException.class,
|
||||
() -> query("diagnostics", at(0, 0))).failure().code());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package p.studio.app.lsp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.session.*;
|
||||
import p.studio.app.compiler.CompilerProjectKnowledge;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.session.*;
|
||||
import p.studio.core.language.TaskLanguageQueries;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Component contract against the actual compiler and in-memory language backend. No transport. */
|
||||
class InProcessLanguageWorkspaceTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper json=new ObjectMapper();
|
||||
final ExecutorService workers=Executors.newVirtualThreadPerTaskExecutor();
|
||||
final ProjectAccessRegistry access=new ProjectAccessRegistry();
|
||||
InProcessLanguageWorkspace language;ProjectSession session;DefaultProjectSessionFactory factory;ProjectCatalogService catalog;TaskLanguageQueries queries;Path root,source;String task;
|
||||
volatile boolean holdContext;
|
||||
final CountDownLatch entered=new CountDownLatch(1),resume=new CountDownLatch(1);
|
||||
volatile String analysisThread;
|
||||
static final String CODE="fn helper() -> int { return 1; }\nfn main() -> int { return helper(); }\n[Frame] fn frame() -> void {}\n";
|
||||
@BeforeEach void open() throws Exception {
|
||||
root=Files.createDirectory(temporary.resolve("app")).toRealPath();
|
||||
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
|
||||
source=Files.createDirectories(root.resolve("src")).resolve("main.pbs");Files.writeString(source,CODE);
|
||||
Files.writeString(source.resolveSibling("mod.barrel"),"pub fn helper() -> int;\npub fn main() -> int;\npub fn frame() -> void;\n");
|
||||
var setup=new ProjectLocalStudioSetupStore(json);catalog=new ProjectCatalogService(temporary,json,setup);
|
||||
var savedKnowledge=new CompilerProjectKnowledge(access,catalog,json);
|
||||
ProjectKnowledge knowledge=new ProjectKnowledge(){
|
||||
public Context context(Path root) {
|
||||
if(holdContext){
|
||||
analysisThread=Thread.currentThread().getName();entered.countDown();boolean interrupted=false;
|
||||
while(resume.getCount()!=0)try{resume.await();}catch(InterruptedException ignored){interrupted=true;}
|
||||
if(interrupted)Thread.currentThread().interrupt();
|
||||
}
|
||||
return savedKnowledge.context(root);
|
||||
}
|
||||
public ReferencePage readReference(Path root,String id,int offset,int limit){return savedKnowledge.readReference(root,id,offset,limit);}
|
||||
};
|
||||
language=new InProcessLanguageWorkspace(null,null,catalog,knowledge,json);
|
||||
factory=new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(json),setup,language,access,
|
||||
new ExecutorOperationExecutor(workers));session=factory.openForPlay(catalog.openProject(root));
|
||||
queries=new TaskLanguageQueries(access,language.savedQueries());
|
||||
assertTrue(session.automation().beginIntegratedActivity().toCompletableFuture().join().success());
|
||||
task=session.automation().acquire().task().value();
|
||||
}
|
||||
@AfterEach void close(){resume.countDown();if(factory!=null)factory.close();if(language!=null)language.close();workers.close();}
|
||||
JsonNode query(String operation,Map<String,Object> parameters){return json.valueToTree(queries.query(root,task,operation,parameters));}
|
||||
Map<String,Object> at(int line,int character){return Map.of("uri",source.toUri().toString(),"position",Map.of("line",line,"character",character));}
|
||||
@Test void allTwentyOperationsAndTaskOwnedSourcesSurviveWithoutTcp() throws Exception {
|
||||
var catalog=new p.studio.app.mcp.McpToolCatalog(json);
|
||||
var sdk=source.resolveSibling("sdk.pbs");String function="fn sdk() -> void { Gfx.clear(0); }";
|
||||
Files.writeString(sdk,"import { Gfx } from @sdk:gfx;\n"+function+"\n");
|
||||
Files.writeString(source.resolveSibling("mod.barrel"),"pub fn helper() -> int;\npub fn main() -> int;\npub fn frame() -> void;\npub fn sdk() -> void;\n");
|
||||
String external=query("definition",Map.of("uri",sdk.toUri().toString(),"position",Map.of("line",1,"character",function.indexOf("clear")+1))).path("result").get(0).path("uri").asText();
|
||||
assertTrue(external.startsWith("prometeu-source:"));
|
||||
String item=query("prepareCallHierarchy",at(0,4)).path("result").get(0).path("itemId").asText();
|
||||
var values=new HashMap<>(at(1,26));values.put("newName","renamed");values.put("itemId",item);
|
||||
values.put("positions",List.of(Map.of("line",0,"character",4)));
|
||||
values.put("range",Map.of("start",Map.of("line",0,"character",0),"end",Map.of("line",0,"character",10)));
|
||||
var invoked=new HashSet<String>();
|
||||
for(var description:catalog.languageQueryDescription().path("operations")) {
|
||||
String operation=description.path("operation").asText();var parameters=new HashMap<String,Object>();
|
||||
description.path("requiredParameters").forEach(k->parameters.put(k.asText(),values.get(k.asText())));
|
||||
if(operation.equals("readExternalSource"))parameters.put("uri",external);
|
||||
assertEquals(operation,query(operation,parameters).path("operation").asText());invoked.add(operation);
|
||||
}
|
||||
assertEquals(20,invoked.size());assertEquals(CODE,Files.readString(source));assertFalse(Files.exists(root.resolve(".studio/lsp.json")));
|
||||
session.automation().finishIntegratedActivity(false).toCompletableFuture().join();
|
||||
session.automation().beginIntegratedActivity().toCompletableFuture().join();task=session.automation().acquire().task().value();
|
||||
assertThrows(IllegalArgumentException.class,()->query("incomingCalls",Map.of("itemId",item)));
|
||||
assertThrows(AutomationException.class,()->query("readExternalSource",Map.of("uri",external)));
|
||||
}
|
||||
@Test void editorAndSavedQueriesHaveIndependentRevisionViewsAndClosingFencesOldService() throws Exception {
|
||||
var editor=session.language();String uri=source.toUri().toString();
|
||||
assertEquals("passed",query("diagnostics",at(0,0)).path("analysis").path("summary").path("validationStatus").asText());
|
||||
session.automation().finishIntegratedActivity(false).toCompletableFuture().join();
|
||||
var invalid=new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(uri,2,"fn main( {"),Map.of());
|
||||
var result=json.valueToTree(editor.query(invalid).toCompletableFuture().get(10,TimeUnit.SECONDS).values());
|
||||
assertFalse(result.path("analysis").path("summary").path("validationStatus").asText().equals("passed"));
|
||||
assertEquals("passed",json.valueToTree(language.savedQueries().query(new TaskIdentity(root,"saved-view-probe"),"diagnostics",at(0,0)))
|
||||
.path("analysis").path("summary").path("validationStatus").asText());
|
||||
assertEquals(ControlResult.Status.DIRTY_DOCUMENTS,session.automation().beginIntegratedActivity().toCompletableFuture().join().status());
|
||||
assertEquals(CODE,Files.readString(source));
|
||||
assertTrue(editor.query(new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(uri,1,CODE),Map.of())).toCompletableFuture().isCompletedExceptionally());
|
||||
editor.closeDocument(uri);
|
||||
assertTrue(session.automation().beginIntegratedActivity().toCompletableFuture().join().success());
|
||||
assertTrue(editor.query(invalid).toCompletableFuture().isCompletedExceptionally());
|
||||
session.close();session=null;
|
||||
assertTrue(editor.query(invalid).toCompletableFuture().isCompletedExceptionally());
|
||||
}
|
||||
@Test void multipleEditorDocumentsShareAnOverlaySnapshotWithoutChangingSavedSources() throws Exception {
|
||||
session.automation().finishIntegratedActivity(false).toCompletableFuture().join();
|
||||
Path extra=source.resolveSibling("extra.pbs");Files.writeString(extra,"fn extra() -> int { return 1; }\n");
|
||||
Files.writeString(source.resolveSibling("mod.barrel"),"pub fn helper() -> int;\npub fn main() -> int;\npub fn frame() -> void;\npub fn extra() -> int;\n");
|
||||
var editor=session.language();
|
||||
editor.query(new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(extra.toUri().toString(),1,
|
||||
"fn extra() -> int { return false; }"),Map.of())).toCompletableFuture().get(10,TimeUnit.SECONDS);
|
||||
var main=new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(source.toUri().toString(),1,CODE),Map.of());
|
||||
var overlaid=json.valueToTree(editor.query(main).toCompletableFuture().get(10,TimeUnit.SECONDS).values());
|
||||
assertNotEquals("passed",overlaid.path("analysis").path("summary").path("validationStatus").asText());
|
||||
editor.closeDocument(extra.toUri().toString());
|
||||
var saved=json.valueToTree(editor.query(main).toCompletableFuture().get(10,TimeUnit.SECONDS).values());
|
||||
assertEquals("passed",saved.path("analysis").path("summary").path("validationStatus").asText());
|
||||
assertEquals("fn extra() -> int { return 1; }\n",Files.readString(extra));
|
||||
}
|
||||
@Test void secondProjectAndReopenDoNotReuseAuthorityOrOldEditorHandles() throws Exception {
|
||||
Path other=Files.createDirectory(temporary.resolve("other"));Files.copy(root.resolve("prometeu.json"),other.resolve("prometeu.json"));
|
||||
Files.createDirectory(other.resolve("src"));Files.copy(source,other.resolve("src/main.pbs"));Files.copy(source.resolveSibling("mod.barrel"),other.resolve("src/mod.barrel"));
|
||||
var second=factory.openForPlay(catalog.openProject(other));
|
||||
assertTrue(second.automation().snapshot().manualAllowed());
|
||||
assertThrows(ControlDeniedException.class,()->queries.query(other,task,"diagnostics",Map.of("uri",other.resolve("src/main.pbs").toUri().toString())));
|
||||
var old=session.language();String oldTask=task;session.close();session=factory.openForPlay(catalog.openProject(root));
|
||||
assertTrue(old.query(new ProjectLanguageService.Request("workspaceSymbols",null,Map.of())).toCompletableFuture().isCompletedExceptionally());
|
||||
assertTrue(session.automation().beginIntegratedActivity().toCompletableFuture().join().success());
|
||||
task=session.automation().acquire().task().value();assertNotEquals(oldTask,task);
|
||||
assertThrows(ControlDeniedException.class,()->queries.query(root,oldTask,"diagnostics",at(0,0)));
|
||||
assertEquals("passed",query("diagnostics",at(0,0)).path("analysis").path("summary").path("validationStatus").asText());
|
||||
assertTrue(second.automation().snapshot().manualAllowed());second.close();
|
||||
}
|
||||
|
||||
@Test void cancellationAndCompletedFutureDoNotPretendTheEditorWorkerTerminated() throws Exception {
|
||||
session.automation().finishIntegratedActivity(false).toCompletableFuture().join();holdContext=true;
|
||||
var editor=session.language();var request=new ProjectLanguageService.Request("workspaceSymbols",null,Map.of());
|
||||
var running=editor.query(request).toCompletableFuture();assertTrue(entered.await(3,TimeUnit.SECONDS));
|
||||
assertTrue(analysisThread.startsWith("studio-editor-language-"));
|
||||
var queued=new ArrayList<CompletableFuture<ProjectLanguageService.Result>>();
|
||||
for(int i=0;i<20;i++)queued.add(editor.query(request).toCompletableFuture());
|
||||
assertTrue(queued.stream().anyMatch(CompletableFuture::isCompletedExceptionally),"Admission must be bounded");
|
||||
running.cancel(true);assertTrue(running.isDone());
|
||||
assertThrows(IllegalStateException.class,session::close,"Cancelled response cannot prove a retained worker stopped");
|
||||
assertFalse(session.automation().snapshot().manualAllowed());
|
||||
holdContext=false;resume.countDown();session.close();
|
||||
assertTrue(queued.stream().allMatch(CompletableFuture::isDone));
|
||||
assertTrue(editor.query(request).toCompletableFuture().isCompletedExceptionally());
|
||||
}
|
||||
@Test void resultFromSupersededEditorSnapshotIsRejectedAfterAnalysis() throws Exception {
|
||||
session.automation().finishIntegratedActivity(false).toCompletableFuture().join();holdContext=true;
|
||||
var editor=session.language();String uri=source.toUri().toString();
|
||||
var first=editor.query(new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(uri,1,CODE),Map.of())).toCompletableFuture();
|
||||
assertTrue(entered.await(3,TimeUnit.SECONDS));
|
||||
var next=editor.query(new ProjectLanguageService.Request("diagnostics",new ProjectLanguageService.Document(uri,2,CODE+"\n"),Map.of())).toCompletableFuture();
|
||||
holdContext=false;resume.countDown();
|
||||
assertThrows(ExecutionException.class,()->first.get(10,TimeUnit.SECONDS));
|
||||
assertEquals(2,json.valueToTree(next.get(10,TimeUnit.SECONDS).values()).path("context").path("document").path("version").asInt());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package p.studio.app.lsp;
|
||||
|
||||
import p.studio.core.project.ProjectCatalogService;
|
||||
import p.studio.core.session.LspLifecyclePort;
|
||||
import p.studio.core.language.LanguageQueryPort;
|
||||
import p.studio.lsp.messages.LspProjectContext;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Runs the existing TCP contract cases against the internal backend unchanged. */
|
||||
class InternalLanguageParityTest extends AutomationLspQueriesTest {
|
||||
private InProcessLanguageWorkspace internal;
|
||||
@Override LspLifecyclePort languageLifecycle(ProjectCatalogService catalog) {
|
||||
internal=new InProcessLanguageWorkspace(null,null,catalog,knowledge,mapper);return internal;
|
||||
}
|
||||
@Override LanguageQueryPort languageQueries(ProjectCatalogService catalog){return internal.savedQueries();}
|
||||
@Override void closeLanguageAndAssertUnavailable(LspProjectContext context) {
|
||||
assertTrue(internal.available(context));session.close();session=null;
|
||||
assertFalse(internal.available(context));assertTrue(lifecycle.endpoint(context).isEmpty());
|
||||
assertFalse(java.nio.file.Files.exists(root.resolve(".studio/lsp.json")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import p.studio.api.automation.AgentIntegrationPreparation;
|
||||
import p.studio.app.acp.CodexAcpConnection;
|
||||
import p.studio.app.install.ManagedStudioInstallation;
|
||||
import p.studio.core.project.preferences.JsonAgentSettingsStore;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Opt-in real adapter/model. Uses existing authentication only, never copies or prints credentials. */
|
||||
@Tag("integration")
|
||||
class IntegratedAiLiveTest extends IntegratedAiMcpTest {
|
||||
@TempDir Path installation;
|
||||
@Override protected AgentIntegrationPreparation preparation() throws Exception {
|
||||
ManagedStudioInstallation.install(Path.of(System.getProperty("studio.test.distribution")),installation);
|
||||
return new StudioAgentPreparation(installation,json);
|
||||
}
|
||||
@Override protected AgentConnection peer(Supplier<String> ignored,Executor executor) {
|
||||
return new CodexAcpConnection(root,json);
|
||||
}
|
||||
@Override protected AcpSettings settings() {
|
||||
String executable=System.getProperty("studio.test.codexAcp","");
|
||||
return executable.isBlank()?new JsonAgentSettingsStore(Path.of(System.getProperty("user.home"),
|
||||
".prometeu-studio","ai-settings.json"),json).load():new AcpSettings(executable,List.of());
|
||||
}
|
||||
@Override protected long promptTimeoutSeconds(){return 180;}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package p.studio.app.mcp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.session.ProjectSession;
|
||||
import p.studio.app.compiler.CompilerProjectKnowledge;
|
||||
import p.studio.app.lsp.InProcessLanguageWorkspace;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.core.language.TaskLanguageQueries;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.session.*;
|
||||
import java.net.http.*;
|
||||
import java.nio.file.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Controlled AgentConnection peer, real authenticated HTTP MCP and compiler; no model/ACP wire. */
|
||||
@Tag("integration")
|
||||
class IntegratedAiMcpTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper json=new ObjectMapper();
|
||||
String credential,connection;
|
||||
LocalMcpServer server;
|
||||
HttpClient client;
|
||||
protected AgentIntegrationPreparation preparation() throws Exception {return new AgentIntegrationPreparation(){
|
||||
public Result prepare(Path root){return new Result(true,"controlled fixture preparation");}
|
||||
public Result status(Path root){return prepare(root);}
|
||||
};}
|
||||
protected AgentConnection peer(Supplier<String> work,Executor executor){return new Peer(work,executor);}
|
||||
protected AcpSettings settings(){return new AcpSettings("controlled-peer",List.of());}
|
||||
protected long promptTimeoutSeconds(){return 25;}
|
||||
ObjectNode args(){return json.createObjectNode().put("projectRoot",root.toString());}
|
||||
HttpResponse<String> post(JsonNode body)throws Exception {
|
||||
var request=HttpRequest.newBuilder(server.connection().endpoint()).timeout(Duration.ofSeconds(15))
|
||||
.header("Authorization","Bearer "+credential).header("Content-Type","application/json")
|
||||
.header("Accept","application/json, text/event-stream").header("MCP-Protocol-Version","2025-06-18");
|
||||
if(connection!=null)request.header("Mcp-Session-Id",connection);
|
||||
return client.send(request.POST(HttpRequest.BodyPublishers.ofString(body.toString())).build(),HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
JsonNode call(String name,ObjectNode arguments)throws Exception {
|
||||
var request=json.createObjectNode().put("jsonrpc","2.0").put("id",UUID.randomUUID().toString()).put("method","tools/call");
|
||||
request.putObject("params").put("name",name).set("arguments",arguments);
|
||||
var response=post(request);assertEquals(200,response.statusCode());
|
||||
var result=json.readTree(response.body()).path("result");assertFalse(result.path("isError").asBoolean(),result.toString());
|
||||
return result.path("structuredContent").path("value");
|
||||
}
|
||||
@Test void openingProvidesContextAndIntegratedActivityQueriesWithoutGrantButtons()throws Exception {
|
||||
root=root.toRealPath();
|
||||
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
|
||||
var source=Files.createDirectories(root.resolve("src")).resolve("main.pbs");
|
||||
Files.writeString(source,"[Frame] fn frame() -> void {}\n");Files.writeString(source.resolveSibling("mod.barrel"),"pub fn frame() -> void;\n");
|
||||
String originalSource=Files.readString(source);var preparation=preparation();
|
||||
var setup=new ProjectLocalStudioSetupStore(json);var access=new ProjectAccessRegistry();
|
||||
var catalog=new ProjectCatalogService(root.getParent(),json,setup);var knowledge=new CompilerProjectKnowledge(access,catalog,json);
|
||||
try(var workers=Executors.newVirtualThreadPerTaskExecutor();var language=new InProcessLanguageWorkspace(null,null,catalog,knowledge,json)) {
|
||||
var taskTools=new DefaultTaskTools(access,catalog,(project,sink)->{throw new AssertionError("No build requested");},Optional.empty());
|
||||
var handlers=new HashMap<String,Function<JsonNode,McpToolResult>>();
|
||||
handlers.putAll(McpTaskTools.handlers(taskTools,json,false));handlers.putAll(McpProjectKnowledgeTools.handlers(knowledge,json));
|
||||
handlers.putAll(McpLanguageTools.handlers(new TaskLanguageQueries(access,language.savedQueries()),json));
|
||||
var calls=new ConcurrentHashMap<String,java.util.concurrent.atomic.AtomicInteger>();
|
||||
handlers.replaceAll((name,handler)->arguments->{calls.computeIfAbsent(name,k->new java.util.concurrent.atomic.AtomicInteger()).incrementAndGet();return handler.apply(arguments);});
|
||||
try(var http=new LocalMcpServer(json,new McpToolRegistry(new McpToolCatalog(json),json,handlers));var httpClient=HttpClient.newHttpClient()) {
|
||||
server=http;client=httpClient;server.start();
|
||||
try(var factory=new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(json),setup,language,access,
|
||||
new ExecutorOperationExecutor(workers),new ProjectConnectionPublisher(server,json),preparation)) {
|
||||
ProjectSession session=factory.openForPlay(catalog.openProject(root));
|
||||
assertTrue(session.automation().snapshot().manualAllowed());assertNull(session.automation().snapshot().task());
|
||||
credential=json.readTree(Files.readString(root.resolve(ProjectConnectionFiles.RELATIVE))).path("credential").asText();
|
||||
var initialize=json.createObjectNode().put("jsonrpc","2.0").put("id",1).put("method","initialize");
|
||||
var params=initialize.putObject("params").put("protocolVersion","2025-06-18");
|
||||
params.putObject("capabilities");params.putObject("clientInfo").put("name","controlled-work-peer").put("version","1");
|
||||
var initialized=post(initialize);assertEquals(200,initialized.statusCode());
|
||||
connection=initialized.headers().firstValue("Mcp-Session-Id").orElseThrow();
|
||||
assertEquals(202,post(json.createObjectNode().put("jsonrpc","2.0").put("method","notifications/initialized")).statusCode());
|
||||
assertEquals("app",call("studio_project_context",args()).path("projectName").asText());
|
||||
var events=new CopyOnWriteArrayList<AgentConnection.Event>();
|
||||
calls.clear();
|
||||
AgentConnection peer=peer(()->{
|
||||
try {
|
||||
assertThrows(ControlDeniedException.class,()->access.enterManual(root));
|
||||
call("studio_project_context",args());
|
||||
assertFalse(call("studio_reference_read",args().put("referenceId","pbs:quickstart")).path("text").asText().isBlank());
|
||||
String task=call("studio_control_acquire",args()).path("taskId").asText();assertFalse(task.isBlank());
|
||||
var query=args().put("taskId",task).put("operation","diagnostics");query.putObject("parameters").put("uri",source.toUri().toString());
|
||||
assertEquals("passed",call("studio_language_query",query).path("analysis").path("summary").path("validationStatus").asText());
|
||||
call("studio_control_release",args().put("taskId",task));assertFalse(session.automation().snapshot().manualAllowed());
|
||||
return "end_turn";
|
||||
}catch(Exception failure){throw new CompletionException(failure);}
|
||||
},workers);
|
||||
var agent=new ProjectAgentConnection(peer,session.automation(),()->preparation.status(root),workers);
|
||||
agent.events(events::add);agent.connect(settings()).toCompletableFuture().join();
|
||||
assertEquals(AgentConnection.State.READY,agent.status().state(),"Existing authentication must be available; never start login automatically");
|
||||
String sessionId=agent.newSession().toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
assertEquals("end_turn",agent.prompt(sessionId,"Qualification in this disposable project. Use only the Prometeu Studio MCP tools: "
|
||||
+"read studio_project_context and pbs:quickstart through studio_reference_read, call studio_control_acquire, "
|
||||
+"then studio_language_query diagnostics for src/main.pbs. Use projectRoot "+root+". Report validation status. "
|
||||
+"Do not edit files, execute commands, launch login, run builds or runtime. Release the task when finished.")
|
||||
.completion().toCompletableFuture().get(promptTimeoutSeconds(),TimeUnit.SECONDS));
|
||||
for(String name:List.of("studio_project_context","studio_reference_read","studio_control_acquire","studio_language_query"))
|
||||
assertTrue(calls.getOrDefault(name,new java.util.concurrent.atomic.AtomicInteger()).get()>0,"Missing actual tool call: "+name);
|
||||
assertTrue(events.stream().anyMatch(e->e.kind()==AgentConnection.Kind.TEXT&&!e.text().isBlank()));
|
||||
assertEquals(originalSource,Files.readString(source));
|
||||
assertTrue(session.automation().snapshot().manualAllowed());assertFalse(agent.busy());
|
||||
assertTrue(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)));
|
||||
assertEquals("app",call("studio_project_context",args()).path("projectName").asText());
|
||||
agent.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);session.close();
|
||||
assertFalse(Files.exists(root.resolve(ProjectConnectionFiles.RELATIVE)));assertFalse(Files.exists(root.resolve(".studio/lsp.json")));
|
||||
assertEquals(401,post(initialize).statusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static final class Peer implements AgentConnection {
|
||||
final Supplier<String> work;final Executor executor;Consumer<Event> events=e->{};
|
||||
Peer(Supplier<String> work,Executor executor){this.work=work;this.executor=executor;}
|
||||
public boolean available(){return true;}public Status status(){return new Status(State.READY,"");}
|
||||
public AutoCloseable observe(Consumer<Status> l){l.accept(status());return ()->{};}
|
||||
public void events(Consumer<Event> l){events=l;}public void permissions(Function<Permission,CompletionStage<String>> h){}
|
||||
public CompletionStage<Void> connect(AcpSettings s){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> login(){throw new AssertionError("No login in controlled test");}
|
||||
public CompletionStage<String> newSession(){return CompletableFuture.completedFuture("controlled-session");}
|
||||
public Turn prompt(String session,String text){return new Turn(CompletableFuture.completedFuture(null),CompletableFuture.supplyAsync(()->{
|
||||
var reason=work.get();events.accept(new Event(session,Kind.TEXT,"tool result received"));return reason;
|
||||
},executor));}
|
||||
public CompletionStage<Void> cancel(String s){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> closeAsync(){return CompletableFuture.completedFuture(null);}
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -115,6 +115,16 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
}
|
||||
return new BaselineDefinition(List.copyOf(mapped));
|
||||
}
|
||||
private Map<Path,String> workspaceOverlays=Map.of();
|
||||
/** An immutable request view, sharing the compiler implementation without sharing buffers. */
|
||||
public CompilerLanguageServiceBridge withOverlays(Map<Path,String> overlays) {
|
||||
var view=new CompilerLanguageServiceBridge(frontendProviderResolver,layouts);
|
||||
view.animationNavigation=animationNavigation;view.workspaceOverlays=Map.copyOf(overlays);return view;
|
||||
}
|
||||
private SourceProviderFactory sources(Map<Path,String> current) {
|
||||
var merged=new java.util.HashMap<>(workspaceOverlays);merged.putAll(current);
|
||||
return SourceProviderFactory.overlayUtf8(merged);
|
||||
}
|
||||
private final AssetSurfaceContextLoader assetSurfaceContextLoader;
|
||||
private final p.animation.GlyphBankLayoutSource layouts;
|
||||
private p.animation.AnimationOriginNavigation animationNavigation;
|
||||
@@ -402,7 +412,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
false,
|
||||
context.projectRoot().toString(),
|
||||
"core-v1",
|
||||
SourceProviderFactory.overlayUtf8(Map.of())));
|
||||
sources(Map.of())));
|
||||
pipelineContext.glyphBankLayoutSource=layouts;
|
||||
BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty());
|
||||
final FrontendPhaseContext frontendPhaseContext = new FrontendPhaseContext(
|
||||
@@ -924,7 +934,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
false,
|
||||
context.projectRoot().toString(),
|
||||
"core-v1",
|
||||
SourceProviderFactory.overlayUtf8(overlays)));
|
||||
sources(overlays)));
|
||||
pipelineContext.glyphBankLayoutSource=layouts;
|
||||
return BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty());
|
||||
}
|
||||
@@ -943,7 +953,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg
|
||||
false,
|
||||
context.projectRoot().toString(),
|
||||
"core-v1",
|
||||
SourceProviderFactory.overlayUtf8(text == null ? Map.of() : Map.of(documentPath, text))));
|
||||
sources(text == null ? Map.of() : Map.of(documentPath, text))));
|
||||
pipelineContext.glyphBankLayoutSource=layouts;
|
||||
BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty());
|
||||
final FileId fileId = findFileId(pipelineContext, documentPath);
|
||||
|
||||
@@ -22,6 +22,10 @@ public interface AgentConnection {
|
||||
record Turn(CompletionStage<Void> accepted, CompletionStage<String> completion) { }
|
||||
|
||||
boolean available();
|
||||
/** Includes admission and finalization, not just the active ACP prompt. */
|
||||
default boolean busy() { return false; }
|
||||
default boolean servicesReady() { return true; }
|
||||
default CompletionStage<Void> recoverActivity() { return CompletableFuture.completedFuture(null); }
|
||||
Status status();
|
||||
AutoCloseable observe(Consumer<Status> listener);
|
||||
void events(Consumer<Event> listener);
|
||||
@@ -31,6 +35,8 @@ public interface AgentConnection {
|
||||
CompletionStage<String> newSession();
|
||||
Turn prompt(String sessionId, String text);
|
||||
CompletionStage<Void> cancel(String sessionId);
|
||||
/** After transport failure, proves native work stopped before editing can resume. */
|
||||
default CompletionStage<Void> awaitQuiescence() { return closeAsync(); }
|
||||
CompletionStage<Void> closeAsync();
|
||||
|
||||
static AgentConnection unavailable() {
|
||||
|
||||
@@ -16,7 +16,18 @@ public interface AutomationSession {
|
||||
default CompletionStage<ControlResult> reclaimDiscardingUnsavedGameData() {
|
||||
return java.util.concurrent.CompletableFuture.failedFuture(new UnsupportedOperationException("Runtime discard is unavailable"));
|
||||
}
|
||||
/** Project-owned infrastructure that must stop before close can succeed. */
|
||||
default OperationSubscription registerProjectShutdown(java.util.function.Supplier<CompletionStage<Void>> shutdown) { return ()->{}; }
|
||||
CompletionStage<ControlResult> closeAsync();
|
||||
/** Ensures project MCP publication, without acquiring editing authority. May perform IO. */
|
||||
default ControlResult prepareIntegratedServices() { return ControlResult.of(ControlResult.Status.GRANTED,""); }
|
||||
/** Studio-owned activity; independent of external human grant actions. */
|
||||
default CompletionStage<ControlResult> beginIntegratedActivity() {
|
||||
return java.util.concurrent.CompletableFuture.failedFuture(new UnsupportedOperationException("Integrated activity is unavailable"));
|
||||
}
|
||||
/** Interrupts managed work while retaining the activity reservation until ACP stops. */
|
||||
default void requestIntegratedCancellation() { }
|
||||
default CompletionStage<ControlResult> finishIntegratedActivity(boolean cancel) { return reclaim(); }
|
||||
/** Internal specialized service work, not a generic MCP shell/tool endpoint. */
|
||||
OperationHandle<AutomationOutcome> submit(TaskIdentity task, String summary, Callable<AutomationOutcome> work);
|
||||
/** Null identity is reserved for a local manual service holding an active manual lease. */
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package p.studio.api.session;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/** Project-owned editor view. MCP uses its independently admitted, saved-file view. */
|
||||
public interface ProjectLanguageService {
|
||||
record Document(String uri, int version, String text) {
|
||||
public Document { Objects.requireNonNull(uri); Objects.requireNonNull(text); if(version<0)throw new IllegalArgumentException("Negative document version"); }
|
||||
}
|
||||
record Request(String operation, Document document, Map<String,Object> parameters) {
|
||||
public Request { Objects.requireNonNull(operation); parameters=p.studio.api.values.ValueMaps.object(parameters); }
|
||||
}
|
||||
record Result(Map<String,Object> values) {
|
||||
public Result { values=p.studio.api.values.ValueMaps.object(values); }
|
||||
}
|
||||
CompletionStage<Result> query(Request request);
|
||||
/** Discards an editor overlay only on an explicit editor close/discard action. */
|
||||
default void closeDocument(String uri) { }
|
||||
static ProjectLanguageService unavailable() {
|
||||
return request -> CompletableFuture.failedFuture(new IllegalStateException("Project language service is unavailable"));
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ public interface ProjectSession extends AutoCloseable {
|
||||
ExecutionSession executionSession();
|
||||
|
||||
p.studio.api.automation.AutomationSession automation();
|
||||
default ProjectLanguageService language() { return ProjectLanguageService.unavailable(); }
|
||||
default java.util.Optional<p.studio.api.automation.EvidenceTools> evidenceTools() { return java.util.Optional.empty(); }
|
||||
default java.util.Optional<p.studio.api.automation.GuestTestTools> guestTestTools() { return java.util.Optional.empty(); }
|
||||
default java.util.Optional<p.studio.api.assets.AssetAuthoringService> assetAuthoring() { return java.util.Optional.empty(); }
|
||||
|
||||
+90
-4
@@ -13,8 +13,14 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
private final OperationExecutor executor;
|
||||
private final AutomationConnectionLifecycle connections;
|
||||
private AutomationConnectionLifecycle.Publication connection;
|
||||
private AutomationConnectionLifecycle.Publication projectConnection;
|
||||
private boolean integratedActivity, integratedFinishing;
|
||||
private CompletableFuture<Void> publicationIdle = CompletableFuture.completedFuture(null);
|
||||
private final List<Consumer<AutomationSnapshot>> listeners = new CopyOnWriteArrayList<>();
|
||||
private final List<java.util.function.Supplier<CompletionStage<Void>>> projectShutdown = new CopyOnWriteArrayList<>();
|
||||
@Override public OperationSubscription registerProjectShutdown(java.util.function.Supplier<CompletionStage<Void>> shutdown) {
|
||||
projectShutdown.add(Objects.requireNonNull(shutdown));return ()->projectShutdown.remove(shutdown);
|
||||
}
|
||||
private final List<DocumentHandoff> documents = new CopyOnWriteArrayList<>();
|
||||
private final Deque<String> calls = new ArrayDeque<>();
|
||||
private ControlState state = ControlState.MANUAL;
|
||||
@@ -58,7 +64,7 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
}
|
||||
private ManualLease enterManual(boolean executionAdmission) {
|
||||
if (closed) throw new ControlDeniedException(ControlResult.Status.CLOSED);
|
||||
if (state != ControlState.MANUAL) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
if (state != ControlState.MANUAL || handoffPending) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
if (executionOwned && !executionAdmission && !executionPreparation.get()) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
if (manualOperations++ == 0) manualIdle = new CompletableFuture<>();
|
||||
stale = capture != null;
|
||||
@@ -137,6 +143,64 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
return () -> { if (documents.remove(participant)) participant.close(); };
|
||||
}
|
||||
|
||||
@Override public ControlResult prepareIntegratedServices(){return openProjectConnection();}
|
||||
|
||||
/** Publishes authenticated project access without creating task/editing authority. */
|
||||
public synchronized ControlResult openProjectConnection() {
|
||||
if(closed)return ControlResult.of(ControlResult.Status.CLOSED,"Project closed");
|
||||
if(projectConnection!=null)return ControlResult.of(ControlResult.Status.GRANTED,"");
|
||||
AutomationConnectionLifecycle.Publication publication=null;
|
||||
try {
|
||||
publication=connections.prepare(root);publication.publish();publication.activate();projectConnection=publication;
|
||||
record("project connection ready");return ControlResult.of(ControlResult.Status.GRANTED,"");
|
||||
}catch(Exception failure){
|
||||
if(publication!=null){publication.invalidate();try{publication.close();}catch(Exception ignored){}}
|
||||
return ControlResult.of(ControlResult.Status.CONNECTION_FAILED,"Project MCP connection could not be prepared");
|
||||
}
|
||||
}
|
||||
|
||||
@Override public CompletionStage<ControlResult> beginIntegratedActivity() {
|
||||
final long attempt;final List<DocumentHandoff> participants;
|
||||
synchronized(this) {
|
||||
if(closed)return result(ControlResult.Status.CLOSED,"Project closed");
|
||||
if(projectConnection==null)return result(ControlResult.Status.CONNECTION_FAILED,"Project MCP connection is not ready; reopen the project");
|
||||
if(state!=ControlState.MANUAL||handoffPending||manualOperations!=0||executionOwned||runtime!=null)
|
||||
return result(ControlResult.Status.BUSY,"Finish manual work or Play before sending to the AI");
|
||||
handoffPending=true;attempt=++generation;participants=List.copyOf(documents);publish();
|
||||
}
|
||||
CompletableFuture<Boolean> dirty=CompletableFuture.completedFuture(false);
|
||||
for(var participant:participants)dirty=dirty.thenCompose(found->participant.hasUnsavedChanges().thenApply(value->found||value)).toCompletableFuture();
|
||||
return dirty.handle((unsaved,failure)->{
|
||||
synchronized(this){
|
||||
if(closed||generation!=attempt)return ControlResult.of(ControlResult.Status.CLOSED,"Activity admission invalidated");
|
||||
handoffPending=false;
|
||||
if(failure!=null){publish();return ControlResult.of(ControlResult.Status.SAVE_FAILED,"Could not check unsaved documents");}
|
||||
if(unsaved){publish();return ControlResult.of(ControlResult.Status.DIRTY_DOCUMENTS,"Save or cancel unsaved edits before sending to the AI");}
|
||||
integratedActivity=true;integratedFinishing=false;state=ControlState.AGENT_WORKING;
|
||||
task=new TaskIdentity(root,UUID.randomUUID().toString());record("integrated activity start");publish();
|
||||
return new ControlResult(ControlResult.Status.ACQUIRED,task,"",controlObservation());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override public void requestIntegratedCancellation() {
|
||||
OperationHandle<AutomationOutcome> operation;
|
||||
synchronized(this){if(!integratedActivity)return;integratedFinishing=true;operation=active;publish();}
|
||||
if(operation!=null)operation.cancel();
|
||||
}
|
||||
@Override public CompletionStage<ControlResult> finishIntegratedActivity(boolean cancel) {
|
||||
final CompletionStage<Void> stopped;final long attempt;
|
||||
synchronized(this){
|
||||
if(!integratedActivity)return state==ControlState.RETURNING_CONTROL?beginReturn(false,null,false):result(ControlResult.Status.RETURNED,"");
|
||||
integratedFinishing=true;record(cancel?"integrated activity cancel":"integrated activity finishing");publish();
|
||||
attempt=generation;
|
||||
stopped=cancel||active==null?CompletableFuture.completedFuture(null):active.termination();
|
||||
}
|
||||
return stopped.thenCompose(v->{synchronized(this){
|
||||
if(generation!=attempt||!integratedActivity)return result(ControlResult.Status.RETURNED,"");
|
||||
}return beginReturn(false,null,false);});
|
||||
}
|
||||
|
||||
@Override public CompletionStage<ControlResult> grant(boolean save) {
|
||||
final long attempt;
|
||||
final List<DocumentHandoff> participants;
|
||||
@@ -173,6 +237,7 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
try {
|
||||
synchronized (this) {
|
||||
if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
if(projectConnection!=null){state=ControlState.WAITING_FOR_AGENT;record("grant");return ControlResult.of(ControlResult.Status.GRANTED,"");}
|
||||
publishing = publicationIdle = new CompletableFuture<>();
|
||||
}
|
||||
prepared = connections.prepare(root);
|
||||
@@ -210,6 +275,8 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
|
||||
@Override public synchronized ControlResult acquire() {
|
||||
if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed").withObservation(controlObservation());
|
||||
if(integratedActivity&&state==ControlState.AGENT_WORKING&&!integratedFinishing)
|
||||
return new ControlResult(ControlResult.Status.ACQUIRED,task,"",controlObservation());
|
||||
if (state != ControlState.WAITING_FOR_AGENT || handoffPending) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required").withObservation(controlObservation());
|
||||
task = new TaskIdentity(root, UUID.randomUUID().toString());
|
||||
diagnosticResult = Map.of(); diagnostics = List.of();
|
||||
@@ -218,9 +285,15 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
}
|
||||
|
||||
@Override public CompletionStage<ControlResult> release(TaskIdentity identity) {
|
||||
synchronized(this){if(integratedActivity&&valid(identity)){
|
||||
record("integrated release requested");return result(ControlResult.Status.RETURNED,"Studio owns activity finalization; editing remains reserved");
|
||||
}}
|
||||
return beginReturn(false, identity, true);
|
||||
}
|
||||
@Override public CompletionStage<ControlResult> reclaim() { return beginReturn(false, null, false); }
|
||||
@Override public CompletionStage<ControlResult> reclaim() {
|
||||
synchronized(this){if(integratedActivity)return result(ControlResult.Status.BUSY,"Cancel the integrated AI activity first");}
|
||||
return beginReturn(false, null, false);
|
||||
}
|
||||
@Override public CompletionStage<ControlResult> reclaimDiscardingUnsavedGameData() {
|
||||
synchronized (this) {
|
||||
if (state != ControlState.RETURNING_CONTROL || returning == null || !returning.isDone())
|
||||
@@ -248,6 +321,7 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
final CompletableFuture<Void> idle, publisherIdle;
|
||||
final List<Runnable> cleanups;
|
||||
final AutomationConnectionLifecycle.Publication publication;
|
||||
final AutomationConnectionLifecycle.Publication projectPublication;
|
||||
synchronized (this) {
|
||||
if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current");
|
||||
if (closing) closed = true;
|
||||
@@ -262,12 +336,15 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
participants = closing ? List.of() : List.copyOf(documents);
|
||||
cleanups = List.copyOf(taskCleanup);
|
||||
publication = connection; connection = null;
|
||||
projectPublication=closing?projectConnection:null;
|
||||
if(closing)projectConnection=null;
|
||||
if (publication != null) publication.invalidate();
|
||||
if(projectPublication!=null)projectPublication.invalidate();
|
||||
publish();
|
||||
}
|
||||
// Never call another service while holding the authority monitor: Debug owns its own lock.
|
||||
CompletionStage<Void> publicationCleanup;
|
||||
try { if (publication != null) publication.close(); publicationCleanup = CompletableFuture.completedFuture(null); }
|
||||
try { if (publication != null) publication.close(); if(projectPublication!=null)projectPublication.close(); publicationCleanup = CompletableFuture.completedFuture(null); }
|
||||
catch (Exception failure) { publicationCleanup = CompletableFuture.failedFuture(new IllegalStateException("Connection cleanup failed; access is revoked")); }
|
||||
CompletionStage<Void> cleanup;
|
||||
try {
|
||||
@@ -276,7 +353,14 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
CompletionStage<Void> stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination();
|
||||
CompletionStage<Void> shutdown = CompletableFuture.completedFuture(null);
|
||||
if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(discardUnsaved); }
|
||||
cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle, publisherIdle, publicationCleanup.toCompletableFuture());
|
||||
var shutdowns=new ArrayList<CompletableFuture<?>>();
|
||||
shutdowns.add(stopped.toCompletableFuture());shutdowns.add(shutdown.toCompletableFuture());
|
||||
shutdowns.add(idle);shutdowns.add(publisherIdle);shutdowns.add(publicationCleanup.toCompletableFuture());
|
||||
if(closing)for(var participant:projectShutdown) {
|
||||
try{shutdowns.add(participant.get().toCompletableFuture());}
|
||||
catch(Exception failure){shutdowns.add(CompletableFuture.failedFuture(failure));}
|
||||
}
|
||||
cleanup = CompletableFuture.allOf(shutdowns.toArray(CompletableFuture[]::new));
|
||||
cleanup = cleanup.whenComplete((v, failure) -> cleanups.forEach(Runnable::run));
|
||||
// Closing disposes documents; an explicit return must refresh them before unlocking.
|
||||
for (var p : participants) cleanup = cleanup.thenCompose(v -> {
|
||||
@@ -290,6 +374,7 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
taskCleanup.removeAll(cleanups);
|
||||
if (ownedRuntime != null) lastRuntimeObservation = ownedRuntime.observation();
|
||||
runtime = null; busy = false; state = ControlState.MANUAL;
|
||||
integratedActivity=false;integratedFinishing=false;
|
||||
cleanupState = ControlObservation.Cleanup.COMPLETED;
|
||||
diagnostics = List.of(); diagnosticResult = Map.of(); publish();
|
||||
result.complete(ControlResult.of(ControlResult.Status.RETURNED, "").withObservation(controlObservation()));
|
||||
@@ -310,6 +395,7 @@ public final class DefaultAutomationSession implements AutomationSession,Executi
|
||||
@Override public synchronized OperationHandle<AutomationOutcome> submit(TaskIdentity identity, String summary,
|
||||
Callable<AutomationOutcome> work) {
|
||||
requireTask(identity);
|
||||
if(integratedFinishing)throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
if (busy) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
busy = true; record(summary);
|
||||
diagnosticResult = Map.of();
|
||||
|
||||
@@ -48,6 +48,7 @@ public final class DefaultProjectSession implements ProjectSession {
|
||||
@Override public ProjectLocalStudioSetup projectLocalStudioSetup() { return setup; }
|
||||
@Override public ExecutionSession executionSession() { return execution; }
|
||||
@Override public p.studio.api.automation.AutomationSession automation() { return automation; }
|
||||
@Override public p.studio.api.session.ProjectLanguageService language() { return lsp.language(project); }
|
||||
@Override public p.studio.api.diagnostic.DiagnosticSources diagnosticSources() {
|
||||
return origin -> automation.snapshot().closed()
|
||||
? new p.studio.api.diagnostic.DiagnosticSources.Source("Project closed", null, "", 0, 0)
|
||||
@@ -61,12 +62,11 @@ public final class DefaultProjectSession implements ProjectSession {
|
||||
if (closed) return;
|
||||
var cleanup = automation.closeAsync().toCompletableFuture().join();
|
||||
if (!cleanup.success()) throw new IllegalStateException(cleanup.diagnostic());
|
||||
closed = true;
|
||||
RuntimeException failure = attempt(accessRegistration::unsubscribe, null);
|
||||
failure = attempt(this::saveProjectLocalStudioState, failure);
|
||||
RuntimeException failure = attempt(this::saveProjectLocalStudioState, null);
|
||||
failure = attempt(execution::close, failure);
|
||||
failure = attempt(() -> lsp.shutdown(project), failure);
|
||||
if (failure != null) throw failure;
|
||||
accessRegistration.unsubscribe();closed = true;
|
||||
}
|
||||
|
||||
private static RuntimeException attempt(Runnable action, RuntimeException prior) {
|
||||
|
||||
+8
-8
@@ -56,19 +56,17 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
|
||||
@Override
|
||||
public synchronized ProjectSession open(ProjectReference projectReference) {
|
||||
return open(projectReference,true);
|
||||
return openProject(projectReference);
|
||||
}
|
||||
@Override public synchronized ProjectSession openForPlay(ProjectReference projectReference){return open(projectReference,false);}
|
||||
@Override public synchronized ProjectSession openForPlay(ProjectReference projectReference){return openProject(projectReference);}
|
||||
|
||||
private ProjectSession open(ProjectReference projectReference,boolean editorInfrastructure) {
|
||||
private ProjectSession openProject(ProjectReference projectReference) {
|
||||
if (closed) throw new IllegalStateException("Project sessions are closing");
|
||||
final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference");
|
||||
final var setup = setupStore.load(project);
|
||||
// Preparation reports readiness independently; opening never grants agent authority.
|
||||
if (editorInfrastructure && setup.agentIntegration().enabled()) preparation.prepare(project.rootPath());
|
||||
LspLifecyclePort lifecycle=editorInfrastructure?lsp:new LspLifecyclePort(){
|
||||
public void boot(ProjectReference ignored){}public void shutdown(ProjectReference ignored){}
|
||||
};
|
||||
// Project services are available independently of an integrated editing activity.
|
||||
if (setup.agentIntegration().enabled()) preparation.prepare(project.rootPath());
|
||||
LspLifecyclePort lifecycle=lsp;
|
||||
final var state = stateStore.load(project);
|
||||
var automation = new DefaultAutomationSession(project.rootPath(), operations, connections);
|
||||
var ready = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
@@ -76,7 +74,9 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
() -> ready.get() && !automation.snapshot().closed(), automation);
|
||||
try { lifecycle.boot(project); }
|
||||
catch (RuntimeException failure) { registration.unsubscribe(); throw failure; }
|
||||
automation.registerDocuments(lifecycle.documents(project, automation::enterManual));
|
||||
ready.set(true);
|
||||
automation.openProjectConnection();
|
||||
var session = new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lifecycle, state, automation, () -> {
|
||||
registration.unsubscribe();
|
||||
synchronized (DefaultProjectSessionFactory.this) { sessions.removeIf(s -> s.automation() == automation); }
|
||||
|
||||
@@ -6,4 +6,15 @@ public interface LspLifecyclePort {
|
||||
void boot(ProjectReference project);
|
||||
|
||||
void shutdown(ProjectReference project);
|
||||
default p.studio.api.automation.DocumentHandoff documents(ProjectReference project,
|
||||
java.util.function.Supplier<p.studio.api.automation.ManualLease> editing) {
|
||||
return new p.studio.api.automation.DocumentHandoff() {
|
||||
public java.util.concurrent.CompletionStage<Boolean> hasUnsavedChanges() { return java.util.concurrent.CompletableFuture.completedFuture(false); }
|
||||
public java.util.concurrent.CompletionStage<Void> saveAll() { return java.util.concurrent.CompletableFuture.completedFuture(null); }
|
||||
public java.util.concurrent.CompletionStage<Void> refreshFromDisk() { return java.util.concurrent.CompletableFuture.completedFuture(null); }
|
||||
};
|
||||
}
|
||||
default p.studio.api.session.ProjectLanguageService language(ProjectReference project) {
|
||||
return p.studio.api.session.ProjectLanguageService.unavailable();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import p.studio.api.ai.*;
|
||||
import p.studio.api.automation.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/** One project activity owns editing admission through ACP and Core worker finalization. */
|
||||
public final class ProjectAgentConnection implements AgentConnection {
|
||||
private final AgentConnection agent;
|
||||
private final AutomationSession automation;
|
||||
private final Supplier<AgentIntegrationPreparation.Result> preparation,repair;
|
||||
private final Executor executor;
|
||||
private final List<Consumer<Status>> observers=new CopyOnWriteArrayList<>();
|
||||
private volatile boolean occupied,closing,cancelling,requiresAgentCleanup;
|
||||
private volatile String activeSession,detail="";
|
||||
private volatile boolean servicesReady;
|
||||
private volatile CompletableFuture<Void> settled=CompletableFuture.completedFuture(null);
|
||||
private volatile CompletableFuture<Void> admissionDone=CompletableFuture.completedFuture(null);
|
||||
private volatile CompletableFuture<String> currentCompletion;
|
||||
private final AutoCloseable observation;
|
||||
private final p.studio.api.operation.OperationSubscription shutdownRegistration;
|
||||
public ProjectAgentConnection(AgentConnection agent,AutomationSession automation,
|
||||
Supplier<AgentIntegrationPreparation.Result> preparation,Executor executor) {
|
||||
this(agent,automation,preparation,preparation,executor);
|
||||
}
|
||||
public ProjectAgentConnection(AgentConnection agent,AutomationSession automation,
|
||||
Supplier<AgentIntegrationPreparation.Result> preparation,Supplier<AgentIntegrationPreparation.Result> repair,Executor executor) {
|
||||
this.agent=Objects.requireNonNull(agent);this.automation=Objects.requireNonNull(automation);
|
||||
this.preparation=Objects.requireNonNull(preparation);this.repair=Objects.requireNonNull(repair);this.executor=Objects.requireNonNull(executor);
|
||||
shutdownRegistration=automation.registerProjectShutdown(agent::closeAsync);
|
||||
observation=agent.observe(s->changed());
|
||||
}
|
||||
public boolean available(){return agent.available();}
|
||||
public boolean busy(){return occupied;}
|
||||
public boolean servicesReady(){return servicesReady;}
|
||||
public Status status(){var s=agent.status();return new Status(s.state(),detail.isBlank()?s.detail():detail);}
|
||||
private void changed(){for(var observer:observers)try{observer.accept(status());}catch(RuntimeException ignored){}}
|
||||
public AutoCloseable observe(Consumer<Status> listener){observers.add(listener);listener.accept(status());return ()->observers.remove(listener);}
|
||||
public void events(Consumer<Event> listener){agent.events(listener);}
|
||||
public void permissions(Function<Permission,CompletionStage<String>> handler){agent.permissions(handler);}
|
||||
public CompletionStage<Void> connect(AcpSettings settings){return agent.connect(settings).thenCompose(v->refreshPreparation(false));}
|
||||
private AgentIntegrationPreparation.Result readiness(boolean retry) {
|
||||
var result=(retry?repair:preparation).get();
|
||||
if(!result.ready())return result;
|
||||
var channel=automation.prepareIntegratedServices();
|
||||
return channel.success()?result:new AgentIntegrationPreparation.Result(false,channel.diagnostic());
|
||||
}
|
||||
private CompletionStage<Void> refreshPreparation(boolean retry){return CompletableFuture.supplyAsync(()->readiness(retry),executor).thenAccept(result->{
|
||||
servicesReady=result.ready();detail=result.ready()?"":"Studio tools: "+result.message();changed();
|
||||
});}
|
||||
public CompletionStage<Void> login(){return agent.login();}
|
||||
public CompletionStage<String> newSession(){return agent.newSession();}
|
||||
public synchronized Turn prompt(String session,String text) {
|
||||
var accepted=new CompletableFuture<Void>();var completion=new CompletableFuture<String>();
|
||||
if(occupied||closing){var f=new IllegalStateException("Project AI activity is still active or finalizing");accepted.completeExceptionally(f);completion.completeExceptionally(f);return new Turn(accepted,completion);}
|
||||
occupied=true;cancelling=false;requiresAgentCleanup=false;activeSession=session;detail="";settled=new CompletableFuture<>();
|
||||
currentCompletion=completion;admissionDone=new CompletableFuture<>();var admissionSettled=admissionDone;changed();
|
||||
CompletableFuture.supplyAsync(()->readiness(false),executor).thenCompose(ready->{
|
||||
servicesReady=ready.ready();
|
||||
if(!ready.ready())return CompletableFuture.failedFuture(new IllegalStateException(ready.message()));
|
||||
if(cancelling||closing)return CompletableFuture.failedFuture(new CancellationException("Cancelled before admission"));
|
||||
return automation.beginIntegratedActivity();
|
||||
}).whenComplete((admission,failure)->{
|
||||
admissionSettled.complete(null);
|
||||
if(failure!=null||admission==null||!admission.success()){
|
||||
Throwable rejected=failure!=null?failure:new IllegalStateException(admission.diagnostic());
|
||||
accepted.completeExceptionally(rejected);releaseLocal(completion);completion.completeExceptionally(rejected);return;
|
||||
}
|
||||
if(cancelling||closing){accepted.completeExceptionally(new CancellationException("Cancelled before delivery"));finish("cancelled",null,completion);return;}
|
||||
try {
|
||||
var turn=agent.prompt(session,text);
|
||||
turn.accepted().whenComplete((v,f)->{if(f==null)accepted.complete(null);else accepted.completeExceptionally(f);});
|
||||
turn.completion().whenComplete((reason,f)->finish(reason,f,completion));
|
||||
}catch(Throwable problem){accepted.completeExceptionally(problem);finish(null,problem,completion);}
|
||||
});
|
||||
return new Turn(accepted,completion);
|
||||
}
|
||||
private synchronized CompletionStage<ControlResult> finalizeActivity(CompletableFuture<String> completion,boolean cancel) {
|
||||
if(currentCompletion!=completion)return CompletableFuture.completedFuture(ControlResult.of(ControlResult.Status.RETURNED,""));
|
||||
return automation.finishIntegratedActivity(cancel);
|
||||
}
|
||||
private void finish(String reason,Throwable failure,CompletableFuture<String> completion) {
|
||||
synchronized(this){if(currentCompletion!=completion)return;detail="Finalizing project work";changed();}
|
||||
if(failure!=null&&agent.status().state()!=State.READY)requiresAgentCleanup=true;
|
||||
CompletableFuture.supplyAsync(()->{
|
||||
if(failure!=null||cancelling)automation.requestIntegratedCancellation();
|
||||
return requiresAgentCleanup?agent.awaitQuiescence():CompletableFuture.<Void>completedFuture(null);
|
||||
},executor).thenCompose(Function.identity()).thenCompose(v->finalizeActivity(completion,cancelling||failure!=null)).whenComplete((result,cleanupFailure)->{
|
||||
if(currentCompletion!=completion)return;
|
||||
if(cleanupFailure!=null||result==null||!result.success()){
|
||||
detail="Project cleanup incomplete: "+(cleanupFailure!=null?Objects.toString(cleanupFailure.getMessage(),"cleanup failed"):result.diagnostic());
|
||||
changed();completion.completeExceptionally(new IllegalStateException(detail,cleanupFailure));
|
||||
// Keep occupied. Explicit recovery or close owns the remaining cleanup.
|
||||
}else {releaseLocal(completion);if(failure==null)completion.complete(reason);else completion.completeExceptionally(failure);}
|
||||
});
|
||||
}
|
||||
private synchronized void releaseLocal(CompletableFuture<String> completion){if(currentCompletion!=completion)return;currentCompletion=null;occupied=false;activeSession=null;detail="";var done=settled;changed();done.complete(null);}
|
||||
public CompletionStage<Void> cancel(String session) {
|
||||
if(!occupied)return CompletableFuture.completedFuture(null);
|
||||
cancelling=true;detail="Cancelling project work";changed();
|
||||
var wait=settled;
|
||||
var interruption=admissionDone.thenRunAsync(automation::requestIntegratedCancellation,executor);
|
||||
return agent.cancel(session).thenCombine(interruption,(v,ignored)->(Void)null).thenCompose(v->wait);
|
||||
}
|
||||
public CompletionStage<Void> recoverActivity() {
|
||||
if(!occupied)return refreshPreparation(true);
|
||||
var completion=currentCompletion;
|
||||
if(completion!=null&&!completion.isDone())return CompletableFuture.failedFuture(new IllegalStateException("Cancel the active request before retrying cleanup"));
|
||||
return CompletableFuture.supplyAsync(()->requiresAgentCleanup?agent.awaitQuiescence():CompletableFuture.<Void>completedFuture(null),executor)
|
||||
.thenCompose(Function.identity()).thenCompose(v->finalizeActivity(completion,true))
|
||||
.thenAccept(result->{if(!result.success())throw new CompletionException(new IllegalStateException(result.diagnostic()));releaseLocal(completion);});
|
||||
}
|
||||
public synchronized CompletionStage<Void> closeAsync() {
|
||||
closing=true;cancelling=true;
|
||||
var completion=currentCompletion;
|
||||
return agent.closeAsync().thenCompose(v->admissionDone)
|
||||
.thenCompose(v->CompletableFuture.supplyAsync(()->finalizeActivity(completion,true),executor).thenCompose(Function.identity()))
|
||||
.thenAccept(result->{if(!result.success())throw new CompletionException(new IllegalStateException(result.diagnostic()));releaseLocal(completion);if(completion!=null)completion.complete("cancelled");})
|
||||
.whenComplete((v,f)->{
|
||||
if(f==null){shutdownRegistration.unsubscribe();try{observation.close();}catch(Exception ignored){}}
|
||||
else closing=false;
|
||||
});
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -90,7 +90,10 @@ final class DefaultProjectSessionTest {
|
||||
java.nio.file.Files.createDirectory(temporaryDirectory.resolve("other"))));
|
||||
var failure = assertThrows(IllegalStateException.class, factory::close);
|
||||
assertEquals(1, failure.getSuppressed().length); assertEquals(2, lsp.shutdowns);
|
||||
factory.close();
|
||||
assertThrows(IllegalStateException.class,factory::close);
|
||||
assertEquals(4,lsp.shutdowns);
|
||||
lsp.failShutdown=false;factory.close();factory.close();
|
||||
assertEquals(6,lsp.shutdowns);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -112,20 +115,20 @@ final class DefaultProjectSessionTest {
|
||||
registration.unsubscribe();
|
||||
}
|
||||
|
||||
@Test void openingPreparesIntegrationAndRemainsManualEvenWhenPreparationIsIncomplete() {
|
||||
@Test void openingPublishesProjectConnectionAndRemainsManualEvenWhenPreparationIsIncomplete() {
|
||||
var mapper = new ObjectMapper(); var calls = new java.util.ArrayList<Path>();
|
||||
var published = new java.util.concurrent.atomic.AtomicInteger();
|
||||
try (var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), new RecordingLsp(), new p.studio.core.project.ProjectAccessRegistry(),
|
||||
new p.studio.core.support.ControlledOperations(), root -> {
|
||||
published.incrementAndGet(); throw new AssertionError("Opening must not publish credentials");
|
||||
published.incrementAndGet();return p.studio.api.automation.AutomationConnectionLifecycle.none().prepare(root);
|
||||
}, root -> {
|
||||
calls.add(root); return new p.studio.api.automation.AgentIntegrationPreparation.Result(false, "Installation missing");
|
||||
})) {
|
||||
var first = factory.open(project());
|
||||
assertEquals(java.util.List.of(project().rootPath()), calls);
|
||||
assertTrue(first.automation().snapshot().manualAllowed());
|
||||
assertNull(first.automation().snapshot().task()); assertEquals(0, published.get());
|
||||
assertNull(first.automation().snapshot().task()); assertEquals(1, published.get());
|
||||
first.close();
|
||||
var reopened = factory.open(project());
|
||||
assertEquals(2, calls.size()); assertTrue(reopened.automation().snapshot().manualAllowed());
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.core.support.ControlledOperations;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ProjectAgentConnectionTest {
|
||||
@TempDir Path root;
|
||||
final ControlledOperations operations=new ControlledOperations();
|
||||
static final class Peer implements AgentConnection {
|
||||
final CompletableFuture<String> done=new CompletableFuture<>();int prompts;
|
||||
boolean holdCancel;State state=State.READY;CompletableFuture<Void> quiescence=CompletableFuture.completedFuture(null),closing=CompletableFuture.completedFuture(null);
|
||||
public boolean available(){return true;}public Status status(){return new Status(state,"");}
|
||||
public AutoCloseable observe(Consumer<Status> l){l.accept(status());return ()->{};}
|
||||
public void events(Consumer<Event> l){} public void permissions(Function<Permission,CompletionStage<String>> h){}
|
||||
public CompletionStage<Void> connect(AcpSettings s){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> login(){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<String> newSession(){return CompletableFuture.completedFuture("session");}
|
||||
public Turn prompt(String id,String text){prompts++;return new Turn(CompletableFuture.completedFuture(null),done);}
|
||||
public CompletionStage<Void> cancel(String id){if(!holdCancel)done.complete("cancelled");return done.handle((v,f)->(Void)null);}
|
||||
public CompletionStage<Void> awaitQuiescence(){return quiescence;}
|
||||
public CompletionStage<Void> closeAsync(){done.complete("cancelled");return closing;}
|
||||
}
|
||||
DefaultAutomationSession authority(){var s=new DefaultAutomationSession(root,operations);assertTrue(s.openProjectConnection().success());return s;}
|
||||
ProjectAgentConnection connection(Peer p,DefaultAutomationSession s){return new ProjectAgentConnection(p,s,()->new AgentIntegrationPreparation.Result(true,"ready"),Runnable::run);}
|
||||
@Test void reservePrecedesPromptAndModelReleaseCannotUnlockIt() {
|
||||
var s=authority();var p=new Peer();var c=connection(p,s);
|
||||
var turn=c.prompt("session","edit");assertTrue(turn.accepted().toCompletableFuture().isDone());
|
||||
assertThrows(ControlDeniedException.class,s::enterManual);assertThrows(ControlDeniedException.class,s::enterExecution);
|
||||
var task=s.acquire().task();assertNotNull(task);
|
||||
assertTrue(s.release(task).toCompletableFuture().join().success());assertFalse(s.snapshot().manualAllowed());
|
||||
p.done.complete("end_turn");assertEquals("end_turn",turn.completion().toCompletableFuture().join());
|
||||
assertFalse(c.busy());assertTrue(s.snapshot().manualAllowed());c.closeAsync().toCompletableFuture().join();
|
||||
}
|
||||
@Test void normalReplyWaitsForToolWorkerAndCancelDoesNotConfuseAcknowledgementWithTermination() {
|
||||
var s=authority();var p=new Peer();var c=connection(p,s);var turn=c.prompt("session","build");
|
||||
var task=s.acquire().task();s.submit(task,"work",()->new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,0,0,List.of(),null));
|
||||
p.done.complete("end_turn");assertTrue(c.busy());assertFalse(turn.completion().toCompletableFuture().isDone());
|
||||
assertThrows(ControlDeniedException.class,s::enterManual);
|
||||
var cancelled=c.cancel("session");assertTrue(operations.last.cancelled);assertFalse(cancelled.toCompletableFuture().isDone());
|
||||
operations.last.finish();cancelled.toCompletableFuture().join();
|
||||
assertFalse(c.busy());assertTrue(s.snapshot().manualAllowed());
|
||||
}
|
||||
@Test void dirtyDocumentsAndActiveManualWorkRejectBeforeSendingWithoutSaving() {
|
||||
var s=authority();var p=new Peer();var c=connection(p,s);
|
||||
try(var manual=s.enterManual()) {assertTrue(c.prompt("session","edit").completion().toCompletableFuture().isCompletedExceptionally());}
|
||||
var registration=s.registerDocuments(new DocumentHandoff(){
|
||||
public CompletionStage<Boolean> hasUnsavedChanges(){return CompletableFuture.completedFuture(true);}
|
||||
public CompletionStage<Void> saveAll(){throw new AssertionError("Must not save implicitly");}
|
||||
public CompletionStage<Void> refreshFromDisk(){throw new AssertionError("Must not refresh a rejected draft");}
|
||||
});
|
||||
assertTrue(c.prompt("session","edit").completion().toCompletableFuture().isCompletedExceptionally());
|
||||
assertEquals(0,p.prompts);assertFalse(c.busy());assertTrue(s.snapshot().manualAllowed());registration.unsubscribe();
|
||||
}
|
||||
@Test void closeDuringDocumentCheckWaitsAndCannotLeaveLateAuthority() {
|
||||
var s=authority();var dirty=new CompletableFuture<Boolean>();
|
||||
s.registerDocuments(new DocumentHandoff(){
|
||||
public CompletionStage<Boolean> hasUnsavedChanges(){return dirty;}
|
||||
public CompletionStage<Void> saveAll(){throw new AssertionError();}
|
||||
public CompletionStage<Void> refreshFromDisk(){return CompletableFuture.completedFuture(null);}
|
||||
});
|
||||
var p=new Peer();var c=connection(p,s);var turn=c.prompt("session","edit");
|
||||
var close=c.closeAsync();assertFalse(close.toCompletableFuture().isDone());
|
||||
dirty.complete(false);close.toCompletableFuture().join();
|
||||
assertEquals(0,p.prompts);assertTrue(s.snapshot().manualAllowed());assertFalse(c.busy());
|
||||
assertTrue(turn.completion().toCompletableFuture().isDone());
|
||||
}
|
||||
@Test void cleanupFailureKeepsReservationUntilExplicitSuccessfulRetry() {
|
||||
var s=authority();var refresh=new java.util.concurrent.atomic.AtomicInteger();
|
||||
s.registerDocuments(new DocumentHandoff(){
|
||||
public CompletionStage<Boolean> hasUnsavedChanges(){return CompletableFuture.completedFuture(false);}
|
||||
public CompletionStage<Void> saveAll(){throw new AssertionError();}
|
||||
public CompletionStage<Void> refreshFromDisk(){return refresh.getAndIncrement()==0?CompletableFuture.failedFuture(new IllegalStateException("disk unavailable")):CompletableFuture.completedFuture(null);}
|
||||
});
|
||||
var p=new Peer();var c=connection(p,s);var turn=c.prompt("session","edit");p.done.complete("end_turn");
|
||||
assertTrue(turn.completion().toCompletableFuture().isCompletedExceptionally());assertTrue(c.busy());
|
||||
assertFalse(s.snapshot().manualAllowed());c.recoverActivity().toCompletableFuture().join();
|
||||
assertFalse(c.busy());assertTrue(s.snapshot().manualAllowed());assertEquals(2,refresh.get());
|
||||
}
|
||||
@Test void toolPreparationIsIndependentOfAcpAndExplicitRetryRepairsIt() {
|
||||
var s=authority();var p=new Peer();var prepared=new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var c=new ProjectAgentConnection(p,s,()->new AgentIntegrationPreparation.Result(prepared.get(),"not prepared"),
|
||||
()->{prepared.set(true);return new AgentIntegrationPreparation.Result(true,"ready");},Runnable::run);
|
||||
c.connect(new AcpSettings("fixture",List.of())).toCompletableFuture().join();
|
||||
assertFalse(c.servicesReady());assertEquals(AgentConnection.State.READY,c.status().state());
|
||||
assertTrue(c.prompt("session","edit").completion().toCompletableFuture().isCompletedExceptionally());assertEquals(0,p.prompts);
|
||||
c.recoverActivity().toCompletableFuture().join();assertTrue(c.servicesReady());assertTrue(s.snapshot().manualAllowed());
|
||||
var turn=c.prompt("session","edit");p.done.complete("end_turn");assertEquals("end_turn",turn.completion().toCompletableFuture().join());
|
||||
}
|
||||
@Test void runningPlayRefusesAiWithoutStoppingTheExecutionOwner() {
|
||||
var s=authority();var p=new Peer();var c=connection(p,s);
|
||||
try(var play=s.enterExecution()) {
|
||||
assertTrue(c.prompt("session","edit").completion().toCompletableFuture().isCompletedExceptionally());
|
||||
assertEquals(0,p.prompts);assertThrows(ControlDeniedException.class,s::enterManual);
|
||||
}
|
||||
var turn=c.prompt("session","edit");assertEquals(1,p.prompts);p.done.complete("end_turn");turn.completion().toCompletableFuture().join();
|
||||
}
|
||||
|
||||
@Test void cancelledToolTerminationDoesNotUnlockWhileAcpPromptIsStillRunning() {
|
||||
var s=authority();var p=new Peer();p.holdCancel=true;var c=connection(p,s);var turn=c.prompt("session","edit");
|
||||
s.submit(s.acquire().task(),"work",()->new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,0,0,List.of(),null));
|
||||
var cancel=c.cancel("session");assertTrue(operations.last.cancelled);operations.last.finish();
|
||||
assertFalse(cancel.toCompletableFuture().isDone());assertTrue(c.busy());assertFalse(s.snapshot().manualAllowed());
|
||||
assertThrows(ControlDeniedException.class,s::enterManual);
|
||||
p.done.complete("cancelled");cancel.toCompletableFuture().join();turn.completion().toCompletableFuture().join();
|
||||
assertTrue(s.snapshot().manualAllowed());assertFalse(c.busy());
|
||||
}
|
||||
@Test void transportFailureWaitsForNativeQuiescenceBeforeReturningEditing() {
|
||||
var s=authority();var p=new Peer();p.quiescence=new CompletableFuture<>();var c=connection(p,s);
|
||||
var turn=c.prompt("session","edit");p.state=AgentConnection.State.FAILED;p.done.completeExceptionally(new IllegalStateException("transport died"));
|
||||
assertFalse(turn.completion().toCompletableFuture().isDone());assertFalse(s.snapshot().manualAllowed());
|
||||
p.quiescence.completeExceptionally(new IllegalStateException("native child still running"));
|
||||
assertTrue(turn.completion().toCompletableFuture().isCompletedExceptionally());assertTrue(c.busy());assertFalse(s.snapshot().manualAllowed());
|
||||
p.quiescence=CompletableFuture.completedFuture(null);c.recoverActivity().toCompletableFuture().join();
|
||||
assertFalse(c.busy());assertTrue(s.snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void projectCloseOwnsNativeAgentShutdownEvenWithoutUiCoordination() {
|
||||
var s=authority();var p=new Peer();p.closing=new CompletableFuture<>();var c=connection(p,s);
|
||||
var turn=c.prompt("session","edit");var closed=s.closeAsync().toCompletableFuture();
|
||||
assertFalse(closed.isDone());assertFalse(s.snapshot().manualAllowed());assertTrue(s.snapshot().closed());
|
||||
assertThrows(ControlDeniedException.class,s::enterManual);
|
||||
p.closing.completeExceptionally(new IllegalStateException("native cleanup incomplete"));
|
||||
assertFalse(closed.join().success());assertTrue(turn.completion().toCompletableFuture().isCompletedExceptionally());
|
||||
p.closing=CompletableFuture.completedFuture(null);assertTrue(s.closeAsync().toCompletableFuture().join().success());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import java.time.Duration
|
||||
|
||||
plugins {
|
||||
id("gradle.java-application-conventions")
|
||||
alias(libs.plugins.javafx)
|
||||
@@ -59,3 +61,17 @@ tasks.register<Test>("desktopTest") {
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
|
||||
|
||||
tasks.register<Test>("aiWorkspaceDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Checks the actual AI project view and recovery labels with a controlled agent (requires a desktop)."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/AiWorkspaceDesktopTest.class")
|
||||
systemProperty("java.awt.headless", "false")
|
||||
systemProperty("javafx.cachedir", layout.buildDirectory.dir("javafx-test-cache").get().asFile.absolutePath)
|
||||
timeout.set(Duration.ofSeconds(60))
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ final class AgentChats implements AutoCloseable {
|
||||
boolean busy(){return running!=null;}
|
||||
boolean running(long id){return Objects.equals(running,id);}
|
||||
String runningTitle(){return running==null?"":drafts.chats().stream().filter(c->c.id()==running).map(LocalChats.Chat::title).findFirst().orElse("");}
|
||||
boolean canSend(long id){return !closing&&!closed&&!busy()&&agent.available()&&agent.status().state()==AgentConnection.State.READY
|
||||
boolean canSend(long id){return !closing&&!closed&&!busy()&&!agent.busy()&&agent.servicesReady()&&agent.available()&&agent.status().state()==AgentConnection.State.READY
|
||||
&&!entry(id).invalid&&!drafts.draft(id).isBlank();}
|
||||
Conversation conversation(long id){return entry(id).conversation;}
|
||||
String activity(long id){return entry(id).invalid?text.apply("ai.session.expired"):entry(id).activity;}
|
||||
@@ -95,8 +95,13 @@ final class AgentChats implements AutoCloseable {
|
||||
private void finish(long id,String stop,Throwable failure){
|
||||
if(closed||!Objects.equals(running,id))return;
|
||||
var chat=entry(id);
|
||||
chat.activity=failure==null?text.apply("cancelled".equals(stop)?"ai.cancelled":"ai.done"):text.apply("ai.error")+": "+failureMessage(failure);
|
||||
chat.conversation.finish(failure!=null?"error":"cancelled".equals(stop)?"cancelled":"done",failure==null?"":failureMessage(failure));
|
||||
String outcome=failure!=null?"error":switch(Objects.toString(stop,"unknown")){
|
||||
case "end_turn" -> "done";case "cancelled" -> "cancelled";
|
||||
case "max_tokens","max_turn_requests" -> "limited";case "refusal" -> "refused";
|
||||
default -> "interrupted";
|
||||
};
|
||||
chat.activity=failure==null?text.apply("ai."+outcome):text.apply("ai.error")+": "+failureMessage(failure);
|
||||
chat.conversation.finish(outcome,failure==null?Objects.toString(stop,""):failureMessage(failure));
|
||||
running=null;cancelling=false;
|
||||
var done=settled;changed.run();done.complete(null);
|
||||
}
|
||||
|
||||
@@ -57,7 +57,11 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable {
|
||||
private boolean deleting;
|
||||
private boolean closed;
|
||||
private boolean synchronizing;
|
||||
private final ChangeListener<Tab> selection = (o, before, after) -> placeComposer();
|
||||
private final ChangeListener<Tab> selection = (o, before, after) -> selectionChanged(after);
|
||||
private void selectionChanged(Tab after) {
|
||||
if(execution!=null&&(execution.busy()||agent.busy())&&after!=ai){tabs.getSelectionModel().select(ai);return;}
|
||||
placeComposer();
|
||||
}
|
||||
private final ChangeListener<LocalChats.Chat> chatSelection = (o, before, after) -> {
|
||||
if (!synchronizing && !closed) {
|
||||
if (after != null) {
|
||||
@@ -135,6 +139,8 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable {
|
||||
});
|
||||
cancel=actionButton("ai.cancel","ai-cancel",this::cancelTurn);
|
||||
recover=actionButton("ai.recover","ai-recover",this::recover);
|
||||
// refreshAgent owns this localized label as the recovery action changes.
|
||||
recover.textProperty().unbind();
|
||||
var commands = new HBox(8, unavailableButton("ai.attach", "ai-attach"), recover, spacer, cancel, send);
|
||||
commands.setAlignment(Pos.CENTER_LEFT);
|
||||
composer.setId("ai-composer");
|
||||
@@ -296,6 +302,11 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable {
|
||||
private void send(){var chat=chats.active();if(chat!=null)execution.send(chat.id());}
|
||||
private void cancelTurn(){cancelPermissions();execution.cancel();}
|
||||
private void recover(){
|
||||
if((agent.busy()||!agent.servicesReady())&&!execution.busy()){
|
||||
agent.recoverActivity().whenComplete((v,f)->Platform.runLater(()->{
|
||||
if(!closed){refreshAgent();if(f!=null)activity.setText(AgentChats.failureMessage(f));}
|
||||
}));return;
|
||||
}
|
||||
var chat=chats.active();if(chat!=null&&chats.draft().isBlank())chats.write(execution.lastRequest(chat.id()));
|
||||
refreshSelection();focusPrompt();
|
||||
}
|
||||
@@ -315,7 +326,12 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable {
|
||||
var chat=chats.active();
|
||||
send.setDisable(chat==null||deleting||!execution.canSend(chat.id()));
|
||||
cancel.setDisable(!execution.busy());
|
||||
recover.setDisable(chat==null||!chats.draft().isBlank()||execution.lastRequest(chat.id()).isBlank());
|
||||
boolean cleanup=(agent.busy()||!agent.servicesReady())&&!execution.busy();
|
||||
recover.setText(context.text(cleanup?(agent.busy()?"ai.cleanup":"ai.tools.retry"):"ai.recover"));
|
||||
recover.setDisable(!cleanup&&(chat==null||!chats.draft().isBlank()||execution.lastRequest(chat.id()).isBlank()));
|
||||
boolean protectedActivity=execution.busy()||agent.busy();
|
||||
for(var tab:tabs.getTabs())if(tab!=ai)tab.setDisable(protectedActivity);
|
||||
if(protectedActivity)tabs.getSelectionModel().select(ai);
|
||||
transcript.show(chat==null?null:execution.conversation(chat.id()));
|
||||
activity.setText(chat==null?"":execution.activity(chat.id()));
|
||||
var status=agent.status();
|
||||
|
||||
+1
-1
@@ -162,7 +162,7 @@ public final class StudioConversation extends BorderPane implements AutoCloseabl
|
||||
}
|
||||
private void refreshFooter(){var footer=getBottom();boolean show=!view.following&&view.unread;footer.setVisible(show);footer.setManaged(show);}
|
||||
private String state(String value){return context.text("conversation.state."+switch(value){
|
||||
case "sending","sent","failed","cancelled","streaming","pending","in_progress","completed","interrupted","done","error" -> value;
|
||||
case "sending","sent","failed","cancelled","streaming","pending","in_progress","completed","interrupted","done","error","limited","refused" -> value;
|
||||
default -> "unknown";
|
||||
});}
|
||||
|
||||
|
||||
+6
-3
@@ -374,6 +374,9 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
gameplay=new Tab(c.text("gameplay.title"),split);gameplay.setId("gameplay-tab");gameplay.setClosable(false);
|
||||
tabs=new StudioTabs(gameplay);tabs.setId("project-tabs");
|
||||
agent=agentConnections.create(ref.rootPath());
|
||||
var projectAgent=agent;
|
||||
var agentState=agent.observe(status->Platform.runLater(()->{if(!closed&&agent==projectAgent)refresh();}));
|
||||
c.onClose(()->{try{agentState.close();}catch(Exception ignored){}});
|
||||
aiWorkspace=new AiWorkspace(c,tabs,()->resources.child(c),agent);
|
||||
var statusFooter=new TabStatusFooter(tabs);
|
||||
var gameplayInfo=Bindings.createStringBinding(()->viewport.scale()>0?
|
||||
@@ -403,7 +406,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
shell.workspace().getChildren().setAll(workspaceScroll);lastLog=-1;refresh();
|
||||
}
|
||||
private void play(){
|
||||
if(busy||closing||controller!=null&&controller.ownsExecution())return;
|
||||
if(busy||closing||agent!=null&&agent.busy()||controller!=null&&controller.ownsExecution())return;
|
||||
var original=localSetup;var ref=project.projectReference();boolean discard=ref.memcardSlots()!=null&&disposableSave;
|
||||
if(ref.memcardSlots()!=null&&!discard&&(original.memcardPath()==null||original.memcardPath().isBlank())){
|
||||
configurationNeeded(context.text("play.memcard.required"),false,true);return;
|
||||
@@ -445,12 +448,12 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
|
||||
var snapshot=project.executionSession().snapshot();var state=snapshot.state();boolean owned=controller!=null&&controller.ownsExecution();
|
||||
if(diagnostics!=null)diagnostics.show(snapshot.diagnostics());
|
||||
play.setText(context.text(owned?"play.stop":"play.start"));play.setAccessibleText(play.getText());
|
||||
play.setDisable(busy||closing||state==ExecutionState.STOPPING);
|
||||
play.setDisable(busy||closing||agent!=null&&agent.busy()||state==ExecutionState.STOPPING);
|
||||
pause.setDisable(busy||closing||state!=ExecutionState.RUNNING&&state!=ExecutionState.PAUSED);
|
||||
pause.setSelected(state==ExecutionState.PAUSED||state==ExecutionState.PAUSING);
|
||||
pause.setText(context.text(state==ExecutionState.PAUSED?"play.resume":"play.pause"));pause.setAccessibleText(pause.getText());
|
||||
if(closeProject!=null)closeProject.setDisable(closing||busy);
|
||||
if(projectSettings!=null)projectSettings.setDisable(closing||busy||owned);
|
||||
if(projectSettings!=null)projectSettings.setDisable(closing||busy||owned||agent!=null&&agent.busy());
|
||||
if(displayedState!=state){displayedState=state;
|
||||
stateLabel.setText(viewContext.text("state."+state.name())+(owned&&disposableSave?" · "+context.text("play.disposable.short"):""));
|
||||
play.getTooltip().hide();pause.getTooltip().hide();
|
||||
|
||||
+8
@@ -243,3 +243,11 @@ diagnostic.source.sdk=SDK
|
||||
diagnostic.source.generated=generated source
|
||||
diagnostic.source.source=source
|
||||
diagnostic.source.dependency=dependency source
|
||||
|
||||
ai.limited=Agent limit reached
|
||||
ai.refused=Request refused
|
||||
ai.interrupted=Stopped with an unconfirmed outcome
|
||||
ai.cleanup=Retry project cleanup
|
||||
conversation.state.limited=Limit reached
|
||||
conversation.state.refused=Refused
|
||||
ai.tools.retry=Retry Studio tools
|
||||
|
||||
+8
@@ -243,3 +243,11 @@ diagnostic.source.sdk=SDK
|
||||
diagnostic.source.generated=fonte gerado
|
||||
diagnostic.source.source=fonte
|
||||
diagnostic.source.dependency=fonte de dependência
|
||||
|
||||
ai.limited=Limite do agente atingido
|
||||
ai.refused=Solicitação recusada
|
||||
ai.interrupted=Interrompido com resultado não confirmado
|
||||
ai.cleanup=Tentar finalizar o projeto
|
||||
conversation.state.limited=Limite atingido
|
||||
conversation.state.refused=Recusado
|
||||
ai.tools.retry=Verificar ferramentas do Studio
|
||||
|
||||
@@ -64,4 +64,15 @@ class AgentChatsTest {
|
||||
var close=m.closeAgent();assertFalse(m.canSend(b.id()));agent.cancelled.completeExceptionally(new IllegalStateException("close failed"));
|
||||
assertTrue(close.toCompletableFuture().isCompletedExceptionally());assertTrue(m.canSend(b.id()));
|
||||
}
|
||||
@Test void stopReasonsPreserveLimitedRefusedAndInterruptedOutcomes() {
|
||||
var reasons=Map.of("end_turn","done","cancelled","cancelled","max_tokens","limited",
|
||||
"max_turn_requests","limited","refusal","refused","future_reason","interrupted");
|
||||
for(var reason:reasons.entrySet()) {
|
||||
var drafts=new LocalChats();var chat=drafts.create();drafts.write("request");
|
||||
var agent=new Agent();var m=model(drafts,agent);m.send(chat.id());agent.ack.complete(null);agent.done.complete(reason.getKey());
|
||||
var terminal=m.conversation(chat.id()).items().getLast();
|
||||
assertEquals(reason.getValue(),terminal.state());assertTrue(terminal.text().contains(reason.getKey()));assertFalse(m.busy());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package p.studio.ui.javafx2.ai;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.stage.Stage;
|
||||
import org.junit.jupiter.api.*;
|
||||
import p.studio.api.ai.*;
|
||||
import p.studio.ui.javafx2.appearance.*;
|
||||
import p.studio.ui.javafx2.i18n.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual project AI view and controls; controlled agent, no model or personal preference writes. */
|
||||
@Tag("integration")
|
||||
class AiWorkspaceDesktopTest {
|
||||
private static boolean toolkitStarted;
|
||||
@BeforeAll static void startToolkit() throws Exception {
|
||||
var ready=new CompletableFuture<Void>();
|
||||
Thread.ofPlatform().daemon().name("ai-view-test-startup").start(()->{
|
||||
try{Platform.startup(()->ready.complete(null));}catch(Throwable failure){ready.completeExceptionally(failure);}
|
||||
});
|
||||
ready.get(15,TimeUnit.SECONDS);toolkitStarted=true;Platform.setImplicitExit(false);
|
||||
}
|
||||
@AfterAll static void stopToolkit(){if(toolkitStarted)Platform.exit();}
|
||||
static <T>T fx(Callable<T> action) throws Exception {
|
||||
var task=new FutureTask<>(action);Platform.runLater(task);return task.get(15,TimeUnit.SECONDS);
|
||||
}
|
||||
@Test void projectViewOpensAndRecoveryLabelsFollowReadinessActivityAndLanguage() throws Exception {
|
||||
var agent=new Peer();
|
||||
var window=fx(()->{
|
||||
var context=new AppearanceContext(PresentationSettings.defaults(Locale.ENGLISH),Messages.load(s->fail(s)),
|
||||
FontResources.load(s->fail(s)),value->{});
|
||||
var tabs=new TabPane(new Tab("Gameplay"));
|
||||
var view=new AiWorkspace(context,tabs,()->context,agent);
|
||||
context.attach(view);
|
||||
var stage=new Stage();stage.setScene(new Scene(view,1000,700));stage.show();
|
||||
return new Window(stage,context,view);
|
||||
});
|
||||
try {
|
||||
for(var language:StudioLanguage.values()) {
|
||||
fx(()->{window.context.update(window.context.settings().withLanguage(language));return null;});
|
||||
fx(()->{
|
||||
var button=(Button)window.view.lookup("#ai-recover");assertNotNull(button);
|
||||
assertEquals(window.context.text("ai.recover"),button.getText());return null;
|
||||
});
|
||||
fx(()->{agent.ready=false;agent.changed();return null;});
|
||||
fx(()->{
|
||||
var button=(Button)window.view.lookup("#ai-recover");
|
||||
assertEquals(window.context.text("ai.tools.retry"),button.getText());assertFalse(button.isDisabled());
|
||||
button.fire();assertEquals(1,agent.recoveries);agent.recoveries=0;return null;
|
||||
});
|
||||
fx(()->{agent.occupied=true;agent.changed();return null;});
|
||||
fx(()->{
|
||||
assertEquals(window.context.text("ai.cleanup"),((Button)window.view.lookup("#ai-recover")).getText());return null;
|
||||
});
|
||||
fx(()->{agent.occupied=false;agent.ready=true;agent.changed();return null;});
|
||||
fx(()->{
|
||||
assertEquals(window.context.text("ai.recover"),((Button)window.view.lookup("#ai-recover")).getText());return null;
|
||||
});
|
||||
}
|
||||
} finally {fx(()->{window.view.close();window.context.close();window.stage.close();return null;});}
|
||||
}
|
||||
record Window(Stage stage,AppearanceContext context,AiWorkspace view){}
|
||||
static final class Peer implements AgentConnection {
|
||||
boolean ready=true,occupied;int recoveries;Consumer<Status> observer=s->{};
|
||||
public boolean available(){return true;}public boolean servicesReady(){return ready;}public boolean busy(){return occupied;}
|
||||
public Status status(){return new Status(State.READY,"");}
|
||||
public AutoCloseable observe(Consumer<Status> listener){observer=listener;listener.accept(status());return ()->observer=s->{};}
|
||||
void changed(){observer.accept(status());}
|
||||
public void events(Consumer<Event> listener){}public void permissions(Function<Permission,CompletionStage<String>> handler){}
|
||||
public CompletionStage<Void> connect(AcpSettings settings){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> login(){throw new AssertionError("No login in UI fixture");}
|
||||
public CompletionStage<String> newSession(){throw new AssertionError("No prompt in UI fixture");}
|
||||
public Turn prompt(String id,String text){throw new AssertionError("No model in UI fixture");}
|
||||
public CompletionStage<Void> cancel(String id){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> recoverActivity(){recoveries++;return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> closeAsync(){return CompletableFuture.completedFuture(null);}
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ Desktop.ini
|
||||
/.codex/config.toml
|
||||
/.studio/mcp/
|
||||
/assets/.prometeu/cache.json
|
||||
/.codex/.studio-mcp.previous.toml
|
||||
|
||||
Reference in New Issue
Block a user