From 481c4794275a646ef5fbb061b0a929e25bca1e7c Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Mon, 23 Nov 2026 19:12:26 +0000 Subject: [PATCH] feat(studio): render structured AI conversations Add reusable UI2 conversation balloons, tool cards, native Markdown, copy actions and controlled streaming scroll. Preserve typed ACP tool updates and chat lifecycle, add Alt+Enter sending, update specifications and qualify the UI through desktop tests. Include the Pong asset cache. --- ...AI Workspace Presentation Specification.md | 61 +++++ ...16. Codex ACP Integration Specification.md | 37 ++- gradle/libs.versions.toml | 2 + .../p/studio/app/acp/CodexAcpConnection.java | 31 ++- .../studio/app/StudioProjectsDesktopTest.java | 32 ++- .../java/p/studio/app/acp/AcpFixture.java | 14 + .../app/acp/CodexAcpConnectionTest.java | 10 + .../java/p/studio/api/ai/AgentConnection.java | 9 +- prometeu-studio-ui-javafx-2/build.gradle.kts | 6 +- .../p/studio/ui/javafx2/ai/AgentChats.java | 29 ++- .../p/studio/ui/javafx2/ai/AiWorkspace.java | 36 ++- .../ui/javafx2/components/Conversation.java | 133 ++++++++++ .../components/ConversationMarkdown.java | 69 +++++ .../javafx2/components/ConversationText.java | 68 +++++ .../components/StudioConversation.java | 246 ++++++++++++++++++ .../ui/javafx2/demo/ComponentGallery.java | 1 + .../ui/javafx2/demo/ConversationGallery.java | 51 ++++ .../ui/javafx2/i18n/messages_en.properties | 36 +++ .../ui/javafx2/i18n/messages_pt_BR.properties | 36 +++ .../p/studio/ui/javafx2/styles/components.css | 33 +++ .../ui/javafx2/FoundationDesktopTest.java | 84 +++++- .../studio/ui/javafx2/ai/AgentChatsTest.java | 8 +- .../components/ConversationMarkdownTest.java | 20 ++ .../javafx2/components/ConversationTest.java | 64 +++++ .../pong/assets/.prometeu/cache.json | 4 + 25 files changed, 1080 insertions(+), 40 deletions(-) create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/Conversation.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationMarkdown.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationText.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioConversation.java create mode 100644 prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ConversationGallery.java create mode 100644 prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/components/ConversationMarkdownTest.java create mode 100644 prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/components/ConversationTest.java create mode 100644 test-projects/pong/assets/.prometeu/cache.json diff --git a/docs/specs/studio/15. AI Workspace Presentation Specification.md b/docs/specs/studio/15. AI Workspace Presentation Specification.md index ddb54aeb..d154924a 100644 --- a/docs/specs/studio/15. AI Workspace Presentation Specification.md +++ b/docs/specs/studio/15. AI Workspace Presentation Specification.md @@ -18,6 +18,13 @@ deletion MUST operate on local state. Loading persisted history and asset attach 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. +With the shared prompt focused, Alt+Enter MUST invoke the same Send action in both +the AI tab and the compact panel. It MUST respect Send availability and consume the +combination even when sending is unavailable, preserving the draft without adding +a newline. Enter alone MUST retain normal multiline editing. The shortcut MUST be +identified in the Send tooltip and accessible help in both languages; it MUST NOT +be installed as a window-wide accelerator. + 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 @@ -67,6 +74,60 @@ or opening another MUST start empty. No chat data MAY be saved by Studio in proj 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. +## Structured conversation component + +The conversation MUST use a reusable component in the UI2 component set, replacing +its history TextArea while retaining the separate prompt compositor. It MUST consume +presentation data and MUST NOT parse ACP, launch processes or own authentication. +The same component MUST have a backend-free gallery specimen with replayable +streaming, Markdown, tools, failure and expansion. + +Items MUST appear in one chronological sequence. User messages MUST use comic-style +speech balloons aligned right; assistant messages MUST use speech balloons aligned +left. Tool calls MUST use centered cards without speech-balloon shapes, with +left-aligned text. Balloon widths MUST adapt to the available space and have a +readable maximum. Long code MUST scroll horizontally inside its block; the +conversation itself MUST NOT require horizontal scrolling. + +Only the assistant balloon under construction MAY receive text deltas. Its text +selection MUST be disabled. Finalized balloon content MUST be immutable; theme, +scale and width changes MAY reflow the same content. A new tool call between +assistant text segments MUST finalize the preceding balloon, and subsequent text +MUST create another balloon. Updates to an existing tool MUST retain its card's +position and MUST NOT rewrite previous balloons. Empty assistant balloons and one +balloon per text delta MUST NOT be generated. + +Assistant messages MUST render CommonMark headings, paragraphs, lists, emphasis, +links and code using a native renderer. HTML MUST remain inert text and images +MUST NOT trigger resource downloads. Finalized messages MUST allow local text +selection and the platform copy shortcut. Selection across multiple messages is +not required. Earlier finalized messages MUST remain selectable while another +balloon streams. Each balloon MUST offer copying its original text, preserving +Markdown; while streaming, this copies the currently received snapshot. Code-copy +controls MUST copy only the code. Copy feedback MUST be brief and preserve layout. + +Tool cards MUST display a readable title and state, with details initially +collapsed. Transitioning to failure MUST expand the card once; users MUST be able +to collapse it again without subsequent updates reopening it. Expanded details +MUST show only input, output and content actually supplied by the agent. Missing +details MUST be identified without inventing a command or result. Non-shell tools +such as read, search and edit MUST use the same card family. + +The conversation MUST follow new content while the user is at its end. Manual +scrolling MUST suspend following without stopping generation or reception. Returning +to the end MUST resume following. New content below the suspended view MUST expose +a localized Go to latest control that resumes following. Updates, expansion and +resize MUST preserve reading position when following is suspended. Recycled cells +and switching chats MUST preserve per-chat expansion and reading/following state. + +User balloons MUST retain submitted text with delivery/failure metadata separate +from immutable content. Existing acknowledgement, draft preservation and manual +recovery rules MUST remain effective. Turn completion, failure and cancellation +MUST be explicit. Tool status MUST NOT imply success merely because the turn ended. +Rendering MUST use incremental item updates and bounded batching rather than +replacing all finalized content for each delta. Content limits and retirement +follow specification 16 and MUST be visible to the user. + ## Studio preferences Studio preferences MUST contain an AI / ACP section identifying Codex as the initial diff --git a/docs/specs/studio/16. Codex ACP Integration Specification.md b/docs/specs/studio/16. Codex ACP Integration Specification.md index d23ea2fd..083eded7 100644 --- a/docs/specs/studio/16. Codex ACP Integration Specification.md +++ b/docs/specs/studio/16. Codex ACP Integration Specification.md @@ -66,12 +66,37 @@ 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. +The conversation MUST retain separate typed items for user messages, streamed +assistant segments, tool calls and terminal results. 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. Presentation follows specification 15. + +The JavaFX-free port MUST preserve tool identity, title, category, state, input, +output and supported content from ACP tool_call/tool_call_update notifications. +Updates MUST route by session and toolCallId. Omitted/null optional fields MUST +retain prior values; explicit empty content MUST clear content. Supplied snapshots +MUST replace their corresponding fields rather than being concatenated as deltas. +Unsupported content MUST NOT be presented as invented shell output. Missing terminal +tool status at turn completion MUST remain an unconfirmed/interrupted outcome. + +Studio's conversation remains transient and bounded, not an authoritative persisted +agent history. Its reducer MUST limit each message/content/output field to 64,000 +UTF-16 code units, tool input to 16,000 and title to 1,000. New tool identities MUST +be nonblank and at most 512 code units. A turn MUST admit at most 256 content items +plus its terminal result, with a shared 200,000-character budget across message text, +titles, input and output; terminal error detail MAY add at most 1,000 characters. +Omitted fields MUST remain unchanged even at the budget boundary. Truncation MUST +preserve UTF-16 surrogate pairs and be indicated visibly. Oversized transport fields +MUST also be bounded before dispatch and carry an explicit truncation marker. + +Completed older turns MUST be retired as complete turns to retain at most 200,000 +characters, 512 items and 20 turns, subject to retaining the newest turn intact +within its own admission limits. The active turn MUST remain retained while running +and MAY temporarily coexist with that completed history budget. History retirement +and admission limits MUST produce a visible localized notice. Virtualization MUST +NOT be treated as a data-memory limit. Repeated deltas or snapshots after reaching a +limit MUST NOT create unlimited empty balloons or entries. Connection loss MUST invalidate bound session IDs. Retained transcripts MUST remain readable, with explicit guidance to create a new chat after reconnecting. Studio MUST diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 6ab50409..c5363275 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,6 +1,7 @@ [versions] javafx = "23.0.2" richtextfx = "0.11.2" +commonmark = "0.24.0" jackson = "2.18.2" jacoco = "0.8.14" lombok = "1.18.42" @@ -12,6 +13,7 @@ spring-boot = "3.5.16" spring-modulith = "1.4.13" [libraries] +commonmark = { group = "org.commonmark", name = "commonmark", version.ref = "commonmark" } tomlj = { group = "org.tomlj", name = "tomlj", version = "1.1.1" } javafx-controls = { group = "org.openjfx", name = "javafx-controls", version.ref = "javafx" } javafx-fxml = { group = "org.openjfx", name = "javafx-fxml", version.ref = "javafx" } diff --git a/prometeu-app/src/main/java/p/studio/app/acp/CodexAcpConnection.java b/prometeu-app/src/main/java/p/studio/app/acp/CodexAcpConnection.java index 23a4135f..83fcb2fc 100644 --- a/prometeu-app/src/main/java/p/studio/app/acp/CodexAcpConnection.java +++ b/prometeu-app/src/main/java/p/studio/app/acp/CodexAcpConnection.java @@ -194,11 +194,38 @@ public final class CodexAcpConnection implements AgentConnection { 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("tool_call")||type.equals("tool_call_update")){ + String toolId=update.path("toolCallId").asText(); + if(!toolId.isBlank()&&toolId.length()<=512){ + String content=null; + if(update.has("content")&&!update.path("content").isNull()){ + var parts=new ArrayList(); + for(var part:update.path("content")){ + if(part.path("type").asText().equals("content")&&part.path("content").path("type").asText().equals("text")) + parts.add(part.path("content").path("text").asText()); + else if(part.path("type").asText().equals("diff")) + parts.add(part.path("path").asText()+"\n"+part.path("oldText").asText()+"\n→\n"+part.path("newText").asText()); + } + content=boundedToolText(String.join("\n",parts)); + } + event=new Event(id,Kind.TOOL,"",new ToolUpdate(toolId,toolField(update,"title"),toolField(update,"kind"), + toolField(update,"status"),toolField(update,"rawInput"),toolField(update,"rawOutput"),content)); + } + } 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 static String toolField(JsonNode update,String field){ + var value=update.get(field); + if(value==null||value.isNull())return null; + return boundedToolText(value.isTextual()?value.asText():value.toPrettyString()); + } + private static String boundedToolText(String text){ + text=message(text); + if(text.length()<=64_000)return text; + int end=Character.isHighSurrogate(text.charAt(63_979))?63_979:63_980; + return text.substring(0,end)+"\n[truncated]"; + } 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();for(var o:params.path("options"))choices.add(new Choice(o.path("optionId").asText(),o.path("name").asText(),o.path("kind").asText())); diff --git a/prometeu-app/src/test/java/p/studio/app/StudioProjectsDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/StudioProjectsDesktopTest.java index ea185477..7248cebb 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioProjectsDesktopTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioProjectsDesktopTest.java @@ -96,6 +96,10 @@ 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())); } + private static void altEnter(TextArea prompt){ + prompt.requestFocus(); + prompt.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"","",KeyCode.ENTER,false,false,true,false)); + } @Test void acpSettingsLoginSendPermissionsDeleteAndCloseFollowTheSelectedChat()throws Exception { var mapper=new ObjectMapper();var setups=new ProjectLocalStudioSetupStore(mapper); var catalog=new ProjectCatalogService(temporary.resolve("projects"),mapper,setups); @@ -134,20 +138,31 @@ class StudioProjectsDesktopTest { fire(h.stage,"ai-prompt-toggle");fire(h.stage,"ai-compact-new-chat"); var selector=fx(()->(ComboBox)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"); + fx(()->{ + prompt.setText("first line");prompt.positionCaret(prompt.getLength()); + prompt.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"","",KeyCode.ENTER,false,false,false,false)); + assertEquals("first line\n",prompt.getText(),"Enter remains a newline"); + assertTrue(((Button)h.stage.getScene().lookup("#ai-send")).getTooltip().getText().contains("Alt+Enter")); + prompt.setText("draft A · personagem");return null; + });fire(h.stage,"ai-compact-new-chat");var b=fx(selector::getValue); + fx(()->{prompt.setText("hold");altEnter(prompt);return null;}); 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())); + fx(()->{altEnter(prompt);assertEquals("draft A · personagem",prompt.getText(),"Unavailable send must preserve the draft without a newline");return null;}); + assertTrue(fx(()->((p.studio.ui.javafx2.components.StudioConversation)h.stage.getScene().lookup("#ai-conversation")).conversation().items().isEmpty())); 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"); + assertTrue(fx(()->((p.studio.ui.javafx2.components.StudioConversation)h.stage.getScene().lookup("#ai-conversation")).conversation().items().stream().anyMatch(i->i.state().equals("cancelled")))); + fx(()->{ + altEnter(prompt);assertEquals("",prompt.getText(),"Empty prompt stays empty"); + assertTrue(h.stage.getScene().lookup("#ai-cancel").isDisabled()); + prompt.setText("reject");altEnter(prompt);return null; + }); 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"); @@ -157,6 +172,13 @@ class StudioProjectsDesktopTest { ((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("tools");return null;});fire(h.stage,"ai-send"); + await(()->fx(()->h.stage.getScene().lookup("#ai-cancel").isDisabled())); + await(()->fx(()->{ + var conversation=(p.studio.ui.javafx2.components.StudioConversation)h.stage.getScene().lookup("#ai-conversation"); + return conversation.conversation().items().stream().anyMatch(i->i.toolId().equals("t1")&&i.state().equals("completed")&&i.title().equals("Read config")&&i.text().equals("configuration")); + })); + capture(h.stage,"acp-structured-conversation-fixture"); 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"))); diff --git a/prometeu-app/src/test/java/p/studio/app/acp/AcpFixture.java b/prometeu-app/src/test/java/p/studio/app/acp/AcpFixture.java index cf43ad62..39bd7e74 100644 --- a/prometeu-app/src/test/java/p/studio/app/acp/AcpFixture.java +++ b/prometeu-app/src/test/java/p/studio/app/acp/AcpFixture.java @@ -59,6 +59,16 @@ public final class AcpFixture { 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; } + if(text.equals("tools")){ + chunk(session,"agent_message_chunk","# Inspection\n\nReading the **configuration**."); + tool(session,JSON.createObjectNode().put("sessionUpdate","tool_call").put("toolCallId","t1").put("title","Read config").put("kind","read").put("status","pending").put("rawInput","config.json")); + tool(session,JSON.createObjectNode().put("sessionUpdate","tool_call_update").put("toolCallId","t1").put("status","in_progress")); + var update=JSON.createObjectNode().put("sessionUpdate","tool_call_update").put("toolCallId","t1").put("status","completed"); + update.putArray("content").addObject().put("type","content").putObject("content").put("type","text").put("text","configuration"); + update.put("rawOutput","result");tool(session,update); + chunk(session,"agent_message_chunk","The configuration is ready."); + reply(id,JSON.createObjectNode().put("stopReason","end_turn"));break; + } chunk(session,"agent_message_chunk","first "); if(text.equals("hold")){pendingPrompt=id;break;} chunk(session,"agent_thought_chunk","PRIVATE_THOUGHT_MUST_NOT_ESCAPE"); @@ -91,6 +101,10 @@ public final class AcpFixture { 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 tool(String session,ObjectNode update)throws Exception { + var frame=JSON.createObjectNode().put("jsonrpc","2.0").put("method","session/update"); + frame.putObject("params").put("sessionId",session).set("update",update);send(frame); + } 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) diff --git a/prometeu-app/src/test/java/p/studio/app/acp/CodexAcpConnectionTest.java b/prometeu-app/src/test/java/p/studio/app/acp/CodexAcpConnectionTest.java index d75ffc43..133d4fca 100644 --- a/prometeu-app/src/test/java/p/studio/app/acp/CodexAcpConnectionTest.java +++ b/prometeu-app/src/test/java/p/studio/app/acp/CodexAcpConnectionTest.java @@ -32,6 +32,16 @@ class CodexAcpConnectionTest { assertThrows(ExecutionException.class,()->await(c.prompt(second,"overlap").completion())); await(c.cancel(first));assertEquals("cancelled",await(held.completion())); } + @Test void toolIdentityAndPartialFieldsSurviveRealStdio()throws Exception { + var c=open("normal");String id=await(c.newSession()); + var events=new CopyOnWriteArrayList();c.events(events::add); + var turn=c.prompt(id,"tools");await(turn.accepted());await(turn.completion()); + var tools=events.stream().filter(e->e.kind()==AgentConnection.Kind.TOOL).toList();assertEquals(3,tools.size()); + var first=tools.get(0).tool();assertEquals("t1",first.id());assertEquals("config.json",first.input()); + var partial=tools.get(1).tool();assertNull(partial.title());assertNull(partial.input());assertNull(partial.content()); + assertEquals("in_progress",partial.status()); + var last=tools.get(2).tool();assertEquals("configuration",last.content());assertEquals("result",last.output()); + } @Test void permissionIsNeverGrantedWithoutAnExplicitChoice()throws Exception { var c=open("normal");String id=await(c.newSession()); var choice=new CompletableFuture();c.permissions(p->{assertEquals(id,p.sessionId());return choice;}); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/ai/AgentConnection.java b/prometeu-studio-api/src/main/java/p/studio/api/ai/AgentConnection.java index 6fff2c72..df5d9075 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/ai/AgentConnection.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/ai/AgentConnection.java @@ -7,9 +7,14 @@ 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 } + enum Kind { TEXT, ACTIVITY, TOOL } record Status(State state, String detail) { } - record Event(String sessionId, Kind kind, String text) { } + /** Null fields in a tool update mean unchanged; empty content explicitly clears it. */ + record ToolUpdate(String id, String title, String category, String status, + String input, String output, String content) { } + record Event(String sessionId, Kind kind, String text, ToolUpdate tool) { + public Event(String sessionId, Kind kind, String text) { this(sessionId, kind, text, null); } + } record Choice(String id, String name, String kind) { } record Permission(String sessionId, String title, String details, List choices) { public Permission(String sessionId,String title,List choices){this(sessionId,title,"",choices);} diff --git a/prometeu-studio-ui-javafx-2/build.gradle.kts b/prometeu-studio-ui-javafx-2/build.gradle.kts index dab4aa3f..1eb8a240 100644 --- a/prometeu-studio-ui-javafx-2/build.gradle.kts +++ b/prometeu-studio-ui-javafx-2/build.gradle.kts @@ -21,7 +21,11 @@ tasks.named("run") { } } -dependencies { implementation(project(":prometeu-studio-api")) } +dependencies { + implementation(project(":prometeu-studio-api")) + implementation(libs.richtextfx) + implementation(libs.commonmark) +} distributions { main { diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AgentChats.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AgentChats.java index c8795a48..f8c52ee4 100644 --- a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AgentChats.java +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AgentChats.java @@ -1,16 +1,16 @@ package p.studio.ui.javafx2.ai; import p.studio.api.ai.AgentConnection; +import p.studio.ui.javafx2.components.Conversation; 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(); + final Conversation conversation = new Conversation(); String activity = ""; String lastRequest = ""; boolean invalid; @@ -44,7 +44,7 @@ final class AgentChats implements AutoCloseable { 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();} + Conversation conversation(long id){return entry(id).conversation;} String activity(long id){return entry(id).invalid?text.apply("ai.session.expired"):entry(id).activity;} String lastRequest(long id){return entry(id).lastRequest;} @@ -53,7 +53,7 @@ final class AgentChats implements AutoCloseable { 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"); + chat.conversation.begin(snapshot); opened.accept(id);changed.run(); CompletionStage session; try{session=chat.session==null?agent.newSession():CompletableFuture.completedFuture(chat.session);} @@ -66,8 +66,10 @@ final class AgentChats implements AutoCloseable { 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(); + if(!closed&&f==null&&entries.containsKey(id)){ + chat.conversation.delivered(); + if(drafts.draft(id).equals(snapshot))drafts.write(id,""); + changed.run(); } })); turn.completion().whenComplete((stop,f)->dispatch.execute(()->finish(id,stop,f))); @@ -76,12 +78,15 @@ final class AgentChats implements AutoCloseable { } 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())){ + for(var item:entries.entrySet())if(!item.getValue().invalid&&Objects.equals(running,item.getKey())&&Objects.equals(item.getValue().session,event.sessionId())){ var chat=item.getValue(); - if(event.kind()==AgentConnection.Kind.TEXT)append(chat,event.text()); + if(event.kind()==AgentConnection.Kind.TEXT)chat.conversation.text(event.text()); + else if(event.kind()==AgentConnection.Kind.TOOL&&event.tool()!=null){ + var tool=event.tool(); + chat.conversation.tool(tool.id(),tool.title(),tool.category(),tool.status(),tool.input(),tool.output(),tool.content()); + } 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; @@ -91,7 +96,7 @@ final class AgentChats implements AutoCloseable { 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"); + chat.conversation.finish(failure!=null?"error":"cancelled".equals(stop)?"cancelled":"done",failure==null?"":failureMessage(failure)); running=null;cancelling=false; var done=settled;changed.run();done.complete(null); } @@ -121,10 +126,6 @@ final class AgentChats implements AutoCloseable { });} 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()) diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AiWorkspace.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AiWorkspace.java index 0ebd5ed1..30fbbb33 100644 --- a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AiWorkspace.java +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/ai/AiWorkspace.java @@ -7,6 +7,10 @@ import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; +import javafx.scene.input.KeyCode; +import javafx.scene.input.KeyCodeCombination; +import javafx.scene.input.KeyCombination; +import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.scene.shape.SVGPath; import p.studio.ui.javafx2.appearance.AppearanceContext; @@ -42,7 +46,7 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { private final Tooltip accessTip = new Tooltip(); private final AgentConnection agent; private final AgentChats execution; - private final TextArea transcript = new TextArea(); + private final StudioConversation transcript; private final Label activity = new Label(); private final Label connectionStatus = new Label(); private final Button send; @@ -117,6 +121,18 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { HBox.setHgrow(spacer, Priority.ALWAYS); send=actionButton("ai.send","ai-send",this::send); send.getStyleClass().add("primary"); + var sendShortcut=new KeyCodeCombination(KeyCode.ENTER,KeyCombination.ALT_DOWN); + prompt.addEventFilter(KeyEvent.KEY_PRESSED,event->{ + if(sendShortcut.match(event)){ + event.consume(); + send.fire(); + } + }); + var sendTip=new Tooltip();send.setTooltip(sendTip); + context.observe(()->{ + String hint=context.text("ai.send.hint");sendTip.setText(hint); + send.setAccessibleHelp(hint);prompt.setAccessibleHelp(hint); + }); 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); @@ -143,8 +159,8 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { 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); + transcript=new StudioConversation(context);transcript.setAssistantName("Codex"); + transcript.setId("ai-conversation");transcript.setMinHeight(90);transcript.setPrefHeight(200); 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); @@ -198,7 +214,7 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { } refreshAccess(); }); - execution=new AgentChats(chats,agent,Platform::runLater,this::refreshItems,id->{ + execution=new AgentChats(chats,agent,Platform::runLater,this::refreshExecution,id->{ chats.select(id);drawerOpen=false;tabs.getSelectionModel().select(ai);refreshSelection(); },context::text); agent.permissions(this::permission); @@ -284,6 +300,15 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { refreshSelection();focusPrompt(); } + private void refreshExecution(){ + if(closed)return; + if(!list.getItems().equals(chats.chats())){refreshItems();return;} + synchronizing=true; + try { if(!prompt.getText().equals(chats.draft()))prompt.setText(chats.draft()); } + finally { synchronizing=false; } + refreshAgent(); + } + private void refreshAgent(){ if(execution==null||closed)return; if(!execution.busy())cancelPermissions(); @@ -291,8 +316,7 @@ public final class AiWorkspace extends SplitPane implements AutoCloseable { 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());} + transcript.show(chat==null?null:execution.conversation(chat.id())); 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()) diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/Conversation.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/Conversation.java new file mode 100644 index 00000000..22913cfc --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/Conversation.java @@ -0,0 +1,133 @@ +package p.studio.ui.javafx2.components; + +import java.util.*; + +/** Transient, toolkit-free conversation reducer. Access only from its owning thread. */ +public final class Conversation { + public enum Role { USER, ASSISTANT, TOOL, RESULT } + public record Item(long id, long turn, Role role, String toolId, String title, + String category, String state, String text, String input, + String output, boolean truncated) { + public boolean streaming() { return role == Role.ASSISTANT && state.equals("streaming"); } + } + public static final int TURN_CHAR_LIMIT = 200_000; + public static final int ITEM_CHAR_LIMIT = 64_000; + public static final int TURN_ITEM_LIMIT = 256; + private final List items = new ArrayList<>(); + private long sequence, turn, active, user; + private int turnChars, turnItems, discarded; + private boolean open, overflow; + private long revision; + + public List items() { return List.copyOf(items); } + public long revision() { return revision; } + public int discarded() { return discarded; } + public boolean limited() { return overflow; } + + public void begin(String prompt) { + if (open) throw new IllegalStateException("A turn is already open"); + trim(); turn++; turnChars = 0; turnItems = 0; open = true; + user = ++sequence; + String value = bounded(prompt, ITEM_CHAR_LIMIT); + add(new Item(user, turn, Role.USER, "", "", "", "sending", value, "", "", value.length() < prompt.length())); + } + public void delivered() { + int index = index(user); + if (index >= 0 && items.get(index).state().equals("sending")) state(index, "sent"); + } + public void text(String delta) { + if (!open || delta.isEmpty()) return; + int index = index(active); + if (index < 0) { + if (turnChars >= TURN_CHAR_LIMIT) { overflow = true; revision++; return; } + if (!room()) return; + active = ++sequence; + add(new Item(active, turn, Role.ASSISTANT, "", "", "", "streaming", "", "", "", false)); + index = items.size() - 1; + } + var before = items.get(index); + String suffix = bounded(delta, Math.min(ITEM_CHAR_LIMIT - before.text().length(), TURN_CHAR_LIMIT - turnChars)); + if (suffix.length() < delta.length()) overflow = true; + replace(index, new Item(before.id(), turn, before.role(), "", "", "", "streaming", + before.text() + suffix, "", "", before.truncated() || suffix.length() < delta.length())); + } + public void tool(String id, String title, String category, String status, String input, String output, String content) { + if (!open || id == null || id.isBlank() || id.length() > 512) return; + int index = -1; + for (int i = 0; i < items.size(); i++) { + var item = items.get(i); + if (item.turn() == turn && item.role() == Role.TOOL && item.toolId().equals(id)) { index = i; break; } + } + if (index < 0) { + seal(); + if (!room()) return; + add(new Item(++sequence, turn, Role.TOOL, id, "", "other", "pending", "", "", "", false)); + index = items.size() - 1; + } + var before = items.get(index); + // Replacing snapshots releases their old budget; omitted fields retain their value. + int[] budget = { TURN_CHAR_LIMIT - turnChars }; + String nextTitle = patch(title, before.title(), 1000, budget); + String nextInput = patch(input, before.input(), 16_000, budget); + String nextContent = patch(content, before.text(), ITEM_CHAR_LIMIT, budget); + String nextOutput = patch(output, before.output(), ITEM_CHAR_LIMIT, budget); + boolean truncated = nextTitle.length() < Objects.requireNonNullElse(title, before.title()).length() + || nextInput.length() < Objects.requireNonNullElse(input, before.input()).length() + || nextContent.length() < Objects.requireNonNullElse(content, before.text()).length() + || nextOutput.length() < Objects.requireNonNullElse(output, before.output()).length(); + overflow |= truncated; + replace(index, new Item(before.id(), turn, Role.TOOL, id, nextTitle, + category == null ? before.category() : cap(category, 80), status == null ? before.state() : cap(status, 80), + nextContent, nextInput, nextOutput, before.truncated() || truncated)); + } + public void finish(String outcome, String detail) { + if (!open) return; + seal(); + int index = index(user); + if (index >= 0 && items.get(index).state().equals("sending")) state(index, outcome.equals("cancelled") ? "cancelled" : "failed"); + for (int i = 0; i < items.size(); i++) { + var item = items.get(i); + if (item.turn() == turn && item.role() == Role.TOOL + && !Set.of("completed", "failed").contains(item.state())) state(i, "interrupted"); + } + // Reserve one terminal item even when the active turn exceeded its item budget. + add(new Item(++sequence, turn, Role.RESULT, "", "", "", outcome, cap(detail, 1000), "", "", false)); + open = false; trim(); + } + private void seal() { int index = index(active); if (index >= 0) state(index, "complete"); active = 0; } + private boolean room() { + if (turnItems < TURN_ITEM_LIMIT) return true; + overflow = true; revision++; return false; + } + private String bounded(String value, int max) { return cap(value, max); } + private static String patch(String incoming, String previous, int limit, int[] budget) { + if(incoming == null) return previous; + String next=cap(incoming,Math.min(limit,Math.max(0,previous.length()+budget[0]))); + budget[0]+=previous.length()-next.length();return next; + } + private static String cap(String value, int max) { + int end = Math.max(0, Math.min(value.length(), max)); + if (end > 0 && end < value.length() && Character.isHighSurrogate(value.charAt(end - 1))) end--; + return value.substring(0, end); + } + private int index(long id) { for (int i = 0; i < items.size(); i++) if (items.get(i).id() == id) return i; return -1; } + private void state(int index, String state) { + var item = items.get(index); + replace(index, new Item(item.id(), item.turn(), item.role(), item.toolId(), item.title(), item.category(), state, + item.text(), item.input(), item.output(), item.truncated())); + } + private void add(Item item) { items.add(item); turnItems++; turnChars += weight(item); revision++; } + private void replace(int index, Item item) { + if (!items.get(index).equals(item)) { turnChars += weight(item) - weight(items.set(index, item)); revision++; } + } + private static int weight(Item item) { return item.text().length() + item.title().length() + item.input().length() + item.output().length(); } + private void trim() { + int chars = items.stream().mapToInt(Conversation::weight).sum(); + while (!items.isEmpty() && items.getFirst().turn() < turn + && (chars > TURN_CHAR_LIMIT || items.size() > 512 || turn - items.getFirst().turn() >= 20)) { + long oldest = items.getFirst().turn(); + while (!items.isEmpty() && items.getFirst().turn() == oldest) { chars -= weight(items.removeFirst()); discarded++; } + revision++; + } + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationMarkdown.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationMarkdown.java new file mode 100644 index 00000000..651858c7 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationMarkdown.java @@ -0,0 +1,69 @@ +package p.studio.ui.javafx2.components; + +import org.commonmark.node.*; +import org.commonmark.parser.Parser; +import java.util.*; + +/** CommonMark to native text sections; never produces HTML or fetches resources. */ +final class ConversationMarkdown { + record Span(int start, int end, List styles) { } + record Section(String text, boolean code, String language, List spans) { } + private static final Parser PARSER = Parser.builder().build(); + private final List
sections = new ArrayList<>(); + private final StringBuilder prose = new StringBuilder(); + private final List spans = new ArrayList<>(); + + static List
parse(String source) { + var result = new ConversationMarkdown(); + result.visit(PARSER.parse(source), List.of(), 0); + result.flush();return List.copyOf(result.sections); + } + private void flush() { + if (!prose.isEmpty()) { + sections.add(new Section(prose.toString().stripTrailing(), false, "", List.copyOf(spans))); + prose.setLength(0);spans.clear(); + } + } + private void append(String text, List styles) { + int begin = prose.length();prose.append(text); + if (!styles.isEmpty() && !text.isEmpty()) spans.add(new Span(begin, prose.length(), styles)); + } + private void visit(org.commonmark.node.Node node, List styles, int depth) { + if (node instanceof FencedCodeBlock code) { + flush();sections.add(new Section(code.getLiteral(), true, code.getInfo(), List.of()));return; + } + if (node instanceof IndentedCodeBlock code) { + flush();sections.add(new Section(code.getLiteral(), true, "", List.of()));return; + } + if (node instanceof Text text) { append(text.getLiteral(), styles);return; } + if (node instanceof Code code) { append(code.getLiteral(), plus(styles,"conversation-inline-code"));return; } + if (node instanceof SoftLineBreak || node instanceof HardLineBreak) { append("\n", styles);return; } + if (node instanceof HtmlInline html) { append(html.getLiteral(), styles);return; } + if (node instanceof HtmlBlock html) { append(html.getLiteral(), styles);return; } + if (node instanceof ThematicBreak) { append("────────\n", styles);return; } + var next = styles; + if (node instanceof StrongEmphasis) next = plus(styles,"conversation-bold"); + if (node instanceof Emphasis) next = plus(styles,"conversation-italic"); + if (node instanceof Heading heading) next = plus(styles,"conversation-heading-"+Math.min(3,heading.getLevel())); + if (node instanceof Link) next = plus(styles,"conversation-link"); + if (node instanceof ListItem) { + String marker = "• "; + if (node.getParent() instanceof OrderedList ordered) { + int number = ordered.getMarkerStartNumber(); + for (var sibling = node.getPrevious(); sibling != null; sibling = sibling.getPrevious()) number++; + marker = number + ". "; + } + append(" ".repeat(depth)+marker, styles); + } + if (node instanceof BlockQuote) append("│ ", styles); + for (var child = node.getFirstChild(); child != null; child = child.getNext()) + visit(child, next, depth + (node instanceof ListItem ? 1 : 0)); + if (node instanceof Link link) append(" ("+link.getDestination()+")", plus(styles,"conversation-link")); + if (node instanceof Image image) append(" ("+image.getDestination()+")", styles); + if (node instanceof Paragraph || node instanceof Heading || node instanceof BlockQuote) + append(node.getParent() instanceof ListItem ? "\n" : "\n\n", List.of()); + } + private static List plus(List values, String value) { + var copy = new ArrayList<>(values);copy.add(value);return List.copyOf(copy); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationText.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationText.java new file mode 100644 index 00000000..3bc1b21a --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/ConversationText.java @@ -0,0 +1,68 @@ +package p.studio.ui.javafx2.components; + +import javafx.scene.control.ScrollPane; +import javafx.scene.input.MouseEvent; +import javafx.scene.input.KeyEvent; +import org.fxmisc.flowless.VirtualizedScrollPane; +import org.fxmisc.richtext.StyleClassedTextArea; +import javafx.beans.binding.Bindings; +import javafx.beans.binding.DoubleExpression; +import javafx.scene.text.*; +import p.studio.ui.javafx2.appearance.AppearanceContext; + +/** Selectable native text, sized to its content. Code owns its horizontal scroll. */ +final class ConversationText extends VirtualizedScrollPane { + private final StyleClassedTextArea area; + ConversationText(ConversationMarkdown.Section section, boolean streaming, AppearanceContext context, DoubleExpression availableWidth) { + super(new StyleClassedTextArea(), section.code() ? ScrollPane.ScrollBarPolicy.AS_NEEDED : ScrollPane.ScrollBarPolicy.NEVER, + ScrollPane.ScrollBarPolicy.NEVER); + area = getContent();area.setEditable(false);area.setWrapText(!section.code()); + area.getStyleClass().addAll("conversation-text", section.code() ? "conversation-code" : "conversation-prose"); + area.replaceText(section.text()); + for (var span : section.spans()) + if (span.start() < area.getLength()) area.setStyle(span.start(), Math.min(span.end(),area.getLength()), span.styles()); + area.setFocusTraversable(!streaming); + if (streaming) { + area.addEventFilter(MouseEvent.ANY, event -> { if (!event.getEventType().equals(MouseEvent.MOUSE_MOVED)) event.consume(); }); + area.addEventFilter(KeyEvent.ANY, KeyEvent::consume); + } + area.setShowCaret(org.fxmisc.richtext.Caret.CaretVisibility.OFF); + setMinWidth(0);setMaxWidth(Double.MAX_VALUE); + // Measure against the known bubble width, rather than nesting two virtual-flow + // height estimates. Initial zero-width estimates otherwise leave huge blank cells. + var paragraphs = new java.util.ArrayList(); + int offset=0,firstSpan=0; + for(String line:section.text().split("\n",-1)){ + var measure=new TextFlow();int position=0; + while(firstSpan=offset+line.length())break; + int start=Math.max(0,span.start()-offset),end=Math.min(line.length(),span.end()-offset); + if(start>=end)continue; + if(start>position)measure.getChildren().add(measureText(line.substring(position,start),java.util.List.of(),context)); + measure.getChildren().add(measureText(line.substring(start,end),span.styles(),context));position=end; + } + if(position Math.max(28., + paragraphs.stream().mapToDouble(paragraph -> Math.ceil(paragraph.prefHeight(section.code()?Double.MAX_VALUE:Math.max(40,availableWidth.get()-8)))).sum() + +(section.code()?28:8)),availableWidth)); + minHeightProperty().bind(prefHeightProperty());maxHeightProperty().bind(prefHeightProperty()); + setAccessibleText(section.text()); + } + private static Text measureText(String text, java.util.List styles, AppearanceContext context) { + double size=16.5*context.settings().scale(); + if(styles.contains("conversation-heading-1"))size*=1.35; + else if(styles.contains("conversation-heading-2"))size*=1.2; + else if(styles.contains("conversation-heading-3"))size*=1.1; + var node=new Text(text); + node.setFont(Font.font(context.family(context.settings().typeface()), + styles.contains("conversation-bold")||styles.stream().anyMatch(s->s.startsWith("conversation-heading"))?FontWeight.BOLD:FontWeight.NORMAL, + styles.contains("conversation-italic")?FontPosture.ITALIC:FontPosture.REGULAR,size)); + return node; + } + void dispose() { prefHeightProperty().unbind();minHeightProperty().unbind();maxHeightProperty().unbind();area.dispose(); } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioConversation.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioConversation.java new file mode 100644 index 00000000..7c770de7 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/components/StudioConversation.java @@ -0,0 +1,246 @@ +package p.studio.ui.javafx2.components; + +import javafx.animation.PauseTransition; +import javafx.animation.AnimationTimer; +import javafx.application.Platform; +import javafx.beans.value.ChangeListener; +import javafx.geometry.*; +import javafx.scene.Node; +import javafx.scene.control.*; +import javafx.scene.control.skin.VirtualFlow; +import javafx.scene.input.*; +import javafx.scene.layout.*; +import javafx.scene.shape.SVGPath; +import javafx.util.Duration; +import p.studio.ui.javafx2.appearance.AppearanceContext; +import java.util.*; + +/** Reusable UI2 conversation: its input contains no agent/transport implementation. FX-thread owned. */ +public final class StudioConversation extends BorderPane implements AutoCloseable { + private static final class ViewState { + final Map expanded = new HashMap<>(); + final Map toolStates = new HashMap<>(); + boolean following = true, unread; + int anchor; + long anchorId; + double offset; + } + private final AppearanceContext context; + private final ListView list = new ListView<>(); + private final Label notice = new Label(); + private final Button latest = new Button(); + private final Map states = new WeakHashMap<>(); + private final Set cells = Collections.newSetFromMap(new WeakHashMap<>()); + private final PauseTransition updates = new PauseTransition(Duration.millis(40)); + private final ChangeListener appearance; + private Conversation source; + private String assistantName; + private ViewState view = new ViewState(); + private long rendered = -1; + private boolean closed, applying; + private int scrollPulses; + private final AnimationTimer endPosition = new AnimationTimer() { + @Override public void handle(long now) { + if(closed||!view.following||scrollPulses++>=8){stop();return;} + list.applyCss();list.layout();var flow=flow(); + if(flow!=null&&!list.getItems().isEmpty()){ + flow.scrollTo(list.getItems().size()-1);flow.layout(); + var last=flow.getVisibleCell(list.getItems().size()-1);if(last!=null)flow.scrollToBottom(last); + } + } + }; + + public StudioConversation(AppearanceContext context) { + this.context = context;getStyleClass().add("studio-conversation"); + setMinSize(0,90);setPrefSize(640,400); + list.getStyleClass().add("conversation-list");list.setMinSize(0,0); + list.setCellFactory(ignored -> {var cell=new Cell();cells.add(cell);return cell;}); + list.setPlaceholder(new Label(context.text("conversation.empty"))); + notice.setWrapText(true);notice.getStyleClass().add("conversation-notice");setTop(notice); + latest.setOnAction(event -> followEnd()); + var footer = new HBox(latest);footer.setAlignment(Pos.CENTER);footer.getStyleClass().add("conversation-footer"); + setCenter(list);setBottom(footer); + list.addEventFilter(ScrollEvent.SCROLL, event -> { + if (Math.abs(event.getDeltaY()) < .01) return; + suspendFollowing(); + Platform.runLater(() -> { if (!closed && event.getDeltaY()<0 && atEnd()) {view.following=true;view.unread=false;refreshFooter();} }); + }); + list.addEventFilter(MouseEvent.MOUSE_PRESSED,event -> { + Node target=event.getTarget() instanceof Node node?node:null; + for(Node node=target;node!=null&&node!=list;node=node.getParent()) if(node instanceof ScrollBar){suspendFollowing();break;} + }); + list.addEventFilter(MouseEvent.MOUSE_RELEASED,event -> { + if(atEnd()){view.following=true;view.unread=false;refreshFooter();} + }); + list.addEventFilter(KeyEvent.KEY_PRESSED, event -> { + if(Set.of(KeyCode.UP,KeyCode.PAGE_UP,KeyCode.HOME,KeyCode.DOWN,KeyCode.PAGE_DOWN,KeyCode.END).contains(event.getCode())) { + suspendFollowing();Platform.runLater(() -> {if(atEnd()){view.following=true;view.unread=false;refreshFooter();}}); + } + }); + list.widthProperty().addListener((o,b,a)->{if(view.following&&!applying)Platform.runLater(()->{if(!closed&&view.following)followEnd();});}); + updates.setOnFinished(event -> render()); + appearance=(o,b,a)->{refreshLabels();cells.forEach(cell->cell.shown=null);list.refresh();}; + context.settingsProperty().addListener(appearance);context.onClose(this::close);refreshLabels(); + } + public void show(Conversation conversation) { + if (closed) return; + if(source!=conversation){ + rememberAnchor();updates.stop();endPosition.stop();source=conversation;rendered=-1; + view=conversation==null?new ViewState():states.computeIfAbsent(conversation,ignored->new ViewState()); + list.getItems().clear();render(false);restoreAnchor(); + } else if(source!=null&&rendered!=source.revision()&&updates.getStatus()!=javafx.animation.Animation.Status.RUNNING) updates.playFromStart(); + } + public void setAssistantName(String name){assistantName=Objects.requireNonNull(name);cells.forEach(cell->cell.shown=null);list.refresh();} + public Conversation conversation() { return source; } + public ListView list() { return list; } + public boolean following() { return view.following; } + public void followEnd() { + view.following=true;view.unread=false;refreshFooter(); + if(!list.getItems().isEmpty()){ + list.scrollTo(list.getItems().size()-1);scrollPulses=0;endPosition.start(); + } + } + private void suspendFollowing(){if(applying)return;endPosition.stop();view.following=false;rememberAnchor();} + @SuppressWarnings("unchecked") private VirtualFlow> flow(){return (VirtualFlow>)list.lookup(".virtual-flow");} + private boolean atEnd(){ + var flow=flow();if(flow==null||list.getItems().isEmpty())return true; + var last=flow.getLastVisibleCell(); + return last!=null&&last.getIndex()>=list.getItems().size()-1&&last.getBoundsInParent().getMaxY()<=flow.getHeight()+2; + } + private void rememberAnchor(){ + var flow=flow();if(flow!=null&&flow.getFirstVisibleCell()!=null){ + var first=flow.getFirstVisibleCell();view.anchor=first.getIndex();view.offset=first.getLayoutY(); + if(first.getItem()!=null)view.anchorId=first.getItem().id(); + } + } + private void restoreAnchor(){ + if(view.following){followEnd();return;} + for(int i=0;i{ + if(!closed&&view==expected&&!view.following){ + list.layout();var flow=flow(); + if(flow!=null){var cell=flow.getVisibleCell(view.anchor);if(cell!=null)flow.scrollPixels(cell.getLayoutY()-view.offset);} + } + }); + } + private void render(){render(true);} + private void render(boolean preserveAnchor){ + if(closed)return; + var next=source==null?List.of():source.items(); + if(source!=null&&rendered==source.revision())return; + if(preserveAnchor)rememberAnchor();applying=true; + try{ + // Remove retired items without rebuilding all retained cells or their selections. + var ids=new HashSet();next.forEach(item->ids.add(item.id())); + boolean retired=list.getItems().removeIf(item->!ids.contains(item.id())); + boolean anchorAffected=retired; + view.expanded.keySet().retainAll(ids);view.toolStates.keySet().retainAll(ids); + for(int i=0;i=list.getItems().size())list.getItems().add(item); + else if(!list.getItems().get(i).equals(item)){if(i<=view.anchor)anchorAffected=true;list.getItems().set(i,item);} + } + rendered=source==null?-1:source.revision(); + if(!view.following)view.unread=true; + refreshLabels(); + if(preserveAnchor&&!view.following&&anchorAffected)restoreAnchor(); + }finally{applying=false;} + if(view.following)followEnd(); + } + private void refreshLabels(){ + latest.setText(context.text("conversation.latest")); + list.setAccessibleText(context.text("conversation.title")); + list.setPlaceholder(new Label(context.text("conversation.empty"))); + notice.setText(source!=null&&(source.discarded()>0||source.limited())?context.text("conversation.limited"):""); + notice.setVisible(!notice.getText().isEmpty());notice.setManaged(notice.isVisible());refreshFooter(); + } + private void refreshFooter(){var footer=getBottom();boolean show=!view.following&&view.unread;footer.setVisible(show);footer.setManaged(show);} + private String state(String value){return context.text("conversation.state."+switch(value){ + case "sending","sent","failed","cancelled","streaming","pending","in_progress","completed","interrupted","done","error" -> value; + default -> "unknown"; + });} + + private final class Cell extends ListCell { + private Conversation.Item shown; + private final List texts=new ArrayList<>(); + private final List feedback=new ArrayList<>(); + private final HBox row=new HBox(); + private final VBox body=new VBox(8); + Cell(){ + getStyleClass().add("conversation-cell");setContentDisplay(ContentDisplay.GRAPHIC_ONLY);setPrefWidth(0); + body.setMinWidth(0);row.setMinWidth(0);row.prefWidthProperty().bind(widthProperty().subtract(24)); + body.maxWidthProperty().bind(javafx.beans.binding.Bindings.min(760,list.widthProperty().subtract(56).multiply(.86))); + body.prefWidthProperty().bind(body.maxWidthProperty()); + } + private void clearContent(){texts.forEach(ConversationText::dispose);texts.clear();feedback.forEach(PauseTransition::stop);feedback.clear();body.getChildren().clear();} + @Override protected void updateItem(Conversation.Item item,boolean empty){ + super.updateItem(item,empty); + if(empty||item==null){shown=null;clearContent();setGraphic(null);return;} + if(item.equals(shown)){setGraphic(row);return;} + shown=item;row.setId("conversation-item-"+item.id());clearContent();row.getChildren().clear();body.getStyleClass().setAll("conversation-body"); + row.setAlignment(switch(item.role()){case USER->Pos.TOP_RIGHT;case ASSISTANT->Pos.TOP_LEFT;default->Pos.TOP_CENTER;}); + if(item.role()==Conversation.Role.TOOL)tool(item); + else if(item.role()==Conversation.Role.RESULT){ + body.getStyleClass().add("conversation-result");body.getChildren().add(label(state(item.state())+(item.text().isBlank()?"":" · "+item.text()))); + }else message(item); + if(item.truncated())body.getChildren().add(label(context.text("conversation.truncated"))); + if(item.role()==Conversation.Role.USER||item.role()==Conversation.Role.ASSISTANT){ + boolean user=item.role()==Conversation.Role.USER; + var tail=new SVGPath();tail.setContent(user?"M 0 0 L 10 14 L 0 9 Z":"M 10 0 L 0 14 L 10 9 Z"); + tail.getStyleClass().add(user?"conversation-tail-user":"conversation-tail-assistant"); + var holder=new VBox(tail);holder.setAlignment(Pos.BOTTOM_CENTER);holder.setTranslateY(4);holder.setMouseTransparent(true); + if(user)row.getChildren().addAll(body,holder);else row.getChildren().addAll(holder,body); + }else row.getChildren().add(body); + setGraphic(row); + } + private Label label(String text){var label=new Label(text);label.setWrapText(true);return label;} + private void message(Conversation.Item item){ + boolean user=item.role()==Conversation.Role.USER; + body.getStyleClass().add(user?"conversation-user":"conversation-assistant"); + var header=new HBox(8);var who=label(user?context.text("conversation.user"):assistantName==null?context.text("conversation.assistant"):assistantName);who.getStyleClass().add("conversation-author"); + var spacer=new Region();HBox.setHgrow(spacer,Priority.ALWAYS);header.getChildren().addAll(who,spacer,copy(item.text())); + body.getChildren().add(header); + var sections=user?List.of(new ConversationMarkdown.Section(item.text(),false,"",List.of())):ConversationMarkdown.parse(item.text()); + for(var section:sections){ + if(section.code()){ + var codeHeader=new HBox(8,label(section.language()),copy(section.text()));codeHeader.setAlignment(Pos.CENTER_LEFT);body.getChildren().add(codeHeader); + } + addText(section,item.streaming()); + } + if(item.streaming()||user&&!item.state().equals("sent"))body.getChildren().add(label(state(item.state()))); + } + + private void tool(Conversation.Item item){ + body.getStyleClass().add("conversation-tool"); + var toggle=new ToggleButton();toggle.setWrapText(true);toggle.setMaxWidth(Double.MAX_VALUE); + toggle.setText((Boolean.TRUE.equals(view.expanded.get(item.id()))?"▾ ":"▸ ")+(item.title().isBlank()?context.text("conversation.tool"):item.title())+" · "+state(item.state())); + toggle.setSelected(Boolean.TRUE.equals(view.expanded.get(item.id())));body.getChildren().add(toggle); + if(toggle.isSelected()){ + if(item.input().isBlank()&&item.output().isBlank()&&item.text().isBlank())body.getChildren().add(label(context.text("conversation.noDetails"))); + else{ + detail("conversation.input",item.input());detail("conversation.output",item.output());detail("conversation.details",item.text()); + } + } + toggle.setOnAction(event->{rememberAnchor();view.expanded.put(item.id(),toggle.isSelected());shown=null;updateItem(item,false);if(view.following)followEnd();}); + } + private void detail(String title,String content){if(!content.isBlank()){body.getChildren().add(label(context.text(title)));addText(new ConversationMarkdown.Section(content,true,"",List.of()),false);}} + private void addText(ConversationMarkdown.Section section,boolean streaming){var text=new ConversationText(section,streaming,context,body.prefWidthProperty().subtract(32));texts.add(text);body.getChildren().add(text);} + private Button copy(String value){ + var button=new Button(context.text("conversation.copy"));button.setMinWidth(105*context.settings().scale());button.getStyleClass().add("conversation-copy"); + button.setOnAction(event->{var content=new ClipboardContent();content.putString(value);Clipboard.getSystemClipboard().setContent(content); + button.setText(context.text("conversation.copied"));var pause=new PauseTransition(Duration.seconds(1.2));feedback.add(pause); + pause.setOnFinished(done->{button.setText(context.text("conversation.copy"));feedback.remove(pause);});pause.play();}); + return button; + } + } + @Override public void close(){ + if(closed)return;closed=true;updates.stop();endPosition.stop();context.settingsProperty().removeListener(appearance); + cells.forEach(Cell::clearContent);states.clear();list.getItems().clear(); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java index 15255033..1724e921 100644 --- a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ComponentGallery.java @@ -30,6 +30,7 @@ public final class ComponentGallery extends VBox { reset.setOnAction(event -> { name.setText("Prometeu"); name.setError(false); feedback.show("feedback.reset",false); }); VBox samples = new VBox(18,new StudioText(context,"components.title").title(),buttons,MinimalShell.labeled(context,"field.name",name),feedback); StudioPanel panel = new StudioPanel(samples); panel.getStyleClass().add("specimen-panel"); getChildren().add(panel); + getChildren().add(new ConversationGallery(context)); getChildren().add(new StudioText(context,"fonts.title").title()); TextArea text = new TextArea(); text.setId("comparison-input"); text.setWrapText(true); text.setPrefRowCount(3); text.setMinWidth(0); boolean[] updating = {false}; diff --git a/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ConversationGallery.java b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ConversationGallery.java new file mode 100644 index 00000000..31b77010 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/main/java/p/studio/ui/javafx2/demo/ConversationGallery.java @@ -0,0 +1,51 @@ +package p.studio.ui.javafx2.demo; + +import javafx.animation.*; +import javafx.scene.layout.VBox; +import javafx.util.Duration; +import p.studio.ui.javafx2.appearance.AppearanceContext; +import p.studio.ui.javafx2.components.*; + +/** A deterministic, backend-free specimen of the same component used by the AI tab. */ +final class ConversationGallery extends VBox { + private final StudioConversation conversation; + private final AppearanceContext context; + private final Timeline timer; + private Conversation model; + private int frame, position; + private String introduction, continuation; + + ConversationGallery(AppearanceContext context) { + super(12);this.context=context; + conversation=new StudioConversation(context);conversation.setId("gallery-conversation"); + conversation.setPrefHeight(520);conversation.setMinHeight(320); + timer=new Timeline(new KeyFrame(Duration.millis(70),event->tick()));timer.setCycleCount(Animation.INDEFINITE); + var replay=new StudioButton(context,"conversation.demo",false);replay.setId("gallery-conversation-replay"); + replay.setOnAction(event->begin(true)); + getChildren().addAll(new StudioText(context,"conversation.gallery").title(),replay,conversation); + context.onClose(timer::stop);begin(false); + } + private void begin(boolean streaming){ + timer.stop();model=new Conversation();frame=0;position=0; + introduction=context.text("conversation.sample.intro");continuation=context.text("conversation.sample.after"); + model.begin(context.text("conversation.sample.user"));model.delivered();conversation.show(model); + if(streaming)timer.playFromStart(); + else{ + model.text(introduction);tool("failed",context.text("conversation.sample.failure")); + model.text(continuation);model.finish("done","");conversation.show(model); + } + } + private void tool(String state,String output){model.tool("checks",context.text("conversation.sample.tool"),"execute",state,"./gradlew test",output,null);} + private void tick(){ + if(frame==0){ + int end=Math.min(introduction.length(),position+8);model.text(introduction.substring(position,end));position=end; + if(position==introduction.length()){tool("pending",null);frame=1;} + }else if(frame<12){if(frame==2)tool("in_progress",null);frame++;} + else if(frame==12){tool("failed",context.text("conversation.sample.failure"));position=0;frame++;} + else{ + int end=Math.min(continuation.length(),position+8);model.text(continuation.substring(position,end));position=end; + if(position==continuation.length()){model.finish("done","");timer.stop();} + } + conversation.show(model); + } +} diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties index b8c48909..e8d5c861 100644 --- a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_en.properties @@ -146,6 +146,7 @@ ai.rename=Rename ai.delete=Delete ai.attach=Add assets ai.send=Send +ai.send.hint=Send (Alt+Enter). Enter inserts a new line. ai.settings.title=AI / ACP ai.settings.agent=Agent ai.settings.authentication=Authentication @@ -186,3 +187,38 @@ 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. + +# Structured conversation +conversation.title=Conversation +conversation.latest=Go to latest +conversation.limited=Some older or oversized content was omitted to keep this conversation responsive. +conversation.truncated=Content truncated. +conversation.tool=Agent action +conversation.copy=Copy +conversation.copied=Copied +conversation.noDetails=No details provided. +conversation.input=Input +conversation.output=Output +conversation.details=Details +conversation.state.sending=Sending… +conversation.state.sent=Sent +conversation.state.failed=Failed +conversation.state.cancelled=Cancelled +conversation.state.streaming=Writing… +conversation.state.pending=Pending +conversation.state.in_progress=Running +conversation.state.completed=Completed +conversation.state.interrupted=Interrupted · outcome unconfirmed +conversation.state.done=Done +conversation.state.error=Error +conversation.state.unknown=Unknown state +conversation.gallery=Conversation component +conversation.demo=Replay streaming example +conversation.user=You +conversation.assistant=AI +conversation.empty=Start a conversation by sending a message. +conversation.sample.user=Inspect the project and run the checks. +conversation.sample.intro=# Project inspection\n\nI found the **source** and the *configuration*.\n\n- Read the project\n- Run the checks\n\n```pbs\nprint("Hello, Prometeu!");\n``` +conversation.sample.tool=Run project checks +conversation.sample.failure=The fixture found a missing configuration value. +conversation.sample.after=The check reported a configuration issue. The details above explain what needs to be adjusted. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties index be665aad..070a35ff 100644 --- a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/i18n/messages_pt_BR.properties @@ -146,6 +146,7 @@ ai.rename=Renomear ai.delete=Apagar ai.attach=Adicionar assets ai.send=Enviar +ai.send.hint=Enviar (Alt+Enter). Enter insere uma nova linha. ai.settings.title=IA / ACP ai.settings.agent=Agente ai.settings.authentication=Autenticação @@ -186,3 +187,38 @@ 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. + +# Structured conversation +conversation.title=Conversa +conversation.latest=Ir para o fim +conversation.limited=Parte do conteúdo antigo ou extenso foi omitida para manter a conversa responsiva. +conversation.truncated=Conteúdo truncado. +conversation.tool=Ação do agente +conversation.copy=Copiar +conversation.copied=Copiado +conversation.noDetails=Nenhum detalhe fornecido. +conversation.input=Entrada +conversation.output=Saída +conversation.details=Detalhes +conversation.state.sending=Enviando… +conversation.state.sent=Enviado +conversation.state.failed=Falhou +conversation.state.cancelled=Cancelado +conversation.state.streaming=Escrevendo… +conversation.state.pending=Pendente +conversation.state.in_progress=Executando +conversation.state.completed=Concluído +conversation.state.interrupted=Interrompido · resultado não confirmado +conversation.state.done=Concluído +conversation.state.error=Erro +conversation.state.unknown=Estado desconhecido +conversation.gallery=Componente de conversa +conversation.demo=Repetir exemplo de streaming +conversation.user=Você +conversation.assistant=IA +conversation.empty=Inicie a conversa enviando uma mensagem. +conversation.sample.user=Inspecione o projeto e execute as verificações. +conversation.sample.intro=# Inspeção do projeto\n\nEncontrei o **código** e a *configuração*.\n\n- Ler o projeto\n- Executar as verificações\n\n```pbs\nprint("Olá, Prometeu!");\n``` +conversation.sample.tool=Executar verificações do projeto +conversation.sample.failure=O exemplo encontrou um valor ausente na configuração. +conversation.sample.after=A verificação apontou um problema na configuração. Os detalhes acima explicam o que precisa ser ajustado. diff --git a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css index 59a03bd5..82a043e9 100644 --- a/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css +++ b/prometeu-studio-ui-javafx-2/src/main/resources/p/studio/ui/javafx2/styles/components.css @@ -133,3 +133,36 @@ .studio-tabs:focused > .tab-header-area > .headers-region > .tab:selected .focus-indicator { -fx-border-color: -studio-focus; -fx-border-width: 1; -fx-border-insets: 0; -fx-border-radius: 0; } + +/* Structured conversation: custom cells never use row selection as text selection. */ +.studio-conversation { -fx-background-color: -studio-workspace; } +.conversation-list { -fx-background-color: transparent; -fx-padding: 4; } +.conversation-list .list-cell, .conversation-list .list-cell:filled:selected, +.conversation-list .list-cell:filled:hover { -fx-background-color: transparent; -fx-padding: 8 10; } +.conversation-list .list-cell:empty { -fx-padding: 0; } +.conversation-body { -fx-padding: 12 16; -fx-background-radius: 14; -fx-border-radius: 14; -fx-border-width: 1; -fx-border-color: -studio-border; } +.conversation-user { -fx-background-color: -studio-surface; } +.conversation-assistant { -fx-background-color: -studio-field; } +.conversation-tail-user { -fx-fill: -studio-surface; -fx-stroke: -studio-border; } +.conversation-tail-assistant { -fx-fill: -studio-field; -fx-stroke: -studio-border; } +.conversation-author { -fx-font-weight: bold; -fx-text-fill: -studio-heading; } +.conversation-copy { -fx-padding: 3 8; -fx-font-size: .85em; } +.conversation-tool { -fx-background-color: -studio-surface; -fx-background-radius: 4; -fx-border-radius: 4; -fx-padding: 8 12; } +.conversation-tool .toggle-button { -fx-alignment: center-left; -fx-background-color: transparent; -fx-border-width: 0; -fx-padding: 4; } +.conversation-result { -fx-padding: 4 8; -fx-border-width: 0; } +.conversation-result .label, .conversation-notice { -fx-text-fill: -studio-muted; -fx-font-size: .85em; } +.conversation-notice, .conversation-footer { -fx-padding: 6 12; } +.conversation-text { -fx-background-color: transparent; -fx-padding: 0; } +.conversation-text .text { -fx-fill: -studio-text; } +.conversation-text .selection { -fx-fill: -studio-focus; -fx-opacity: .45; } +.conversation-code { -fx-background-color: -studio-background; -fx-padding: 4; } +.conversation-bold { -fx-font-weight: bold; } +.conversation-italic { -fx-font-style: italic; } +.conversation-heading-1 { -fx-font-size: 1.35em; -fx-font-weight: bold; } +.conversation-heading-2 { -fx-font-size: 1.2em; -fx-font-weight: bold; } +.conversation-heading-3 { -fx-font-size: 1.1em; -fx-font-weight: bold; } +.conversation-link { -fx-underline: true; } +.conversation-inline-code { -fx-font-weight: bold; } + +.conversation-text .paragraph-box { -fx-padding: 0; } +.conversation-text .paragraph-text { -fx-line-spacing: 0; } diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java index 4095e229..cd14d771 100644 --- a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/FoundationDesktopTest.java @@ -98,6 +98,12 @@ class FoundationDesktopTest { }); fx(() -> {((ScrollPane)window.stage.getScene().getRoot()).setVvalue(1);return null;}); capture(window,"fonts-and-licenses"); + fx(()->{((Button)window.stage.getScene().lookup("#gallery-conversation-replay")).fire();return null;}); + settleFrames(); + fx(()->{ + var conversation=(StudioConversation)window.stage.getScene().lookup("#gallery-conversation"); + assertTrue(conversation.conversation().items().stream().anyMatch(Conversation.Item::streaming));return null; + }); } finally { fx(() -> {window.stage.close();assertTrue(window.context.isClosed());return null;}); } for(int i=0;i<3;i++) { Window reopened=fx(() -> open(false)); @@ -110,6 +116,82 @@ class FoundationDesktopTest { fx(() -> {assertTrue(reopened.shell.workspace().getChildren().isEmpty());reopened.stage.close();assertTrue(reopened.context.isClosed());assertThrows(IllegalStateException.class,() -> reopened.context.update(reopened.context.settings().withTheme(Theme.LIGHT)));return null;}); } } + @Test void conversationComponentMarkdownCopyStreamingScrollAndAppearance() throws Exception { + var context=fx(()->new AppearanceContext(PresentationSettings.defaults(Locale.ENGLISH),messages,fonts,value->{})); + var model=new Conversation();model.begin("Please inspect the project");model.delivered(); + String answer="# Inspection\n\nA **formatted** response with a list:\n\n- source\n- configuration\n\n```java\nSystem.out.println(123); // a long line that should scroll inside its code block rather than widen the whole conversation\n```"; + model.text(answer);model.tool("test","Run checks","execute","pending","./gradlew test",null,null); + model.tool("test",null,null,"failed",null,"One check failed",null);model.text("I will explain the failure."); + var component=fx(()->new StudioConversation(context)); + var window=fx(()->{var stage=new Stage();context.attach(component);stage.setScene(new Scene(component,900,760));stage.setOnHidden(e->context.close());stage.show();component.show(model);return new Window(stage,context,null,null);}); + try { + settleFrames(); + fx(()->{ + component.list().scrollTo(0);component.applyCss();component.layout(); + var bubble=component.lookup("#conversation-item-2");assertNotNull(bubble); + var copy=(Button)bubble.lookup(".conversation-copy");copy.fire(); + assertEquals(answer,javafx.scene.input.Clipboard.getSystemClipboard().getString()); + assertEquals("Copied",copy.getText()); + var areas=bubble.lookupAll(".conversation-text").stream().filter(n->n instanceof org.fxmisc.richtext.StyleClassedTextArea) + .map(n->(org.fxmisc.richtext.StyleClassedTextArea)n).toList(); + assertFalse(areas.isEmpty());var area=areas.getFirst();assertFalse(area.isEditable()); + area.selectRange(0,10);area.copy();assertEquals(area.getText().substring(0,10),javafx.scene.input.Clipboard.getSystemClipboard().getString()); + assertTrue(areas.stream().anyMatch(a->!a.isWrapText())); + return null; + }); + for(Theme theme:Theme.values())for(StudioLanguage language:StudioLanguage.values()){ + fx(()->{context.update(context.settings().withTheme(theme).withLanguage(language));component.followEnd();return null;}); + capture(window,"conversation-"+theme+"-"+language); + } + fx(()->{ + component.followEnd();component.applyCss();component.layout(); + var active=component.lookup("#conversation-item-4");assertNotNull(active); + assertTrue(active.lookupAll(".conversation-text").stream().filter(n->n instanceof org.fxmisc.richtext.StyleClassedTextArea).noneMatch(Node::isFocusTraversable)); + var tool=component.lookup("#conversation-item-3");assertNotNull(tool);assertTrue(((ToggleButton)tool.lookup(".toggle-button")).isSelected()); + ((ToggleButton)tool.lookup(".toggle-button")).fire(); + model.tool("test",null,null,"failed",null,"Updated diagnostic",null);model.text(" More detail.\n"+"Streaming line\n".repeat(80));component.show(model);return null; + }); + settleFrames(); + fx(()->{ + component.list().scrollTo(0);component.applyCss();component.layout(); + javafx.event.Event.fireEvent(component.list(),new javafx.scene.input.ScrollEvent(javafx.scene.input.ScrollEvent.SCROLL, + 0,0,0,0,false,false,false,false,false,false,0,40,0,40, + javafx.scene.input.ScrollEvent.HorizontalTextScrollUnits.NONE,0,javafx.scene.input.ScrollEvent.VerticalTextScrollUnits.NONE,0,0,null)); + model.text("still arriving");component.show(model);return null; + }); + settleFrames(); + fx(()->{ + assertFalse(component.following());assertTrue(component.getBottom().isVisible()); + var other=new Conversation();other.begin("Another chat");other.delivered();other.text("Other response");other.finish("done", ""); + component.show(other);assertTrue(component.following());component.show(model);assertFalse(component.following()); + return null; + }); + settleFrames(); + fx(()->{ + var flow=(javafx.scene.control.skin.VirtualFlow)component.list().lookup(".virtual-flow"); + assertEquals(0,flow.getFirstVisibleCell().getIndex(),"Changing chats must restore the reading anchor"); + component.followEnd();assertTrue(component.following());model.finish("done", "");component.show(model);return null; + }); + settleFrames(); + fx(()->{context.update(context.settings().withScale(1.5));window.stage.setWidth(560);window.stage.setHeight(650);component.followEnd();return null;}); + capture(window,"conversation-narrow-large-text"); + fx(()->{ + assertTrue(component.list().getWidth()<=component.getWidth()+1); + var horizontal=component.list().lookupAll(".scroll-bar").stream().filter(n->n instanceof ScrollBar bar&&bar.getOrientation()==javafx.geometry.Orientation.HORIZONTAL).map(n->(ScrollBar)n).findFirst().orElseThrow(); + assertFalse(horizontal.isVisible(),"The conversation must not scroll horizontally"); + var flow=(javafx.scene.control.skin.VirtualFlow)component.list().lookup(".virtual-flow"); + var last=flow.getLastVisibleCell(); + assertEquals(component.list().getItems().size()-1,last.getIndex(),"Follow mode must reveal the last item"); + assertTrue(last.getBoundsInParent().getMaxY()<=flow.getHeight()+2,"Follow mode must reach the bottom of the last item"); + assertTrue(component.list().getItems().stream().noneMatch(Conversation.Item::streaming)); + for(var node:component.lookupAll(".conversation-text"))if(node instanceof org.fxmisc.richtext.StyleClassedTextArea area&&area.getText().contains("still arriving")){ + var bounds=area.getParagraphBoundsOnScreen(area.getParagraphs().size()-1).orElseThrow(); + assertTrue(bounds.getMaxY()<=area.localToScreen(area.getBoundsInLocal()).getMaxY()+2,"Last line must not be clipped inside the bubble"); + } + component.show(new Conversation());assertTrue(component.list().getItems().isEmpty());component.show(model);return null; + }); + } finally {fx(()->{window.stage.close();return null;});} + } private static Window open(boolean gallery) { var context=new AppearanceContext(PresentationSettings.defaults(Locale.ENGLISH),messages,fonts,value -> { }); var shell=new MinimalShell(context); ComponentGallery specimens=gallery?new ComponentGallery(context):null; @@ -141,7 +223,7 @@ class FoundationDesktopTest { } private static void settleFrames() throws Exception { CountDownLatch settled=new CountDownLatch(1); - fx(() -> {new AnimationTimer(){int count;@Override public void handle(long now){if(++count==3){stop();settled.countDown();}}}.start();return null;}); + fx(() -> {new AnimationTimer(){int count;@Override public void handle(long now){if(++count==10){stop();settled.countDown();}}}.start();return null;}); assertTrue(settled.await(5,TimeUnit.SECONDS),"JavaFX pulses did not settle"); } private static T fx(Callable task) throws Exception { diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/ai/AgentChatsTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/ai/AgentChatsTest.java index 25b9c990..f9761a52 100644 --- a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/ai/AgentChatsTest.java +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/ai/AgentChatsTest.java @@ -26,19 +26,21 @@ class AgentChatsTest { } private AgentChats model(LocalChats drafts,Agent agent){return new AgentChats(drafts,agent,Runnable::run,()->{},drafts::select,key->key);} + private static String log(AgentChats model,long id){return model.conversation(id).items().stream().map(p.studio.ui.javafx2.components.Conversation.Item::text).reduce("",String::concat);} + @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")); + assertTrue(log(m,b.id()).contains("answer B"));assertFalse(log(m,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")); + assertEquals("first",drafts.draft());assertTrue(log(m,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())); @@ -58,7 +60,7 @@ class AgentChatsTest { 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 b=drafts.create();drafts.write("new");assertTrue(m.canSend(b.id()));assertFalse(log(m,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())); } diff --git a/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/components/ConversationMarkdownTest.java b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/components/ConversationMarkdownTest.java new file mode 100644 index 00000000..4117bd08 --- /dev/null +++ b/prometeu-studio-ui-javafx-2/src/test/java/p/studio/ui/javafx2/components/ConversationMarkdownTest.java @@ -0,0 +1,20 @@ +package p.studio.ui.javafx2.components; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class ConversationMarkdownTest { + @Test void markdownProducesStyledProseAndLiteralCodeWithoutHtmlExecution() { + var sections = ConversationMarkdown.parse("# Title\n\n**bold** and *italic* [guide](https://example.org)\n\n1. first\n2. second\n\n```java\nreturn 1;\n```\n\n"); + assertEquals(3,sections.size()); + assertTrue(sections.getFirst().text().contains("1. first")); + assertTrue(sections.getFirst().spans().stream().anyMatch(s->s.styles().contains("conversation-bold"))); + assertTrue(sections.getFirst().text().contains("guide (https://example.org)")); + assertTrue(sections.get(1).code());assertEquals("return 1;\n",sections.get(1).text()); + assertEquals("java",sections.get(1).language());assertTrue(sections.getLast().text().contains("