feat(studio): coordinate integrated AI activity and internal language services
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

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:
2026-11-27 09:58:57 +00:00
parent 802a13a6aa
commit e6542df56e
46 changed files with 1485 additions and 180 deletions
+15
View File
@@ -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);}
}
}