feat(studio): add AI workspace with Codex ACP integration
This commit is contained in:
@@ -168,6 +168,19 @@ tasks.withType<Test>().configureEach {
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayProcessTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayDesktopTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioProjectsDesktopTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/CodexAcpSmokeTest.class") }
|
||||
tasks.register<Test>("codexAcpSmoke") {
|
||||
group = "verification"
|
||||
description = "Sends one minimal ACP prompt using an existing ChatGPT login in a disposable project."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/CodexAcpSmokeTest.class")
|
||||
systemProperty("studio.test.codexAcp", providers.gradleProperty("studioCodexAcp").getOrElse(""))
|
||||
systemProperty("studio.test.codexProject", providers.gradleProperty("studioCodexProject").getOrElse(""))
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
tasks.register<Test>("studioProjectsDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies launcher, new-project wizard, loading shield and window lifecycle on a desktop."
|
||||
|
||||
@@ -184,6 +184,11 @@ public class StudioApplicationConfiguration {
|
||||
return new p.studio.core.project.preferences.JsonRuntimeSettingsStore(
|
||||
Path.of(System.getProperty("user.home"), ".prometeu-studio", "runtime-settings.json"), mapper);
|
||||
}
|
||||
@Bean
|
||||
p.studio.api.preferences.AgentSettingsStore agentSettingsStore(ObjectMapper mapper) {
|
||||
return new p.studio.core.project.preferences.JsonAgentSettingsStore(
|
||||
Path.of(System.getProperty("user.home"),".prometeu-studio","ai-settings.json"),mapper);
|
||||
}
|
||||
|
||||
@Bean
|
||||
ProjectActivityHistoryStore projectActivityHistoryStore(ObjectMapper mapper) {
|
||||
@@ -332,7 +337,7 @@ 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.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings) {
|
||||
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
|
||||
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
@@ -341,6 +346,8 @@ public class StudioApplicationConfiguration {
|
||||
activityHistoryStore, connectionGuide);
|
||||
factory.setAnimationService(animationService);
|
||||
factory.setRuntimeSettings(runtimeSettings);
|
||||
factory.setAgentSettings(agentSettings);
|
||||
factory.setAgentConnections(root->new p.studio.app.acp.CodexAcpConnection(root,mapper));
|
||||
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);}});
|
||||
|
||||
@@ -36,6 +36,11 @@ public final class StudioUiFactory {
|
||||
private p.studio.ui.javafx2.window.WindowResources interactiveResources;
|
||||
private p.studio.api.preferences.RuntimeSettingsStore runtimeSettings;
|
||||
private String initialRuntime;
|
||||
private p.studio.api.preferences.AgentSettingsStore agentSettings;
|
||||
private p.studio.api.ai.AcpSettings initialAgent;
|
||||
public void setAgentSettings(p.studio.api.preferences.AgentSettingsStore settings){agentSettings=Objects.requireNonNull(settings);}
|
||||
private p.studio.api.ai.AgentConnectionFactory agentConnections;
|
||||
public void setAgentConnections(p.studio.api.ai.AgentConnectionFactory factory){agentConnections=Objects.requireNonNull(factory);}
|
||||
public void setRuntimeSettings(p.studio.api.preferences.RuntimeSettingsStore settings) { runtimeSettings=Objects.requireNonNull(settings); }
|
||||
public void enableInteractive(ExecutionControllerFactory factory,
|
||||
java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> saver) {
|
||||
@@ -44,11 +49,15 @@ public final class StudioUiFactory {
|
||||
public void prepareInteractive(){
|
||||
interactiveResources=new p.studio.ui.javafx2.window.WindowResources();
|
||||
initialRuntime=Objects.requireNonNull(runtimeSettings,"runtimeSettings").load();
|
||||
initialAgent=Objects.requireNonNull(agentSettings,"agentSettings").load();
|
||||
}
|
||||
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
|
||||
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
|
||||
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
var coordinator=new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources,languageCatalog,windowStateStore,runtimeSettings,initialRuntime);
|
||||
if(agentConnections!=null)coordinator.setAgentConnections(agentConnections);
|
||||
coordinator.setAgentSettings(agentSettings,initialAgent);
|
||||
return coordinator;
|
||||
}
|
||||
private final ProjectCatalog projectCatalog;
|
||||
private final KnownProjects knownProjects;
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.ai.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.*;
|
||||
|
||||
/** ACP v1 line transport. Owns only its launched process tree, never the caller's Codex process. */
|
||||
public final class CodexAcpConnection implements AgentConnection {
|
||||
private final Path root;
|
||||
private final ObjectMapper json;
|
||||
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
private final ExecutorService writer = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("studio-acp-writer").factory());
|
||||
private final Map<String, CompletableFuture<JsonNode>> pending = new ConcurrentHashMap<>();
|
||||
private final Set<String> sessions = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> cancelling = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, CompletableFuture<String>> turns = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletableFuture<Void>> accepted = new ConcurrentHashMap<>();
|
||||
private final Map<String, ObjectNode> permissionRequests = new ConcurrentHashMap<>();
|
||||
private final CopyOnWriteArrayList<Consumer<Status>> observers = new CopyOnWriteArrayList<>();
|
||||
private final AtomicLong sequence = new AtomicLong();
|
||||
private final Object outputLock = new Object();
|
||||
private final Object terminationLock = new Object();
|
||||
private volatile Status status = new Status(State.DISCONNECTED, "");
|
||||
private volatile Process process;
|
||||
private volatile Writer output;
|
||||
private volatile Consumer<Event> events = e -> {};
|
||||
private volatile Function<Permission, CompletionStage<String>> permissions = p -> CompletableFuture.completedFuture(null);
|
||||
private volatile boolean closing;
|
||||
private volatile boolean chatGptLogin;
|
||||
private volatile CompletableFuture<Void> shutdown;
|
||||
private volatile long connectionEpoch;
|
||||
private final Set<ProcessHandle> ownedProcesses = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public CodexAcpConnection(Path root, ObjectMapper mapper) { this.root=root.toAbsolutePath().normalize();json=mapper.copy(); }
|
||||
public boolean available(){return true;}
|
||||
public Status status(){return status;}
|
||||
public AutoCloseable observe(Consumer<Status> listener){observers.add(listener);listener.accept(status);return ()->observers.remove(listener);}
|
||||
public void events(Consumer<Event> listener){events=Objects.requireNonNull(listener);}
|
||||
public void permissions(Function<Permission,CompletionStage<String>> handler){permissions=Objects.requireNonNull(handler);}
|
||||
private void state(State value,String detail){status=new Status(value,detail);for(var l:observers)try{l.accept(status);}catch(RuntimeException ignored){}}
|
||||
private static String message(Throwable failure){
|
||||
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();
|
||||
String text=Objects.toString(failure.getMessage(),failure.getClass().getSimpleName());
|
||||
text = message(text);
|
||||
return text.substring(0,Math.min(text.length(),1000));
|
||||
}
|
||||
|
||||
public synchronized CompletionStage<Void> connect(AcpSettings settings){
|
||||
if(closing)return CompletableFuture.failedFuture(new IllegalStateException("Agent connection is closed"));
|
||||
if(status.state()!=State.DISCONNECTED&&status.state()!=State.FAILED)
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Agent is already connected"));
|
||||
state(State.CONNECTING,"");
|
||||
long epoch=++connectionEpoch;
|
||||
return CompletableFuture.runAsync(()->{
|
||||
var owned=new java.util.concurrent.atomic.AtomicReference<Process>();
|
||||
try{
|
||||
terminate();
|
||||
var command=new ArrayList<String>();command.add(settings.executable());command.addAll(settings.arguments());
|
||||
var builder=new ProcessBuilder(command).directory(root.toFile());
|
||||
builder.environment().remove("OPENAI_API_KEY");builder.environment().remove("CODEX_API_KEY");
|
||||
builder.environment().put("INITIAL_AGENT_MODE","workspace-write");
|
||||
synchronized(this){if(closing)throw new IOException("Connection closed");process=builder.start();output=new OutputStreamWriter(process.getOutputStream(),StandardCharsets.UTF_8);}
|
||||
Process launched=process;
|
||||
owned.set(launched);
|
||||
ownedProcesses.add(launched.toHandle());
|
||||
workers.submit(()->track(launched));
|
||||
workers.submit(()->read(launched,epoch));workers.submit(()->{try(var stderr=launched.getErrorStream()){stderr.transferTo(OutputStream.nullOutputStream());}catch(IOException ignored){}});
|
||||
var result=request("initialize",json.createObjectNode().put("protocolVersion",1)
|
||||
.set("clientInfo",json.createObjectNode().put("name","prometeu-studio").put("version","1")),20).join();
|
||||
if(result.path("protocolVersion").asInt()!=1)throw new IOException("Incompatible ACP protocol");
|
||||
chatGptLogin=false;
|
||||
for(var method:result.path("authMethods"))if(method.path("id").asText().equals("chat-gpt"))chatGptLogin=true;
|
||||
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);
|
||||
}
|
||||
},workers);
|
||||
}
|
||||
|
||||
private CompletableFuture<JsonNode> queryAuth(){
|
||||
return request("auth/status",json.createObjectNode(),10).thenApply(value->{auth(value);return value;});
|
||||
}
|
||||
private void auth(JsonNode value){
|
||||
if(closing||status.state()==State.CONNECTING)return;
|
||||
boolean ready=false;
|
||||
if(value.path("state").asText().equals("authenticated"))
|
||||
for(var account:value.path("accounts"))if(account.path("active").asBoolean(true)&&account.path("label").asText().toLowerCase(Locale.ROOT).contains("chatgpt"))ready=true;
|
||||
state(ready?State.READY:State.CONNECTED,"");
|
||||
}
|
||||
public CompletionStage<Void> login(){
|
||||
if(!chatGptLogin||closing)return CompletableFuture.failedFuture(new IllegalStateException("Connect the ChatGPT-capable agent first"));
|
||||
state(State.AUTHENTICATING,"");
|
||||
return request("authenticate",json.createObjectNode().put("methodId","chat-gpt"),180)
|
||||
.thenCompose(v->queryAuth()).thenAccept(v->{})
|
||||
.whenComplete((v,f)->{if(f!=null&&!closing&&status.state()!=State.FAILED)state(State.CONNECTED,message(f));});
|
||||
}
|
||||
public CompletionStage<String> newSession(){
|
||||
if(status.state()!=State.READY)return CompletableFuture.failedFuture(new IllegalStateException("Sign in with ChatGPT first"));
|
||||
ObjectNode params=json.createObjectNode().put("cwd",root.toString());params.putArray("mcpServers");
|
||||
return request("session/new",params,30).thenCompose(result->{
|
||||
String id=result.path("sessionId").asText();
|
||||
if(id.isBlank())return CompletableFuture.failedFuture(new IllegalStateException("Agent returned no session ID"));
|
||||
boolean mode=false;for(var m:result.path("modes").path("availableModes"))if(m.path("id").asText().equals("workspace-write"))mode=true;
|
||||
if(!mode)return CompletableFuture.failedFuture(new IllegalStateException("Agent does not offer workspace-write mode"));
|
||||
return request("session/set_mode",json.createObjectNode().put("sessionId",id).put("modeId","workspace-write"),10)
|
||||
.thenApply(v->{sessions.add(id);return id;});
|
||||
});
|
||||
}
|
||||
public synchronized Turn prompt(String id,String text){
|
||||
var acknowledgement=new CompletableFuture<Void>();var done=new CompletableFuture<String>();
|
||||
if(status.state()!=State.READY||!sessions.contains(id)||!turns.isEmpty()||text.isBlank()){
|
||||
var failure=new IllegalStateException("Agent is not ready or another request is running");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);return new Turn(acknowledgement,done);
|
||||
}
|
||||
cancelling.remove(id);turns.put(id,done);accepted.put(id,acknowledgement);
|
||||
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"));}
|
||||
else{
|
||||
if(failure instanceof TimeoutException)state(State.FAILED,"Agent request timed out");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);
|
||||
if(failure instanceof TimeoutException){Process owned=process;workers.submit(()->{terminate(owned);fail(failure);});}
|
||||
}
|
||||
});
|
||||
return new Turn(acknowledgement,done);
|
||||
}
|
||||
public CompletionStage<Void> cancel(String id){
|
||||
var turn=turns.get(id);if(turn==null)return CompletableFuture.completedFuture(null);
|
||||
cancelling.add(id);cancelPermissions(id);
|
||||
notify("session/cancel",json.createObjectNode().put("sessionId",id));
|
||||
return turn.handle((v,f)->(Void)null).toCompletableFuture().orTimeout(10,TimeUnit.SECONDS)
|
||||
.exceptionallyCompose(failure->CompletableFuture.runAsync(()->{
|
||||
terminate();fail(new IOException("Cancellation timed out; agent disconnected"));
|
||||
},workers));
|
||||
}
|
||||
|
||||
private CompletableFuture<JsonNode> request(String method,ObjectNode params,int seconds){
|
||||
String id=Long.toString(sequence.incrementAndGet());var result=new CompletableFuture<JsonNode>();
|
||||
if(closing){result.completeExceptionally(new IOException("Connection closed"));return result;}
|
||||
pending.put(id,result);
|
||||
send(json.createObjectNode().put("jsonrpc","2.0").put("id",id).put("method",method).set("params",params))
|
||||
.whenComplete((v,f)->{if(f!=null)result.completeExceptionally(f);});
|
||||
result.orTimeout(seconds,TimeUnit.SECONDS).whenComplete((v,f)->pending.remove(id));return result;
|
||||
}
|
||||
private void notify(String method,ObjectNode params){send(json.createObjectNode().put("jsonrpc","2.0").put("method",method).set("params",params));}
|
||||
private CompletableFuture<Void> send(JsonNode frame){
|
||||
Writer destination=output;
|
||||
try{return CompletableFuture.runAsync(()->{try{write(frame,destination);}catch(IOException failure){throw new CompletionException(failure);}},writer);}
|
||||
catch(RejectedExecutionException failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
private void write(JsonNode message,Writer destination)throws IOException{
|
||||
synchronized(outputLock){if(destination==null||output!=destination)throw new IOException("ACP is disconnected");destination.write(json.writeValueAsString(message));destination.write('\n');destination.flush();}
|
||||
}
|
||||
private void read(Process launched,long epoch){
|
||||
try(var input=new BufferedReader(new InputStreamReader(launched.getInputStream(),StandardCharsets.UTF_8))){
|
||||
StringBuilder line=new StringBuilder();int c;
|
||||
while((c=input.read())!=-1){
|
||||
if(c=='\n'){if(!line.isEmpty()&&process==launched)receive(json.readTree(line.toString()));line.setLength(0);}
|
||||
else if(c!='\r'){if(line.length()>=4*1024*1024)throw new IOException("ACP frame exceeds limit");line.append((char)c);}
|
||||
}
|
||||
if(!closing&&process==launched){fail(epoch,new IOException("ACP process disconnected"));workers.submit(()->terminate(launched));}
|
||||
}catch(Throwable failure){if(!closing&&process==launched){fail(epoch,failure);workers.submit(()->terminate(launched));}}
|
||||
}
|
||||
private void receive(JsonNode message)throws IOException{
|
||||
if(message.has("method")){
|
||||
String method=message.path("method").asText();var params=message.path("params");
|
||||
if(method.equals("session/update"))update(params);
|
||||
else if(method.equals("auth/status_update"))auth(params);
|
||||
else if(method.equals("session/request_permission")&&message.has("id"))permission(message);
|
||||
else if(message.has("id"))send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",message.get("id"))
|
||||
.set("error",json.createObjectNode().put("code",-32601).put("message","Unsupported client method")));
|
||||
}else if(message.has("id")){
|
||||
var response=pending.get(message.path("id").asText());
|
||||
if(response!=null){
|
||||
if(message.has("error"))response.completeExceptionally(new IOException(message(message.path("error").path("message").asText("ACP error"))));
|
||||
else if(message.has("result"))response.complete(message.path("result"));
|
||||
else response.completeExceptionally(new IOException("Invalid ACP response: result is missing"));
|
||||
}
|
||||
}
|
||||
}
|
||||
private static String message(String value){return value.replaceAll("(?i)(sk-[A-Za-z0-9_-]+|Bearer\\s+\\S+)","[redacted]");}
|
||||
private void update(JsonNode params){
|
||||
String id=params.path("sessionId").asText();if(!sessions.contains(id))return;
|
||||
var update=params.path("update");String type=update.path("sessionUpdate").asText();
|
||||
Event event=null;
|
||||
if(type.equals("agent_message_chunk")&&update.path("content").path("type").asText().equals("text"))
|
||||
event=new Event(id,Kind.TEXT,update.path("content").path("text").asText());
|
||||
else if(type.equals("tool_call")||type.equals("tool_call_update"))
|
||||
event=new Event(id,Kind.ACTIVITY,update.path("title").asText(update.path("status").asText("Tool activity")));
|
||||
else if(type.equals("agent_thought_chunk"))event=new Event(id,Kind.ACTIVITY,"Working");
|
||||
if(event!=null){var acknowledgement=accepted.get(id);if(acknowledgement!=null)acknowledgement.complete(null);events.accept(event);}
|
||||
}
|
||||
private void permission(JsonNode message){
|
||||
var params=message.path("params");String session=params.path("sessionId").asText();String key=message.path("id").toString();
|
||||
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();
|
||||
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)))
|
||||
.whenComplete((choice,failure)->replyPermission(key,failure==null&&choices.stream().anyMatch(c->c.id().equals(choice))?choice:null));}
|
||||
catch(RuntimeException failure){replyPermission(key,null);}
|
||||
}
|
||||
private void replyPermission(String key,String choice){
|
||||
var request=permissionRequests.remove(key);if(request==null)return;
|
||||
var outcome=json.createObjectNode().put("outcome",choice==null?"cancelled":"selected");if(choice!=null)outcome.put("optionId",choice);
|
||||
send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",request.get("id"))
|
||||
.set("result",json.createObjectNode().set("outcome",outcome)));
|
||||
}
|
||||
private void cancelPermissions(String id){for(var e:permissionRequests.entrySet())if(e.getValue().path("sessionId").asText().equals(id))replyPermission(e.getKey(),null);}
|
||||
private void fail(Throwable failure){
|
||||
fail(connectionEpoch,failure);
|
||||
}
|
||||
private synchronized void fail(long epoch,Throwable failure){
|
||||
if(epoch!=connectionEpoch)return;
|
||||
sessions.clear();
|
||||
var requests=List.copyOf(pending.values());
|
||||
if(!closing)state(State.FAILED,message(failure));
|
||||
for(var f:requests)f.completeExceptionally(failure);
|
||||
}
|
||||
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));
|
||||
closing=true;state(State.CLOSING,"");
|
||||
shutdown=CompletableFuture.runAsync(()->{
|
||||
try{CompletableFuture.allOf(stopping.toArray(CompletableFuture[]::new)).get(11,TimeUnit.SECONDS);}catch(Exception ignored){}
|
||||
try{terminate();fail(new IOException("Connection closed"));state(State.CLOSED,"");writer.shutdownNow();workers.shutdown();}
|
||||
catch(RuntimeException failure){state(State.FAILED,message(failure));synchronized(this){shutdown=null;}throw failure;}
|
||||
},workers);
|
||||
return shutdown;
|
||||
}
|
||||
private void track(Process launched){
|
||||
while(launched==process&&launched.isAlive()){
|
||||
launched.descendants().forEach(ownedProcesses::add);
|
||||
try{Thread.sleep(100);}catch(InterruptedException e){Thread.currentThread().interrupt();return;}
|
||||
}
|
||||
}
|
||||
private void terminate(){terminate(process);}
|
||||
private void terminate(Process owned){synchronized(terminationLock){
|
||||
if(owned==null||owned!=process)return;
|
||||
owned.descendants().forEach(ownedProcesses::add);
|
||||
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();}
|
||||
tree.stream().filter(ProcessHandle::isAlive).forEach(ProcessHandle::destroyForcibly);
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3);
|
||||
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");
|
||||
process=null;output=null;ownedProcesses.clear();
|
||||
}}
|
||||
}
|
||||
@@ -42,16 +42,36 @@ class StudioProjectsDesktopTest {
|
||||
}
|
||||
@BeforeAll static void start()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);}
|
||||
@AfterAll static void end(){Platform.exit();}
|
||||
static void fire(Stage stage,String id)throws Exception {fx(()->{var b=(Button)stage.getScene().lookup("#"+id);assertNotNull(b,id);assertFalse(b.isDisabled(),id);b.fire();return null;});}
|
||||
static void fire(Stage stage,String id)throws Exception {fx(()->{var b=(ButtonBase)stage.getScene().lookup("#"+id);assertNotNull(b,id);assertFalse(b.isDisabled(),id);b.fire();return null;});}
|
||||
static Stage wizard()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#wizard-name")!=null).findFirst().orElseThrow());}
|
||||
static Stage shield()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#loading-phase")!=null).findFirst().orElseThrow());}
|
||||
static Stage settings()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#settings-dialog")!=null).findFirst().orElseThrow());}
|
||||
static void foreground(Stage stage)throws Exception {
|
||||
for(int attempt=0;attempt<3;attempt++) {
|
||||
if(fx(stage::isFocused))return;
|
||||
fx(()->{stage.toFront();stage.requestFocus();return null;});
|
||||
Thread.sleep(150);
|
||||
if(fx(stage::isFocused))return;
|
||||
StudioPlayDesktopTest.focus(stage);
|
||||
}
|
||||
assertTrue(fx(stage::isFocused),"Desktop qualification requires the project window in the foreground");
|
||||
}
|
||||
static Stage chatDialog(String id)throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#"+id)!=null).findFirst().orElseThrow());}
|
||||
static void chatAction(Stage stage,String id)throws Exception {
|
||||
fx(()->{var menu=(MenuButton)stage.getScene().lookup("#ai-chat-actions");
|
||||
assertFalse(menu.isDisabled());var item=menu.getItems().stream().filter(i->id.equals(i.getId())).findFirst().orElseThrow();
|
||||
assertFalse(item.isDisable());item.fire();return null;});
|
||||
}
|
||||
|
||||
private record Harness(StudioWindowCoordinator2 window,Stage stage,ExecutorService worker) implements AutoCloseable {
|
||||
@Override public void close()throws Exception {fx(window::closeAsync).toCompletableFuture().get(15,TimeUnit.SECONDS);worker.shutdown();assertTrue(worker.awaitTermination(10,TimeUnit.SECONDS));}
|
||||
}
|
||||
private Harness harness(ProjectCatalog catalog,KnownProjects known,ProjectLocalStudioSetupStore setups,
|
||||
WindowStateStore windows,RuntimeSettingsStore runtimes)throws Exception {
|
||||
return harness(catalog,known,setups,windows,runtimes,null);
|
||||
}
|
||||
private Harness harness(ProjectCatalog catalog,KnownProjects known,ProjectLocalStudioSetupStore setups,
|
||||
WindowStateStore windows,RuntimeSettingsStore runtimes,ExecutionControllerFactory executions)throws Exception {
|
||||
var initial=PresentationSettings.defaults(Locale.ENGLISH);
|
||||
var resources=new WindowResources(initial,new SettingsStore(){public PresentationSettings load(){return initial;}public void save(PresentationSettings value){assertFalse(Platform.isFxApplicationThread());}});
|
||||
var executor=Executors.newFixedThreadPool(3);
|
||||
@@ -66,7 +86,7 @@ class StudioProjectsDesktopTest {
|
||||
}
|
||||
};
|
||||
String global=runtimes.load();Stage stage=fx(Stage::new);
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,sessions,null,setups::save,executor,resources,()->List.of(),windows,runtimes,global));
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,sessions,executions,setups::save,executor,resources,()->List.of(),windows,runtimes,global));
|
||||
fx(()->{window.showLauncher();return null;});await(()->fx(()->window.launcherStage().isShowing()));
|
||||
return new Harness(window,stage,executor);
|
||||
}
|
||||
@@ -76,6 +96,96 @@ class StudioProjectsDesktopTest {
|
||||
private static void closeProject(Harness harness)throws Exception {
|
||||
fx(()->{harness.window.requestCloseProject();return null;});await(()->fx(()->harness.window.projectSession()==null&&harness.window.launcherStage().isShowing()));
|
||||
}
|
||||
@Test void acpSettingsLoginSendPermissionsDeleteAndCloseFollowTheSelectedChat()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("ACP Game",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));known.remember(project);
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
var connection=new AtomicReference<p.studio.app.acp.CodexAcpConnection>();
|
||||
Path globalFile=temporary.resolve("ai-settings.json");
|
||||
var globals=new p.studio.core.project.preferences.JsonAgentSettingsStore(globalFile,mapper);
|
||||
var command=List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",System.getProperty("studio.test.classpath"),
|
||||
p.studio.app.acp.AcpFixture.class.getName(),"login-delayed-cancel");
|
||||
var legacy=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(project.rootPath().resolve(".studio/setup.json").toFile());
|
||||
legacy.putObject("acp").put("executable","/obsolete/npx").putArray("arguments");
|
||||
mapper.writeValue(project.rootPath().resolve(".studio/setup.json").toFile(),legacy);
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)){
|
||||
var initial=globals.load();
|
||||
fx(()->{h.window.setAgentSettings(globals,initial);h.window.setAgentConnections(root->{var c=new p.studio.app.acp.CodexAcpConnection(root,mapper);connection.set(c);return c;});
|
||||
h.window.openPreferences();return null;});var cancelled=settings();
|
||||
fx(()->{assertTrue(cancelled.getScene().lookup("#ai-connect").isDisabled());
|
||||
((TextField)cancelled.getScene().lookup("#ai-executable")).setText("do-not-save");return null;});
|
||||
fire(cancelled,"settings-cancel");assertEquals(initial,globals.load());
|
||||
fx(()->{h.window.openPreferences();return null;});var draft=settings();
|
||||
fx(()->{((TextField)draft.getScene().lookup("#ai-executable")).setText(command.getFirst());
|
||||
((TextArea)draft.getScene().lookup("#ai-arguments")).setText(String.join("\n",command.subList(1,command.size())));return null;});
|
||||
fire(draft,"settings-apply");await(()->fx(()->!draft.isShowing()));
|
||||
open(h,project);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
fx(()->{h.window.openProjectSettings(false);return null;});var projectSettings=settings();
|
||||
assertNull(fx(()->projectSettings.getScene().lookup("#ai-executable")),"ACP must not be configured per project");fire(projectSettings,"settings-cancel");
|
||||
fx(()->{h.window.openPreferences();return null;});var configuration=settings();
|
||||
await(()->fx(()->!configuration.getScene().lookup("#ai-login").isDisabled()));fire(configuration,"ai-login");
|
||||
await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.READY);
|
||||
assertEquals(command.getFirst(),globals.load().executable());
|
||||
fx(()->{((ScrollPane)((javafx.scene.layout.BorderPane)configuration.getScene().getRoot()).getCenter()).setVvalue(1);return null;});
|
||||
capture(configuration,"acp-connected-settings");fire(configuration,"settings-cancel");
|
||||
fire(h.stage,"ai-prompt-toggle");fire(h.stage,"ai-compact-new-chat");
|
||||
var selector=fx(()->(ComboBox<Object>)h.stage.getScene().lookup("#ai-chat-select"));var a=fx(selector::getValue);
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
fx(()->{prompt.setText("draft A · personagem");return null;});fire(h.stage,"ai-compact-new-chat");var b=fx(selector::getValue);
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
await(()->fx(()->"ai-tab".equals(tabs.getSelectionModel().getSelectedItem().getId())&&prompt.getText().isEmpty()));
|
||||
fx(()->{selector.setValue(a);return null;});assertEquals("draft A · personagem",fx(prompt::getText));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-conversation")).getText()));
|
||||
assertTrue(fx(()->((Label)h.stage.getScene().lookup("#ai-connection-status")).getText().contains("Chat 2")));
|
||||
fire(h.stage,"ai-cancel");await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertFalse(fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");
|
||||
await(()->fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
fx(()->{selector.setValue(b);return null;});assertEquals("",fx(prompt::getText));
|
||||
assertTrue(fx(()->((TextArea)h.stage.getScene().lookup("#ai-conversation")).getText().contains("Cancelled")));
|
||||
fx(()->{prompt.setText("reject");return null;});fire(h.stage,"ai-send");
|
||||
await(()->fx(()->((Label)h.stage.getScene().lookup("#ai-activity")).getText().contains("fixture rejection")));
|
||||
assertEquals("reject",fx(prompt::getText));
|
||||
fx(()->{prompt.setText("permission");return null;});fire(h.stage,"ai-send");
|
||||
await(()->fx(()->Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#ai-permission-dialog")!=null)));
|
||||
var permission=chatDialog("ai-permission-dialog");capture(permission,"acp-explicit-permission");
|
||||
fx(()->{var pane=(DialogPane)permission.getScene().lookup("#ai-permission-dialog");
|
||||
((Button)pane.lookupButton(ButtonType.CANCEL)).fire();return null;});
|
||||
await(()->fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
assertTrue(Files.readString(project.rootPath().resolve("permission.json")).contains("cancelled"));
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");await(()->fx(()->prompt.getText().isEmpty()));
|
||||
chatAction(h.stage,"ai-compact-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertEquals(2,fx(()->selector.getItems().size()),"Delete must wait for cancellation to finish");
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");await(()->fx(()->selector.getItems().size()==1));
|
||||
assertEquals(a,fx(selector::getValue));assertEquals("draft A · personagem",fx(prompt::getText));
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");await(()->fx(()->prompt.getText().isEmpty()));
|
||||
capture(h.stage,"acp-live-conversation-fixture");
|
||||
fx(()->{h.window.requestCloseProject();return null;});await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertNotNull(fx(h.window::projectSession),"Project stays owned until the agent stops");
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");
|
||||
await(()->fx(()->h.window.projectSession()==null&&h.window.launcherStage().isShowing()));
|
||||
assertEquals(p.studio.api.ai.AgentConnection.State.CLOSED,connection.get().status().state());
|
||||
assertFalse(ProcessHandle.of(Long.parseLong(Files.readString(project.rootPath().resolve("parent.pid")))).map(ProcessHandle::isAlive).orElse(false));
|
||||
open(h,project);fire(h.stage,"ai-prompt-toggle");
|
||||
assertEquals(0,fx(()->((ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select")).getItems().size()));
|
||||
assertEquals(command.getFirst(),globals.load().executable());closeProject(h);
|
||||
var second=catalog.createProject(new ProjectCreationRequest("Second ACP Game",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
open(h,second);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
assertFalse(mapper.readTree(second.rootPath().resolve(".studio/setup.json").toFile()).has("acp"));
|
||||
assertEquals(command.getFirst(),globals.load().executable());
|
||||
}
|
||||
try(var restarted=harness(catalog,known,setups,windows,runtimes)){
|
||||
var reloaded=new p.studio.core.project.preferences.JsonAgentSettingsStore(globalFile,mapper);var initial=reloaded.load();
|
||||
fx(()->{restarted.window.setAgentSettings(reloaded,initial);restarted.window.setAgentConnections(root->{var c=new p.studio.app.acp.CodexAcpConnection(root,mapper);connection.set(c);return c;});return null;});
|
||||
open(restarted,project);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
assertEquals(command.getFirst(),reloaded.load().executable());
|
||||
}
|
||||
}
|
||||
@Test void projectChromeKeepsEqualStripsAndContextualFooterAcrossThemesAndScales()throws Exception{
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
@@ -94,7 +204,7 @@ class StudioProjectsDesktopTest {
|
||||
for(double width:new double[]{1200,680}){
|
||||
fx(()->{h.stage.setWidth(width);h.stage.setHeight(width==680?480:850);return null;});
|
||||
capture(h.stage,"chrome-"+theme+"-"+language+"-"+scale+"-"+width);
|
||||
fx(()->{var scene=h.stage.getScene();var header=(javafx.scene.layout.Region)scene.lookup("#studio-header");var footer=(Label)scene.lookup("#studio-footer");
|
||||
fx(()->{var scene=h.stage.getScene();var header=(javafx.scene.layout.Region)scene.lookup("#studio-header");var footer=(javafx.scene.layout.Region)scene.lookup("#studio-footer-bar");
|
||||
assertEquals(header.getHeight(),footer.getHeight(),.1);
|
||||
assertEquals(scene.getHeight(),footer.localToScene(0,footer.getHeight()).getY(),1);
|
||||
var play=scene.lookup("#play").localToScene(scene.lookup("#play").getBoundsInLocal());
|
||||
@@ -115,6 +225,7 @@ class StudioProjectsDesktopTest {
|
||||
assertTrue(workspace.getBackground()==null||workspace.getBackground().getFills().size()<=1,"Workspace must not retain the layered panel bevel");
|
||||
var menu=((MenuBar)scene.lookup("#studio-menus")).getMenus().getFirst();assertEquals("Prometeu Studio",menu.getText());assertNotNull(menu.getGraphic());
|
||||
var tabs=(TabPane)scene.lookup("#project-tabs");assertTrue(tabs.getStyleClass().contains("studio-tabs"));
|
||||
assertUniformTabs(tabs);
|
||||
assertTrue(tabs.lookupAll(".tab").stream().filter(n->n instanceof javafx.scene.layout.Region).allMatch(n->((javafx.scene.layout.Region)n).getShape()!=null));
|
||||
var split=(SplitPane)scene.lookup("#gameplay-split");assertSame(split,tabs.getTabs().getFirst().getContent());
|
||||
assertEquals(javafx.geometry.Orientation.VERTICAL,split.getOrientation());
|
||||
@@ -135,6 +246,7 @@ class StudioProjectsDesktopTest {
|
||||
capture(h.stage,"empty-tab");
|
||||
fx(()->{assertFalse(h.stage.getScene().lookup("#tab-content-outline").isVisible(),"Empty tab must not keep the previous outline");
|
||||
((TabPane)h.stage.getScene().lookup("#project-tabs")).getTabs().remove(unknown);
|
||||
((TabPane)h.stage.getScene().lookup("#project-tabs")).getSelectionModel().selectFirst();
|
||||
assertTrue(((Label)h.stage.getScene().lookup("#studio-footer")).getText().startsWith("Gameplay"));return null;});
|
||||
capture(h.stage,"restored-gameplay-tab");
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#tab-content-outline").isVisible()));
|
||||
@@ -148,6 +260,276 @@ class StudioProjectsDesktopTest {
|
||||
fx(()->{execution.transitionToResuming();execution.transitionToRunning();execution.transitionToStopping();execution.transitionToStopped();return null;});
|
||||
}
|
||||
}
|
||||
@Test void aiVisualSharesOnePromptAndDiscardsItOnProjectClose()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("AI presentation",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
var ai=fx(()->tabs.getTabs().stream().filter(t->"ai-tab".equals(t.getId())).findFirst().orElseThrow());
|
||||
var surface=fx(()->h.stage.getScene().lookup("#game-surface"));
|
||||
foreground(h.stage);
|
||||
fx(()->{surface.requestFocus();return null;});
|
||||
var access=fx(()->(ToggleButton)h.stage.getScene().lookup("#ai-prompt-toggle"));
|
||||
assertFalse(fx(access::isSelected));
|
||||
var inactiveBackground=fx(()->access.getBackground());
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
assertNotNull(prompt);
|
||||
assertTrue(fx(prompt::isDisabled));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
capture(h.stage,"ai-drawer-initial-focus");
|
||||
assertTrue(fx(access::isSelected));
|
||||
assertNotEquals(inactiveBackground,fx(access::getBackground),"An open prompt needs a distinct footer control background");
|
||||
assertNull(fx(()->h.stage.getScene().lookup("#ai-prompt-collapse")));
|
||||
assertSame(prompt,fx(()->h.stage.getScene().getFocusOwner()),"Opening the drawer must move keyboard focus to the prompt");
|
||||
await(()->fx(prompt::isFocused));assertFalse(fx(surface::isFocused));
|
||||
fx(()->{prompt.setText("Draft across views · personagem");return null;});
|
||||
capture(h.stage,"ai-drawer-dark-en");
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var host=(SplitPane)scene.lookup("#ai-workspace-host");
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var upper=host.getItems().getFirst();
|
||||
assertTrue(upper.localToScene(upper.getBoundsInLocal()).getMaxY()<=drawer.localToScene(0,0).getY());
|
||||
var footer=scene.lookup("#studio-footer-bar");
|
||||
assertTrue(drawer.localToScene(drawer.getBoundsInLocal()).getMaxY()<=footer.localToScene(0,0).getY());
|
||||
host.setDividerPositions(.45);return null;
|
||||
});
|
||||
capture(h.stage,"ai-drawer-resized");
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
await(()->fx(surface::isFocused));
|
||||
assertFalse(fx(access::isSelected));
|
||||
assertNull(fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
assertEquals("Draft across views · personagem",fx(prompt::getText));
|
||||
|
||||
fx(()->{tabs.getSelectionModel().select(ai);return null;});
|
||||
capture(h.stage,"ai-workspace-dark-en");
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
assertSame(prompt,scene.lookup("#ai-prompt"));
|
||||
assertEquals(1,scene.getRoot().lookupAll("#ai-prompt").size());
|
||||
assertNull(scene.lookup("#ai-prompt-drawer"));
|
||||
assertTrue(((SplitPane)scene.lookup("#ai-workspace-host")).getItems().size()==1);
|
||||
for(String id:List.of("ai-load-chat","ai-attach","ai-send"))
|
||||
assertTrue(scene.lookup("#"+id).isDisabled(),id);
|
||||
assertEquals(1,((ListView<?>)scene.lookup("#ai-chats")).getItems().size());
|
||||
return null;
|
||||
});
|
||||
fire(h.stage,"ai-prompt-toggle");await(()->fx(prompt::isFocused));
|
||||
assertTrue(fx(access::isSelected),"The inline composer remains visible when its footer icon is clicked");
|
||||
assertEquals("Draft across views · personagem",fx(prompt::getText));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
|
||||
// Theme/language/scale changes preserve the one draft and keep constrained layouts scrollable.
|
||||
for(Theme theme:Theme.values())for(StudioLanguage language:StudioLanguage.values()) {
|
||||
fx(()->{h.window.openPreferences();return null;});var preferences=settings();
|
||||
fx(()->{
|
||||
((ComboBox<Theme>)preferences.getScene().lookup("#theme-select")).setValue(theme);
|
||||
((ComboBox<StudioLanguage>)preferences.getScene().lookup("#language-select")).setValue(language);
|
||||
((ComboBox<Double>)preferences.getScene().lookup("#scale-select")).setValue(2.);
|
||||
return null;
|
||||
});
|
||||
fire(preferences,"settings-apply");await(()->fx(()->!preferences.isShowing()));
|
||||
fx(()->{h.stage.setWidth(680);h.stage.setHeight(480);return null;});
|
||||
capture(h.stage,"ai-drawer-min-200-"+theme+"-"+language);
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var host=(SplitPane)scene.lookup("#ai-workspace-host");
|
||||
assertTrue(drawer.getHeight()>=90);
|
||||
assertTrue(((javafx.scene.layout.Region)host.getItems().getFirst()).getHeight()>=80);
|
||||
assertEquals(1,scene.getRoot().lookupAll("#ai-prompt").size());
|
||||
assertEquals("Draft across views · personagem",prompt.getText());
|
||||
assertEquals(language==StudioLanguage.PORTUGUESE?"IA":"AI",ai.getText());
|
||||
assertUniformTabs(tabs);
|
||||
((ScrollPane)scene.lookup("#project-workspace-scroll")).setVvalue(1);
|
||||
drawer.setVvalue(1);
|
||||
return null;
|
||||
});
|
||||
capture(h.stage,"ai-drawer-min-200-bottom-"+theme+"-"+language);
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var visible=drawer.lookup(".viewport");
|
||||
var viewport=visible.localToScene(visible.getBoundsInLocal());
|
||||
var send=scene.lookup("#ai-send");
|
||||
var command=send.localToScene(send.getBoundsInLocal());
|
||||
assertTrue(command.getMaxY()<=viewport.getMaxY()+1,"Scrolling must reveal the bottom prompt controls");
|
||||
tabs.getSelectionModel().select(ai);return null;
|
||||
});
|
||||
capture(h.stage,"ai-workspace-min-200-"+theme+"-"+language);
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
}
|
||||
fx(()->{h.stage.setWidth(1200);h.stage.setHeight(850);h.window.openPreferences();return null;});
|
||||
var finalPreferences=settings();
|
||||
fx(()->{
|
||||
((ComboBox<StudioLanguage>)finalPreferences.getScene().lookup("#language-select")).setValue(StudioLanguage.PORTUGUESE);
|
||||
((ComboBox<Double>)finalPreferences.getScene().lookup("#scale-select")).setValue(1.);
|
||||
return null;
|
||||
});
|
||||
fire(finalPreferences,"settings-apply");await(()->fx(()->!finalPreferences.isShowing()));
|
||||
fx(()->{tabs.getSelectionModel().select(ai);return null;});
|
||||
capture(h.stage,"ai-workspace-light-pt");
|
||||
fx(()->{h.window.openPreferences();return null;});var configuration=settings();
|
||||
capture(configuration,"ai-settings-chatgpt-only");
|
||||
fx(()->{
|
||||
var scene=configuration.getScene();
|
||||
assertEquals("Codex",((Label)scene.lookup("#ai-agent")).getText());
|
||||
assertEquals("Login ChatGPT",((Label)scene.lookup("#ai-authentication")).getText());
|
||||
assertTrue(scene.lookup("#ai-login").isDisabled());
|
||||
assertNull(scene.lookup("#ai-api-key"));return null;
|
||||
});
|
||||
fire(configuration,"settings-cancel");
|
||||
closeProject(h);
|
||||
assertEquals("",fx(prompt::getText),"Closing a project must discard its transient prompt");
|
||||
open(h,project);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
assertNotSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-prompt")).getText()));
|
||||
}
|
||||
}
|
||||
@Test void startingPlayCollapsesThePromptWithoutDiscardingTheText()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("Play navigation",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return "/fixture/runtime";}public void save(String path){}};
|
||||
var starts=new AtomicInteger();
|
||||
ExecutionControllerFactory executions=(ref,setup,session)->new ExecutionController(){
|
||||
@SuppressWarnings("unchecked") public p.studio.api.operation.OperationHandle<ExecutionSnapshot> play(){
|
||||
starts.incrementAndGet();
|
||||
return (p.studio.api.operation.OperationHandle<ExecutionSnapshot>)Proxy.newProxyInstance(getClass().getClassLoader(),
|
||||
new Class[]{p.studio.api.operation.OperationHandle.class},(proxy,method,args)->{
|
||||
if(method.getName().equals("completion"))return CompletableFuture.completedFuture(session.snapshot());
|
||||
throw new AssertionError(method.getName());
|
||||
});
|
||||
}
|
||||
public void stop(){} public void close(){}
|
||||
};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes,executions)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));StudioPlayDesktopTest.focus(h.stage);
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
fx(()->{prompt.setText("Keep this draft while playing");tabs.getSelectionModel().selectLast();return null;});
|
||||
// Exercise starting from the AI tab, and then from Gameplay with an open drawer.
|
||||
for(int expected=1;expected<=2;expected++) {
|
||||
fire(h.stage,"play");int count=expected;await(()->starts.get()==count);
|
||||
await(()->fx(()->"game-surface".equals(h.stage.getScene().getFocusOwner().getId())));
|
||||
fx(()->{
|
||||
assertEquals("gameplay-tab",tabs.getSelectionModel().getSelectedItem().getId());
|
||||
assertNull(h.stage.getScene().lookup("#ai-prompt-drawer"));
|
||||
assertFalse(((ToggleButton)h.stage.getScene().lookup("#ai-prompt-toggle")).isSelected());
|
||||
assertEquals("Keep this draft while playing",prompt.getText());return null;
|
||||
});
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
}
|
||||
capture(h.stage,"ai-footer-active-uniform-tabs");
|
||||
}
|
||||
}
|
||||
private static void assertUniformTabs(TabPane tabs) {
|
||||
var headers=tabs.lookupAll(".tab").stream().filter(javafx.scene.layout.Region.class::isInstance)
|
||||
.map(javafx.scene.layout.Region.class::cast).toList();
|
||||
assertTrue(headers.size()>=2);
|
||||
double width=headers.getFirst().getWidth();
|
||||
for(var header:headers)assertEquals(width,header.getWidth(),1,"All tab headers must have equal width");
|
||||
}
|
||||
@Test @SuppressWarnings("unchecked") void localChatsSynchronizeDraftsDialogsAndProjectLifetime()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("Local chats",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var other=catalog.createProject(new ProjectCreationRequest("Another project",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));StudioPlayDesktopTest.focus(h.stage);
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
var selector=fx(()->(ComboBox<Object>)h.stage.getScene().lookup("#ai-chat-select"));
|
||||
assertTrue(fx(prompt::isDisabled));assertTrue(fx(selector::isDisabled));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
var a=fx(selector::getValue);
|
||||
assertNotNull(a);assertEquals("gameplay-tab",fx(()->tabs.getSelectionModel().getSelectedItem().getId()));
|
||||
String draftA="A\ntexto com espaços ",draftB="B · personagem";
|
||||
fx(()->{prompt.setText(draftA);tabs.getSelectionModel().selectLast();return null;});
|
||||
var list=fx(()->(ListView<Object>)h.stage.getScene().lookup("#ai-chats"));
|
||||
fire(h.stage,"ai-new-chat");var b=fx(selector::getValue);assertNotEquals(a,b);
|
||||
fx(()->{assertEquals("",prompt.getText());prompt.setText(draftB);list.getSelectionModel().select(a);return null;});
|
||||
assertEquals(draftA,fx(prompt::getText));assertEquals(a,fx(selector::getValue));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();selector.setValue(b);return null;});
|
||||
assertEquals(draftB,fx(prompt::getText));assertEquals(b,fx(()->list.getSelectionModel().getSelectedItem()));
|
||||
fx(()->{list.getSelectionModel().clearSelection();selector.setValue(null);return null;});
|
||||
await(()->fx(()->b.equals(selector.getValue())&&b.equals(list.getSelectionModel().getSelectedItem())));
|
||||
assertEquals(draftB,fx(prompt::getText));
|
||||
|
||||
chatAction(h.stage,"ai-compact-rename-chat");Stage rename=chatDialog("ai-rename-dialog");
|
||||
fx(()->{((TextField)rename.getScene().lookup("#ai-rename-title")).setText(" \n ");return null;});
|
||||
fire(rename,"ai-dialog-confirm");
|
||||
assertTrue(fx(rename::isShowing));assertTrue(fx(()->rename.getScene().lookup("#ai-rename-error").isVisible()));
|
||||
assertEquals(b,fx(selector::getValue));assertEquals(draftB,fx(prompt::getText));
|
||||
fx(()->{((TextField)rename.getScene().lookup("#ai-rename-title")).setText(" Sprite work ");return null;});
|
||||
fire(rename,"ai-dialog-confirm");await(()->fx(()->!rename.isShowing()));
|
||||
var renamedB=fx(selector::getValue);
|
||||
fx(()->{assertEquals("Sprite work",((Labeled)selector.getButtonCell()).getText());
|
||||
assertEquals(renamedB,list.getSelectionModel().getSelectedItem());
|
||||
assertTrue(((Label)h.stage.getScene().lookup("#ai-chat-title")).getText().contains("Sprite work"));
|
||||
assertEquals(draftB,prompt.getText());tabs.getSelectionModel().selectLast();return null;});
|
||||
fire(h.stage,"ai-rename-chat");Stage cancelledRename=chatDialog("ai-rename-dialog");
|
||||
fx(()->{((TextField)cancelledRename.getScene().lookup("#ai-rename-title")).setText("Do not apply");return null;});
|
||||
fire(cancelledRename,"ai-dialog-cancel");assertEquals(renamedB,fx(selector::getValue));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
chatAction(h.stage,"ai-compact-delete-chat");Stage cancelledDelete=chatDialog("ai-delete-dialog");
|
||||
assertTrue(fx(()->((DialogPane)cancelledDelete.getScene().lookup("#ai-delete-dialog")).getContentText().contains("Sprite work")));
|
||||
fire(cancelledDelete,"ai-dialog-cancel");assertEquals(2,fx(()->list.getItems().size()));assertEquals(draftB,fx(prompt::getText));
|
||||
capture(h.stage,"ai-local-chats-footer");
|
||||
|
||||
fx(()->{tabs.getSelectionModel().selectLast();return null;});
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertEquals(a,fx(selector::getValue));assertEquals(draftA,fx(prompt::getText));
|
||||
fire(h.stage,"ai-new-chat");var c=fx(selector::getValue);
|
||||
fx(()->{prompt.setText("C");list.getSelectionModel().select(a);return null;});
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertEquals(c,fx(selector::getValue));assertEquals("C",fx(prompt::getText));
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertTrue(fx(()->list.getItems().isEmpty()));assertNull(fx(selector::getValue));assertTrue(fx(prompt::isDisabled));
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#ai-rename-chat").isDisabled()));
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#ai-delete-chat").isDisabled()));
|
||||
fire(h.stage,"ai-new-chat");
|
||||
fx(()->{prompt.setText("Discard on close");h.window.openPreferences();return null;});Stage preferences=settings();
|
||||
fx(()->{((ComboBox<Theme>)preferences.getScene().lookup("#theme-select")).setValue(Theme.LIGHT);
|
||||
((ComboBox<StudioLanguage>)preferences.getScene().lookup("#language-select")).setValue(StudioLanguage.PORTUGUESE);return null;});
|
||||
fire(preferences,"settings-apply");await(()->fx(()->!preferences.isShowing()));
|
||||
assertEquals("Discard on close",fx(prompt::getText));
|
||||
fire(h.stage,"ai-rename-chat");Stage portugueseRename=chatDialog("ai-rename-dialog");
|
||||
assertEquals("Renomear chat",fx(portugueseRename::getTitle));
|
||||
fx(()->{((TextField)portugueseRename.getScene().lookup("#ai-rename-title")).setText("Trabalho local");return null;});
|
||||
fire(portugueseRename,"ai-dialog-confirm");capture(h.stage,"ai-local-chats-light-pt");
|
||||
fire(h.stage,"ai-rename-chat");Stage pending=chatDialog("ai-rename-dialog");
|
||||
// Closing with a dialog open must discard it without applying its edited title.
|
||||
closeProject(h);assertFalse(fx(pending::isShowing));
|
||||
assertEquals("",fx(prompt::getText));assertTrue(fx(()->list.getItems().isEmpty()));
|
||||
open(h,project);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
var reopenedSelector=fx(()->(ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select"));
|
||||
assertTrue(fx(()->reopenedSelector.getItems().isEmpty()));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
fx(()->{((TextArea)h.stage.getScene().lookup("#ai-prompt")).setText("First project only");return null;});
|
||||
closeProject(h);open(h,other);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
assertTrue(fx(()->((ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select")).getItems().isEmpty()));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-prompt")).getText()));
|
||||
}
|
||||
}
|
||||
@Test void geometryAndSettingsSurviveCoordinatorRestartAndKeepScopesSeparate()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** A real stdio peer, deliberately independent from the production client. No model or credentials. */
|
||||
public final class AcpFixture {
|
||||
private static final ObjectMapper JSON=new ObjectMapper();
|
||||
private static String pendingPrompt,session;
|
||||
private static int sessions;
|
||||
private static String mode;
|
||||
public static void main(String[] args)throws Exception {
|
||||
mode=args.length==0?"normal":args[0];
|
||||
if(mode.equals("child")){Thread.sleep(600_000);return;}
|
||||
Files.writeString(Path.of("parent.pid"),""+ProcessHandle.current().pid());
|
||||
if(mode.equals("tree")){
|
||||
var child=new ProcessBuilder(javaCommand("child")).redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
Files.writeString(Path.of("child.pid"),""+child.pid());
|
||||
}
|
||||
try(var input=new BufferedReader(new InputStreamReader(System.in))){
|
||||
for(String line;(line=input.readLine())!=null;){
|
||||
JsonNode message=JSON.readTree(line);String method=message.path("method").asText();var p=message.path("params");
|
||||
String id=message.path("id").asText();
|
||||
switch(method){
|
||||
case "initialize" -> {
|
||||
var result=JSON.createObjectNode().put("protocolVersion",mode.equals("incompatible")?2:1);
|
||||
result.putArray("authMethods").addObject().put("id",mode.equals("api-only")?"api-key":"chat-gpt").put("name","ChatGPT");
|
||||
reply(id,result);
|
||||
}
|
||||
case "auth/status" -> {
|
||||
var result=JSON.createObjectNode().put("state",mode.startsWith("login")?"unauthenticated":"authenticated");
|
||||
result.putArray("accounts").addObject().put("label","ChatGPT Pro").put("active",true);reply(id,result);
|
||||
}
|
||||
case "authenticate" -> {
|
||||
if(!p.path("methodId").asText().equals("chat-gpt"))throw new AssertionError("Only ChatGPT login");
|
||||
mode=mode.equals("login-delayed-cancel")?"delayed-cancel":"normal";reply(id,JSON.createObjectNode());
|
||||
}
|
||||
case "session/new" -> {
|
||||
if(!Path.of(p.path("cwd").asText()).toRealPath().equals(Path.of("").toRealPath()))throw new AssertionError("cwd");
|
||||
var result=JSON.createObjectNode().put("sessionId","s"+(++sessions));
|
||||
result.putObject("modes").putArray("availableModes").addObject().put("id","workspace-write");reply(id,result);
|
||||
}
|
||||
case "session/set_mode" -> {
|
||||
if(!p.path("modeId").asText().equals("workspace-write"))throw new AssertionError("Agent must use workspace-write/on-request");
|
||||
Files.writeString(Path.of(p.path("sessionId").asText()+".mode"),p.path("modeId").asText());reply(id,JSON.createObjectNode());
|
||||
}
|
||||
case "session/prompt" -> {
|
||||
session=p.path("sessionId").asText();String text=p.path("prompt").get(0).path("text").asText();
|
||||
if(!Files.exists(Path.of(session+".mode")))throw new AssertionError("Mode must be selected before prompt");
|
||||
if(text.equals("reject")){error(id,"fixture rejection");break;}
|
||||
if(text.equals("crash")){System.exit(3);}
|
||||
if(text.equals("malformed")){System.out.println("not json");System.out.flush();break;}
|
||||
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");
|
||||
params.putArray("options").addObject().put("optionId","yes").put("name","Allow once").put("kind","allow_once");send(request);break;
|
||||
}
|
||||
chunk(session,"agent_message_chunk","first ");
|
||||
if(text.equals("hold")){pendingPrompt=id;break;}
|
||||
chunk(session,"agent_thought_chunk","PRIVATE_THOUGHT_MUST_NOT_ESCAPE");
|
||||
chunk(session,"agent_message_chunk","second");reply(id,JSON.createObjectNode().put("stopReason","end_turn"));
|
||||
}
|
||||
case "session/cancel" -> {
|
||||
if(mode.equals("ignore-cancel"))break;
|
||||
if(mode.equals("delayed-cancel")){
|
||||
Files.writeString(Path.of("cancel.requested"),"waiting");
|
||||
long end=System.nanoTime()+java.util.concurrent.TimeUnit.SECONDS.toNanos(8);
|
||||
while(!Files.exists(Path.of("release.cancel"))&&System.nanoTime()<end)Thread.sleep(20);
|
||||
Files.deleteIfExists(Path.of("release.cancel"));
|
||||
Files.deleteIfExists(Path.of("cancel.requested"));
|
||||
}
|
||||
if(pendingPrompt!=null){reply(pendingPrompt,JSON.createObjectNode().put("stopReason","cancelled"));pendingPrompt=null;}
|
||||
}
|
||||
case "" -> {
|
||||
if(id.equals("permit")){
|
||||
Files.writeString(Path.of("permission.json"),message.path("result").toString());
|
||||
if(pendingPrompt!=null){chunk(session,"agent_message_chunk","permission answered");
|
||||
reply(pendingPrompt,JSON.createObjectNode().put("stopReason","end_turn"));pendingPrompt=null;}
|
||||
}
|
||||
}
|
||||
default -> error(id,"Unknown fixture method");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static List<String> javaCommand(String mode){
|
||||
return List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",
|
||||
System.getProperty("studio.test.classpath",System.getProperty("java.class.path")),AcpFixture.class.getName(),mode);
|
||||
}
|
||||
private static void chunk(String session,String kind,String value)throws Exception {
|
||||
var frame=JSON.createObjectNode().put("jsonrpc","2.0").put("method","session/update");
|
||||
frame.putObject("params").put("sessionId",session).putObject("update").put("sessionUpdate",kind)
|
||||
.putObject("content").put("type","text").put("text",value);send(frame);
|
||||
}
|
||||
private static void reply(String id,JsonNode result)throws Exception {send(JSON.createObjectNode().put("jsonrpc","2.0").put("id",id).set("result",result));}
|
||||
private static void error(String id,String message)throws Exception {
|
||||
var frame=JSON.createObjectNode().put("jsonrpc","2.0").put("id",id);frame.putObject("error").put("code",-32603).put("message",message);send(frame);
|
||||
}
|
||||
private static void send(JsonNode value)throws Exception {System.out.println(JSON.writeValueAsString(value));System.out.flush();}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CodexAcpConnectionTest {
|
||||
@TempDir Path root;
|
||||
private CodexAcpConnection connection;
|
||||
private static <T>T await(CompletionStage<T> operation)throws Exception{return operation.toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
private AcpSettings fixture(String mode){var command=AcpFixture.javaCommand(mode);return new AcpSettings(command.getFirst(),command.subList(1,command.size()));}
|
||||
private CodexAcpConnection open(String mode)throws Exception {
|
||||
connection=new CodexAcpConnection(root,new ObjectMapper());await(connection.connect(fixture(mode)));return connection;
|
||||
}
|
||||
@AfterEach void close()throws Exception{if(connection!=null)await(connection.closeAsync());}
|
||||
|
||||
@Test void loginStreamingIndependentSessionsAndCancellationUseRealStdio()throws Exception {
|
||||
var c=open("login");assertEquals(AgentConnection.State.CONNECTED,c.status().state());
|
||||
await(c.login());assertEquals(AgentConnection.State.READY,c.status().state());
|
||||
String first=await(c.newSession()),second=await(c.newSession());assertNotEquals(first,second);
|
||||
var events=new CopyOnWriteArrayList<AgentConnection.Event>();c.events(events::add);
|
||||
var turn=c.prompt(second,"stream");await(turn.accepted());assertEquals("end_turn",await(turn.completion()));
|
||||
assertEquals("first second",events.stream().filter(e->e.kind()==AgentConnection.Kind.TEXT).map(AgentConnection.Event::text).reduce("",String::concat));
|
||||
assertTrue(events.stream().allMatch(e->e.sessionId().equals(second)));
|
||||
assertTrue(events.stream().noneMatch(e->e.text().contains("PRIVATE_THOUGHT")));
|
||||
var held=c.prompt(first,"hold");await(held.accepted());
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(second,"overlap").completion()));
|
||||
await(c.cancel(first));assertEquals("cancelled",await(held.completion()));
|
||||
}
|
||||
@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 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"));
|
||||
c.permissions(p->CompletableFuture.completedFuture("yes"));await(c.prompt(id,"permission").completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("selected"));
|
||||
var requested=new CountDownLatch(1);c.permissions(p->{requested.countDown();return new CompletableFuture<>();});
|
||||
var pending=c.prompt(id,"permission");assertTrue(requested.await(5,TimeUnit.SECONDS));await(c.cancel(id));await(pending.completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("cancelled"));
|
||||
}
|
||||
@Test void rejectionDoesNotAcknowledgeDeliveryAndFailureCanReconnect()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());var rejected=c.prompt(id,"reject");
|
||||
assertThrows(ExecutionException.class,()->await(rejected.accepted()));assertThrows(ExecutionException.class,()->await(rejected.completion()));
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"crash").completion()));
|
||||
assertEquals(AgentConnection.State.FAILED,c.status().state());await(c.connect(fixture("normal")));
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"old session").completion()));
|
||||
await(c.prompt(await(c.newSession()),"new session").completion());
|
||||
}
|
||||
@Test void incompatibleAndApiOnlyAgentsFailAndCloseOwnedProcesses()throws Exception {
|
||||
connection=new CodexAcpConnection(root,new ObjectMapper());
|
||||
assertThrows(ExecutionException.class,()->await(connection.connect(fixture("incompatible"))));
|
||||
assertEquals(AgentConnection.State.FAILED,connection.status().state());
|
||||
assertThrows(ExecutionException.class,()->await(connection.connect(fixture("api-only"))));
|
||||
}
|
||||
@Test void closeWaitsForTurnAndEntireOwnedProcessTree()throws Exception {
|
||||
var c=open("tree");String id=await(c.newSession());var held=c.prompt(id,"hold");await(held.accepted());
|
||||
long parent=Long.parseLong(Files.readString(root.resolve("parent.pid"))),child=Long.parseLong(Files.readString(root.resolve("child.pid")));
|
||||
await(c.closeAsync());assertEquals("cancelled",await(held.completion()));
|
||||
assertFalse(ProcessHandle.of(parent).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
}
|
||||
@Test void unresponsiveCancellationTerminatesTheProcessBeforeResolving()throws Exception {
|
||||
var c=open("ignore-cancel");String id=await(c.newSession());var held=c.prompt(id,"hold");await(held.accepted());
|
||||
long pid=Long.parseLong(Files.readString(root.resolve("parent.pid")));long start=System.nanoTime();
|
||||
await(c.cancel(id));assertTrue(System.nanoTime()-start<TimeUnit.SECONDS.toNanos(20));
|
||||
assertFalse(ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertTrue(held.completion().toCompletableFuture().isCompletedExceptionally());
|
||||
assertEquals(AgentConnection.State.FAILED,c.status().state());
|
||||
}
|
||||
@Test void malformedFramesFailTheTurnAndCleanupAllowsANewConnection()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"malformed").completion()));
|
||||
await(c.connect(fixture("normal")));await(c.prompt(await(c.newSession()),"stream").completion());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Explicit live gate. Uses the user's existing ChatGPT session; never runs in ordinary tests. */
|
||||
class CodexAcpSmokeTest {
|
||||
@TempDir Path project;
|
||||
private AcpSettings settings(){
|
||||
String executable=System.getProperty("studio.test.codexAcp","");
|
||||
return executable.isBlank()?new p.studio.core.project.preferences.JsonAgentSettingsStore(
|
||||
Path.of(System.getProperty("user.home"),".prometeu-studio","ai-settings.json"),new ObjectMapper()).load()
|
||||
:new AcpSettings(executable,List.of());
|
||||
}
|
||||
@Test void existingChatGptLoginCanAnswerThroughThePinnedAdapter()throws Exception {
|
||||
var c=new CodexAcpConnection(project,new ObjectMapper());
|
||||
var output=new CopyOnWriteArrayList<String>();c.events(e->{if(e.kind()==AgentConnection.Kind.TEXT)output.add(e.text());});
|
||||
try{
|
||||
c.connect(settings()).toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
|
||||
while(c.status().state()!=AgentConnection.State.READY&&System.nanoTime()<end)Thread.sleep(50);
|
||||
assertEquals(AgentConnection.State.READY,c.status().state(),"Existing ChatGPT login must be recognized; smoke never opens browser login");
|
||||
String session=c.newSession().toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
assertEquals("end_turn",c.prompt(session,"Responda apenas OK. Não use ferramentas, não leia nem altere arquivos, não execute comandos.")
|
||||
.completion().toCompletableFuture().get(120,TimeUnit.SECONDS));
|
||||
assertFalse(String.join("",output).isBlank());
|
||||
try(var files=Files.list(project)){assertEquals(0,files.count(),"Minimal conversation must not alter project files");}
|
||||
}finally{c.closeAsync().toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
System.out.println("Live Codex ACP: initialized v1, existing ChatGPT login recognized, workspace-write session answered, project unchanged, owned process tree stopped.");
|
||||
}
|
||||
@Test void sameGlobalInstallationConnectsFromTheSelectedExistingProject()throws Exception {
|
||||
String root=System.getProperty("studio.test.codexProject","");
|
||||
org.junit.jupiter.api.Assumptions.assumeFalse(root.isBlank(),"Optional existing-project connection qualification");
|
||||
assertTrue(Files.isDirectory(Path.of(root)));
|
||||
var c=new CodexAcpConnection(Path.of(root),new ObjectMapper());
|
||||
try{
|
||||
c.connect(settings()).toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
|
||||
while(c.status().state()!=AgentConnection.State.READY&&System.nanoTime()<end)Thread.sleep(50);
|
||||
assertEquals(AgentConnection.State.READY,c.status().state());
|
||||
assertFalse(c.newSession().toCompletableFuture().get(40,TimeUnit.SECONDS).isBlank());
|
||||
// No prompt or tools are sent to the real project.
|
||||
}finally{c.closeAsync().toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
System.out.println("Live existing-project ACP: same global configuration, existing ChatGPT login, project cwd session created, no prompt/tools, owned processes stopped.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user