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:
+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());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user