feat(studio): add AI workspace with Codex ACP integration
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/head This commit looks good

This commit is contained in:
2026-11-23 03:11:33 +00:00
parent a2b6a81a27
commit ae7d01aa99
36 changed files with 2550 additions and 28 deletions
@@ -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.");
}
}