feat(studio): add AI workspace with Codex ACP integration
This commit is contained in:
@@ -60,7 +60,8 @@ The foundation MUST have display-free tests of its own locale/preferences/resour
|
||||
Initial qualification is on available macOS. Windows/Linux, assistive-technology walkthroughs and native IME composition require their own evidence. Logical scene snapshots MUST NOT be presented as proof of physical pixel alignment at every HiDPI scale.
|
||||
|
||||
Project navigation and integrated Play are specified separately by specification
|
||||
14. Document host, free docking, ACP, asset workflows, code/LSP editor, scene/entity
|
||||
14; the AI workspace presentation is specified separately by specification 15.
|
||||
Document host, free docking, ACP transport, asset workflows, code/LSP editor, scene/entity
|
||||
authoring, pixels/audio editing and shipping remain outside this foundation
|
||||
contract. Backend integrations MUST use existing application services; domain logic
|
||||
MUST NOT be duplicated here.
|
||||
|
||||
@@ -64,10 +64,15 @@ standalone foundation shell/gallery retains its decorative panel.
|
||||
|
||||
Tabs MUST retain native selection, focus and keyboard behavior and the inherited
|
||||
Studio typeface. Tabs MUST use stepped upper corners and a flat base without the
|
||||
lower bevel or bottom outline of a button. The selected tab MUST join the content
|
||||
lower bevel or bottom outline of a button. Tab headers MUST have equal width,
|
||||
sized to the longest current title
|
||||
with its padding and controls, and recomputed when language, font, scale or the tab
|
||||
set changes. Native overflow navigation MUST remain available in narrow windows.
|
||||
The selected tab MUST join the content
|
||||
surface, with a gold accent on its top and sides. Semantic theme colors MUST retain
|
||||
distinct selected, hovered, disabled and focused states. This slice MUST NOT add
|
||||
placeholder editors or extra tabs.
|
||||
placeholder editors. The separate AI presentation is governed by
|
||||
[specification 15](15.%20AI%20Workspace%20Presentation%20Specification.md).
|
||||
|
||||
The gold outline MUST continue from the active tab header around its entire content
|
||||
area, joining the header's sides without drawing a line across the opening below
|
||||
@@ -89,7 +94,7 @@ Play. Existing headless, MCP, evidence, tests and agent contracts remain availab
|
||||
through their existing entry points and services. Their preservation takes
|
||||
precedence over interactive convenience.
|
||||
|
||||
Editors, workspaces, AI prompts, tuning during Play,
|
||||
Editors, functional agent integration, tuning during Play,
|
||||
breakpoints, hot reload, PMC builds and distribution/export are outside this
|
||||
slice. Future packaging belongs in Studio as a separate action; Play MUST NOT
|
||||
implicitly package a PMC or a distributable runtime.
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# AI Workspace Presentation Specification
|
||||
|
||||
Status: Implemented presentation, local chats and initial ACP integration. Owner: `studio`.
|
||||
|
||||
## Scope
|
||||
|
||||
The JavaFX 2 project shell MUST expose an AI tab alongside Gameplay, an AI prompt
|
||||
entry in the footer and an AI / ACP section in Studio preferences. This contract
|
||||
extends specifications 13–14 without changing execution ownership, runtime input
|
||||
contracts or existing execution services. Opening a project connects the installed agent using the shared Studio configuration.
|
||||
|
||||
## Workspace and prompt
|
||||
|
||||
The AI tab MUST place the chat manager on the left and the conversation area and
|
||||
prompt on the right. Empty conversations MUST use brief localized text, without
|
||||
invented responses or agent activity. Chat creation, selection, renaming and
|
||||
deletion MUST operate on local state. Loading persisted history and asset attachment
|
||||
MUST remain visibly disabled. Sending follows the ACP contract in specification 16.
|
||||
The compact manager MUST expose a chat selector, New chat and an actions menu.
|
||||
|
||||
The footer MUST retain the selected tab's information and reserve a fixed slot at
|
||||
the right for an AI icon. The icon MUST have a localized tooltip, accessible name
|
||||
and visible keyboard focus. It MUST expose a selected state and an accent
|
||||
background while the prompt is visible, including its inline AI-tab form.
|
||||
In other tabs, activating it MUST open or collapse a
|
||||
prompt panel above the footer. The panel MUST reduce the available content height
|
||||
rather than overlap it. A native divider MUST adjust its height, with minimum
|
||||
sizes for the upper content and panel; constrained content MUST remain scrollable.
|
||||
The footer control MUST be the sole open/collapse control; the prompt panel MUST
|
||||
NOT contain a separate collapse button.
|
||||
|
||||
In the AI tab, activating the footer icon MUST focus the existing prompt. The
|
||||
same compositor MUST move between the AI tab and the compact panel: two prompts
|
||||
MUST NOT appear simultaneously. Opening/collapsing, tab selection and changes to
|
||||
theme, language or text scale MUST retain the entered text. Collapsing MUST return
|
||||
focus to a usable control. Focusing the prompt MUST release Gameplay keyboard input.
|
||||
Starting Play MUST collapse the external drawer before selecting Gameplay and
|
||||
focusing the game. This MUST preserve the draft, including when Play starts from
|
||||
the AI tab, so returning to Gameplay does not reopen the drawer automatically.
|
||||
|
||||
## Local chats and drafts
|
||||
|
||||
Each project view MUST own one in-memory chat collection and active selection.
|
||||
Opening a project MUST start without chats. New chat MUST work in either manager,
|
||||
create a stable local identity and numbered initial title, select the new chat and
|
||||
allow writing its initially empty draft. It MUST keep the current workspace tab.
|
||||
Without a chat, writing MUST be disabled and the UI MUST direct the user to create
|
||||
one. The footer entry MUST focus New chat when no editable prompt is available.
|
||||
|
||||
The full list and compact selector MUST share the same collection and active
|
||||
chat. The prompt MUST identify its destination. Selecting in either manager MUST
|
||||
restore exactly that chat's text while retaining all other drafts. A title MUST
|
||||
NOT serve as chat identity. Presentation changes, opening/collapsing the panel,
|
||||
Settings and starting/stopping Play MUST preserve the collection and drafts.
|
||||
|
||||
Rename MUST be available from both managers, trim external whitespace and reject
|
||||
empty titles. Cancelling or invalid input MUST leave identity, title, selection
|
||||
and draft unchanged. Delete MUST identify the target and require confirmation.
|
||||
Cancelling MUST not alter state. Confirming MUST remove only that chat and draft;
|
||||
if active, select the next chat in creation order, otherwise the previous one.
|
||||
Deleting the last chat MUST return to no selection and disable writing/rename/delete.
|
||||
|
||||
Chats, titles, selection and drafts MUST remain transient project-view state.
|
||||
The UI MUST briefly explain that they are discarded on project close. Closing
|
||||
MUST cancel owned chat dialogs and discard this state; reopening the same project
|
||||
or opening another MUST start empty. No chat data MAY be saved by Studio in project files, setup, preferences or a
|
||||
database. Local creation/selection/rename MUST NOT start an ACP session; the first
|
||||
send creates it lazily. The agent MAY retain its own independent history.
|
||||
|
||||
## Studio preferences
|
||||
|
||||
Studio preferences MUST contain an AI / ACP section identifying Codex as the initial
|
||||
agent and ChatGPT login as the only authentication choice. It MUST expose the
|
||||
shared launch configuration, Connect, login and current connection state.
|
||||
The section MUST NOT offer API keys, future authentication choices or billing
|
||||
explanations. Login MUST be enabled only after connection and disabled when the
|
||||
existing ChatGPT login is recognized. Configuration and execution follow
|
||||
[the ACP integration contract](16.%20Codex%20ACP%20Integration%20Specification.md).
|
||||
|
||||
## Verification and later capabilities
|
||||
|
||||
Presentation MUST use the existing Studio components, semantic theme colors and
|
||||
English/Portuguese bundles. Desktop qualification MUST exercise prompt ownership,
|
||||
focus, resizing, independent drafts, synchronized selection, rename validation,
|
||||
deletion/cancellation, project lifetime, unavailable operations and settings, in
|
||||
both themes and languages, including constrained windows and large text scale.
|
||||
Display-free state tests MUST cover independent drafts, stable identity on rename,
|
||||
invalid operations, deletion selection and project isolation/disposal.
|
||||
|
||||
Codex connection, sending, streaming, explicit permissions and cancellation follow
|
||||
[specification 16](16.%20Codex%20ACP%20Integration%20Specification.md). Asset attachment
|
||||
and persisted chat resumption remain future capabilities. Integration MUST preserve
|
||||
shared-composer ownership, independent drafts and the project lifetime boundary.
|
||||
@@ -0,0 +1,120 @@
|
||||
# Codex ACP Integration Specification
|
||||
|
||||
Status: Implemented initial conversation slice. Owner: `studio`.
|
||||
|
||||
## Scope and ownership
|
||||
|
||||
The Studio JavaFX 2 project shell MUST consume an asynchronous, JavaFX-free
|
||||
`AgentConnection` port in Studio API. The application MUST own the process adapter
|
||||
and composition. UI MUST NOT launch processes or parse ACP; Core MUST NOT depend
|
||||
on JavaFX. This extends specifications 8 and 15 and does not change runtime or MCP
|
||||
authority. Assets, model selection, persistent chat indexing and history resumption
|
||||
are outside this slice.
|
||||
|
||||
## Project connection and authentication
|
||||
|
||||
Studio preferences MUST offer Codex, ChatGPT login, executable, an ordered argument
|
||||
vector, Connect and connection state. Launch settings MUST be machine-local and
|
||||
shared by every project in `~/.prometeu-studio/ai-settings.json`. Project setup MUST
|
||||
NOT override them. Legacy project `acp` values MUST be ignored without losing runtime,
|
||||
save, indentation or MCP intent; new setup writes MUST omit the legacy field. A
|
||||
project MUST NOT silently supply the global default. Apply MUST save without
|
||||
restarting a connected agent; changed settings apply at the next connection.
|
||||
Connect MUST save the configuration before launching it. With no project open,
|
||||
preferences MUST remain editable, while connection/login indicate that a project
|
||||
must first be opened.
|
||||
|
||||
The default executable MUST be `~/.prometeu-studio/bin/codex-acp`, with no arguments.
|
||||
The explicit installer MUST stage adapter 2.9.0 under
|
||||
`~/.prometeu-studio/agents/codex-acp/2.9.0`, use a working Node 22+ absolute executable
|
||||
and set its PATH in the stable launcher. Runtime MUST NOT depend on npx or temporary
|
||||
files. The launcher SHOULD reuse an installed compatible Codex 0.171.x through
|
||||
CODEX_PATH; otherwise it MUST use the package dependency. Installation MUST be
|
||||
idempotent, refuse replacing an unmanaged launcher and preserve an existing explicit
|
||||
global preference. It MUST NOT modify system Node/npm or authentication. Installation
|
||||
is explicit; opening a project MUST NOT download or update the adapter.
|
||||
|
||||
After a project is successfully presented, Studio MUST connect using global launch
|
||||
settings and that project's root as cwd. Process, ACP sessions, transcript and drafts
|
||||
MUST remain project-owned. Connection failure MUST remain visible and direct the
|
||||
user to Studio preferences. The executable MUST be invoked directly, without shell
|
||||
text evaluation. No browser login MAY start automatically; existing ChatGPT login is
|
||||
reused, or explicit login remains available in preferences for the opened project.
|
||||
|
||||
The adapter MUST negotiate ACP v1 over stdio JSON-RPC, require the `chat-gpt`
|
||||
authentication method and recognize existing active ChatGPT authentication through
|
||||
`auth/status` and status updates. Explicit login MUST request only `chat-gpt`;
|
||||
the adapter owns browser login and credential storage. Studio MUST NOT offer API
|
||||
keys or billing indications, forward inherited OPENAI_API_KEY/CODEX_API_KEY, save
|
||||
credentials in setup/AIE, or expose raw environment/stderr in UI or evidence.
|
||||
Connection/authentication failures MUST remain visible and MUST NOT imply readiness.
|
||||
|
||||
## Sessions, sending and drafts
|
||||
|
||||
Each local chat MUST lazily obtain its own ACP session on first send. Sessions MUST
|
||||
use the project cwd and select the offered `workspace-write` mode before prompting,
|
||||
which uses Codex's on-request permission policy. No unattended approval mode is
|
||||
introduced. Only one request MAY run per project; selecting chats and editing their
|
||||
independent drafts MUST remain possible while it runs.
|
||||
|
||||
Send MUST snapshot only the selected draft, select its chat and open AI, collapsing
|
||||
the external prompt. Responses MUST route by session rather than current selection.
|
||||
ACP has no separate prompt-accepted response: first relevant agent progress or a
|
||||
successful prompt response MUST acknowledge delivery. The corresponding draft MUST
|
||||
clear only if still identical to the snapshot. Pre-delivery failure MUST preserve
|
||||
it; edits made while sending MUST survive. The submitted text and failures MUST
|
||||
remain in the conversation. Recover last request MUST copy that text only into an
|
||||
empty draft. Failed work MUST NOT be automatically resubmitted.
|
||||
|
||||
The log MUST show user text, streamed agent text, tool activity and terminal
|
||||
result/error/cancellation. Thought content MUST NOT be stored or shown; generic
|
||||
working activity MAY be shown. Current activity and connection state MUST remain
|
||||
visible, including the running chat identity when another chat is selected. The
|
||||
Studio log is a bounded plain-text view (last 200,000 characters per chat), not an
|
||||
authoritative persisted agent history.
|
||||
|
||||
Connection loss MUST invalidate bound session IDs. Retained transcripts MUST remain
|
||||
readable, with explicit guidance to create a new chat after reconnecting. Studio MUST
|
||||
NOT silently create a replacement session pretending to retain conversation context.
|
||||
|
||||
## Permission and cancellation
|
||||
|
||||
Each `session/request_permission` MUST require an explicit choice from its offered
|
||||
options. The owned, nonblocking dialog MUST identify the chat and requested action,
|
||||
with a bounded scrollable action preview when supplied. Closing/cancelling MUST
|
||||
return cancelled; unknown options MUST NOT authorize. Cancellation, turn completion
|
||||
and project close MUST dismiss stale permission dialogs. UI callbacks MUST run on FX;
|
||||
protocol IO and process waits MUST run off FX.
|
||||
|
||||
Cancel MUST send `session/cancel` and await the active prompt's terminal response.
|
||||
If unresponsive for ten seconds, the connection MUST terminate its owned process
|
||||
tree and invalidate sessions before cancellation finishes. Deleting a running chat
|
||||
MUST confirm, cancel and await termination before removing local state. Failure MUST
|
||||
retain the chat and report an error. Deletion MUST NOT undo project changes or claim
|
||||
to delete the agent's own persisted history.
|
||||
|
||||
Project close MUST cancel and await the agent alongside runtime shutdown, then
|
||||
terminate the owned process tree before discarding chats/drafts and closing the
|
||||
project session. Cancellation has a ten-second grace; process termination MUST
|
||||
escalate from graceful destruction to force with bounded waits (two plus three
|
||||
seconds). A termination failure MUST keep closure visibly incomplete and allow
|
||||
cleanup retry. Cleanup MUST target only the launched process and tracked descendants,
|
||||
never unrelated Codex processes.
|
||||
|
||||
## Transport and verification
|
||||
|
||||
Requests MUST correlate IDs, support asynchronous notifications and incoming
|
||||
permission requests, bound frame size to 4 MiB and use finite RPC timeouts. Missing
|
||||
or incompatible agents, rejection, malformed frames, process death and timeout MUST
|
||||
fail visibly. Unsupported incoming methods MUST receive method-not-found. Reconnect
|
||||
MUST dispose the previous transport before launch and fence old process output.
|
||||
|
||||
Display-free tests MUST exercise real stdio peers, handshake/authentication,
|
||||
independent sessions, explicit permission choices, cancellation, unresponsive peers,
|
||||
malformed/disconnected transport and process-tree cleanup. Chat-state tests MUST
|
||||
cover independent drafts, delivery failure, edits during delivery, session creation
|
||||
cancellation, delete waiting and invalidated sessions. Desktop tests MUST exercise
|
||||
the actual settings, prompt, chat routing, permissions and project lifetime with a
|
||||
controlled backend. The opt-in live smoke MUST use a disposable project and an
|
||||
existing ChatGPT login, request no tools or file changes, and await full shutdown.
|
||||
Live smoke MUST NOT run as part of ordinary unit tests.
|
||||
@@ -308,3 +308,15 @@ External PNGs require an opaque project-bound grant issued by explicit human
|
||||
source selection. Validate canonical scope, expected bytes and PNG bounds before
|
||||
staging, then revalidate relevant source bytes at commit. A path, hash or
|
||||
caller-supplied claim alone is not an external-source grant.
|
||||
|
||||
## ACP configuration belongs to Studio
|
||||
|
||||
ACP launch settings MUST be machine-local Studio preferences in
|
||||
`~/.prometeu-studio/ai-settings.json`, with an executable and ordered literal arguments.
|
||||
They MUST NOT be persisted in project setup or restored as project state. Readers
|
||||
MUST ignore legacy project `acp` fields while preserving runtime/save paths,
|
||||
indentation and MCP `agentIntegration` intent. New setup writes MUST omit that field.
|
||||
A legacy project MUST NOT override or automatically seed the global preference.
|
||||
Credentials, session IDs, chats and drafts MUST NOT be stored in either setup or
|
||||
launch preferences. Connection state is transient and cwd/sessions remain per project.
|
||||
See [the ACP contract](16.%20Codex%20ACP%20Integration%20Specification.md).
|
||||
|
||||
@@ -16,6 +16,12 @@ remain shared. The normal/installed app uses the new chooser and Play frontend;
|
||||
[`14. Integrated Play Specification.md`](14.%20Integrated%20Play%20Specification.md)
|
||||
owns project flow, execution authority, transport/presentation, input, saves and
|
||||
qualification boundaries.
|
||||
[`15. AI Workspace Presentation Specification.md`](15.%20AI%20Workspace%20Presentation%20Specification.md)
|
||||
defines the AI tab, shared footer prompt, transient local chats/drafts and
|
||||
global Studio ACP preferences with project-owned sessions.
|
||||
[`16. Codex ACP Integration Specification.md`](16.%20Codex%20ACP%20Integration%20Specification.md)
|
||||
defines initial ChatGPT authentication, real conversation, permissions, cancellation
|
||||
and process lifetime. Asset attachment and persisted chat resumption remain unavailable.
|
||||
|
||||
## Purpose
|
||||
|
||||
|
||||
@@ -168,6 +168,19 @@ tasks.withType<Test>().configureEach {
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayProcessTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayDesktopTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioProjectsDesktopTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/CodexAcpSmokeTest.class") }
|
||||
tasks.register<Test>("codexAcpSmoke") {
|
||||
group = "verification"
|
||||
description = "Sends one minimal ACP prompt using an existing ChatGPT login in a disposable project."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/CodexAcpSmokeTest.class")
|
||||
systemProperty("studio.test.codexAcp", providers.gradleProperty("studioCodexAcp").getOrElse(""))
|
||||
systemProperty("studio.test.codexProject", providers.gradleProperty("studioCodexProject").getOrElse(""))
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
tasks.register<Test>("studioProjectsDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies launcher, new-project wizard, loading shield and window lifecycle on a desktop."
|
||||
|
||||
@@ -184,6 +184,11 @@ public class StudioApplicationConfiguration {
|
||||
return new p.studio.core.project.preferences.JsonRuntimeSettingsStore(
|
||||
Path.of(System.getProperty("user.home"), ".prometeu-studio", "runtime-settings.json"), mapper);
|
||||
}
|
||||
@Bean
|
||||
p.studio.api.preferences.AgentSettingsStore agentSettingsStore(ObjectMapper mapper) {
|
||||
return new p.studio.core.project.preferences.JsonAgentSettingsStore(
|
||||
Path.of(System.getProperty("user.home"),".prometeu-studio","ai-settings.json"),mapper);
|
||||
}
|
||||
|
||||
@Bean
|
||||
ProjectActivityHistoryStore projectActivityHistoryStore(ObjectMapper mapper) {
|
||||
@@ -332,7 +337,7 @@ public class StudioApplicationConfiguration {
|
||||
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide,
|
||||
p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations,
|
||||
p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore,
|
||||
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings) {
|
||||
p.studio.api.preferences.RuntimeSettingsStore runtimeSettings,p.studio.api.preferences.AgentSettingsStore agentSettings) {
|
||||
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
|
||||
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
@@ -341,6 +346,8 @@ public class StudioApplicationConfiguration {
|
||||
activityHistoryStore, connectionGuide);
|
||||
factory.setAnimationService(animationService);
|
||||
factory.setRuntimeSettings(runtimeSettings);
|
||||
factory.setAgentSettings(agentSettings);
|
||||
factory.setAgentConnections(root->new p.studio.app.acp.CodexAcpConnection(root,mapper));
|
||||
factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper,
|
||||
new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access),
|
||||
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}});
|
||||
|
||||
@@ -36,6 +36,11 @@ public final class StudioUiFactory {
|
||||
private p.studio.ui.javafx2.window.WindowResources interactiveResources;
|
||||
private p.studio.api.preferences.RuntimeSettingsStore runtimeSettings;
|
||||
private String initialRuntime;
|
||||
private p.studio.api.preferences.AgentSettingsStore agentSettings;
|
||||
private p.studio.api.ai.AcpSettings initialAgent;
|
||||
public void setAgentSettings(p.studio.api.preferences.AgentSettingsStore settings){agentSettings=Objects.requireNonNull(settings);}
|
||||
private p.studio.api.ai.AgentConnectionFactory agentConnections;
|
||||
public void setAgentConnections(p.studio.api.ai.AgentConnectionFactory factory){agentConnections=Objects.requireNonNull(factory);}
|
||||
public void setRuntimeSettings(p.studio.api.preferences.RuntimeSettingsStore settings) { runtimeSettings=Objects.requireNonNull(settings); }
|
||||
public void enableInteractive(ExecutionControllerFactory factory,
|
||||
java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> saver) {
|
||||
@@ -44,11 +49,15 @@ public final class StudioUiFactory {
|
||||
public void prepareInteractive(){
|
||||
interactiveResources=new p.studio.ui.javafx2.window.WindowResources();
|
||||
initialRuntime=Objects.requireNonNull(runtimeSettings,"runtimeSettings").load();
|
||||
initialAgent=Objects.requireNonNull(agentSettings,"agentSettings").load();
|
||||
}
|
||||
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
|
||||
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
|
||||
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
var coordinator=new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
|
||||
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources,languageCatalog,windowStateStore,runtimeSettings,initialRuntime);
|
||||
if(agentConnections!=null)coordinator.setAgentConnections(agentConnections);
|
||||
coordinator.setAgentSettings(agentSettings,initialAgent);
|
||||
return coordinator;
|
||||
}
|
||||
private final ProjectCatalog projectCatalog;
|
||||
private final KnownProjects knownProjects;
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import p.studio.api.ai.*;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.*;
|
||||
|
||||
/** ACP v1 line transport. Owns only its launched process tree, never the caller's Codex process. */
|
||||
public final class CodexAcpConnection implements AgentConnection {
|
||||
private final Path root;
|
||||
private final ObjectMapper json;
|
||||
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
|
||||
private final ExecutorService writer = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("studio-acp-writer").factory());
|
||||
private final Map<String, CompletableFuture<JsonNode>> pending = new ConcurrentHashMap<>();
|
||||
private final Set<String> sessions = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> cancelling = ConcurrentHashMap.newKeySet();
|
||||
private final Map<String, CompletableFuture<String>> turns = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletableFuture<Void>> accepted = new ConcurrentHashMap<>();
|
||||
private final Map<String, ObjectNode> permissionRequests = new ConcurrentHashMap<>();
|
||||
private final CopyOnWriteArrayList<Consumer<Status>> observers = new CopyOnWriteArrayList<>();
|
||||
private final AtomicLong sequence = new AtomicLong();
|
||||
private final Object outputLock = new Object();
|
||||
private final Object terminationLock = new Object();
|
||||
private volatile Status status = new Status(State.DISCONNECTED, "");
|
||||
private volatile Process process;
|
||||
private volatile Writer output;
|
||||
private volatile Consumer<Event> events = e -> {};
|
||||
private volatile Function<Permission, CompletionStage<String>> permissions = p -> CompletableFuture.completedFuture(null);
|
||||
private volatile boolean closing;
|
||||
private volatile boolean chatGptLogin;
|
||||
private volatile CompletableFuture<Void> shutdown;
|
||||
private volatile long connectionEpoch;
|
||||
private final Set<ProcessHandle> ownedProcesses = ConcurrentHashMap.newKeySet();
|
||||
|
||||
public CodexAcpConnection(Path root, ObjectMapper mapper) { this.root=root.toAbsolutePath().normalize();json=mapper.copy(); }
|
||||
public boolean available(){return true;}
|
||||
public Status status(){return status;}
|
||||
public AutoCloseable observe(Consumer<Status> listener){observers.add(listener);listener.accept(status);return ()->observers.remove(listener);}
|
||||
public void events(Consumer<Event> listener){events=Objects.requireNonNull(listener);}
|
||||
public void permissions(Function<Permission,CompletionStage<String>> handler){permissions=Objects.requireNonNull(handler);}
|
||||
private void state(State value,String detail){status=new Status(value,detail);for(var l:observers)try{l.accept(status);}catch(RuntimeException ignored){}}
|
||||
private static String message(Throwable failure){
|
||||
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();
|
||||
String text=Objects.toString(failure.getMessage(),failure.getClass().getSimpleName());
|
||||
text = message(text);
|
||||
return text.substring(0,Math.min(text.length(),1000));
|
||||
}
|
||||
|
||||
public synchronized CompletionStage<Void> connect(AcpSettings settings){
|
||||
if(closing)return CompletableFuture.failedFuture(new IllegalStateException("Agent connection is closed"));
|
||||
if(status.state()!=State.DISCONNECTED&&status.state()!=State.FAILED)
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Agent is already connected"));
|
||||
state(State.CONNECTING,"");
|
||||
long epoch=++connectionEpoch;
|
||||
return CompletableFuture.runAsync(()->{
|
||||
var owned=new java.util.concurrent.atomic.AtomicReference<Process>();
|
||||
try{
|
||||
terminate();
|
||||
var command=new ArrayList<String>();command.add(settings.executable());command.addAll(settings.arguments());
|
||||
var builder=new ProcessBuilder(command).directory(root.toFile());
|
||||
builder.environment().remove("OPENAI_API_KEY");builder.environment().remove("CODEX_API_KEY");
|
||||
builder.environment().put("INITIAL_AGENT_MODE","workspace-write");
|
||||
synchronized(this){if(closing)throw new IOException("Connection closed");process=builder.start();output=new OutputStreamWriter(process.getOutputStream(),StandardCharsets.UTF_8);}
|
||||
Process launched=process;
|
||||
owned.set(launched);
|
||||
ownedProcesses.add(launched.toHandle());
|
||||
workers.submit(()->track(launched));
|
||||
workers.submit(()->read(launched,epoch));workers.submit(()->{try(var stderr=launched.getErrorStream()){stderr.transferTo(OutputStream.nullOutputStream());}catch(IOException ignored){}});
|
||||
var result=request("initialize",json.createObjectNode().put("protocolVersion",1)
|
||||
.set("clientInfo",json.createObjectNode().put("name","prometeu-studio").put("version","1")),20).join();
|
||||
if(result.path("protocolVersion").asInt()!=1)throw new IOException("Incompatible ACP protocol");
|
||||
chatGptLogin=false;
|
||||
for(var method:result.path("authMethods"))if(method.path("id").asText().equals("chat-gpt"))chatGptLogin=true;
|
||||
if(!chatGptLogin)throw new IOException("Agent does not offer ChatGPT authentication");
|
||||
if(!closing){state(State.CONNECTED,"");queryAuth().join();}
|
||||
}catch(Throwable failure){
|
||||
terminate(owned.get());fail(epoch,failure);throw new CompletionException(failure);
|
||||
}
|
||||
},workers);
|
||||
}
|
||||
|
||||
private CompletableFuture<JsonNode> queryAuth(){
|
||||
return request("auth/status",json.createObjectNode(),10).thenApply(value->{auth(value);return value;});
|
||||
}
|
||||
private void auth(JsonNode value){
|
||||
if(closing||status.state()==State.CONNECTING)return;
|
||||
boolean ready=false;
|
||||
if(value.path("state").asText().equals("authenticated"))
|
||||
for(var account:value.path("accounts"))if(account.path("active").asBoolean(true)&&account.path("label").asText().toLowerCase(Locale.ROOT).contains("chatgpt"))ready=true;
|
||||
state(ready?State.READY:State.CONNECTED,"");
|
||||
}
|
||||
public CompletionStage<Void> login(){
|
||||
if(!chatGptLogin||closing)return CompletableFuture.failedFuture(new IllegalStateException("Connect the ChatGPT-capable agent first"));
|
||||
state(State.AUTHENTICATING,"");
|
||||
return request("authenticate",json.createObjectNode().put("methodId","chat-gpt"),180)
|
||||
.thenCompose(v->queryAuth()).thenAccept(v->{})
|
||||
.whenComplete((v,f)->{if(f!=null&&!closing&&status.state()!=State.FAILED)state(State.CONNECTED,message(f));});
|
||||
}
|
||||
public CompletionStage<String> newSession(){
|
||||
if(status.state()!=State.READY)return CompletableFuture.failedFuture(new IllegalStateException("Sign in with ChatGPT first"));
|
||||
ObjectNode params=json.createObjectNode().put("cwd",root.toString());params.putArray("mcpServers");
|
||||
return request("session/new",params,30).thenCompose(result->{
|
||||
String id=result.path("sessionId").asText();
|
||||
if(id.isBlank())return CompletableFuture.failedFuture(new IllegalStateException("Agent returned no session ID"));
|
||||
boolean mode=false;for(var m:result.path("modes").path("availableModes"))if(m.path("id").asText().equals("workspace-write"))mode=true;
|
||||
if(!mode)return CompletableFuture.failedFuture(new IllegalStateException("Agent does not offer workspace-write mode"));
|
||||
return request("session/set_mode",json.createObjectNode().put("sessionId",id).put("modeId","workspace-write"),10)
|
||||
.thenApply(v->{sessions.add(id);return id;});
|
||||
});
|
||||
}
|
||||
public synchronized Turn prompt(String id,String text){
|
||||
var acknowledgement=new CompletableFuture<Void>();var done=new CompletableFuture<String>();
|
||||
if(status.state()!=State.READY||!sessions.contains(id)||!turns.isEmpty()||text.isBlank()){
|
||||
var failure=new IllegalStateException("Agent is not ready or another request is running");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);return new Turn(acknowledgement,done);
|
||||
}
|
||||
cancelling.remove(id);turns.put(id,done);accepted.put(id,acknowledgement);
|
||||
var params=json.createObjectNode().put("sessionId",id);params.putArray("prompt").addObject().put("type","text").put("text",text);
|
||||
request("session/prompt",params,1800).whenComplete((result,failure)->{
|
||||
turns.remove(id);accepted.remove(id);cancelling.remove(id);cancelPermissions(id);
|
||||
if(failure==null){acknowledgement.complete(null);done.complete(result.path("stopReason").asText("end_turn"));}
|
||||
else{
|
||||
if(failure instanceof TimeoutException)state(State.FAILED,"Agent request timed out");
|
||||
acknowledgement.completeExceptionally(failure);done.completeExceptionally(failure);
|
||||
if(failure instanceof TimeoutException){Process owned=process;workers.submit(()->{terminate(owned);fail(failure);});}
|
||||
}
|
||||
});
|
||||
return new Turn(acknowledgement,done);
|
||||
}
|
||||
public CompletionStage<Void> cancel(String id){
|
||||
var turn=turns.get(id);if(turn==null)return CompletableFuture.completedFuture(null);
|
||||
cancelling.add(id);cancelPermissions(id);
|
||||
notify("session/cancel",json.createObjectNode().put("sessionId",id));
|
||||
return turn.handle((v,f)->(Void)null).toCompletableFuture().orTimeout(10,TimeUnit.SECONDS)
|
||||
.exceptionallyCompose(failure->CompletableFuture.runAsync(()->{
|
||||
terminate();fail(new IOException("Cancellation timed out; agent disconnected"));
|
||||
},workers));
|
||||
}
|
||||
|
||||
private CompletableFuture<JsonNode> request(String method,ObjectNode params,int seconds){
|
||||
String id=Long.toString(sequence.incrementAndGet());var result=new CompletableFuture<JsonNode>();
|
||||
if(closing){result.completeExceptionally(new IOException("Connection closed"));return result;}
|
||||
pending.put(id,result);
|
||||
send(json.createObjectNode().put("jsonrpc","2.0").put("id",id).put("method",method).set("params",params))
|
||||
.whenComplete((v,f)->{if(f!=null)result.completeExceptionally(f);});
|
||||
result.orTimeout(seconds,TimeUnit.SECONDS).whenComplete((v,f)->pending.remove(id));return result;
|
||||
}
|
||||
private void notify(String method,ObjectNode params){send(json.createObjectNode().put("jsonrpc","2.0").put("method",method).set("params",params));}
|
||||
private CompletableFuture<Void> send(JsonNode frame){
|
||||
Writer destination=output;
|
||||
try{return CompletableFuture.runAsync(()->{try{write(frame,destination);}catch(IOException failure){throw new CompletionException(failure);}},writer);}
|
||||
catch(RejectedExecutionException failure){return CompletableFuture.failedFuture(failure);}
|
||||
}
|
||||
private void write(JsonNode message,Writer destination)throws IOException{
|
||||
synchronized(outputLock){if(destination==null||output!=destination)throw new IOException("ACP is disconnected");destination.write(json.writeValueAsString(message));destination.write('\n');destination.flush();}
|
||||
}
|
||||
private void read(Process launched,long epoch){
|
||||
try(var input=new BufferedReader(new InputStreamReader(launched.getInputStream(),StandardCharsets.UTF_8))){
|
||||
StringBuilder line=new StringBuilder();int c;
|
||||
while((c=input.read())!=-1){
|
||||
if(c=='\n'){if(!line.isEmpty()&&process==launched)receive(json.readTree(line.toString()));line.setLength(0);}
|
||||
else if(c!='\r'){if(line.length()>=4*1024*1024)throw new IOException("ACP frame exceeds limit");line.append((char)c);}
|
||||
}
|
||||
if(!closing&&process==launched){fail(epoch,new IOException("ACP process disconnected"));workers.submit(()->terminate(launched));}
|
||||
}catch(Throwable failure){if(!closing&&process==launched){fail(epoch,failure);workers.submit(()->terminate(launched));}}
|
||||
}
|
||||
private void receive(JsonNode message)throws IOException{
|
||||
if(message.has("method")){
|
||||
String method=message.path("method").asText();var params=message.path("params");
|
||||
if(method.equals("session/update"))update(params);
|
||||
else if(method.equals("auth/status_update"))auth(params);
|
||||
else if(method.equals("session/request_permission")&&message.has("id"))permission(message);
|
||||
else if(message.has("id"))send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",message.get("id"))
|
||||
.set("error",json.createObjectNode().put("code",-32601).put("message","Unsupported client method")));
|
||||
}else if(message.has("id")){
|
||||
var response=pending.get(message.path("id").asText());
|
||||
if(response!=null){
|
||||
if(message.has("error"))response.completeExceptionally(new IOException(message(message.path("error").path("message").asText("ACP error"))));
|
||||
else if(message.has("result"))response.complete(message.path("result"));
|
||||
else response.completeExceptionally(new IOException("Invalid ACP response: result is missing"));
|
||||
}
|
||||
}
|
||||
}
|
||||
private static String message(String value){return value.replaceAll("(?i)(sk-[A-Za-z0-9_-]+|Bearer\\s+\\S+)","[redacted]");}
|
||||
private void update(JsonNode params){
|
||||
String id=params.path("sessionId").asText();if(!sessions.contains(id))return;
|
||||
var update=params.path("update");String type=update.path("sessionUpdate").asText();
|
||||
Event event=null;
|
||||
if(type.equals("agent_message_chunk")&&update.path("content").path("type").asText().equals("text"))
|
||||
event=new Event(id,Kind.TEXT,update.path("content").path("text").asText());
|
||||
else if(type.equals("tool_call")||type.equals("tool_call_update"))
|
||||
event=new Event(id,Kind.ACTIVITY,update.path("title").asText(update.path("status").asText("Tool activity")));
|
||||
else if(type.equals("agent_thought_chunk"))event=new Event(id,Kind.ACTIVITY,"Working");
|
||||
if(event!=null){var acknowledgement=accepted.get(id);if(acknowledgement!=null)acknowledgement.complete(null);events.accept(event);}
|
||||
}
|
||||
private void permission(JsonNode message){
|
||||
var params=message.path("params");String session=params.path("sessionId").asText();String key=message.path("id").toString();
|
||||
var choices=new ArrayList<Choice>();for(var o:params.path("options"))choices.add(new Choice(o.path("optionId").asText(),o.path("name").asText(),o.path("kind").asText()));
|
||||
ObjectNode request=json.createObjectNode().set("id",message.get("id"));request.put("sessionId",session);permissionRequests.put(key,request);
|
||||
if(!turns.containsKey(session)||cancelling.contains(session)||closing){replyPermission(key,null);return;}
|
||||
String details=params.path("toolCall").toPrettyString();
|
||||
if(details.length()>16_000)details=details.substring(0,16_000)+"\n…";
|
||||
try{permissions.apply(new Permission(session,params.path("toolCall").path("title").asText("Agent action"),details,List.copyOf(choices)))
|
||||
.whenComplete((choice,failure)->replyPermission(key,failure==null&&choices.stream().anyMatch(c->c.id().equals(choice))?choice:null));}
|
||||
catch(RuntimeException failure){replyPermission(key,null);}
|
||||
}
|
||||
private void replyPermission(String key,String choice){
|
||||
var request=permissionRequests.remove(key);if(request==null)return;
|
||||
var outcome=json.createObjectNode().put("outcome",choice==null?"cancelled":"selected");if(choice!=null)outcome.put("optionId",choice);
|
||||
send(json.createObjectNode().put("jsonrpc","2.0").<ObjectNode>set("id",request.get("id"))
|
||||
.set("result",json.createObjectNode().set("outcome",outcome)));
|
||||
}
|
||||
private void cancelPermissions(String id){for(var e:permissionRequests.entrySet())if(e.getValue().path("sessionId").asText().equals(id))replyPermission(e.getKey(),null);}
|
||||
private void fail(Throwable failure){
|
||||
fail(connectionEpoch,failure);
|
||||
}
|
||||
private synchronized void fail(long epoch,Throwable failure){
|
||||
if(epoch!=connectionEpoch)return;
|
||||
sessions.clear();
|
||||
var requests=List.copyOf(pending.values());
|
||||
if(!closing)state(State.FAILED,message(failure));
|
||||
for(var f:requests)f.completeExceptionally(failure);
|
||||
}
|
||||
public synchronized CompletionStage<Void> closeAsync(){
|
||||
if(shutdown!=null)return shutdown;
|
||||
var stopping=new ArrayList<CompletableFuture<Void>>();for(String id:turns.keySet())stopping.add(cancel(id).toCompletableFuture().exceptionally(f->null));
|
||||
closing=true;state(State.CLOSING,"");
|
||||
shutdown=CompletableFuture.runAsync(()->{
|
||||
try{CompletableFuture.allOf(stopping.toArray(CompletableFuture[]::new)).get(11,TimeUnit.SECONDS);}catch(Exception ignored){}
|
||||
try{terminate();fail(new IOException("Connection closed"));state(State.CLOSED,"");writer.shutdownNow();workers.shutdown();}
|
||||
catch(RuntimeException failure){state(State.FAILED,message(failure));synchronized(this){shutdown=null;}throw failure;}
|
||||
},workers);
|
||||
return shutdown;
|
||||
}
|
||||
private void track(Process launched){
|
||||
while(launched==process&&launched.isAlive()){
|
||||
launched.descendants().forEach(ownedProcesses::add);
|
||||
try{Thread.sleep(100);}catch(InterruptedException e){Thread.currentThread().interrupt();return;}
|
||||
}
|
||||
}
|
||||
private void terminate(){terminate(process);}
|
||||
private void terminate(Process owned){synchronized(terminationLock){
|
||||
if(owned==null||owned!=process)return;
|
||||
owned.descendants().forEach(ownedProcesses::add);
|
||||
var tree=ownedProcesses.stream().filter(p->p.pid()!=owned.pid()).toList();
|
||||
tree.forEach(ProcessHandle::destroy);owned.toHandle().destroy();
|
||||
try{if(!owned.waitFor(2,TimeUnit.SECONDS))owned.toHandle().destroyForcibly();}catch(InterruptedException e){Thread.currentThread().interrupt();owned.toHandle().destroyForcibly();}
|
||||
tree.stream().filter(ProcessHandle::isAlive).forEach(ProcessHandle::destroyForcibly);
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3);
|
||||
try{owned.waitFor(3,TimeUnit.SECONDS);for(var child:tree)if(child.isAlive())child.onExit().get(Math.max(1,deadline-System.nanoTime()),TimeUnit.NANOSECONDS);}
|
||||
catch(Exception e){throw new CompletionException(e);}
|
||||
if(owned.isAlive()||tree.stream().anyMatch(ProcessHandle::isAlive))throw new IllegalStateException("Agent process did not terminate");
|
||||
process=null;output=null;ownedProcesses.clear();
|
||||
}}
|
||||
}
|
||||
@@ -42,16 +42,36 @@ class StudioProjectsDesktopTest {
|
||||
}
|
||||
@BeforeAll static void start()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);}
|
||||
@AfterAll static void end(){Platform.exit();}
|
||||
static void fire(Stage stage,String id)throws Exception {fx(()->{var b=(Button)stage.getScene().lookup("#"+id);assertNotNull(b,id);assertFalse(b.isDisabled(),id);b.fire();return null;});}
|
||||
static void fire(Stage stage,String id)throws Exception {fx(()->{var b=(ButtonBase)stage.getScene().lookup("#"+id);assertNotNull(b,id);assertFalse(b.isDisabled(),id);b.fire();return null;});}
|
||||
static Stage wizard()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#wizard-name")!=null).findFirst().orElseThrow());}
|
||||
static Stage shield()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#loading-phase")!=null).findFirst().orElseThrow());}
|
||||
static Stage settings()throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#settings-dialog")!=null).findFirst().orElseThrow());}
|
||||
static void foreground(Stage stage)throws Exception {
|
||||
for(int attempt=0;attempt<3;attempt++) {
|
||||
if(fx(stage::isFocused))return;
|
||||
fx(()->{stage.toFront();stage.requestFocus();return null;});
|
||||
Thread.sleep(150);
|
||||
if(fx(stage::isFocused))return;
|
||||
StudioPlayDesktopTest.focus(stage);
|
||||
}
|
||||
assertTrue(fx(stage::isFocused),"Desktop qualification requires the project window in the foreground");
|
||||
}
|
||||
static Stage chatDialog(String id)throws Exception {return fx(()->(Stage)Window.getWindows().stream().filter(w->w.isShowing()&&w.getScene().lookup("#"+id)!=null).findFirst().orElseThrow());}
|
||||
static void chatAction(Stage stage,String id)throws Exception {
|
||||
fx(()->{var menu=(MenuButton)stage.getScene().lookup("#ai-chat-actions");
|
||||
assertFalse(menu.isDisabled());var item=menu.getItems().stream().filter(i->id.equals(i.getId())).findFirst().orElseThrow();
|
||||
assertFalse(item.isDisable());item.fire();return null;});
|
||||
}
|
||||
|
||||
private record Harness(StudioWindowCoordinator2 window,Stage stage,ExecutorService worker) implements AutoCloseable {
|
||||
@Override public void close()throws Exception {fx(window::closeAsync).toCompletableFuture().get(15,TimeUnit.SECONDS);worker.shutdown();assertTrue(worker.awaitTermination(10,TimeUnit.SECONDS));}
|
||||
}
|
||||
private Harness harness(ProjectCatalog catalog,KnownProjects known,ProjectLocalStudioSetupStore setups,
|
||||
WindowStateStore windows,RuntimeSettingsStore runtimes)throws Exception {
|
||||
return harness(catalog,known,setups,windows,runtimes,null);
|
||||
}
|
||||
private Harness harness(ProjectCatalog catalog,KnownProjects known,ProjectLocalStudioSetupStore setups,
|
||||
WindowStateStore windows,RuntimeSettingsStore runtimes,ExecutionControllerFactory executions)throws Exception {
|
||||
var initial=PresentationSettings.defaults(Locale.ENGLISH);
|
||||
var resources=new WindowResources(initial,new SettingsStore(){public PresentationSettings load(){return initial;}public void save(PresentationSettings value){assertFalse(Platform.isFxApplicationThread());}});
|
||||
var executor=Executors.newFixedThreadPool(3);
|
||||
@@ -66,7 +86,7 @@ class StudioProjectsDesktopTest {
|
||||
}
|
||||
};
|
||||
String global=runtimes.load();Stage stage=fx(Stage::new);
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,sessions,null,setups::save,executor,resources,()->List.of(),windows,runtimes,global));
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,sessions,executions,setups::save,executor,resources,()->List.of(),windows,runtimes,global));
|
||||
fx(()->{window.showLauncher();return null;});await(()->fx(()->window.launcherStage().isShowing()));
|
||||
return new Harness(window,stage,executor);
|
||||
}
|
||||
@@ -76,6 +96,96 @@ class StudioProjectsDesktopTest {
|
||||
private static void closeProject(Harness harness)throws Exception {
|
||||
fx(()->{harness.window.requestCloseProject();return null;});await(()->fx(()->harness.window.projectSession()==null&&harness.window.launcherStage().isShowing()));
|
||||
}
|
||||
@Test void acpSettingsLoginSendPermissionsDeleteAndCloseFollowTheSelectedChat()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("ACP Game",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));known.remember(project);
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
var connection=new AtomicReference<p.studio.app.acp.CodexAcpConnection>();
|
||||
Path globalFile=temporary.resolve("ai-settings.json");
|
||||
var globals=new p.studio.core.project.preferences.JsonAgentSettingsStore(globalFile,mapper);
|
||||
var command=List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",System.getProperty("studio.test.classpath"),
|
||||
p.studio.app.acp.AcpFixture.class.getName(),"login-delayed-cancel");
|
||||
var legacy=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(project.rootPath().resolve(".studio/setup.json").toFile());
|
||||
legacy.putObject("acp").put("executable","/obsolete/npx").putArray("arguments");
|
||||
mapper.writeValue(project.rootPath().resolve(".studio/setup.json").toFile(),legacy);
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)){
|
||||
var initial=globals.load();
|
||||
fx(()->{h.window.setAgentSettings(globals,initial);h.window.setAgentConnections(root->{var c=new p.studio.app.acp.CodexAcpConnection(root,mapper);connection.set(c);return c;});
|
||||
h.window.openPreferences();return null;});var cancelled=settings();
|
||||
fx(()->{assertTrue(cancelled.getScene().lookup("#ai-connect").isDisabled());
|
||||
((TextField)cancelled.getScene().lookup("#ai-executable")).setText("do-not-save");return null;});
|
||||
fire(cancelled,"settings-cancel");assertEquals(initial,globals.load());
|
||||
fx(()->{h.window.openPreferences();return null;});var draft=settings();
|
||||
fx(()->{((TextField)draft.getScene().lookup("#ai-executable")).setText(command.getFirst());
|
||||
((TextArea)draft.getScene().lookup("#ai-arguments")).setText(String.join("\n",command.subList(1,command.size())));return null;});
|
||||
fire(draft,"settings-apply");await(()->fx(()->!draft.isShowing()));
|
||||
open(h,project);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
fx(()->{h.window.openProjectSettings(false);return null;});var projectSettings=settings();
|
||||
assertNull(fx(()->projectSettings.getScene().lookup("#ai-executable")),"ACP must not be configured per project");fire(projectSettings,"settings-cancel");
|
||||
fx(()->{h.window.openPreferences();return null;});var configuration=settings();
|
||||
await(()->fx(()->!configuration.getScene().lookup("#ai-login").isDisabled()));fire(configuration,"ai-login");
|
||||
await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.READY);
|
||||
assertEquals(command.getFirst(),globals.load().executable());
|
||||
fx(()->{((ScrollPane)((javafx.scene.layout.BorderPane)configuration.getScene().getRoot()).getCenter()).setVvalue(1);return null;});
|
||||
capture(configuration,"acp-connected-settings");fire(configuration,"settings-cancel");
|
||||
fire(h.stage,"ai-prompt-toggle");fire(h.stage,"ai-compact-new-chat");
|
||||
var selector=fx(()->(ComboBox<Object>)h.stage.getScene().lookup("#ai-chat-select"));var a=fx(selector::getValue);
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
fx(()->{prompt.setText("draft A · personagem");return null;});fire(h.stage,"ai-compact-new-chat");var b=fx(selector::getValue);
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
await(()->fx(()->"ai-tab".equals(tabs.getSelectionModel().getSelectedItem().getId())&&prompt.getText().isEmpty()));
|
||||
fx(()->{selector.setValue(a);return null;});assertEquals("draft A · personagem",fx(prompt::getText));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-conversation")).getText()));
|
||||
assertTrue(fx(()->((Label)h.stage.getScene().lookup("#ai-connection-status")).getText().contains("Chat 2")));
|
||||
fire(h.stage,"ai-cancel");await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertFalse(fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");
|
||||
await(()->fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
fx(()->{selector.setValue(b);return null;});assertEquals("",fx(prompt::getText));
|
||||
assertTrue(fx(()->((TextArea)h.stage.getScene().lookup("#ai-conversation")).getText().contains("Cancelled")));
|
||||
fx(()->{prompt.setText("reject");return null;});fire(h.stage,"ai-send");
|
||||
await(()->fx(()->((Label)h.stage.getScene().lookup("#ai-activity")).getText().contains("fixture rejection")));
|
||||
assertEquals("reject",fx(prompt::getText));
|
||||
fx(()->{prompt.setText("permission");return null;});fire(h.stage,"ai-send");
|
||||
await(()->fx(()->Window.getWindows().stream().anyMatch(w->w.isShowing()&&w.getScene().lookup("#ai-permission-dialog")!=null)));
|
||||
var permission=chatDialog("ai-permission-dialog");capture(permission,"acp-explicit-permission");
|
||||
fx(()->{var pane=(DialogPane)permission.getScene().lookup("#ai-permission-dialog");
|
||||
((Button)pane.lookupButton(ButtonType.CANCEL)).fire();return null;});
|
||||
await(()->fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled()));
|
||||
assertTrue(Files.readString(project.rootPath().resolve("permission.json")).contains("cancelled"));
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");await(()->fx(()->prompt.getText().isEmpty()));
|
||||
chatAction(h.stage,"ai-compact-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertEquals(2,fx(()->selector.getItems().size()),"Delete must wait for cancellation to finish");
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");await(()->fx(()->selector.getItems().size()==1));
|
||||
assertEquals(a,fx(selector::getValue));assertEquals("draft A · personagem",fx(prompt::getText));
|
||||
fx(()->{prompt.setText("hold");return null;});fire(h.stage,"ai-send");await(()->fx(()->prompt.getText().isEmpty()));
|
||||
capture(h.stage,"acp-live-conversation-fixture");
|
||||
fx(()->{h.window.requestCloseProject();return null;});await(()->Files.exists(project.rootPath().resolve("cancel.requested")));
|
||||
assertNotNull(fx(h.window::projectSession),"Project stays owned until the agent stops");
|
||||
Files.writeString(project.rootPath().resolve("release.cancel"),"continue");
|
||||
await(()->fx(()->h.window.projectSession()==null&&h.window.launcherStage().isShowing()));
|
||||
assertEquals(p.studio.api.ai.AgentConnection.State.CLOSED,connection.get().status().state());
|
||||
assertFalse(ProcessHandle.of(Long.parseLong(Files.readString(project.rootPath().resolve("parent.pid")))).map(ProcessHandle::isAlive).orElse(false));
|
||||
open(h,project);fire(h.stage,"ai-prompt-toggle");
|
||||
assertEquals(0,fx(()->((ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select")).getItems().size()));
|
||||
assertEquals(command.getFirst(),globals.load().executable());closeProject(h);
|
||||
var second=catalog.createProject(new ProjectCreationRequest("Second ACP Game",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
open(h,second);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
assertFalse(mapper.readTree(second.rootPath().resolve(".studio/setup.json").toFile()).has("acp"));
|
||||
assertEquals(command.getFirst(),globals.load().executable());
|
||||
}
|
||||
try(var restarted=harness(catalog,known,setups,windows,runtimes)){
|
||||
var reloaded=new p.studio.core.project.preferences.JsonAgentSettingsStore(globalFile,mapper);var initial=reloaded.load();
|
||||
fx(()->{restarted.window.setAgentSettings(reloaded,initial);restarted.window.setAgentConnections(root->{var c=new p.studio.app.acp.CodexAcpConnection(root,mapper);connection.set(c);return c;});return null;});
|
||||
open(restarted,project);await(()->connection.get().status().state()==p.studio.api.ai.AgentConnection.State.CONNECTED);
|
||||
assertEquals(command.getFirst(),reloaded.load().executable());
|
||||
}
|
||||
}
|
||||
@Test void projectChromeKeepsEqualStripsAndContextualFooterAcrossThemesAndScales()throws Exception{
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
@@ -94,7 +204,7 @@ class StudioProjectsDesktopTest {
|
||||
for(double width:new double[]{1200,680}){
|
||||
fx(()->{h.stage.setWidth(width);h.stage.setHeight(width==680?480:850);return null;});
|
||||
capture(h.stage,"chrome-"+theme+"-"+language+"-"+scale+"-"+width);
|
||||
fx(()->{var scene=h.stage.getScene();var header=(javafx.scene.layout.Region)scene.lookup("#studio-header");var footer=(Label)scene.lookup("#studio-footer");
|
||||
fx(()->{var scene=h.stage.getScene();var header=(javafx.scene.layout.Region)scene.lookup("#studio-header");var footer=(javafx.scene.layout.Region)scene.lookup("#studio-footer-bar");
|
||||
assertEquals(header.getHeight(),footer.getHeight(),.1);
|
||||
assertEquals(scene.getHeight(),footer.localToScene(0,footer.getHeight()).getY(),1);
|
||||
var play=scene.lookup("#play").localToScene(scene.lookup("#play").getBoundsInLocal());
|
||||
@@ -115,6 +225,7 @@ class StudioProjectsDesktopTest {
|
||||
assertTrue(workspace.getBackground()==null||workspace.getBackground().getFills().size()<=1,"Workspace must not retain the layered panel bevel");
|
||||
var menu=((MenuBar)scene.lookup("#studio-menus")).getMenus().getFirst();assertEquals("Prometeu Studio",menu.getText());assertNotNull(menu.getGraphic());
|
||||
var tabs=(TabPane)scene.lookup("#project-tabs");assertTrue(tabs.getStyleClass().contains("studio-tabs"));
|
||||
assertUniformTabs(tabs);
|
||||
assertTrue(tabs.lookupAll(".tab").stream().filter(n->n instanceof javafx.scene.layout.Region).allMatch(n->((javafx.scene.layout.Region)n).getShape()!=null));
|
||||
var split=(SplitPane)scene.lookup("#gameplay-split");assertSame(split,tabs.getTabs().getFirst().getContent());
|
||||
assertEquals(javafx.geometry.Orientation.VERTICAL,split.getOrientation());
|
||||
@@ -135,6 +246,7 @@ class StudioProjectsDesktopTest {
|
||||
capture(h.stage,"empty-tab");
|
||||
fx(()->{assertFalse(h.stage.getScene().lookup("#tab-content-outline").isVisible(),"Empty tab must not keep the previous outline");
|
||||
((TabPane)h.stage.getScene().lookup("#project-tabs")).getTabs().remove(unknown);
|
||||
((TabPane)h.stage.getScene().lookup("#project-tabs")).getSelectionModel().selectFirst();
|
||||
assertTrue(((Label)h.stage.getScene().lookup("#studio-footer")).getText().startsWith("Gameplay"));return null;});
|
||||
capture(h.stage,"restored-gameplay-tab");
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#tab-content-outline").isVisible()));
|
||||
@@ -148,6 +260,276 @@ class StudioProjectsDesktopTest {
|
||||
fx(()->{execution.transitionToResuming();execution.transitionToRunning();execution.transitionToStopping();execution.transitionToStopped();return null;});
|
||||
}
|
||||
}
|
||||
@Test void aiVisualSharesOnePromptAndDiscardsItOnProjectClose()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("AI presentation",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
var ai=fx(()->tabs.getTabs().stream().filter(t->"ai-tab".equals(t.getId())).findFirst().orElseThrow());
|
||||
var surface=fx(()->h.stage.getScene().lookup("#game-surface"));
|
||||
foreground(h.stage);
|
||||
fx(()->{surface.requestFocus();return null;});
|
||||
var access=fx(()->(ToggleButton)h.stage.getScene().lookup("#ai-prompt-toggle"));
|
||||
assertFalse(fx(access::isSelected));
|
||||
var inactiveBackground=fx(()->access.getBackground());
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
assertNotNull(prompt);
|
||||
assertTrue(fx(prompt::isDisabled));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
capture(h.stage,"ai-drawer-initial-focus");
|
||||
assertTrue(fx(access::isSelected));
|
||||
assertNotEquals(inactiveBackground,fx(access::getBackground),"An open prompt needs a distinct footer control background");
|
||||
assertNull(fx(()->h.stage.getScene().lookup("#ai-prompt-collapse")));
|
||||
assertSame(prompt,fx(()->h.stage.getScene().getFocusOwner()),"Opening the drawer must move keyboard focus to the prompt");
|
||||
await(()->fx(prompt::isFocused));assertFalse(fx(surface::isFocused));
|
||||
fx(()->{prompt.setText("Draft across views · personagem");return null;});
|
||||
capture(h.stage,"ai-drawer-dark-en");
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var host=(SplitPane)scene.lookup("#ai-workspace-host");
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var upper=host.getItems().getFirst();
|
||||
assertTrue(upper.localToScene(upper.getBoundsInLocal()).getMaxY()<=drawer.localToScene(0,0).getY());
|
||||
var footer=scene.lookup("#studio-footer-bar");
|
||||
assertTrue(drawer.localToScene(drawer.getBoundsInLocal()).getMaxY()<=footer.localToScene(0,0).getY());
|
||||
host.setDividerPositions(.45);return null;
|
||||
});
|
||||
capture(h.stage,"ai-drawer-resized");
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
await(()->fx(surface::isFocused));
|
||||
assertFalse(fx(access::isSelected));
|
||||
assertNull(fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
assertEquals("Draft across views · personagem",fx(prompt::getText));
|
||||
|
||||
fx(()->{tabs.getSelectionModel().select(ai);return null;});
|
||||
capture(h.stage,"ai-workspace-dark-en");
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
assertSame(prompt,scene.lookup("#ai-prompt"));
|
||||
assertEquals(1,scene.getRoot().lookupAll("#ai-prompt").size());
|
||||
assertNull(scene.lookup("#ai-prompt-drawer"));
|
||||
assertTrue(((SplitPane)scene.lookup("#ai-workspace-host")).getItems().size()==1);
|
||||
for(String id:List.of("ai-load-chat","ai-attach","ai-send"))
|
||||
assertTrue(scene.lookup("#"+id).isDisabled(),id);
|
||||
assertEquals(1,((ListView<?>)scene.lookup("#ai-chats")).getItems().size());
|
||||
return null;
|
||||
});
|
||||
fire(h.stage,"ai-prompt-toggle");await(()->fx(prompt::isFocused));
|
||||
assertTrue(fx(access::isSelected),"The inline composer remains visible when its footer icon is clicked");
|
||||
assertEquals("Draft across views · personagem",fx(prompt::getText));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
|
||||
// Theme/language/scale changes preserve the one draft and keep constrained layouts scrollable.
|
||||
for(Theme theme:Theme.values())for(StudioLanguage language:StudioLanguage.values()) {
|
||||
fx(()->{h.window.openPreferences();return null;});var preferences=settings();
|
||||
fx(()->{
|
||||
((ComboBox<Theme>)preferences.getScene().lookup("#theme-select")).setValue(theme);
|
||||
((ComboBox<StudioLanguage>)preferences.getScene().lookup("#language-select")).setValue(language);
|
||||
((ComboBox<Double>)preferences.getScene().lookup("#scale-select")).setValue(2.);
|
||||
return null;
|
||||
});
|
||||
fire(preferences,"settings-apply");await(()->fx(()->!preferences.isShowing()));
|
||||
fx(()->{h.stage.setWidth(680);h.stage.setHeight(480);return null;});
|
||||
capture(h.stage,"ai-drawer-min-200-"+theme+"-"+language);
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var host=(SplitPane)scene.lookup("#ai-workspace-host");
|
||||
assertTrue(drawer.getHeight()>=90);
|
||||
assertTrue(((javafx.scene.layout.Region)host.getItems().getFirst()).getHeight()>=80);
|
||||
assertEquals(1,scene.getRoot().lookupAll("#ai-prompt").size());
|
||||
assertEquals("Draft across views · personagem",prompt.getText());
|
||||
assertEquals(language==StudioLanguage.PORTUGUESE?"IA":"AI",ai.getText());
|
||||
assertUniformTabs(tabs);
|
||||
((ScrollPane)scene.lookup("#project-workspace-scroll")).setVvalue(1);
|
||||
drawer.setVvalue(1);
|
||||
return null;
|
||||
});
|
||||
capture(h.stage,"ai-drawer-min-200-bottom-"+theme+"-"+language);
|
||||
fx(()->{
|
||||
var scene=h.stage.getScene();
|
||||
var drawer=(ScrollPane)scene.lookup("#ai-prompt-drawer");
|
||||
var visible=drawer.lookup(".viewport");
|
||||
var viewport=visible.localToScene(visible.getBoundsInLocal());
|
||||
var send=scene.lookup("#ai-send");
|
||||
var command=send.localToScene(send.getBoundsInLocal());
|
||||
assertTrue(command.getMaxY()<=viewport.getMaxY()+1,"Scrolling must reveal the bottom prompt controls");
|
||||
tabs.getSelectionModel().select(ai);return null;
|
||||
});
|
||||
capture(h.stage,"ai-workspace-min-200-"+theme+"-"+language);
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
}
|
||||
fx(()->{h.stage.setWidth(1200);h.stage.setHeight(850);h.window.openPreferences();return null;});
|
||||
var finalPreferences=settings();
|
||||
fx(()->{
|
||||
((ComboBox<StudioLanguage>)finalPreferences.getScene().lookup("#language-select")).setValue(StudioLanguage.PORTUGUESE);
|
||||
((ComboBox<Double>)finalPreferences.getScene().lookup("#scale-select")).setValue(1.);
|
||||
return null;
|
||||
});
|
||||
fire(finalPreferences,"settings-apply");await(()->fx(()->!finalPreferences.isShowing()));
|
||||
fx(()->{tabs.getSelectionModel().select(ai);return null;});
|
||||
capture(h.stage,"ai-workspace-light-pt");
|
||||
fx(()->{h.window.openPreferences();return null;});var configuration=settings();
|
||||
capture(configuration,"ai-settings-chatgpt-only");
|
||||
fx(()->{
|
||||
var scene=configuration.getScene();
|
||||
assertEquals("Codex",((Label)scene.lookup("#ai-agent")).getText());
|
||||
assertEquals("Login ChatGPT",((Label)scene.lookup("#ai-authentication")).getText());
|
||||
assertTrue(scene.lookup("#ai-login").isDisabled());
|
||||
assertNull(scene.lookup("#ai-api-key"));return null;
|
||||
});
|
||||
fire(configuration,"settings-cancel");
|
||||
closeProject(h);
|
||||
assertEquals("",fx(prompt::getText),"Closing a project must discard its transient prompt");
|
||||
open(h,project);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
assertNotSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-prompt")).getText()));
|
||||
}
|
||||
}
|
||||
@Test void startingPlayCollapsesThePromptWithoutDiscardingTheText()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("Play navigation",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return "/fixture/runtime";}public void save(String path){}};
|
||||
var starts=new AtomicInteger();
|
||||
ExecutionControllerFactory executions=(ref,setup,session)->new ExecutionController(){
|
||||
@SuppressWarnings("unchecked") public p.studio.api.operation.OperationHandle<ExecutionSnapshot> play(){
|
||||
starts.incrementAndGet();
|
||||
return (p.studio.api.operation.OperationHandle<ExecutionSnapshot>)Proxy.newProxyInstance(getClass().getClassLoader(),
|
||||
new Class[]{p.studio.api.operation.OperationHandle.class},(proxy,method,args)->{
|
||||
if(method.getName().equals("completion"))return CompletableFuture.completedFuture(session.snapshot());
|
||||
throw new AssertionError(method.getName());
|
||||
});
|
||||
}
|
||||
public void stop(){} public void close(){}
|
||||
};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes,executions)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));StudioPlayDesktopTest.focus(h.stage);
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
fx(()->{prompt.setText("Keep this draft while playing");tabs.getSelectionModel().selectLast();return null;});
|
||||
// Exercise starting from the AI tab, and then from Gameplay with an open drawer.
|
||||
for(int expected=1;expected<=2;expected++) {
|
||||
fire(h.stage,"play");int count=expected;await(()->starts.get()==count);
|
||||
await(()->fx(()->"game-surface".equals(h.stage.getScene().getFocusOwner().getId())));
|
||||
fx(()->{
|
||||
assertEquals("gameplay-tab",tabs.getSelectionModel().getSelectedItem().getId());
|
||||
assertNull(h.stage.getScene().lookup("#ai-prompt-drawer"));
|
||||
assertFalse(((ToggleButton)h.stage.getScene().lookup("#ai-prompt-toggle")).isSelected());
|
||||
assertEquals("Keep this draft while playing",prompt.getText());return null;
|
||||
});
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
assertSame(prompt,fx(()->h.stage.getScene().lookup("#ai-prompt")));
|
||||
}
|
||||
capture(h.stage,"ai-footer-active-uniform-tabs");
|
||||
}
|
||||
}
|
||||
private static void assertUniformTabs(TabPane tabs) {
|
||||
var headers=tabs.lookupAll(".tab").stream().filter(javafx.scene.layout.Region.class::isInstance)
|
||||
.map(javafx.scene.layout.Region.class::cast).toList();
|
||||
assertTrue(headers.size()>=2);
|
||||
double width=headers.getFirst().getWidth();
|
||||
for(var header:headers)assertEquals(width,header.getWidth(),1,"All tab headers must have equal width");
|
||||
}
|
||||
@Test @SuppressWarnings("unchecked") void localChatsSynchronizeDraftsDialogsAndProjectLifetime()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
var known=new KnownProjectsService(temporary.resolve("known.txt"),catalog);
|
||||
var project=catalog.createProject(new ProjectCreationRequest("Local chats",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var other=catalog.createProject(new ProjectCreationRequest("Another project",catalog.projectsRoot(),"pbs",1,ProjectTarget.Game,"src",4,null));
|
||||
var windows=new p.studio.core.project.preferences.JsonWindowStateStore(temporary.resolve("windows.json"),mapper);
|
||||
RuntimeSettingsStore runtimes=new RuntimeSettingsStore(){public String load(){return null;}public void save(String path){}};
|
||||
try(var h=harness(catalog,known,setups,windows,runtimes)) {
|
||||
open(h,project);await(()->fx(h.stage::isShowing));StudioPlayDesktopTest.focus(h.stage);
|
||||
var tabs=fx(()->(TabPane)h.stage.getScene().lookup("#project-tabs"));
|
||||
fire(h.stage,"ai-prompt-toggle");
|
||||
var prompt=fx(()->(TextArea)h.stage.getScene().lookup("#ai-prompt"));
|
||||
var selector=fx(()->(ComboBox<Object>)h.stage.getScene().lookup("#ai-chat-select"));
|
||||
assertTrue(fx(prompt::isDisabled));assertTrue(fx(selector::isDisabled));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
var a=fx(selector::getValue);
|
||||
assertNotNull(a);assertEquals("gameplay-tab",fx(()->tabs.getSelectionModel().getSelectedItem().getId()));
|
||||
String draftA="A\ntexto com espaços ",draftB="B · personagem";
|
||||
fx(()->{prompt.setText(draftA);tabs.getSelectionModel().selectLast();return null;});
|
||||
var list=fx(()->(ListView<Object>)h.stage.getScene().lookup("#ai-chats"));
|
||||
fire(h.stage,"ai-new-chat");var b=fx(selector::getValue);assertNotEquals(a,b);
|
||||
fx(()->{assertEquals("",prompt.getText());prompt.setText(draftB);list.getSelectionModel().select(a);return null;});
|
||||
assertEquals(draftA,fx(prompt::getText));assertEquals(a,fx(selector::getValue));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();selector.setValue(b);return null;});
|
||||
assertEquals(draftB,fx(prompt::getText));assertEquals(b,fx(()->list.getSelectionModel().getSelectedItem()));
|
||||
fx(()->{list.getSelectionModel().clearSelection();selector.setValue(null);return null;});
|
||||
await(()->fx(()->b.equals(selector.getValue())&&b.equals(list.getSelectionModel().getSelectedItem())));
|
||||
assertEquals(draftB,fx(prompt::getText));
|
||||
|
||||
chatAction(h.stage,"ai-compact-rename-chat");Stage rename=chatDialog("ai-rename-dialog");
|
||||
fx(()->{((TextField)rename.getScene().lookup("#ai-rename-title")).setText(" \n ");return null;});
|
||||
fire(rename,"ai-dialog-confirm");
|
||||
assertTrue(fx(rename::isShowing));assertTrue(fx(()->rename.getScene().lookup("#ai-rename-error").isVisible()));
|
||||
assertEquals(b,fx(selector::getValue));assertEquals(draftB,fx(prompt::getText));
|
||||
fx(()->{((TextField)rename.getScene().lookup("#ai-rename-title")).setText(" Sprite work ");return null;});
|
||||
fire(rename,"ai-dialog-confirm");await(()->fx(()->!rename.isShowing()));
|
||||
var renamedB=fx(selector::getValue);
|
||||
fx(()->{assertEquals("Sprite work",((Labeled)selector.getButtonCell()).getText());
|
||||
assertEquals(renamedB,list.getSelectionModel().getSelectedItem());
|
||||
assertTrue(((Label)h.stage.getScene().lookup("#ai-chat-title")).getText().contains("Sprite work"));
|
||||
assertEquals(draftB,prompt.getText());tabs.getSelectionModel().selectLast();return null;});
|
||||
fire(h.stage,"ai-rename-chat");Stage cancelledRename=chatDialog("ai-rename-dialog");
|
||||
fx(()->{((TextField)cancelledRename.getScene().lookup("#ai-rename-title")).setText("Do not apply");return null;});
|
||||
fire(cancelledRename,"ai-dialog-cancel");assertEquals(renamedB,fx(selector::getValue));
|
||||
fx(()->{tabs.getSelectionModel().selectFirst();return null;});
|
||||
chatAction(h.stage,"ai-compact-delete-chat");Stage cancelledDelete=chatDialog("ai-delete-dialog");
|
||||
assertTrue(fx(()->((DialogPane)cancelledDelete.getScene().lookup("#ai-delete-dialog")).getContentText().contains("Sprite work")));
|
||||
fire(cancelledDelete,"ai-dialog-cancel");assertEquals(2,fx(()->list.getItems().size()));assertEquals(draftB,fx(prompt::getText));
|
||||
capture(h.stage,"ai-local-chats-footer");
|
||||
|
||||
fx(()->{tabs.getSelectionModel().selectLast();return null;});
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertEquals(a,fx(selector::getValue));assertEquals(draftA,fx(prompt::getText));
|
||||
fire(h.stage,"ai-new-chat");var c=fx(selector::getValue);
|
||||
fx(()->{prompt.setText("C");list.getSelectionModel().select(a);return null;});
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertEquals(c,fx(selector::getValue));assertEquals("C",fx(prompt::getText));
|
||||
fire(h.stage,"ai-delete-chat");fire(chatDialog("ai-delete-dialog"),"ai-dialog-confirm");
|
||||
assertTrue(fx(()->list.getItems().isEmpty()));assertNull(fx(selector::getValue));assertTrue(fx(prompt::isDisabled));
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#ai-rename-chat").isDisabled()));
|
||||
assertTrue(fx(()->h.stage.getScene().lookup("#ai-delete-chat").isDisabled()));
|
||||
fire(h.stage,"ai-new-chat");
|
||||
fx(()->{prompt.setText("Discard on close");h.window.openPreferences();return null;});Stage preferences=settings();
|
||||
fx(()->{((ComboBox<Theme>)preferences.getScene().lookup("#theme-select")).setValue(Theme.LIGHT);
|
||||
((ComboBox<StudioLanguage>)preferences.getScene().lookup("#language-select")).setValue(StudioLanguage.PORTUGUESE);return null;});
|
||||
fire(preferences,"settings-apply");await(()->fx(()->!preferences.isShowing()));
|
||||
assertEquals("Discard on close",fx(prompt::getText));
|
||||
fire(h.stage,"ai-rename-chat");Stage portugueseRename=chatDialog("ai-rename-dialog");
|
||||
assertEquals("Renomear chat",fx(portugueseRename::getTitle));
|
||||
fx(()->{((TextField)portugueseRename.getScene().lookup("#ai-rename-title")).setText("Trabalho local");return null;});
|
||||
fire(portugueseRename,"ai-dialog-confirm");capture(h.stage,"ai-local-chats-light-pt");
|
||||
fire(h.stage,"ai-rename-chat");Stage pending=chatDialog("ai-rename-dialog");
|
||||
// Closing with a dialog open must discard it without applying its edited title.
|
||||
closeProject(h);assertFalse(fx(pending::isShowing));
|
||||
assertEquals("",fx(prompt::getText));assertTrue(fx(()->list.getItems().isEmpty()));
|
||||
open(h,project);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
var reopenedSelector=fx(()->(ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select"));
|
||||
assertTrue(fx(()->reopenedSelector.getItems().isEmpty()));
|
||||
fire(h.stage,"ai-compact-new-chat");
|
||||
fx(()->{((TextArea)h.stage.getScene().lookup("#ai-prompt")).setText("First project only");return null;});
|
||||
closeProject(h);open(h,other);await(()->fx(h.stage::isShowing));fire(h.stage,"ai-prompt-toggle");
|
||||
assertTrue(fx(()->((ComboBox<?>)h.stage.getScene().lookup("#ai-chat-select")).getItems().isEmpty()));
|
||||
assertEquals("",fx(()->((TextArea)h.stage.getScene().lookup("#ai-prompt")).getText()));
|
||||
}
|
||||
}
|
||||
@Test void geometryAndSettingsSurviveCoordinatorRestartAndKeepScopesSeparate()throws Exception {
|
||||
var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper);
|
||||
var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
/** A real stdio peer, deliberately independent from the production client. No model or credentials. */
|
||||
public final class AcpFixture {
|
||||
private static final ObjectMapper JSON=new ObjectMapper();
|
||||
private static String pendingPrompt,session;
|
||||
private static int sessions;
|
||||
private static String mode;
|
||||
public static void main(String[] args)throws Exception {
|
||||
mode=args.length==0?"normal":args[0];
|
||||
if(mode.equals("child")){Thread.sleep(600_000);return;}
|
||||
Files.writeString(Path.of("parent.pid"),""+ProcessHandle.current().pid());
|
||||
if(mode.equals("tree")){
|
||||
var child=new ProcessBuilder(javaCommand("child")).redirectOutput(ProcessBuilder.Redirect.DISCARD).redirectError(ProcessBuilder.Redirect.DISCARD).start();
|
||||
Files.writeString(Path.of("child.pid"),""+child.pid());
|
||||
}
|
||||
try(var input=new BufferedReader(new InputStreamReader(System.in))){
|
||||
for(String line;(line=input.readLine())!=null;){
|
||||
JsonNode message=JSON.readTree(line);String method=message.path("method").asText();var p=message.path("params");
|
||||
String id=message.path("id").asText();
|
||||
switch(method){
|
||||
case "initialize" -> {
|
||||
var result=JSON.createObjectNode().put("protocolVersion",mode.equals("incompatible")?2:1);
|
||||
result.putArray("authMethods").addObject().put("id",mode.equals("api-only")?"api-key":"chat-gpt").put("name","ChatGPT");
|
||||
reply(id,result);
|
||||
}
|
||||
case "auth/status" -> {
|
||||
var result=JSON.createObjectNode().put("state",mode.startsWith("login")?"unauthenticated":"authenticated");
|
||||
result.putArray("accounts").addObject().put("label","ChatGPT Pro").put("active",true);reply(id,result);
|
||||
}
|
||||
case "authenticate" -> {
|
||||
if(!p.path("methodId").asText().equals("chat-gpt"))throw new AssertionError("Only ChatGPT login");
|
||||
mode=mode.equals("login-delayed-cancel")?"delayed-cancel":"normal";reply(id,JSON.createObjectNode());
|
||||
}
|
||||
case "session/new" -> {
|
||||
if(!Path.of(p.path("cwd").asText()).toRealPath().equals(Path.of("").toRealPath()))throw new AssertionError("cwd");
|
||||
var result=JSON.createObjectNode().put("sessionId","s"+(++sessions));
|
||||
result.putObject("modes").putArray("availableModes").addObject().put("id","workspace-write");reply(id,result);
|
||||
}
|
||||
case "session/set_mode" -> {
|
||||
if(!p.path("modeId").asText().equals("workspace-write"))throw new AssertionError("Agent must use workspace-write/on-request");
|
||||
Files.writeString(Path.of(p.path("sessionId").asText()+".mode"),p.path("modeId").asText());reply(id,JSON.createObjectNode());
|
||||
}
|
||||
case "session/prompt" -> {
|
||||
session=p.path("sessionId").asText();String text=p.path("prompt").get(0).path("text").asText();
|
||||
if(!Files.exists(Path.of(session+".mode")))throw new AssertionError("Mode must be selected before prompt");
|
||||
if(text.equals("reject")){error(id,"fixture rejection");break;}
|
||||
if(text.equals("crash")){System.exit(3);}
|
||||
if(text.equals("malformed")){System.out.println("not json");System.out.flush();break;}
|
||||
if(text.equals("permission")){
|
||||
pendingPrompt=id;
|
||||
var request=JSON.createObjectNode().put("jsonrpc","2.0").put("method","session/request_permission").put("id","permit");
|
||||
var params=request.putObject("params").put("sessionId",session);params.putObject("toolCall").put("title","Run fixture action");
|
||||
params.putArray("options").addObject().put("optionId","yes").put("name","Allow once").put("kind","allow_once");send(request);break;
|
||||
}
|
||||
chunk(session,"agent_message_chunk","first ");
|
||||
if(text.equals("hold")){pendingPrompt=id;break;}
|
||||
chunk(session,"agent_thought_chunk","PRIVATE_THOUGHT_MUST_NOT_ESCAPE");
|
||||
chunk(session,"agent_message_chunk","second");reply(id,JSON.createObjectNode().put("stopReason","end_turn"));
|
||||
}
|
||||
case "session/cancel" -> {
|
||||
if(mode.equals("ignore-cancel"))break;
|
||||
if(mode.equals("delayed-cancel")){
|
||||
Files.writeString(Path.of("cancel.requested"),"waiting");
|
||||
long end=System.nanoTime()+java.util.concurrent.TimeUnit.SECONDS.toNanos(8);
|
||||
while(!Files.exists(Path.of("release.cancel"))&&System.nanoTime()<end)Thread.sleep(20);
|
||||
Files.deleteIfExists(Path.of("release.cancel"));
|
||||
Files.deleteIfExists(Path.of("cancel.requested"));
|
||||
}
|
||||
if(pendingPrompt!=null){reply(pendingPrompt,JSON.createObjectNode().put("stopReason","cancelled"));pendingPrompt=null;}
|
||||
}
|
||||
case "" -> {
|
||||
if(id.equals("permit")){
|
||||
Files.writeString(Path.of("permission.json"),message.path("result").toString());
|
||||
if(pendingPrompt!=null){chunk(session,"agent_message_chunk","permission answered");
|
||||
reply(pendingPrompt,JSON.createObjectNode().put("stopReason","end_turn"));pendingPrompt=null;}
|
||||
}
|
||||
}
|
||||
default -> error(id,"Unknown fixture method");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
static List<String> javaCommand(String mode){
|
||||
return List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp",
|
||||
System.getProperty("studio.test.classpath",System.getProperty("java.class.path")),AcpFixture.class.getName(),mode);
|
||||
}
|
||||
private static void chunk(String session,String kind,String value)throws Exception {
|
||||
var frame=JSON.createObjectNode().put("jsonrpc","2.0").put("method","session/update");
|
||||
frame.putObject("params").put("sessionId",session).putObject("update").put("sessionUpdate",kind)
|
||||
.putObject("content").put("type","text").put("text",value);send(frame);
|
||||
}
|
||||
private static void reply(String id,JsonNode result)throws Exception {send(JSON.createObjectNode().put("jsonrpc","2.0").put("id",id).set("result",result));}
|
||||
private static void error(String id,String message)throws Exception {
|
||||
var frame=JSON.createObjectNode().put("jsonrpc","2.0").put("id",id);frame.putObject("error").put("code",-32603).put("message",message);send(frame);
|
||||
}
|
||||
private static void send(JsonNode value)throws Exception {System.out.println(JSON.writeValueAsString(value));System.out.flush();}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CodexAcpConnectionTest {
|
||||
@TempDir Path root;
|
||||
private CodexAcpConnection connection;
|
||||
private static <T>T await(CompletionStage<T> operation)throws Exception{return operation.toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
private AcpSettings fixture(String mode){var command=AcpFixture.javaCommand(mode);return new AcpSettings(command.getFirst(),command.subList(1,command.size()));}
|
||||
private CodexAcpConnection open(String mode)throws Exception {
|
||||
connection=new CodexAcpConnection(root,new ObjectMapper());await(connection.connect(fixture(mode)));return connection;
|
||||
}
|
||||
@AfterEach void close()throws Exception{if(connection!=null)await(connection.closeAsync());}
|
||||
|
||||
@Test void loginStreamingIndependentSessionsAndCancellationUseRealStdio()throws Exception {
|
||||
var c=open("login");assertEquals(AgentConnection.State.CONNECTED,c.status().state());
|
||||
await(c.login());assertEquals(AgentConnection.State.READY,c.status().state());
|
||||
String first=await(c.newSession()),second=await(c.newSession());assertNotEquals(first,second);
|
||||
var events=new CopyOnWriteArrayList<AgentConnection.Event>();c.events(events::add);
|
||||
var turn=c.prompt(second,"stream");await(turn.accepted());assertEquals("end_turn",await(turn.completion()));
|
||||
assertEquals("first second",events.stream().filter(e->e.kind()==AgentConnection.Kind.TEXT).map(AgentConnection.Event::text).reduce("",String::concat));
|
||||
assertTrue(events.stream().allMatch(e->e.sessionId().equals(second)));
|
||||
assertTrue(events.stream().noneMatch(e->e.text().contains("PRIVATE_THOUGHT")));
|
||||
var held=c.prompt(first,"hold");await(held.accepted());
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(second,"overlap").completion()));
|
||||
await(c.cancel(first));assertEquals("cancelled",await(held.completion()));
|
||||
}
|
||||
@Test void permissionIsNeverGrantedWithoutAnExplicitChoice()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());
|
||||
var choice=new CompletableFuture<String>();c.permissions(p->{assertEquals(id,p.sessionId());return choice;});
|
||||
var turn=c.prompt(id,"permission");assertFalse(turn.completion().toCompletableFuture().isDone());
|
||||
choice.complete("invalid-option");await(turn.completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("cancelled"));
|
||||
c.permissions(p->CompletableFuture.completedFuture("yes"));await(c.prompt(id,"permission").completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("selected"));
|
||||
var requested=new CountDownLatch(1);c.permissions(p->{requested.countDown();return new CompletableFuture<>();});
|
||||
var pending=c.prompt(id,"permission");assertTrue(requested.await(5,TimeUnit.SECONDS));await(c.cancel(id));await(pending.completion());
|
||||
assertTrue(Files.readString(root.resolve("permission.json")).contains("cancelled"));
|
||||
}
|
||||
@Test void rejectionDoesNotAcknowledgeDeliveryAndFailureCanReconnect()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());var rejected=c.prompt(id,"reject");
|
||||
assertThrows(ExecutionException.class,()->await(rejected.accepted()));assertThrows(ExecutionException.class,()->await(rejected.completion()));
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"crash").completion()));
|
||||
assertEquals(AgentConnection.State.FAILED,c.status().state());await(c.connect(fixture("normal")));
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"old session").completion()));
|
||||
await(c.prompt(await(c.newSession()),"new session").completion());
|
||||
}
|
||||
@Test void incompatibleAndApiOnlyAgentsFailAndCloseOwnedProcesses()throws Exception {
|
||||
connection=new CodexAcpConnection(root,new ObjectMapper());
|
||||
assertThrows(ExecutionException.class,()->await(connection.connect(fixture("incompatible"))));
|
||||
assertEquals(AgentConnection.State.FAILED,connection.status().state());
|
||||
assertThrows(ExecutionException.class,()->await(connection.connect(fixture("api-only"))));
|
||||
}
|
||||
@Test void closeWaitsForTurnAndEntireOwnedProcessTree()throws Exception {
|
||||
var c=open("tree");String id=await(c.newSession());var held=c.prompt(id,"hold");await(held.accepted());
|
||||
long parent=Long.parseLong(Files.readString(root.resolve("parent.pid"))),child=Long.parseLong(Files.readString(root.resolve("child.pid")));
|
||||
await(c.closeAsync());assertEquals("cancelled",await(held.completion()));
|
||||
assertFalse(ProcessHandle.of(parent).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertFalse(ProcessHandle.of(child).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
}
|
||||
@Test void unresponsiveCancellationTerminatesTheProcessBeforeResolving()throws Exception {
|
||||
var c=open("ignore-cancel");String id=await(c.newSession());var held=c.prompt(id,"hold");await(held.accepted());
|
||||
long pid=Long.parseLong(Files.readString(root.resolve("parent.pid")));long start=System.nanoTime();
|
||||
await(c.cancel(id));assertTrue(System.nanoTime()-start<TimeUnit.SECONDS.toNanos(20));
|
||||
assertFalse(ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false));
|
||||
assertTrue(held.completion().toCompletableFuture().isCompletedExceptionally());
|
||||
assertEquals(AgentConnection.State.FAILED,c.status().state());
|
||||
}
|
||||
@Test void malformedFramesFailTheTurnAndCleanupAllowsANewConnection()throws Exception {
|
||||
var c=open("normal");String id=await(c.newSession());
|
||||
assertThrows(ExecutionException.class,()->await(c.prompt(id,"malformed").completion()));
|
||||
await(c.connect(fixture("normal")));await(c.prompt(await(c.newSession()),"stream").completion());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package p.studio.app.acp;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Explicit live gate. Uses the user's existing ChatGPT session; never runs in ordinary tests. */
|
||||
class CodexAcpSmokeTest {
|
||||
@TempDir Path project;
|
||||
private AcpSettings settings(){
|
||||
String executable=System.getProperty("studio.test.codexAcp","");
|
||||
return executable.isBlank()?new p.studio.core.project.preferences.JsonAgentSettingsStore(
|
||||
Path.of(System.getProperty("user.home"),".prometeu-studio","ai-settings.json"),new ObjectMapper()).load()
|
||||
:new AcpSettings(executable,List.of());
|
||||
}
|
||||
@Test void existingChatGptLoginCanAnswerThroughThePinnedAdapter()throws Exception {
|
||||
var c=new CodexAcpConnection(project,new ObjectMapper());
|
||||
var output=new CopyOnWriteArrayList<String>();c.events(e->{if(e.kind()==AgentConnection.Kind.TEXT)output.add(e.text());});
|
||||
try{
|
||||
c.connect(settings()).toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
|
||||
while(c.status().state()!=AgentConnection.State.READY&&System.nanoTime()<end)Thread.sleep(50);
|
||||
assertEquals(AgentConnection.State.READY,c.status().state(),"Existing ChatGPT login must be recognized; smoke never opens browser login");
|
||||
String session=c.newSession().toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
assertEquals("end_turn",c.prompt(session,"Responda apenas OK. Não use ferramentas, não leia nem altere arquivos, não execute comandos.")
|
||||
.completion().toCompletableFuture().get(120,TimeUnit.SECONDS));
|
||||
assertFalse(String.join("",output).isBlank());
|
||||
try(var files=Files.list(project)){assertEquals(0,files.count(),"Minimal conversation must not alter project files");}
|
||||
}finally{c.closeAsync().toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
System.out.println("Live Codex ACP: initialized v1, existing ChatGPT login recognized, workspace-write session answered, project unchanged, owned process tree stopped.");
|
||||
}
|
||||
@Test void sameGlobalInstallationConnectsFromTheSelectedExistingProject()throws Exception {
|
||||
String root=System.getProperty("studio.test.codexProject","");
|
||||
org.junit.jupiter.api.Assumptions.assumeFalse(root.isBlank(),"Optional existing-project connection qualification");
|
||||
assertTrue(Files.isDirectory(Path.of(root)));
|
||||
var c=new CodexAcpConnection(Path.of(root),new ObjectMapper());
|
||||
try{
|
||||
c.connect(settings()).toCompletableFuture().get(40,TimeUnit.SECONDS);
|
||||
long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
|
||||
while(c.status().state()!=AgentConnection.State.READY&&System.nanoTime()<end)Thread.sleep(50);
|
||||
assertEquals(AgentConnection.State.READY,c.status().state());
|
||||
assertFalse(c.newSession().toCompletableFuture().get(40,TimeUnit.SECONDS).isBlank());
|
||||
// No prompt or tools are sent to the real project.
|
||||
}finally{c.closeAsync().toCompletableFuture().get(25,TimeUnit.SECONDS);}
|
||||
assertEquals(AgentConnection.State.CLOSED,c.status().state());
|
||||
System.out.println("Live existing-project ACP: same global configuration, existing ChatGPT login, project cwd session created, no prompt/tools, owned processes stopped.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package p.studio.api.ai;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Non-secret machine-local Studio launch settings. Arguments are a vector, never shell text. */
|
||||
public record AcpSettings(String executable, List<String> arguments) {
|
||||
public AcpSettings {
|
||||
executable = executable == null || executable.isBlank() ? defaultExecutable() : executable.strip();
|
||||
arguments = arguments == null ? List.of() : List.copyOf(arguments);
|
||||
if (executable.indexOf('\0') >= 0 || arguments.stream().anyMatch(a -> a.indexOf('\0') >= 0))
|
||||
throw new IllegalArgumentException("Invalid ACP launch settings");
|
||||
}
|
||||
private static String defaultExecutable() {
|
||||
return java.nio.file.Path.of(System.getProperty("user.home"),".prometeu-studio","bin","codex-acp").toString();
|
||||
}
|
||||
public static AcpSettings defaults() { return new AcpSettings(defaultExecutable(),List.of()); }
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package p.studio.api.ai;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
|
||||
/** Asynchronous project-owned agent port. Callbacks may arrive on worker threads. */
|
||||
public interface AgentConnection {
|
||||
enum State { DISCONNECTED, CONNECTING, CONNECTED, AUTHENTICATING, READY, FAILED, CLOSING, CLOSED }
|
||||
enum Kind { TEXT, ACTIVITY }
|
||||
record Status(State state, String detail) { }
|
||||
record Event(String sessionId, Kind kind, String text) { }
|
||||
record Choice(String id, String name, String kind) { }
|
||||
record Permission(String sessionId, String title, String details, List<Choice> choices) {
|
||||
public Permission(String sessionId,String title,List<Choice> choices){this(sessionId,title,"",choices);}
|
||||
}
|
||||
record Turn(CompletionStage<Void> accepted, CompletionStage<String> completion) { }
|
||||
|
||||
boolean available();
|
||||
Status status();
|
||||
AutoCloseable observe(Consumer<Status> listener);
|
||||
void events(Consumer<Event> listener);
|
||||
void permissions(Function<Permission, CompletionStage<String>> handler);
|
||||
CompletionStage<Void> connect(AcpSettings settings);
|
||||
CompletionStage<Void> login();
|
||||
CompletionStage<String> newSession();
|
||||
Turn prompt(String sessionId, String text);
|
||||
CompletionStage<Void> cancel(String sessionId);
|
||||
CompletionStage<Void> closeAsync();
|
||||
|
||||
static AgentConnection unavailable() {
|
||||
return new AgentConnection() {
|
||||
private final Status status = new Status(State.DISCONNECTED, "");
|
||||
private <T> CompletionStage<T> missing() { return CompletableFuture.failedFuture(new IllegalStateException("Agent integration unavailable")); }
|
||||
public boolean available(){return false;} public Status status(){return status;}
|
||||
public AutoCloseable observe(Consumer<Status> l){l.accept(status);return ()->{};}
|
||||
public void events(Consumer<Event> l){} public void permissions(Function<Permission,CompletionStage<String>> h){}
|
||||
public CompletionStage<Void> connect(AcpSettings s){return missing();} public CompletionStage<Void> login(){return missing();}
|
||||
public CompletionStage<String> newSession(){return missing();}
|
||||
public Turn prompt(String s,String t){return new Turn(missing(),missing());}
|
||||
public CompletionStage<Void> cancel(String s){return CompletableFuture.completedFuture(null);}
|
||||
public CompletionStage<Void> closeAsync(){return CompletableFuture.completedFuture(null);}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package p.studio.api.ai;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface AgentConnectionFactory {
|
||||
AgentConnection create(Path projectRoot);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package p.studio.api.preferences;
|
||||
|
||||
import p.studio.api.ai.AcpSettings;
|
||||
|
||||
/** Machine-local Studio agent configuration, shared by every project. IO belongs off FX. */
|
||||
public interface AgentSettingsStore {
|
||||
AcpSettings load();
|
||||
void save(AcpSettings settings);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.ai.AcpSettings;
|
||||
import p.studio.api.preferences.AgentSettingsStore;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Global launch settings only; no credentials, session IDs or project state. */
|
||||
public final class JsonAgentSettingsStore implements AgentSettingsStore {
|
||||
private final Path file;
|
||||
private final ObjectMapper mapper;
|
||||
public JsonAgentSettingsStore(Path file,ObjectMapper mapper){this.file=file.toAbsolutePath().normalize();this.mapper=mapper.copy();}
|
||||
@Override public synchronized AcpSettings load(){
|
||||
if(!Files.exists(file))return AcpSettings.defaults();
|
||||
try{return Objects.requireNonNull(mapper.readValue(file.toFile(),AcpSettings.class),"Empty Studio AI settings");}
|
||||
catch(IOException failure){throw new UncheckedIOException("Unable to read Studio AI settings: "+file,failure);}
|
||||
}
|
||||
@Override public synchronized void save(AcpSettings settings){AtomicSettingsFile.write(file,mapper,Objects.requireNonNull(settings));}
|
||||
}
|
||||
+12
@@ -79,6 +79,18 @@ final class ProjectLocalStudioSetupStoreTest {
|
||||
final Path projectRoot = tempDir.resolve(name);
|
||||
return new ProjectReference("Main", "1.0.0", "pbs", 1, ProjectTarget.Game, projectRoot);
|
||||
}
|
||||
@Test void legacyProjectAcpIsIgnoredWithoutLosingExecutionSettings() throws Exception {
|
||||
var mapper=new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
var service=new ProjectLocalStudioSetupStore(mapper);
|
||||
var project=project("acp");
|
||||
var value=new ProjectLocalStudioSetup("/runtime",null,null,"/save");
|
||||
service.save(project,value);
|
||||
var legacy=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.readTree(ProjectStudioPaths.setupPath(project).toFile());
|
||||
legacy.putObject("acp").put("executable","/obsolete/project-specific-npx").putArray("arguments").add("ignored");
|
||||
mapper.writeValue(ProjectStudioPaths.setupPath(project).toFile(),legacy);
|
||||
assertEquals(value,service.load(project));service.save(project,service.load(project));
|
||||
org.junit.jupiter.api.Assertions.assertFalse(mapper.readTree(ProjectStudioPaths.setupPath(project).toFile()).has("acp"));
|
||||
}
|
||||
@Test void explicitMediaSelectionIsLocalAndSurvivesSetupRoundTrip() {
|
||||
var service = new ProjectLocalStudioSetupStore(new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
var project = project("media");
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package p.studio.core.project.preferences;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.ai.AcpSettings;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AgentSettingsStoreTest {
|
||||
@TempDir Path root;
|
||||
@Test void machineDefaultUsesStableLauncherWithoutNpx(){
|
||||
var settings=new JsonAgentSettingsStore(root.resolve("ai-settings.json"),new ObjectMapper()).load();
|
||||
assertEquals(Path.of(System.getProperty("user.home"),".prometeu-studio","bin","codex-acp").toString(),settings.executable());
|
||||
assertTrue(settings.arguments().isEmpty());assertFalse(Files.exists(root.resolve("ai-settings.json")));
|
||||
}
|
||||
@Test void globalSettingsSurviveRestartAndKeepLiteralArguments(){
|
||||
var file=root.resolve("state/ai-settings.json");var mapper=new ObjectMapper();
|
||||
var value=new AcpSettings("/path with spaces/codex-acp",List.of("literal $(text)","two words"));
|
||||
new JsonAgentSettingsStore(file,mapper).save(value);
|
||||
assertEquals(value,new JsonAgentSettingsStore(file,mapper).load());
|
||||
assertFalse(Files.exists(root.resolve("project/.studio/setup.json")));
|
||||
}
|
||||
@Test void unreadablePreferencesAreReportedInsteadOfSilentlyReplacingConfiguration()throws Exception {
|
||||
var file=Files.writeString(root.resolve("ai-settings.json"),"{ invalid");
|
||||
assertThrows(java.io.UncheckedIOException.class,()->new JsonAgentSettingsStore(file,new ObjectMapper()).load());
|
||||
assertEquals("{ invalid",Files.readString(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;
|
||||
}
|
||||
}
|
||||
+15
@@ -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();
|
||||
|
||||
+1
-1
@@ -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);
|
||||
|
||||
+54
-2
@@ -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",()->{
|
||||
|
||||
+52
-10
@@ -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);}
|
||||
});
|
||||
|
||||
+61
@@ -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.
|
||||
|
||||
+61
@@ -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.
|
||||
|
||||
+22
-4
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# Explicit, per-user installation. Never modifies system Node/npm, Codex login or project files.
|
||||
studio_state_root="${STUDIO_STATE_ROOT:-$HOME/.prometeu-studio}"
|
||||
studio_adapter_version=2.9.0
|
||||
studio_node="${STUDIO_NODE_BIN:-}"
|
||||
if [ -z "$studio_node" ]; then
|
||||
for studio_candidate in "$(command -v node 2>/dev/null || true)" /opt/homebrew/bin/node "$HOME"/.nvm/versions/node/v*/bin/node; do
|
||||
[ -x "$studio_candidate" ] || continue
|
||||
if "$studio_candidate" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' >/dev/null 2>&1; then
|
||||
studio_node="$studio_candidate"; break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if [ -z "$studio_node" ] || ! "$studio_node" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' >/dev/null 2>&1; then
|
||||
echo 'A working Node.js 22+ is required. Set STUDIO_NODE_BIN to its absolute executable.' >&2; exit 1
|
||||
fi
|
||||
studio_node_dir="$(cd "$(dirname "$studio_node")" && pwd)"
|
||||
studio_node="$studio_node_dir/$(basename "$studio_node")"
|
||||
studio_install="$studio_state_root/agents/codex-acp/$studio_adapter_version"
|
||||
studio_entry="$studio_install/node_modules/@agentclientprotocol/codex-acp/dist/index.js"
|
||||
studio_package="$studio_install/node_modules/@agentclientprotocol/codex-acp/package.json"
|
||||
studio_existing_version=""
|
||||
if [ -f "$studio_package" ]; then
|
||||
studio_existing_version="$("$studio_node" -p 'require(process.argv[1]).version' "$studio_package")"
|
||||
fi
|
||||
if [ "$studio_existing_version" != "$studio_adapter_version" ] || [ ! -f "$studio_entry" ]; then
|
||||
studio_npm="${STUDIO_NPM_CLI:-$studio_node_dir/../lib/node_modules/npm/bin/npm-cli.js}"
|
||||
if [ ! -f "$studio_npm" ]; then echo 'npm CLI not found beside Node. Set STUDIO_NPM_CLI to npm-cli.js.' >&2; exit 1; fi
|
||||
PATH="$studio_node_dir:$PATH" "$studio_node" "$studio_npm" install --prefix "$studio_install" \
|
||||
"@agentclientprotocol/codex-acp@$studio_adapter_version" --registry=https://registry.npmjs.org \
|
||||
--ignore-scripts --no-audit --no-fund
|
||||
fi
|
||||
studio_codex="${STUDIO_CODEX_BIN:-$(command -v codex 2>/dev/null || true)}"
|
||||
if [ -n "$studio_codex" ]; then
|
||||
case "$("$studio_codex" --version 2>/dev/null || true)" in
|
||||
'codex-cli 0.171.'*) ;;
|
||||
*) studio_codex="" ;;
|
||||
esac
|
||||
fi
|
||||
mkdir -p "$studio_state_root/bin"
|
||||
studio_launcher="$studio_state_root/bin/codex-acp"
|
||||
if [ -e "$studio_launcher" ] && [ "$(sed -n '2p' "$studio_launcher")" != '# Prometeu managed ACP launcher' ]; then
|
||||
echo "Refusing to replace an unmanaged launcher: $studio_launcher" >&2; exit 1
|
||||
fi
|
||||
studio_temporary="$(mktemp "$studio_state_root/bin/.codex-acp.XXXXXX")"
|
||||
trap 'if [ -n "$studio_temporary" ]; then rm -f "$studio_temporary"; fi' EXIT
|
||||
{
|
||||
printf '#!/bin/bash\n# Prometeu managed ACP launcher\n'
|
||||
printf 'export PATH=%q:"$PATH"\n' "$studio_node_dir"
|
||||
if [ -n "$studio_codex" ]; then printf 'export CODEX_PATH=%q\n' "$studio_codex"; else printf 'unset CODEX_PATH\n'; fi
|
||||
printf 'exec %q %q "$@"\n' "$studio_node" "$studio_entry"
|
||||
} > "$studio_temporary"
|
||||
chmod 700 "$studio_temporary"
|
||||
mv -f "$studio_temporary" "$studio_launcher"
|
||||
studio_temporary=""
|
||||
# Preserve an explicit global choice. Never import settings from an arbitrary project.
|
||||
"$studio_node" - "$studio_state_root/ai-settings.json" "$studio_launcher" <<'JS'
|
||||
const fs = require('node:fs');
|
||||
const [file, executable] = process.argv.slice(2);
|
||||
try { fs.writeFileSync(file, JSON.stringify({executable, arguments: []}, null, 2) + '\n', {flag: 'wx', mode: 0o600}); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
JS
|
||||
printf 'Installed Codex ACP %s: %s\n' "$studio_adapter_version" "$studio_launcher"
|
||||
printf 'Node: %s\n' "$studio_node"
|
||||
if [ -n "$studio_codex" ]; then printf 'Reusing Codex: %s\n' "$studio_codex"; else printf 'Using the adapter package compatible Codex dependency.\n'; fi
|
||||
Reference in New Issue
Block a user