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
+76 -2
View File
@@ -100,5 +100,79 @@ cleanup blocks a replacement opening and offers an explicit cleanup retry.
`closeAsync()` completes after coordinated session and presentation teardown;
callers must await it off the FX thread before shutting down their worker pool.
No editor host, ACP, domain workspace, asset authoring, debug or shipping view is
mounted in this product. Native Play remains behind the execution API.
The project shell also includes the **AI workspace**: a left chat manager,
conversation log and editable prompt. The right-hand footer icon opens a compact
prompt from other tabs, with a chat selector, New chat and actions menu. Its native
divider resizes the panel without covering the content. The same compositor moves
into the AI tab; there the footer icon focuses it. Text survives tab changes,
collapse and presentation changes, and is discarded when the project closes.
The footer icon is the only open/collapse control and remains highlighted while
the prompt is visible. Starting Play collapses the drawer while preserving the
text. Tab headers share a uniform width that follows the longest current title
and the active presentation settings.
Studio preferences show **AI / ACP**, Codex and ChatGPT login only.
Both managers support **local chats**: create/select, rename and confirmed delete.
They share one active conversation, with an independent text draft per chat. A
project opens without chats; create one to enable writing. Renaming keeps the
draft and identity, and deleting selects the next/previous remaining chat.
Cancelling a dialog leaves the chat unchanged. All chats and drafts are temporary
and are discarded on project close, including any open chat dialog. Reopening
starts empty.
**Prometeu Studio > Preferences > AI / ACP** saves one non-secret executable and
literal argument vector for every project in `~/.prometeu-studio/ai-settings.json`.
Project settings do not contain ACP configuration. Legacy `acp` fields in project
setup are ignored and omitted by later setup writes; runtime/save/indentation and
MCP intent remain intact. An arbitrary project never becomes the global default.
Install the pinned adapter once, from the Studio repository:
```sh
bash scripts/install-codex-acp.sh
```
The installer needs a working Node.js 22+ and npm for initial installation. It stages
`@agentclientprotocol/codex-acp@2.9.0` under
`~/.prometeu-studio/agents/codex-acp/2.9.0` and publishes the stable launcher
`~/.prometeu-studio/bin/codex-acp`. It selects a working Node, checks common NVM
locations and embeds its absolute path/PATH so desktop launch does not depend on
your terminal environment. `STUDIO_NODE_BIN` can explicitly select Node;
`STUDIO_NPM_CLI` can select npm-cli.js. A compatible installed Codex 0.171.x is reused;
otherwise the adapter uses its package dependency. The installer preserves a custom
global preference and refuses to replace an unmanaged launcher. It does not modify
system Node/npm, project files or ChatGPT login. Re-running the installer reuses the
pinned installed package. No npx or temporary launcher is needed at runtime.
Opening a project automatically connects the installed adapter using these shared
settings and that project's root as cwd. An existing Codex ChatGPT login is reused.
Without a login, open Studio preferences and explicitly sign in; no browser opens
automatically. Connection and login actions operate on the opened project's process;
settings can also be saved from the launcher. Changes apply at the next connection.
Sessions and drafts remain isolated by project. Sending creates one session per chat,
opens AI and streams its response into that chat even when selection changes. One
request runs per project. Cancel waits for termination; deleting a running chat or
closing the project first cancels it. Permission requests require an explicit choice.
Transport/process ownership live in the application behind a neutral Studio API port.
The draft clears only after agent progress or successful completion, and only if
it still matches the sent text. A rejection retains it; Recover last request copies
the last submitted text only into an empty draft. After connection loss, old
conversations remain readable but require a new chat to send after reconnection.
Studio chats remain temporary; the agent may keep separate history. Loading that
history and asset attachment are disabled. Creating/selecting/renaming local chats
does not start ACP or authenticate.
The contract is [AI workspace presentation](../docs/specs/studio/15.%20AI%20Workspace%20Presentation%20Specification.md).
The execution contract is [Codex ACP integration](../docs/specs/studio/16.%20Codex%20ACP%20Integration%20Specification.md).
The opt-in real gate sends a minimal no-tools prompt using an **existing** ChatGPT
login in a disposable directory; it does not open browser login:
```sh
./gradlew :prometeu-app:test --tests p.studio.app.acp.CodexAcpConnectionTest
./gradlew :prometeu-app:codexAcpSmoke
# Optional existing-project handshake, without prompts or tools there:
./gradlew :prometeu-app:codexAcpSmoke -PstudioCodexProject=/absolute/path/to/project
```
No editor host, asset authoring, debug or shipping view is mounted in this product.
Native Play remains behind the execution API.
@@ -0,0 +1,139 @@
package p.studio.ui.javafx2.ai;
import p.studio.api.ai.AgentConnection;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
/** Project chat execution state; all mutations are dispatched onto its owner thread. */
final class AgentChats implements AutoCloseable {
private static final int LOG_LIMIT = 200_000;
private static final class Chat {
String session;
StringBuilder log = new StringBuilder();
String activity = "";
String lastRequest = "";
boolean invalid;
}
private final LocalChats drafts;
private final AgentConnection agent;
private final Executor dispatch;
private final Runnable changed;
private final LongConsumer opened;
private final Function<String,String> text;
private final Map<Long,Chat> entries = new HashMap<>();
private final AutoCloseable observation;
private Long running;
private boolean cancelling, closing, closed;
private CompletableFuture<Void> settled = CompletableFuture.completedFuture(null);
AgentChats(LocalChats drafts, AgentConnection agent, Executor dispatch, Runnable changed,
LongConsumer opened, Function<String,String> text) {
this.drafts=drafts;this.agent=agent;this.dispatch=dispatch;this.changed=changed;this.opened=opened;this.text=text;
agent.events(event->dispatch.execute(()->event(event)));
observation=agent.observe(status->dispatch.execute(()->{
if(closed)return;
if(status.state()==AgentConnection.State.CONNECTING||status.state()==AgentConnection.State.FAILED||status.state()==AgentConnection.State.CLOSED)
entries.values().stream().filter(c->c.session!=null).forEach(c->c.invalid=true);
changed.run();
}));
}
private Chat entry(long id){return entries.computeIfAbsent(id,ignored->new Chat());}
boolean busy(){return running!=null;}
boolean running(long id){return Objects.equals(running,id);}
String runningTitle(){return running==null?"":drafts.chats().stream().filter(c->c.id()==running).map(LocalChats.Chat::title).findFirst().orElse("");}
boolean canSend(long id){return !closing&&!closed&&!busy()&&agent.available()&&agent.status().state()==AgentConnection.State.READY
&&!entry(id).invalid&&!drafts.draft(id).isBlank();}
String log(long id){return entry(id).log.toString();}
String activity(long id){return entry(id).invalid?text.apply("ai.session.expired"):entry(id).activity;}
String lastRequest(long id){return entry(id).lastRequest;}
void send(long id){
if(!canSend(id))return;
var chat=entry(id);String snapshot=drafts.draft(id);
running=id;cancelling=false;settled=new CompletableFuture<>();
chat.lastRequest=snapshot;chat.activity=text.apply("ai.working");
append(chat,"\n"+text.apply("ai.you")+"\n"+snapshot+"\n\nCodex\n");
opened.accept(id);changed.run();
CompletionStage<String> session;
try{session=chat.session==null?agent.newSession():CompletableFuture.completedFuture(chat.session);}
catch(RuntimeException failure){finish(id,null,failure);return;}
session.whenComplete((sessionId,failure)->dispatch.execute(()->{
if(closed)return;
if(failure!=null){finish(id,null,failure);return;}
chat.session=sessionId;
if(cancelling||closing){finish(id,"cancelled",null);return;}
try{
var turn=agent.prompt(sessionId,snapshot);
turn.accepted().whenComplete((v,f)->dispatch.execute(()->{
if(!closed&&f==null&&entries.containsKey(id)&&drafts.draft(id).equals(snapshot)){
drafts.write(id,"");changed.run();
}
}));
turn.completion().whenComplete((stop,f)->dispatch.execute(()->finish(id,stop,f)));
}catch(RuntimeException f){finish(id,null,f);}
}));
}
private void event(AgentConnection.Event event){
if(closed)return;
for(var item:entries.entrySet())if(!item.getValue().invalid&&Objects.equals(item.getValue().session,event.sessionId())){
var chat=item.getValue();
if(event.kind()==AgentConnection.Kind.TEXT)append(chat,event.text());
else {
String status=event.text().equals("Working")?text.apply("ai.working"):event.text();
if(!event.text().equals("Working")&&!status.equals(chat.activity))append(chat,"\n["+status+"]\n");
chat.activity=status;
}
changed.run();return;
}
}
private void finish(long id,String stop,Throwable failure){
if(closed||!Objects.equals(running,id))return;
var chat=entry(id);
chat.activity=failure==null?text.apply("cancelled".equals(stop)?"ai.cancelled":"ai.done"):text.apply("ai.error")+": "+failureMessage(failure);
append(chat,"\n\n["+chat.activity+"]\n");
running=null;cancelling=false;
var done=settled;changed.run();done.complete(null);
}
CompletionStage<Void> cancel(){
if(running==null)return CompletableFuture.completedFuture(null);
cancelling=true;var chat=entry(running);var turnSettled=settled;chat.activity=text.apply("ai.cancelling");changed.run();
if(chat.session==null)return turnSettled;
var completed=new CompletableFuture<Void>();
agent.cancel(chat.session).whenComplete((v,f)->dispatch.execute(()->{
if(f!=null){chat.activity=text.apply("ai.error")+": "+failureMessage(f);changed.run();completed.completeExceptionally(f);}
else turnSettled.whenComplete((x,error)->{if(error==null)completed.complete(null);else completed.completeExceptionally(error);});
}));
return completed;
}
CompletionStage<Void> delete(long id){
CompletionStage<Void> stop=Objects.equals(running,id)?cancel():CompletableFuture.completedFuture(null);
var done=new CompletableFuture<Void>();
stop.whenComplete((v,f)->dispatch.execute(()->{
if(closed){done.complete(null);return;}
if(f==null){entries.remove(id);drafts.delete(id);changed.run();done.complete(null);}
else done.completeExceptionally(f);
}));
return done;
}
CompletionStage<Void> closeAgent(){closing=true;changed.run();return agent.closeAsync().whenComplete((v,f)->{
if(f!=null)dispatch.execute(()->{closing=false;changed.run();});
});}
boolean permissionFor(String session){return !closed&&!closing&&!cancelling&&running!=null&&Objects.equals(entry(running).session,session);}
String permissionTitle(String session){return permissionFor(session)?runningTitle():"";}
private void append(Chat chat,String value){
chat.log.append(value);
if(chat.log.length()>LOG_LIMIT)chat.log.delete(0,chat.log.length()-LOG_LIMIT);
}
static String failureMessage(Throwable failure){
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();
String value=Objects.toString(failure.getMessage(),failure.getClass().getSimpleName())
.replaceAll("(?i)(sk-[A-Za-z0-9_-]+|Bearer\\s+\\S+)","[redacted]");
return value.substring(0,Math.min(1000,value.length()));
}
@Override public void close(){
closed=true;entries.clear();
try{observation.close();}catch(Exception ignored){}
agent.events(e->{});settled.complete(null);
}
}
@@ -0,0 +1,85 @@
package p.studio.ui.javafx2.ai;
import javafx.event.ActionEvent;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.*;
import p.studio.ui.javafx2.appearance.AppearanceContext;
import p.studio.ui.javafx2.components.StudioText;
import java.util.function.*;
/** Owned, nonblocking project dialogs. Closing the view cancels any pending edit. */
final class AiChatDialogs implements AutoCloseable {
private final Supplier<AppearanceContext> contexts;
private Dialog<?> current;
private boolean closed;
AiChatDialogs(Supplier<AppearanceContext> contexts) { this.contexts = contexts; }
void rename(Window owner, String title, Consumer<String> accepted) {
if (closed || current != null) return;
var context = contexts.get();
var dialog = new TextInputDialog(title);
prepare(dialog, owner, context, "ai-rename-dialog", "ai.rename.title", "ai.rename");
dialog.getEditor().setId("ai-rename-title");
dialog.getEditor().getStyleClass().add("studio-field");
context.observe(() -> {
dialog.setContentText(context.text("ai.rename.name"));
dialog.getEditor().setAccessibleText(context.text("ai.rename.name"));
});
var error = new StudioText(context, "ai.rename.required");
error.setId("ai-rename-error");
error.getStyleClass().add("project-error");
error.setVisible(false); error.setManaged(false);
dialog.getDialogPane().setContent(new VBox(8, dialog.getDialogPane().getContent(), error));
dialog.getDialogPane().lookupButton(ButtonType.OK).addEventFilter(ActionEvent.ACTION, event -> {
if (dialog.getEditor().getText().strip().isEmpty()) {
error.setVisible(true); error.setManaged(true); event.consume();
if (dialog.getDialogPane().getScene().getWindow() instanceof Stage stage) stage.sizeToScene();
}
});
dialog.setOnHidden(event -> {
current = null; context.close();
if (!closed && dialog.getResult() != null) accepted.accept(dialog.getResult());
});
dialog.show();
dialog.getEditor().requestFocus();
dialog.getEditor().selectAll();
}
void delete(Window owner, String title, Runnable accepted) {
if (closed || current != null) return;
var context = contexts.get();
var dialog = new Alert(Alert.AlertType.CONFIRMATION, "", ButtonType.OK, ButtonType.CANCEL);
prepare(dialog, owner, context, "ai-delete-dialog", "ai.delete.title", "ai.delete");
context.observe(() -> dialog.setContentText(context.text("ai.delete.confirm", title)));
dialog.setOnHidden(event -> {
current = null; context.close();
if (!closed && dialog.getResult() == ButtonType.OK) accepted.run();
});
dialog.show();
}
private void prepare(Dialog<?> dialog, Window owner, AppearanceContext context,
String id, String titleKey, String confirmKey) {
current = dialog;
dialog.initOwner(owner);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.setResizable(true);
dialog.getDialogPane().setId(id);
dialog.setHeaderText(null);
context.attach(dialog.getDialogPane());
context.observe(() -> dialog.setTitle(context.text(titleKey)));
var confirm = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
var cancel = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
confirm.setId("ai-dialog-confirm"); cancel.setId("ai-dialog-cancel");
confirm.getStyleClass().add("studio-button"); cancel.getStyleClass().add("studio-button");
context.bindText(confirm, confirmKey);
context.bindText(cancel, "settings.cancel");
}
@Override public void close() {
closed = true;
if (current != null) current.close();
}
}
@@ -0,0 +1,430 @@
package p.studio.ui.javafx2.ai;
import javafx.beans.value.ChangeListener;
import javafx.application.Platform;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.shape.SVGPath;
import p.studio.ui.javafx2.appearance.AppearanceContext;
import p.studio.ui.javafx2.components.*;
import p.studio.api.ai.AgentConnection;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
/** Project-owned transient chats, shared composer and asynchronous agent presentation. */
public final class AiWorkspace extends SplitPane implements AutoCloseable {
private final AppearanceContext context;
private final TabPane tabs;
private final Tab ai;
private final ScrollPane page;
private final ScrollPane drawer = new ScrollPane();
private final BorderPane conversation = new BorderPane();
private final VBox composer = new VBox(8);
private final TextArea prompt = new TextArea();
private final ToggleButton access = new ToggleButton();
private final LocalChats chats = new LocalChats();
private final AiChatDialogs dialogs;
private final ListView<LocalChats.Chat> list = new ListView<>();
private final StudioSelect<LocalChats.Chat> selector;
private final MenuButton actions = new MenuButton();
private final MenuItem renameAction = new MenuItem();
private final MenuItem deleteAction = new MenuItem();
private final Button renameButton;
private final Button deleteButton;
private final Button createChatButton;
private final Label promptLabel = new Label();
private final Label chatTitle = new Label();
private final Tooltip accessTip = new Tooltip();
private final AgentConnection agent;
private final AgentChats execution;
private final TextArea transcript = new TextArea();
private final Label activity = new Label();
private final Label connectionStatus = new Label();
private final Button send;
private final Button cancel;
private final Button recover;
private final Map<Dialog<?>,CompletableFuture<String>> permissionDialogs = new HashMap<>();
private final Supplier<AppearanceContext> dialogContexts;
private boolean deleting;
private boolean closed;
private boolean synchronizing;
private final ChangeListener<Tab> selection = (o, before, after) -> placeComposer();
private final ChangeListener<LocalChats.Chat> chatSelection = (o, before, after) -> {
if (!synchronizing && !closed) {
if (after != null) {
chats.select(after.id());
refreshSelection();
} else {
// Let native selection changes finish before restoring the project-owned selection.
Platform.runLater(() -> { if (!closed) refreshSelection(); });
}
}
};
private final ChangeListener<String> draftChanges = (o, before, after) -> {
if (!synchronizing && !closed && chats.active() != null) { chats.write(after); refreshAgent(); }
};
private Node previousFocus;
private boolean drawerOpen;
private double divider = .65;
public AiWorkspace(AppearanceContext context, TabPane tabs, Supplier<AppearanceContext> dialogContexts) {
this(context,tabs,dialogContexts,AgentConnection.unavailable());
}
public AiWorkspace(AppearanceContext context, TabPane tabs, Supplier<AppearanceContext> dialogContexts, AgentConnection agent) {
this.context = context;
this.tabs = tabs;
this.agent = agent; this.dialogContexts=dialogContexts;
dialogs = new AiChatDialogs(dialogContexts);
setId("ai-workspace-host");
getStyleClass().addAll("studio-workspace-split", "studio-ai-dock");
setOrientation(Orientation.VERTICAL);
setMinWidth(0);
prompt.setId("ai-prompt");
prompt.setWrapText(true);
prompt.setPrefRowCount(3);
prompt.setMinHeight(70);
promptLabel.setLabelFor(prompt);
promptLabel.setWrapText(true);
selector = new StudioSelect<>(context, "ai.chat", LocalChats.Chat::title);
// With no selection, the native skin owns the display cell's prompt text.
selector.setButtonCell(chatCell());
selector.setId("ai-chat-select");
selector.setMinWidth(90);
createChatButton = actionButton("ai.newChat", "ai-compact-new-chat", this::newChat);
actions.setId("ai-chat-actions");
actions.getStyleClass().add("studio-compact-action");
context.bindText(actions, "ai.actions");
var loadAction = new MenuItem(); loadAction.setDisable(true);
renameAction.setId("ai-compact-rename-chat"); deleteAction.setId("ai-compact-delete-chat");
renameAction.setOnAction(e -> renameChat()); deleteAction.setOnAction(e -> deleteChat());
context.observe(() -> {
loadAction.setText(context.text("ai.load"));
renameAction.setText(context.text("ai.rename")); deleteAction.setText(context.text("ai.delete"));
});
actions.getItems().addAll(loadAction, renameAction, deleteAction);
selector.setPrefWidth(180);
var compactManager = new FlowPane(8, 8, selector, createChatButton, actions);
compactManager.setAlignment(Pos.CENTER_LEFT);
compactManager.setId("ai-compact-manager");
var spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
send=actionButton("ai.send","ai-send",this::send);
send.getStyleClass().add("primary");
cancel=actionButton("ai.cancel","ai-cancel",this::cancelTurn);
recover=actionButton("ai.recover","ai-recover",this::recover);
var commands = new HBox(8, unavailableButton("ai.attach", "ai-attach"), recover, spacer, cancel, send);
commands.setAlignment(Pos.CENTER_LEFT);
composer.setId("ai-composer");
composer.getStyleClass().add("studio-ai-composer");
composer.setMinWidth(300);
composer.setMinHeight(Region.USE_PREF_SIZE);
composer.getChildren().addAll(compactManager, promptLabel, prompt, commands, new StudioText(context, "ai.local.temporary"));
VBox.setVgrow(prompt, Priority.ALWAYS);
list.setId("ai-chats");
list.setCellFactory(view -> chatCell());
list.setPlaceholder(new StudioText(context, "ai.chats.empty"));
list.setMinHeight(80);
context.observe(() -> list.setAccessibleText(context.text("ai.chats")));
renameButton = actionButton("ai.rename", "ai-rename-chat", this::renameChat);
deleteButton = actionButton("ai.delete", "ai-delete-chat", this::deleteChat);
var chatActions = new FlowPane(8, 8, actionButton("ai.newChat", "ai-new-chat", this::newChat),
unavailableButton("ai.load", "ai-load-chat"), renameButton, deleteButton);
var sidebar = new VBox(12, new StudioText(context, "ai.chats").title(), list, chatActions);
sidebar.setId("ai-chat-manager");
sidebar.getStyleClass().add("studio-ai-sidebar");
sidebar.setMinWidth(150);
sidebar.setPrefWidth(220);
VBox.setVgrow(list, Priority.ALWAYS);
transcript.setId("ai-conversation");transcript.setEditable(false);transcript.setWrapText(true);
transcript.setPromptText(context.text("ai.conversation.empty"));transcript.setMinHeight(90);
activity.setId("ai-activity");activity.setWrapText(true);
connectionStatus.setId("ai-connection-status");connectionStatus.setWrapText(true);
var history=new VBox(8,transcript,activity);VBox.setVgrow(transcript,Priority.ALWAYS);
conversation.setCenter(history);
chatTitle.setId("ai-chat-title"); chatTitle.setWrapText(true);
chatTitle.getStyleClass().add("studio-ai-chat-title");
conversation.setTop(new VBox(8,chatTitle,connectionStatus));
var content = new BorderPane(conversation, null, null, null, sidebar);
content.setId("ai-workspace");
content.setMinWidth(480);
content.setMinHeight(Region.USE_PREF_SIZE);
ai = new Tab(context.text("ai.title"), content);
ai.setId("ai-tab");
ai.setClosable(false);
context.observe(() -> ai.setText(context.text("ai.title")));
tabs.getTabs().add(ai);
page = new ScrollPane(tabs);
page.setId("ai-tab-page");
page.setFitToWidth(true);
page.setFitToHeight(true);
page.setMinSize(0, 90);
drawer.setId("ai-prompt-drawer");
drawer.setFitToWidth(true);
drawer.setFitToHeight(true);
drawer.setMinSize(0, 100);
getItems().add(page);
tabs.getSelectionModel().selectedItemProperty().addListener(selection);
list.getSelectionModel().selectedItemProperty().addListener(chatSelection);
selector.valueProperty().addListener(chatSelection);
prompt.textProperty().addListener(draftChanges);
var icon = new SVGPath();
icon.setContent("M 8 0 L 10 6 L 16 8 L 10 10 L 8 16 L 6 10 L 0 8 L 6 6 Z");
icon.getStyleClass().add("studio-ai-icon");
icon.setMouseTransparent(true);
access.setGraphic(icon);
access.setId("ai-prompt-toggle");
access.getStyleClass().add("studio-ai-access");
access.setMaxHeight(Double.MAX_VALUE);
access.setTooltip(accessTip);
access.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> rememberFocus());
access.setOnAction(e -> {
if (isAiSelected()) focusPrompt();
else if (drawerOpen) closeDrawer();
else {
rememberFocus();
drawerOpen = true;
placeComposer();
focusPrompt();
}
refreshAccess();
});
execution=new AgentChats(chats,agent,Platform::runLater,this::refreshItems,id->{
chats.select(id);drawerOpen=false;tabs.getSelectionModel().select(ai);refreshSelection();
},context::text);
agent.permissions(this::permission);
placeComposer();
context.observe(() -> { refreshLocalText(); refreshAccess(); refreshAgent(); });
refreshItems();
context.onClose(this::close);
}
private static ListCell<LocalChats.Chat> chatCell() {
return new ListCell<>() {
@Override protected void updateItem(LocalChats.Chat item, boolean empty) {
super.updateItem(item, empty);
setText(empty || item == null ? null : item.title());
}
};
}
private Button actionButton(String key, String id, Runnable action) {
var button = new StudioButton(context, key, false);
button.setId(id); button.getStyleClass().add("studio-compact-action");
button.setOnAction(e -> action.run());
context.onClose(() -> button.setOnAction(null));
return button;
}
private void newChat() {
chats.create(); refreshItems(); focusPrompt();
}
private void renameChat() {
var chat = chats.active(); if (chat == null) return;
dialogs.rename(getScene().getWindow(), chat.title(), title -> {
chats.rename(chat.id(), title); refreshItems(); focusPrompt();
});
}
private void deleteChat() {
var chat = chats.active(); if (chat == null) return;
dialogs.delete(getScene().getWindow(), chat.title(), () -> {
deleting=true;if(execution.running(chat.id()))cancelPermissions();refreshSelection();
execution.delete(chat.id()).whenComplete((v,f)->Platform.runLater(()->{
if(closed)return;deleting=false;refreshItems();
if(f!=null)activity.setText(context.text("ai.error")+": "+AgentChats.failureMessage(f));
if (chats.active() != null) focusPrompt();else access.requestFocus();
}));
});
}
private void refreshItems() {
if(closed)return;
synchronizing = true;
try {
var items = chats.chats();
list.getItems().setAll(items); selector.getItems().setAll(items);
updateSelection();
} finally { synchronizing = false; }
}
private void refreshSelection() {
synchronizing = true;
try { updateSelection(); } finally { synchronizing = false; }
}
private void updateSelection() {
var active = chats.active();
list.getSelectionModel().select(active); selector.setValue(active);
selector.setDisable(active == null);
list.setFocusTraversable(active != null);
prompt.setDisable(active == null);
if(!prompt.getText().equals(chats.draft()))prompt.setText(chats.draft());
renameButton.setDisable(active == null||deleting); deleteButton.setDisable(active == null||deleting);
renameAction.setDisable(active == null||deleting); deleteAction.setDisable(active == null||deleting);
actions.setDisable(active == null||deleting);
refreshLocalText();
refreshAgent();
}
private void send(){var chat=chats.active();if(chat!=null)execution.send(chat.id());}
private void cancelTurn(){cancelPermissions();execution.cancel();}
private void recover(){
var chat=chats.active();if(chat!=null&&chats.draft().isBlank())chats.write(execution.lastRequest(chat.id()));
refreshSelection();focusPrompt();
}
private void refreshAgent(){
if(execution==null||closed)return;
if(!execution.busy())cancelPermissions();
var chat=chats.active();
send.setDisable(chat==null||deleting||!execution.canSend(chat.id()));
cancel.setDisable(!execution.busy());
recover.setDisable(chat==null||!chats.draft().isBlank()||execution.lastRequest(chat.id()).isBlank());
String value=chat==null?"":execution.log(chat.id());
if(!transcript.getText().equals(value)){transcript.setText(value);transcript.positionCaret(transcript.getLength());}
activity.setText(chat==null?"":execution.activity(chat.id()));
var status=agent.status();
connectionStatus.setText(context.text("ai.connection."+status.state().name())+(status.detail().isBlank()?"":" · "+status.detail())
+(execution.busy()?" · "+context.text("ai.running.for",execution.runningTitle()):""));
}
private CompletionStage<String> permission(AgentConnection.Permission request){
var result=new CompletableFuture<String>();
Platform.runLater(()->{
if(closed||!execution.permissionFor(request.sessionId())){result.complete(null);return;}
var child=dialogContexts.get();var dialog=new Alert(Alert.AlertType.NONE);
dialog.initOwner(getScene().getWindow());dialog.setResizable(true);dialog.setTitle(child.text("ai.permission"));
dialog.setHeaderText(child.text("ai.permission")+" · "+execution.permissionTitle(request.sessionId()));
if(request.details().isBlank())dialog.setContentText(request.title());
else{
var detail=new TextArea(request.details());detail.setEditable(false);detail.setWrapText(true);detail.setPrefRowCount(8);
dialog.getDialogPane().setContent(new VBox(8,new Label(request.title()),detail));
}
dialog.getDialogPane().setId("ai-permission-dialog");child.attach(dialog.getDialogPane());
var options=new LinkedHashMap<ButtonType,String>();
for(var choice:request.choices()){
var button=new ButtonType(choice.name(),ButtonBar.ButtonData.OTHER);options.put(button,choice.id());dialog.getButtonTypes().add(button);
}
dialog.getButtonTypes().add(ButtonType.CANCEL);
permissionDialogs.put(dialog,result);
dialog.setOnHidden(e->{permissionDialogs.remove(dialog);child.close();result.complete(options.get(dialog.getResult()));});
dialog.show();dialog.getDialogPane().lookupButton(ButtonType.CANCEL).requestFocus();
});
return result;
}
private void cancelPermissions(){
for(var dialog:List.copyOf(permissionDialogs.keySet())){permissionDialogs.get(dialog).complete(null);dialog.close();}
}
public CompletionStage<Void> closeAgent(){cancelPermissions();return execution.closeAgent();}
public Label connectionStatus(){return connectionStatus;}
private void refreshLocalText() {
var active = chats.active();
String destination = active == null ? context.text("ai.noChat") : active.title();
chatTitle.setText(destination);
promptLabel.setText(active == null ? context.text("ai.prompt") : context.text("ai.prompt.for", destination));
prompt.setAccessibleText(promptLabel.getText());
prompt.setPromptText(context.text(active == null ? "ai.createFirst" : "ai.prompt.placeholder"));
selector.setPromptText(context.text("ai.noChat"));
}
private Button unavailableButton(String key, String id) {
var button = new StudioButton(context, key, key.equals("ai.send"));
button.setId(id);
button.getStyleClass().add("studio-compact-action");
button.setDisable(true);
return button;
}
private boolean isAiSelected() { return tabs.getSelectionModel().getSelectedItem() == ai; }
private void rememberFocus() {
if (getScene() != null && getScene().getFocusOwner() != access)
previousFocus = getScene().getFocusOwner();
}
private void focusPrompt() {
// ScrollPane skins attach newly moved content during CSS/layout, before it can take focus.
applyCss();
layout();
if (chats.active() == null) createChatButton.requestFocus();
else prompt.requestFocus();
}
private void closeDrawer() {
drawerOpen = false;
placeComposer();
if (canRestoreFocus(previousFocus)) previousFocus.requestFocus();
else access.requestFocus();
previousFocus = null;
}
private boolean canRestoreFocus(Node node) {
if (node == null || node.getScene() != getScene() || node.isDisabled()) return false;
for (Node current = node; current != null; current = current.getParent())
if (!current.isVisible()) return false;
return true;
}
private void placeComposer() {
if (closed) return;
if (getItems().contains(drawer)) divider = getDividerPositions()[0];
conversation.setBottom(null);
drawer.setContent(null);
boolean docked = !isAiSelected() && drawerOpen;
if (isAiSelected()) conversation.setBottom(composer);
else if (docked) drawer.setContent(composer);
if (docked && !getItems().contains(drawer)) {
getItems().add(drawer);
setDividerPositions(divider);
} else if (!docked) getItems().remove(drawer);
refreshAccess();
}
private void refreshAccess() {
String key = isAiSelected() ? "ai.focus" : drawerOpen ? "ai.collapse" : "ai.open";
access.setAccessibleText(context.text(key));
accessTip.setText(context.text(key));
access.setSelected(isAiSelected() || drawerOpen);
}
/** Starting Play closes the external drawer without changing the draft or restoring old focus. */
public void collapseForPlayback() {
drawerOpen = false;
previousFocus = null;
placeComposer();
}
public ToggleButton accessButton() { return access; }
public Tab tab() { return ai; }
@Override public void close() {
if (closed) return;
closed = true;
cancelPermissions();execution.close();agent.permissions(p->CompletableFuture.completedFuture(null));
dialogs.close();
tabs.getSelectionModel().selectedItemProperty().removeListener(selection);
list.getSelectionModel().selectedItemProperty().removeListener(chatSelection);
selector.valueProperty().removeListener(chatSelection);
prompt.textProperty().removeListener(draftChanges);
chats.close(); list.getItems().clear(); selector.getItems().clear(); selector.setValue(null);
prompt.clear();
prompt.setDisable(true); renameAction.setOnAction(null); deleteAction.setOnAction(null);
previousFocus = null;
accessTip.hide();
access.setOnAction(null);
conversation.setBottom(null);
drawer.setContent(null);
}
}
@@ -0,0 +1,71 @@
package p.studio.ui.javafx2.ai;
import java.util.*;
/** Transient state for one project view. No JavaFX, storage or agent session ownership. */
final class LocalChats implements AutoCloseable {
record Chat(long id, String title) { }
private static final class Entry {
Chat chat;
String draft = "";
Entry(Chat chat) { this.chat = chat; }
}
private final LinkedHashMap<Long, Entry> entries = new LinkedHashMap<>();
private Long selected;
private long sequence;
private boolean closed;
List<Chat> chats() { return entries.values().stream().map(entry -> entry.chat).toList(); }
Chat active() { return selected == null ? null : entries.get(selected).chat; }
String draft() { return selected == null ? "" : entries.get(selected).draft; }
String draft(long id) { return entry(id).draft; }
void write(long id, String text) { entry(id).draft = Objects.requireNonNull(text); }
Chat create() {
requireOpen();
long id = ++sequence;
var chat = new Chat(id, "Chat " + id);
entries.put(id, new Entry(chat));
selected = id;
return chat;
}
void select(long id) { entry(id); selected = id; }
void write(String text) {
requireOpen();
if (selected == null) throw new IllegalStateException("No active chat");
entries.get(selected).draft = Objects.requireNonNull(text);
}
void rename(long id, String title) {
var entry = entry(id);
String normalized = Objects.requireNonNull(title).strip();
if (normalized.isEmpty()) throw new IllegalArgumentException("Chat title is required");
entry.chat = new Chat(id, normalized);
}
void delete(long id) {
entry(id);
var order = new ArrayList<>(entries.keySet());
int index = order.indexOf(id);
entries.remove(id);
if (Objects.equals(selected, id)) {
selected = index + 1 < order.size() ? order.get(index + 1) : index > 0 ? order.get(index - 1) : null;
}
}
private Entry entry(long id) {
requireOpen();
var entry = entries.get(id);
if (entry == null) throw new IllegalArgumentException("Unknown local chat");
return entry;
}
private void requireOpen() { if (closed) throw new IllegalStateException("Project view is closed"); }
@Override public void close() {
closed = true;
entries.clear();
selected = null;
}
}
@@ -24,6 +24,7 @@ public final class StudioTabs extends TabPane {
return Math.max(super.computeMinHeight(width),snappedTopInset()+snappedBottomInset()+header+content);
}
@Override protected void layoutChildren(){
uniformTabWidths();
super.layoutChildren();
for(var node:lookupAll(".tab"))if(node instanceof Region header&&!header.getProperties().containsKey(OUTLINE)){
header.getProperties().put(OUTLINE,Boolean.TRUE);PixelGeometry.applyTab(header);
@@ -31,6 +32,20 @@ public final class StudioTabs extends TabPane {
if(!getChildren().contains(contentOutline))getChildren().add(contentOutline);
layoutContentOutline();
}
private void uniformTabWidths(){
double width=0;
for(var node:lookupAll(".tab"))if(node instanceof Region header&&header.lookup(".tab-label") instanceof Label label){
double natural=label.prefWidth(-1);
var close=header.lookup(".tab-close-button");
if(close instanceof Region button&&button.isManaged())natural+=button.prefWidth(-1);
width=Math.max(width,natural+header.getInsets().getLeft()+header.getInsets().getRight());
}
if(width>0){
width=Math.ceil(width);
if(getTabMinWidth()!=width)setTabMinWidth(width);
if(getTabMaxWidth()!=width)setTabMaxWidth(width);
}
}
private void layoutContentOutline(){
var selected=getSelectionModel().getSelectedItem();var content=selected==null?null:selected.getContent();
var area=content==null?null:content.getParent();
@@ -12,7 +12,7 @@ public final class TabStatusFooter extends Label implements AutoCloseable {
private final ChangeListener<Tab> selected=(o,a,b)->refresh();
private final ListChangeListener<Tab> removed=change->{while(change.next())for(Tab tab:change.getRemoved())information.remove(tab);refresh();};
public TabStatusFooter(TabPane tabs){
this.tabs=tabs;setId("studio-footer");getStyleClass().addAll("studio-information-strip","studio-footer");
this.tabs=tabs;setId("studio-footer");getStyleClass().add("studio-footer-information");
setMaxWidth(Double.MAX_VALUE);setWrapText(false);
tabs.getSelectionModel().selectedItemProperty().addListener(selected);tabs.getTabs().addListener(removed);
var tooltip=new Tooltip();tooltip.textProperty().bind(textProperty());setTooltip(tooltip);
@@ -7,7 +7,9 @@ import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import p.studio.api.preferences.RuntimeSettingsStore;
import p.studio.api.preferences.AgentSettingsStore;
import p.studio.api.project.*;
import p.studio.api.ai.*;
import p.studio.ui.javafx2.appearance.*;
import p.studio.ui.javafx2.components.*;
import p.studio.ui.javafx2.i18n.StudioLanguage;
@@ -20,7 +22,8 @@ final class SettingsDialogs {
record ProjectSettings(ProjectLocalStudioSetup setup, boolean disposable) { }
private SettingsDialogs() { }
static Stage preferences(Stage owner,WindowResources resources,AppearanceContext parent,String currentRuntime,
boolean runtimeLocked,RuntimeSettingsStore store,Executor executor,Consumer<String> applied,Consumer<Boolean> working) {
boolean runtimeLocked,RuntimeSettingsStore store,Executor executor,Consumer<String> applied,Consumer<Boolean> working,
AcpSettings currentAgent,AgentSettingsStore agentSettings,AgentConnection connection,Consumer<AcpSettings> agentApplied) {
var context=resources.draft(parent);
var dialog=new Form(owner,context,"preferences.title",executor,working);
var theme=new StudioSelect<Theme>(context,"theme.label",v->context.text(v.labelKey()),Theme.values());
@@ -37,9 +40,14 @@ final class SettingsDialogs {
MinimalShell.labeled(context,"theme.label",theme),MinimalShell.labeled(context,"language.label",language),
MinimalShell.labeled(context,"font.label",font),MinimalShell.labeled(context,"scale.label",scale),
new Separator(),MinimalShell.labeled(context,"preferences.runtime",runtimeRow));
var agentForm=new AgentForm(context,dialog,currentAgent,agentSettings,connection,executor,agentApplied);
dialog.apply.setOnAction(e->{
String path=normalize(runtime.getText());var settings=context.settings();
dialog.submit(()->{if(!runtimeLocked)store.save(path);},()->{parent.update(settings);if(!runtimeLocked)applied.accept(path);});
AcpSettings launch;
try{launch=agentForm.value();}catch(RuntimeException failure){dialog.feedback.setText(failure.getMessage());return;}
dialog.submit(()->{if(!runtimeLocked)store.save(path);agentSettings.save(launch);},()->{
parent.update(settings);if(!runtimeLocked)applied.accept(path);agentApplied.accept(launch);
});
});
dialog.stage.show();return dialog.stage;
}
@@ -74,6 +82,50 @@ final class SettingsDialogs {
dialog.stage.show();if(savingSection&&project.memcardSlots()!=null)Platform.runLater(()->{dialog.page.setVvalue(1);save.requestFocus();});
return dialog.stage;
}
private static final class AgentForm {
private final TextField executable;
private final TextArea arguments;
AgentForm(AppearanceContext context,Form dialog,AcpSettings initial,AgentSettingsStore settings,
AgentConnection connection,Executor executor,Consumer<AcpSettings> applied){
var agent=new StudioText(context,"ai.agent.codex");agent.setId("ai-agent");
var authentication=new StudioText(context,"ai.auth.chatgpt");authentication.setId("ai-authentication");
executable=new StudioTextField();executable.setId("ai-executable");executable.setText(initial.executable());
arguments=new TextArea(String.join("\n",initial.arguments()));arguments.setId("ai-arguments");arguments.setPrefRowCount(3);arguments.setWrapText(true);
var status=new Label();status.setId("ai-settings-status");status.setWrapText(true);
var connect=button(context,"ai.connect","ai-connect",()->{});
var login=button(context,"ai.auth.login","ai-login",()->{});
Runnable refresh=()->{
var state=connection.status();status.setText(!connection.available()?context.text("ai.openProject"):context.text("ai.connection."+state.state().name())+(state.detail().isBlank()?"":" · "+state.detail()));
boolean editable=state.state()==AgentConnection.State.DISCONNECTED||state.state()==AgentConnection.State.FAILED;
connect.setDisable(!connection.available()||!editable);
login.setDisable(!connection.available()||state.state()!=AgentConnection.State.CONNECTED);
};
var observation=connection.observe(value->Platform.runLater(()->{if(dialog.stage.isShowing())refresh.run();}));
context.onClose(()->{try{observation.close();}catch(Exception ignored){}});context.observe(refresh);
connect.setOnAction(e->{
AcpSettings launch;
try{launch=value();}catch(RuntimeException failure){dialog.feedback.setText(failure.getMessage());return;}
connect.setDisable(true);dialog.apply.setDisable(true);
CompletableFuture.runAsync(()->settings.save(launch),executor).whenComplete((v,f)->Platform.runLater(()->{
dialog.apply.setDisable(false);
if(f!=null){dialog.feedback.setText(ProjectOpening.unwrap(f).getMessage());refresh.run();return;}
applied.accept(launch);
connection.connect(launch).whenComplete((ignored,failure)->Platform.runLater(()->{
if(dialog.stage.isShowing()){if(failure!=null)dialog.feedback.setText(ProjectOpening.unwrap(failure).getMessage());refresh.run();}
}));
}));
});
login.setOnAction(e->connection.login().whenComplete((v,f)->Platform.runLater(()->{
if(dialog.stage.isShowing()){if(f!=null)dialog.feedback.setText(ProjectOpening.unwrap(f).getMessage());refresh.run();}
})));
dialog.fields.getChildren().addAll(new Separator(),new StudioText(context,"ai.settings.title").title(),
MinimalShell.labeled(context,"ai.settings.agent",agent),
MinimalShell.labeled(context,"ai.settings.authentication",authentication),
MinimalShell.labeled(context,"ai.executable",executable),MinimalShell.labeled(context,"ai.arguments",arguments),
new StudioText(context,"ai.launch.help"),new StudioText(context,"ai.global.help"),new HBox(12,connect,login),status);
}
AcpSettings value(){return new AcpSettings(executable.getText(),arguments.getText().isEmpty()?java.util.List.of():arguments.getText().lines().toList());}
}
private static String normalize(String text){return text==null||text.isBlank()?null:text.trim();}
private static HBox directory(AppearanceContext context,Stage owner,TextField path){
var row=new HBox(12,path,button(context,"play.browse",path.getId()+"-browse",()->{
@@ -15,6 +15,7 @@ import p.studio.api.project.*;
import p.studio.api.session.*;
import p.studio.api.preferences.*;
import p.studio.ui.javafx2.appearance.AppearanceContext;
import p.studio.ui.javafx2.ai.AiWorkspace;
import p.studio.ui.javafx2.components.*;
import p.studio.ui.javafx2.play.PlaybackViewport;
import p.studio.ui.javafx2.shell.MinimalShell;
@@ -77,6 +78,23 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
private Button configurationAction;
private TabPane tabs;
private Tab gameplay;
private AiWorkspace aiWorkspace;
private p.studio.api.ai.AgentConnectionFactory agentConnections=root->p.studio.api.ai.AgentConnection.unavailable();
private p.studio.api.ai.AgentConnection agent;
private p.studio.api.ai.AcpSettings globalAgent=p.studio.api.ai.AcpSettings.defaults();
private AgentSettingsStore agentSettings=new AgentSettingsStore(){
private p.studio.api.ai.AcpSettings value=p.studio.api.ai.AcpSettings.defaults();
public p.studio.api.ai.AcpSettings load(){return value;}
public void save(p.studio.api.ai.AcpSettings settings){value=settings;}
};
public void setAgentSettings(AgentSettingsStore settings,p.studio.api.ai.AcpSettings initial){
if(project!=null)throw new IllegalStateException("Configure Studio before opening a project");
agentSettings=Objects.requireNonNull(settings);globalAgent=Objects.requireNonNull(initial);
}
public void setAgentConnections(p.studio.api.ai.AgentConnectionFactory factory){
if(project!=null)throw new IllegalStateException("Configure agents before opening a project");
agentConnections=Objects.requireNonNull(factory);
}
private Label stateLabel;
private TextArea logs;
private long lastLog=-1;
@@ -131,7 +149,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
public void phase(ProjectOpening.Phase phase){loadingPhase=phase;updateLoadingText();}
public void resolved(ProjectReference reference){loadingProject.setText(reference.name());}
public void prepare(ProjectSession session,WindowGeometry geometry){project=session;showProject();restoreGeometry(geometry);}
public void present(){stage.setTitle(project.projectReference().name()+" · "+context.text("brand"));stage.show();stage.toFront();hideLoading();createdProject=null;refresh();}
public void present(){stage.setTitle(project.projectReference().name()+" · "+context.text("brand"));stage.show();stage.toFront();hideLoading();createdProject=null;refresh();connectAgent();}
public void discard(){if(projectGeometry!=null){projectGeometry.close();projectGeometry=null;}stage.hide();project=null;play=null;if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();}
public void failed(Throwable failure,boolean cleanupRequired){hideLoading();showChooser();
String detail=diagnostic(failure);
@@ -273,7 +291,8 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
if(closed||closing||busy)return;if(settingsStage!=null&&settingsStage.isShowing()){settingsStage.toFront();return;}
Stage owner=launcherStage.isShowing()?launcherStage:stage;
settingsStage=SettingsDialogs.preferences(owner,resources,context,defaultRuntime,
controller!=null&&controller.ownsExecution(),runtimeSettings,executor,value->defaultRuntime=value,this::settingsWorking);
controller!=null&&controller.ownsExecution(),runtimeSettings,executor,value->defaultRuntime=value,this::settingsWorking,
globalAgent,agentSettings,agent==null?p.studio.api.ai.AgentConnection.unavailable():agent,value->globalAgent=value);
}
public void openProjectSettings(boolean savingSection){
if(project==null||closed||closing||busy||controller!=null&&controller.ownsExecution())return;
@@ -283,6 +302,15 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
defaultRuntime,runtimeSettings,saveSetup,executor,value->{if(project==owner){localSetup=value.setup();disposableSave=value.disposable();notice.setText("");configurationAction.setVisible(false);configurationAction.setManaged(false);}},
this::settingsWorking,savingSection);
}
private void connectAgent(){
if(agent.available()){
var origin=agent;var owner=project;
agent.connect(globalAgent).whenComplete((v,f)->Platform.runLater(()->{
if(f!=null&&project==owner&&agent==origin&&!closing&&!closed)
configurationNeeded(context.text("feedback.error",diagnostic(f)),true,false);
}));
}
}
private void configurationNeeded(String message,boolean global,boolean savingSection){
notice.setText(message);configurationAction.setVisible(true);configurationAction.setManaged(true);
configurationAction.setText(context.text(global?"settings.open.preferences":"settings.open.project"));
@@ -332,6 +360,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
viewport.setMinHeight(64);
logs=new TextArea();logs.setId("execution-logs");logs.setEditable(false);logs.setPrefRowCount(4);logs.setWrapText(true);logs.setMinHeight(64);
var split=new SplitPane(game,logs);split.setId("gameplay-split");split.getStyleClass().add("studio-gameplay-split");
split.getStyleClass().add("studio-workspace-split");
split.setOrientation(javafx.geometry.Orientation.VERTICAL);split.setDividerPositions(.8);
// Apply the initial ratio after the native window has received its actual size.
var initialSplit=new AnimationTimer(){@Override public void handle(long now){
@@ -340,24 +369,34 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
initialSplit.start();c.onClose(initialSplit::stop);
gameplay=new Tab(c.text("gameplay.title"),split);gameplay.setId("gameplay-tab");gameplay.setClosable(false);
tabs=new StudioTabs(gameplay);tabs.setId("project-tabs");
agent=agentConnections.create(ref.rootPath());
aiWorkspace=new AiWorkspace(c,tabs,()->resources.child(c),agent);
var statusFooter=new TabStatusFooter(tabs);
var gameplayInfo=Bindings.createStringBinding(()->viewport.scale()>0?
c.text("gameplay.footer",c.text("play.scale.value",viewport.scale()*100,viewport.scale())):c.text("gameplay.footer.waiting"),
viewport.scaleProperty(),c.settingsProperty());
statusFooter.information(gameplay,gameplayInfo);
var aiInfo=Bindings.createStringBinding(()->c.text("ai.title")+" · "+aiWorkspace.connectionStatus().getText(),
c.settingsProperty(),aiWorkspace.connectionStatus().textProperty());
statusFooter.information(aiWorkspace.tab(),aiInfo);
statusFooter.setMinWidth(0);HBox.setHgrow(statusFooter,Priority.ALWAYS);
var footerBar=new HBox(12,statusFooter,aiWorkspace.accessButton());
footerBar.setAlignment(javafx.geometry.Pos.CENTER_LEFT);footerBar.setId("studio-footer-bar");
footerBar.getStyleClass().addAll("studio-information-strip","studio-footer");
var stripHeight=Bindings.createDoubleBinding(()->Math.ceil(identity.getFont().getSize()*1.7),identity.fontProperty());
for(var strip:new Region[]{header,statusFooter}){
for(var strip:new Region[]{header,footerBar}){
strip.minHeightProperty().bind(stripHeight);strip.prefHeightProperty().bind(stripHeight);strip.maxHeightProperty().bind(stripHeight);
}
c.onClose(()->{statusFooter.close();gameplayInfo.dispose();
for(var strip:new Region[]{header,statusFooter}){strip.minHeightProperty().unbind();strip.prefHeightProperty().unbind();strip.maxHeightProperty().unbind();}
c.onClose(()->{statusFooter.close();gameplayInfo.dispose();aiInfo.dispose();
for(var strip:new Region[]{header,footerBar}){strip.minHeightProperty().unbind();strip.prefHeightProperty().unbind();strip.maxHeightProperty().unbind();}
stripHeight.dispose();});
// Keep reusable feedback in the same themed parent across project views.
if(bottom.getChildren().size()>1)bottom.getChildren().remove(1);
bottom.getChildren().add(statusFooter);
bottom.getChildren().add(footerBar);
c.observe(()->{gameplay.setText(c.text("gameplay.title"));displayedState=null;refresh();});
var page=new ScrollPane(tabs);page.setFitToWidth(true);page.setFitToHeight(true);page.setMinSize(0,0);
shell.workspace().getChildren().setAll(page);lastLog=-1;refresh();
var workspaceScroll=new ScrollPane(aiWorkspace);workspaceScroll.setId("project-workspace-scroll");
workspaceScroll.setFitToWidth(true);workspaceScroll.setFitToHeight(true);workspaceScroll.setMinSize(0,0);
shell.workspace().getChildren().setAll(workspaceScroll);lastLog=-1;refresh();
}
private void play(){
if(busy||closing||controller!=null&&controller.ownsExecution())return;
@@ -374,6 +413,7 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
if(closing||exitRequested||projectCloseRequested){requestCloseProject();return;}
safe(()->{if(controller!=null)controller.close();
controller=executions.create(ref,effective,project.executionSession(),new PlayOptions(discard));
aiWorkspace.collapseForPlayback();
tabs.getSelectionModel().select(gameplay);observe(controller.play().completion());viewport.focusGame();
if(stage.isIconified()||!Window.getWindows().stream().anyMatch(w->w.isFocused()&&belongsToStudio(w)))pauseForFocus();refresh();});
});
@@ -435,13 +475,15 @@ public final class StudioWindowCoordinator2 implements AutoCloseable {
CompletionStage<Void> stopping;
try{stopping=controller==null?CompletableFuture.completedFuture(null):controller.stopAsync();}
catch(RuntimeException failure){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;}
stopping.whenComplete((v,f)->Platform.runLater(()->{
var runtimeStopping=stopping;
CompletionStage<Void> agentStopping=aiWorkspace==null?CompletableFuture.completedFuture(null):aiWorkspace.closeAgent();
CompletableFuture.allOf(runtimeStopping.toCompletableFuture(),agentStopping.toCompletableFuture()).whenComplete((v,f)->Platform.runLater(()->{
if(f!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(f);refresh();return;}
var oldProject=project;var oldController=controller;
if(projectGeometry!=null){projectGeometry.close();projectGeometry=null;}
background(()->closeOwned(oldProject,oldController),(warning,failure)->{
if(failure!=null){closing=false;exitRequested=false;projectCloseRequested=false;error(failure);refresh();return;}
project=null;controller=null;closing=false;projectCloseRequested=false;play=null;notice.setText("");
project=null;controller=null;agent=null;closing=false;projectCloseRequested=false;play=null;notice.setText("");
if(viewport!=null){viewport.close();viewport=null;}if(viewContext!=null){viewContext.close();viewContext=null;}shell.workspace().getChildren().clear();
if(exitRequested)finishExit();else {showChooser();if(warning!=null)error(warning);}
});
@@ -125,3 +125,64 @@ play.scale.waiting=Waiting for image
gameplay.footer=Gameplay · {0}
gameplay.footer.waiting=Gameplay · Waiting for image
ai.title=AI
ai.footer=AI · Not connected
ai.open=Open AI prompt
ai.focus=Focus AI prompt
ai.collapse=Collapse prompt
ai.prompt=Prompt
ai.prompt.placeholder=Write a request…
ai.chat=Chat
ai.noChat=No chat selected
ai.chats=Chats
ai.chats.empty=No chats yet.
ai.conversation.empty=Your conversation will appear here.
ai.unavailable=Sending and agent connection are not available yet.
ai.newChat=New chat
ai.actions=Actions
ai.load=Load
ai.rename=Rename
ai.delete=Delete
ai.attach=Add assets
ai.send=Send
ai.settings.title=AI / ACP
ai.settings.agent=Agent
ai.settings.authentication=Authentication
ai.agent.codex=Codex
ai.auth.chatgpt=ChatGPT login
ai.auth.login=Sign in with ChatGPT
ai.prompt.for=Prompt · {0}
ai.createFirst=Create a chat to write a request.
ai.local.temporary=Chats and drafts are discarded when this project closes.
ai.rename.title=Rename chat
ai.rename.name=Chat name
ai.rename.required=Enter a chat name.
ai.delete.title=Delete chat
ai.delete.confirm=Delete chat “{0}” and its draft? A running request will be cancelled first. Project changes are kept.
ai.cancel=Cancel request
ai.running.for=Working in {0}
ai.recover=Recover last request
ai.connect=Connect
ai.executable=ACP executable
ai.arguments=Arguments (one per line)
ai.launch.help=Uses the installed Studio Codex ACP adapter. If missing, run the Studio adapter installer once.
ai.working=Working…
ai.cancelling=Cancelling…
ai.cancelled=Cancelled
ai.done=Finished
ai.error=Request failed
ai.you=You
ai.permission=Codex requests permission
ai.session.expired=Connection ended. Create a new chat after reconnecting; this conversation remains readable.
ai.connection.DISCONNECTED=Connect Codex in Studio preferences → AI / ACP.
ai.connection.CONNECTING=Connecting to Codex…
ai.connection.CONNECTED=Connected · sign in with ChatGPT in Studio preferences.
ai.connection.AUTHENTICATING=Waiting for ChatGPT login in your browser…
ai.connection.READY=Codex · ChatGPT connected
ai.connection.FAILED=Codex disconnected
ai.connection.CLOSING=Stopping Codex…
ai.connection.CLOSED=Codex stopped
ai.global.help=Shared by all projects. Changes apply at the next connection.
ai.openProject=Open a project to connect or sign in. These settings apply to all projects.
@@ -125,3 +125,64 @@ play.scale.waiting=Aguardando imagem
gameplay.footer=Gameplay · {0}
gameplay.footer.waiting=Gameplay · Aguardando imagem
ai.title=IA
ai.footer=IA · Não conectada
ai.open=Abrir prompt de IA
ai.focus=Focar prompt de IA
ai.collapse=Recolher prompt
ai.prompt=Prompt
ai.prompt.placeholder=Escreva um pedido…
ai.chat=Chat
ai.noChat=Nenhum chat selecionado
ai.chats=Chats
ai.chats.empty=Nenhum chat ainda.
ai.conversation.empty=Sua conversa aparecerá aqui.
ai.unavailable=O envio e a conexão com o agente ainda não estão disponíveis.
ai.newChat=Novo chat
ai.actions=Ações
ai.load=Carregar
ai.rename=Renomear
ai.delete=Apagar
ai.attach=Adicionar assets
ai.send=Enviar
ai.settings.title=IA / ACP
ai.settings.agent=Agente
ai.settings.authentication=Autenticação
ai.agent.codex=Codex
ai.auth.chatgpt=Login ChatGPT
ai.auth.login=Entrar com ChatGPT
ai.prompt.for=Prompt · {0}
ai.createFirst=Crie um chat para escrever um pedido.
ai.local.temporary=Chats e rascunhos são descartados ao fechar este projeto.
ai.rename.title=Renomear chat
ai.rename.name=Nome do chat
ai.rename.required=Informe um nome para o chat.
ai.delete.title=Apagar chat
ai.delete.confirm=Apagar o chat “{0}” e seu rascunho? Um pedido em execução será cancelado primeiro. Alterações no projeto são mantidas.
ai.cancel=Cancelar pedido
ai.running.for=Trabalhando em {0}
ai.recover=Recuperar último pedido
ai.connect=Conectar
ai.executable=Executável ACP
ai.arguments=Argumentos (um por linha)
ai.launch.help=Usa o adaptador ACP do Codex instalado para o Studio. Se estiver ausente, execute o instalador do adaptador uma vez.
ai.working=Trabalhando…
ai.cancelling=Cancelando…
ai.cancelled=Cancelado
ai.done=Concluído
ai.error=Falha no pedido
ai.you=Você
ai.permission=Codex solicita permissão
ai.session.expired=Conexão encerrada. Crie um novo chat após reconectar; esta conversa continua disponível para leitura.
ai.connection.DISCONNECTED=Conecte o Codex em Preferências do Studio → IA / ACP.
ai.connection.CONNECTING=Conectando ao Codex…
ai.connection.CONNECTED=Conectado · entre com ChatGPT nas preferências do Studio.
ai.connection.AUTHENTICATING=Aguardando login ChatGPT no navegador…
ai.connection.READY=Codex · ChatGPT conectado
ai.connection.FAILED=Codex desconectado
ai.connection.CLOSING=Encerrando Codex…
ai.connection.CLOSED=Codex encerrado
ai.global.help=Compartilhado por todos os projetos. Alterações valem na próxima conexão.
ai.openProject=Abra um projeto para conectar ou entrar. Estas configurações valem para todos os projetos.
@@ -87,18 +87,36 @@
.studio-information-strip { -fx-background-color: -studio-surface; -fx-padding: 4 14; }
.studio-header { -fx-border-color: -studio-border; -fx-border-width: 1 0 1 0; }
.studio-footer { -fx-border-color: -studio-border; -fx-border-width: 1 0 0 0; -fx-text-fill: -studio-muted; }
.studio-footer-information { -fx-text-fill: -studio-muted; }
.studio-tabs > .tab-header-area { -fx-padding: 0; }
.studio-tabs > .tab-header-area > .tab-header-background { -fx-background-color: -studio-surface; }
.studio-tabs > .tab-content-area { -fx-background-color: -studio-workspace; -fx-padding: 2; }
.studio-tab-content-outline { -fx-fill: transparent; -fx-stroke: -studio-accent; -fx-stroke-width: 2; }
.studio-gameplay-split { -fx-background-color: transparent; -fx-padding: 0; }
.studio-gameplay-split:vertical > .split-pane-divider {
.studio-workspace-split { -fx-background-color: transparent; -fx-padding: 0; }
.studio-workspace-split:vertical > .split-pane-divider {
/* The native skin uses preferred width as divider thickness in both orientations. */
-fx-background-color: -studio-border; -fx-padding: 0 4;
-fx-pref-width: 8; -fx-cursor: v-resize;
}
.studio-gameplay-split > .split-pane-divider:hover { -fx-background-color: -studio-accent; }
.studio-gameplay-split > .split-pane-divider > .vertical-grabber { -fx-background-color: -studio-highlight; -fx-padding: 1 14; }
.studio-workspace-split > .split-pane-divider:hover { -fx-background-color: -studio-accent; }
.studio-workspace-split > .split-pane-divider > .vertical-grabber { -fx-background-color: -studio-highlight; -fx-padding: 1 14; }
.studio-ai-sidebar { -fx-background-color: -studio-surface; -fx-padding: 12; -fx-border-color: -studio-border; -fx-border-width: 0 1 0 0; }
.studio-ai-empty { -fx-padding: 18; }
.studio-ai-chat-title { -fx-padding: 12; -fx-text-fill: -studio-heading; }
.studio-ai-composer { -fx-padding: 12; -fx-background-color: -studio-surface; -fx-border-color: -studio-border; -fx-border-width: 1 0 0 0; }
.studio-ai-composer .text-area { -fx-prompt-text-fill: -studio-muted; }
.studio-root .studio-compact-action { -fx-min-height: 0; -fx-padding: .4em .65em; }
.studio-root .menu-button.studio-compact-action { -fx-background-color: -studio-field; -fx-background-radius: 0; }
.studio-root .menu-button.studio-compact-action .label { -fx-text-fill: -studio-text; }
.studio-root .menu-button.studio-compact-action .arrow { -fx-background-color: -studio-text; }
.studio-root .menu-button.studio-compact-action:disabled { -fx-opacity: .45; }
.studio-ai-access { -fx-background-color: transparent; -fx-background-radius: 0; -fx-padding: 1 8; -fx-min-height: 0; -fx-cursor: hand; }
.studio-ai-access:hover { -fx-background-color: -studio-field; }
.studio-ai-access:selected { -fx-background-color: -studio-accent; }
.studio-ai-access:selected .studio-ai-icon { -fx-fill: -studio-on-accent; }
.studio-ai-access:focused { -fx-border-color: -studio-focus; -fx-border-width: 1; -fx-border-insets: 0; }
.studio-ai-access:selected:focused { -fx-border-color: -studio-on-accent; }
.studio-ai-icon { -fx-fill: -studio-accent; }
.studio-tabs > .tab-header-area > .headers-region > .tab {
-fx-background-color: -studio-border, -studio-surface;
-fx-background-insets: 0, 2 2 0 2;
@@ -0,0 +1,65 @@
package p.studio.ui.javafx2.ai;
import org.junit.jupiter.api.Test;
import p.studio.api.ai.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import static org.junit.jupiter.api.Assertions.*;
class AgentChatsTest {
private static final class Agent implements AgentConnection {
Status status=new Status(State.READY,"");Consumer<Status> observer=s->{};Consumer<Event> sink=e->{};
CompletableFuture<String> session=CompletableFuture.completedFuture("session");
CompletableFuture<Void> ack=new CompletableFuture<>(),cancelled=new CompletableFuture<>();
CompletableFuture<String> done=new CompletableFuture<>();String submitted;int prompts;
public boolean available(){return true;}public Status status(){return status;}
public AutoCloseable observe(Consumer<Status> o){observer=o;o.accept(status);return ()->{};}
void state(State s){status=new Status(s,"");observer.accept(status);}
public void events(Consumer<Event> s){sink=s;}public void permissions(Function<Permission,CompletionStage<String>> h){}
public CompletionStage<Void> connect(AcpSettings s){return CompletableFuture.completedFuture(null);}
public CompletionStage<Void> login(){return CompletableFuture.completedFuture(null);}
public CompletionStage<String> newSession(){return session;}
public Turn prompt(String id,String value){prompts++;submitted=value;return new Turn(ack,done);}
public CompletionStage<Void> cancel(String id){return cancelled;}
public CompletionStage<Void> closeAsync(){return cancelled;}
}
private AgentChats model(LocalChats drafts,Agent agent){return new AgentChats(drafts,agent,Runnable::run,()->{},drafts::select,key->key);}
@Test void selectedSnapshotClearsOnlyItsUnchangedDraftAndStreamsToItsOwnChat(){
var drafts=new LocalChats();var a=drafts.create();drafts.write("A");var b=drafts.create();drafts.write("B");
var agent=new Agent();var m=model(drafts,agent);m.send(b.id());assertEquals("B",agent.submitted);
assertFalse(m.canSend(a.id()));drafts.select(a.id());agent.ack.complete(null);
assertEquals("A",drafts.draft());assertEquals("",drafts.draft(b.id()));
agent.sink.accept(new AgentConnection.Event("session",AgentConnection.Kind.TEXT,"answer B"));
assertTrue(m.log(b.id()).contains("answer B"));assertFalse(m.log(a.id()).contains("answer B"));
agent.done.complete("end_turn");assertFalse(m.busy());assertTrue(m.canSend(a.id()));
}
@Test void preDeliveryRejectionKeepsDraftAndLateFailurePreservesNewWriting(){
var drafts=new LocalChats();var chat=drafts.create();drafts.write("first");var agent=new Agent();var m=model(drafts,agent);
m.send(chat.id());agent.ack.completeExceptionally(new IllegalStateException("rejected"));agent.done.completeExceptionally(new IllegalStateException("rejected"));
assertEquals("first",drafts.draft());assertTrue(m.log(chat.id()).contains("rejected"));
agent.ack=new CompletableFuture<>();agent.done=new CompletableFuture<>();m.send(chat.id());
drafts.write("new writing");agent.ack.complete(null);agent.done.completeExceptionally(new IllegalStateException("late failure"));
assertEquals("new writing",drafts.draft());assertEquals("first",m.lastRequest(chat.id()));
}
@Test void cancelDuringSessionCreationDoesNotSendOrDiscardTheDraft(){
var drafts=new LocalChats();var chat=drafts.create();drafts.write("keep");var agent=new Agent();agent.session=new CompletableFuture<>();
var m=model(drafts,agent);m.send(chat.id());var stop=m.cancel();assertFalse(stop.toCompletableFuture().isDone());
agent.session.complete("session");assertTrue(stop.toCompletableFuture().isDone());assertEquals(0,agent.prompts);assertEquals("keep",drafts.draft());
}
@Test void deletingRunningChatWaitsForTerminationAndKeepsOtherDrafts(){
var drafts=new LocalChats();var a=drafts.create();drafts.write("A");var b=drafts.create();drafts.write("B");
var agent=new Agent();var m=model(drafts,agent);m.send(b.id());var deleted=m.delete(b.id());
assertEquals(2,drafts.chats().size());agent.cancelled.complete(null);assertFalse(deleted.toCompletableFuture().isDone());
agent.done.complete("cancelled");assertTrue(deleted.toCompletableFuture().isDone());assertEquals(a,drafts.active());assertEquals("A",drafts.draft());
}
@Test void lostConnectionInvalidatesBoundChatsAndCloseFailureCanBeRetried(){
var drafts=new LocalChats();var a=drafts.create();drafts.write("A");var agent=new Agent();var m=model(drafts,agent);
m.send(a.id());agent.ack.complete(null);agent.done.complete("end_turn");drafts.write("next");
agent.state(AgentConnection.State.FAILED);agent.state(AgentConnection.State.READY);assertFalse(m.canSend(a.id()));
var b=drafts.create();drafts.write("new");assertTrue(m.canSend(b.id()));assertFalse(m.log(a.id()).isEmpty());
var close=m.closeAgent();assertFalse(m.canSend(b.id()));agent.cancelled.completeExceptionally(new IllegalStateException("close failed"));
assertTrue(close.toCompletableFuture().isCompletedExceptionally());assertTrue(m.canSend(b.id()));
}
}
@@ -0,0 +1,51 @@
package p.studio.ui.javafx2.ai;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class LocalChatsTest {
@Test void conversationsHaveIndependentDraftsAndStableIdentityAcrossRename() {
var chats = new LocalChats();
assertNull(chats.active()); assertEquals("", chats.draft()); assertTrue(chats.chats().isEmpty());
assertThrows(IllegalStateException.class, () -> chats.write("unowned"));
var a = chats.create(); chats.write("A\ntexto com espaços ");
var b = chats.create(); assertEquals("", chats.draft()); chats.write("B · personagem");
chats.select(a.id()); assertEquals("A\ntexto com espaços ", chats.draft());
chats.rename(a.id(), " Personagem ");
assertEquals(a.id(), chats.active().id()); assertEquals("Personagem", chats.active().title());
assertEquals("A\ntexto com espaços ", chats.draft());
chats.select(b.id()); assertEquals("B · personagem", chats.draft());
assertThrows(IllegalArgumentException.class, () -> chats.rename(b.id(), " \n "));
assertEquals(b, chats.active()); assertEquals("B · personagem", chats.draft());
}
@Test void deletionSelectsNextThenPreviousAndOnlyRemovesTheTarget() {
var chats = new LocalChats();
var a = chats.create(); chats.write("A");
var b = chats.create(); chats.write("B");
var c = chats.create(); chats.write("C");
chats.select(b.id()); chats.delete(b.id());
assertEquals(c, chats.active()); assertEquals("C", chats.draft());
chats.delete(c.id()); assertEquals(a, chats.active()); assertEquals("A", chats.draft());
var d = chats.create(); chats.write("D"); chats.delete(a.id());
assertEquals(d, chats.active()); assertEquals("D", chats.draft());
chats.delete(d.id()); assertNull(chats.active()); assertTrue(chats.chats().isEmpty());
assertEquals("", chats.draft());
}
@Test void invalidTargetsDoNotChangeSelectionOrText() {
var chats = new LocalChats(); var a = chats.create(); chats.write("keep");
assertThrows(IllegalArgumentException.class, () -> chats.select(999));
assertThrows(IllegalArgumentException.class, () -> chats.delete(999));
assertThrows(IllegalArgumentException.class, () -> chats.rename(999, "title"));
assertEquals(a, chats.active()); assertEquals("keep", chats.draft());
}
@Test void closingDiscardsStateAndAnotherProjectIsIndependent() {
var first = new LocalChats(); first.create(); first.write("secret draft");
var other = new LocalChats(); assertTrue(other.chats().isEmpty());
first.close(); assertTrue(first.chats().isEmpty()); assertNull(first.active()); assertEquals("", first.draft());
assertThrows(IllegalStateException.class, first::create);
other.create(); assertEquals("", other.draft());
}
}