From 3bf24f1e3155c5e6d8e2f46f1ba3823fb88517d8 Mon Sep 17 00:00:00 2001 From: Aref Behboudi Date: Wed, 25 Nov 2026 21:46:57 +0200 Subject: [PATCH 1/5] Add multiple chat sessions with titles A conversation (the web chat, a Telegram chat, a Discord channel, ...) can now have several sessions; the one that became active last is the active one. ChatSessions keeps everything about a session in its Spring AI session metadata: its conversation key, its title and when it last became active. Sessions from before keep working as their conversation's session under their old fixed id, and are tagged with their conversation the first time it changes. /new [name] in the web chat and every messaging channel starts a new session without reaching the model. After an exchange, the main model titles an untitled session in the background; after three attempts without a topic, or when the call fails, the first line of the first message is the title. Titles are unique per conversation and a title set by the user is never replaced. The web chat gets a sidebar with the chats, a search field and the other channels' conversations, and a header with the chat's title and a rename button. --- README.md | 10 + app/build.gradle | 2 + .../java/ai/javaclaw/chat/ChatChannel.java | 181 +++++++- .../main/java/ai/javaclaw/chat/ChatHtml.java | 108 ++++- .../chat/ws/ChatWebSocketHandler.java | 51 +- app/src/main/resources/static/chat/chat.css | 205 ++++++++- app/src/main/resources/static/chat/chat.js | 54 ++- .../main/resources/templates/chat.html.peb | 90 ++-- .../ai/javaclaw/JavaClawApplicationTests.java | 6 +- .../ai/javaclaw/chat/ChatChannelTest.java | 193 ++++++-- .../java/ai/javaclaw/chat/ChatHtmlTest.java | 55 ++- .../chat/ChatMarkdownBrowserTest.java | 225 +++++++-- .../javaclaw/chat/InMemoryChatSessions.java | 42 ++ .../chat/ws/ChatStreamingIntegrationTest.java | 14 +- .../chat/ws/ChatWebSocketHandlerTest.java | 85 ++-- .../java/ai/javaclaw/agent/AgentRequest.java | 15 +- .../java/ai/javaclaw/agent/ChatCommands.java | 70 +++ .../java/ai/javaclaw/agent/ChatHistory.java | 51 +- .../java/ai/javaclaw/agent/ChatSessions.java | 434 ++++++++++++++++++ .../ai/javaclaw/agent/ConversationKey.java | 128 ++++++ .../java/ai/javaclaw/agent/DefaultAgent.java | 47 +- .../java/ai/javaclaw/agent/SessionTitles.java | 217 +++++++++ .../session/SessionStoreConfiguration.java | 11 +- .../java/ai/javaclaw/tasks/TaskHandler.java | 58 +-- .../ai/javaclaw/agent/ChatCommandsTest.java | 73 +++ .../ai/javaclaw/agent/ChatHistoryTest.java | 27 +- .../ai/javaclaw/agent/ChatSessionsTest.java | 288 ++++++++++++ .../javaclaw/agent/ConversationKeyTest.java | 104 +++++ .../ai/javaclaw/agent/DefaultAgentTest.java | 43 +- .../agent/DefaultAgentToolLoopTest.java | 9 +- .../ai/javaclaw/agent/SessionTitlesTest.java | 270 +++++++++++ .../ai/javaclaw/agent/TestSessionStore.java | 65 +++ .../SessionStoreConfigurationTest.java | 29 +- .../ai/javaclaw/tasks/TaskHandlerTest.java | 85 +--- .../ai/javaclaw/tasks/TaskManagerTest.java | 5 +- .../channels/discord/DiscordChannel.java | 14 +- .../DiscordChannelAutoConfiguration.java | 4 +- .../channels/discord/DiscordChannelTest.java | 23 +- .../teams/TeamsWebhookController.java | 18 +- .../teams/TeamsWebhookControllerTest.java | 41 +- .../channels/telegram/TelegramChannel.java | 33 +- .../TelegramChannelAutoConfiguration.java | 4 +- .../telegram/TelegramChannelTest.java | 58 ++- .../channels/whatsapp/WhatsAppChannel.java | 10 +- .../WhatsAppChannelAutoConfiguration.java | 6 +- .../whatsapp/WhatsAppChannelTest.java | 26 +- .../java/ai/javaclaw/chat/ui/ChatView.java | 36 +- .../ai/javaclaw/chat/ui/ChatViewTest.java | 56 ++- 48 files changed, 3077 insertions(+), 602 deletions(-) create mode 100644 app/src/test/java/ai/javaclaw/chat/InMemoryChatSessions.java create mode 100644 base/src/main/java/ai/javaclaw/agent/ChatCommands.java create mode 100644 base/src/main/java/ai/javaclaw/agent/ChatSessions.java create mode 100644 base/src/main/java/ai/javaclaw/agent/ConversationKey.java create mode 100644 base/src/main/java/ai/javaclaw/agent/SessionTitles.java create mode 100644 base/src/test/java/ai/javaclaw/agent/ChatCommandsTest.java create mode 100644 base/src/test/java/ai/javaclaw/agent/ChatSessionsTest.java create mode 100644 base/src/test/java/ai/javaclaw/agent/ConversationKeyTest.java create mode 100644 base/src/test/java/ai/javaclaw/agent/SessionTitlesTest.java create mode 100644 base/src/test/java/ai/javaclaw/agent/TestSessionStore.java diff --git a/README.md b/README.md index f05f070f..e24caa0a 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,16 @@ The `workspace/` directory is the agent's home: Available at [http://localhost:8080/chat](http://localhost:8080/chat). Uses WebSocket for real-time delivery and falls back to REST polling when no WebSocket session is active. +### Chats, titles and `/new` + +Every conversation (the web chat, a Telegram chat, a Discord channel, …) can have several chats; the one you used last is the active one, and new messages go there. + +- **New chat**: type `/new` in any channel, optionally followed by a name (`/new Trip to Lisbon`; on Telegram also `/new@yourbot`). It starts a fresh chat and keeps the old one. The command itself never reaches the model. +- **Titles**: after the first exchange, the model gives the chat a short title in the background. If that fails, the first line of your first message becomes the title. Titles in a conversation are unique: a duplicate becomes `Title #2`. +- **Web chat**: the sidebar lists your web chats (latest first) with a search field, and the other channels' conversations below them, read-only. Click a chat to switch to it, or use the pencil in the header to rename it. + +Chats from before this feature keep working as each conversation's first chat. + ### Telegram Configure during onboarding or by setting: diff --git a/app/build.gradle b/app/build.gradle index e70be469..cc42e74c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -46,6 +46,8 @@ dependencies { runtimeOnly 'com.h2database:h2' testImplementation 'org.springframework.boot:spring-boot-starter-test' + // The chat tests run ChatSessions on Spring AI's in-memory session store + testImplementation 'org.springframework.ai:spring-ai-session' testImplementation 'org.springframework.boot:spring-boot-starter-data-jdbc-test' testImplementation 'org.springframework.boot:spring-boot-starter-restclient-test' testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test' diff --git a/app/src/main/java/ai/javaclaw/chat/ChatChannel.java b/app/src/main/java/ai/javaclaw/chat/ChatChannel.java index 964dfcf9..7fba5a63 100644 --- a/app/src/main/java/ai/javaclaw/chat/ChatChannel.java +++ b/app/src/main/java/ai/javaclaw/chat/ChatChannel.java @@ -3,8 +3,13 @@ import ai.javaclaw.agent.Agent; import ai.javaclaw.agent.AgentEvent; import ai.javaclaw.agent.AgentRequest; +import ai.javaclaw.agent.ChatCommands; import ai.javaclaw.agent.ChatHistory; +import ai.javaclaw.agent.ChatSessions; +import ai.javaclaw.agent.ConversationKey; import ai.javaclaw.agent.SessionChannel; +import ai.javaclaw.agent.SessionKind; +import ai.javaclaw.agent.SessionTitles; import ai.javaclaw.channels.Channel; import ai.javaclaw.channels.ChannelMessageReceivedEvent; import ai.javaclaw.channels.ChannelRegistry; @@ -12,6 +17,7 @@ import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.core.Ordered; +import org.springframework.context.event.EventListener; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; @@ -25,6 +31,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicReference; @@ -32,6 +39,10 @@ * GUI channel for the web chat interface. * Pushes messages directly to the active WebSocket session when connected, * falling back to an in-memory queue for REST polling. + * + *

The page shows one session at a time: the web conversation's active session, which it can + * continue, or another channel's conversation, read-only. Every view sends the header, the sidebar, + * the messages and the composer together. */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) @@ -42,17 +53,31 @@ public class ChatChannel implements Channel { /** The longest tool output a history message carries; live tool results are not cut. */ static final int MAX_HISTORY_TOOL_OUTPUT = 20_000; + /** The web chat's conversation, shared with the Vaadin chat at {@code /ui}. */ + static final ConversationKey WEB = ConversationKey.web(); + + /** Shown in a session without messages. */ + static final String WELCOME = "Hi! I'm your JavaClaw assistant. How can I help you today?"; private final Agent agent; private final ChannelRegistry channelRegistry; + private final ChatSessions chatSessions; + private final ChatCommands chatCommands; private final ChatHistory chatHistory; private final ObjectMapper objectMapper; private final ConcurrentLinkedQueue pendingMessages = new ConcurrentLinkedQueue<>(); private final AtomicReference wsSession = new AtomicReference<>(); + /** The other channel's session the page shows read-only; null while it shows the web chat. */ + private final AtomicReference shownChannelSession = new AtomicReference<>(); + /** A WebSocket session takes one message at a time; streaming, titles and tasks all send. */ + private final Object sendLock = new Object(); - public ChatChannel(Agent agent, ChannelRegistry channelRegistry, ChatHistory chatHistory, ObjectMapper objectMapper) { + public ChatChannel(Agent agent, ChannelRegistry channelRegistry, ChatSessions chatSessions, + ChatCommands chatCommands, ChatHistory chatHistory, ObjectMapper objectMapper) { this.agent = agent; this.channelRegistry = channelRegistry; + this.chatSessions = chatSessions; + this.chatCommands = chatCommands; this.chatHistory = chatHistory; this.objectMapper = objectMapper; channelRegistry.registerChannel(this); @@ -84,8 +109,10 @@ public void clearWsSession(WebSocketSession session) { */ public void sendHtml(String... html) throws IOException { WebSocketSession session = wsSession.get(); - if (session != null && session.isOpen()) { - session.sendMessage(new TextMessage(String.join(System.lineSeparator(), html))); + synchronized (sendLock) { + if (session != null && session.isOpen()) { + session.sendMessage(new TextMessage(String.join(System.lineSeparator(), html))); + } } } @@ -115,30 +142,134 @@ public void flushPendingMessages() { } } + // --- Views --------------------------------------------------------------------------------- + /** - * Returns all known conversation IDs, always with "web" first. + * Shows the web conversation's active session, which the page continues. + * + * @param notices agent messages shown below the history that are not part of it, such as the + * reply to a command */ - public List conversationIds() { - List result = new ArrayList<>(); - result.add("web"); - chatHistory.conversationIds().stream() - .filter(id -> !id.equals("web")) - .forEach(result::add); - return result; + public void showWebChat(String... notices) throws IOException { + shownChannelSession.set(null); + String sessionId = webSession(); + List bubbles = new ArrayList<>(notices.length == 0 ? loadHistoryAsHtml(sessionId) : history(sessionId)); + for (String notice : notices) { + bubbles.add(ChatHtml.agentBubble(notice, Instant.now())); + } + ChatSessions.Summary session = webSessionSummary(sessionId); + sendView(ChatHtml.chatHeader(session, true), sessionId, bubbles, ChatHtml.chatInputArea(true, null)); + } + + /** Shows another channel's conversation, read-only, by the id of its active session. */ + public void showChannel(String sessionId) throws IOException { + ChatSessions.Summary session = chatSessions.summary(sessionId); + shownChannelSession.set(sessionId); + String label = ChatHtml.channelLabel(session.channel()) + " · " + session.title(); + sendView(ChatHtml.chatHeader(session, false), sessionId, loadHistoryAsHtml(sessionId), + ChatHtml.chatInputArea(false, label)); + } + + /** Starts a new web chat session and shows it. */ + public void newChat() throws IOException { + chatSessions.create(WEB, SessionKind.CHAT, SessionChannel.WEB, null); + showWebChat(); } /** - * Loads conversation history for the given conversationId as HTML messages, one turn at a time: - * the user message, then one agent message with the turn's tool calls and all its text, the way - * a live answer looks. Returns a single welcome bubble if no history exists yet. + * Makes an earlier web chat session active and shows it. + * + * @throws IllegalArgumentException if it is not a web chat session */ - public List loadHistoryAsHtml(String conversationId) { - List turns = chatHistory.turns(conversationId); - if (turns.isEmpty()) { - return List.of(ChatHtml.agentBubble("Hi! I'm your JavaClaw assistant. How can I help you today?", null)); + public void switchTo(String sessionId) throws IOException { + chatSessions.switchTo(WEB, sessionId); + showWebChat(); + } + + /** + * Renames a web chat session; the header and the sidebar follow. + * + * @throws IllegalArgumentException if the title is blank or it is not a web chat session + */ + public void rename(String sessionId, String title) throws IOException { + chatSessions.rename(WEB, sessionId, title); + refreshTitles(); + } + + /** + * Runs a chat command ({@link ChatCommands}) typed in the web chat, and shows the result. + * + * @return whether {@code message} was a command; if not, it is for the agent + */ + public boolean runCommand(String message) throws IOException { + Optional reply = chatCommands.handle(WEB, SessionChannel.WEB, message); + if (reply.isEmpty()) { + return false; + } + showWebChat(reply.get()); + return true; + } + + /** A session got its title in the background: the sidebar and the header show it. */ + @EventListener + void onSessionTitled(SessionTitles.SessionTitled event) { + try { + refreshTitles(); + } catch (IOException | RuntimeException e) { + log.warn("Could not show the new title of session {}: {}", event.sessionId(), e.getMessage()); } + } + + /** Sends the header and the sidebar of what the page shows, leaving the messages alone. */ + private void refreshTitles() throws IOException { + if (wsSession.get() == null) { + return; + } + String channelSession = shownChannelSession.get(); + String shownId = channelSession == null ? webSession() : channelSession; + String header = channelSession == null + ? ChatHtml.chatHeader(webSessionSummary(shownId), true) + : ChatHtml.chatHeader(chatSessions.summary(channelSession), false); + sendHtml(Htmx.oobInnerHtml("chat-header", header), Htmx.oobInnerHtml("chat-sessions", sessionLists(shownId))); + } + + private void sendView(String header, String shownId, List bubbles, String inputArea) throws IOException { + sendHtml( + Htmx.oobInnerHtml("chat-header", header), + Htmx.oobInnerHtml("chat-sessions", sessionLists(shownId)), + Htmx.oobInnerHtml("chat-messages", String.join(System.lineSeparator(), bubbles)), + Htmx.oobReplace("typing-indicator", ""), + Htmx.oobInnerHtml("chat-input-area", inputArea)); + } + + private String sessionLists(String shownId) { + return ChatHtml.sessionLists(chatSessions.list(WEB), chatSessions.otherConversations(WEB), shownId); + } + + private String webSession() { + return chatSessions.active(WEB, SessionKind.CHAT, SessionChannel.WEB); + } + + private ChatSessions.Summary webSessionSummary(String sessionId) { + return chatSessions.list(WEB).stream() + .filter(session -> session.id().equals(sessionId)) + .findFirst() + .orElseGet(() -> chatSessions.summary(sessionId)); + } + + /** + * Loads a session's history as HTML messages, one turn at a time: the user message, then one + * agent message with the turn's tool calls and all its text, the way a live answer looks. + * Returns a single welcome bubble if the session has no messages yet. + */ + public List loadHistoryAsHtml(String sessionId) { + List bubbles = history(sessionId); + return bubbles.isEmpty() ? List.of(ChatHtml.agentBubble(WELCOME, null)) : bubbles; + } + + private List history(String sessionId) { List bubbles = new ArrayList<>(); - for (ChatHistory.Turn turn : turns) { + for (ChatHistory.Turn turn : chatHistory.turns(sessionId)) { if (turn.question() != null) { bubbles.add(ChatHtml.userBubble(turn.question(), turn.askedAt())); } @@ -180,15 +311,16 @@ private String toolsJson(List toolCalls) { } /** - * Handles a chat message from the web UI for the given conversationId. + * Handles a chat message from the web UI: it goes to the web conversation's active session. * The response is streamed to the WebSocket session as JSON frames * ({@code chunk}/{@code toolCall}/{@code toolResult}/{@code done}/{@code error}), each with the * time it was sent; the page shows the first frame's time as the time of the answer. */ - public void chat(String conversationId, String message) { + public void chat(String message) { channelRegistry.publishMessageReceivedEvent(new ChannelMessageReceivedEvent(getName(), message)); - agent.respondTo(AgentRequest.chat(conversationId, SessionChannel.WEB, message), event -> sendFrame(switch (event) { + String conversationId = WEB.value(); + agent.respondTo(AgentRequest.chat(WEB, SessionChannel.WEB, message), event -> sendFrame(switch (event) { case AgentEvent.Token t -> frame(StreamFrameType.CHUNK, conversationId, t.text()); case AgentEvent.ToolCall c -> frame(StreamFrameType.TOOL_CALL, conversationId, toolData(c.id(), c.name(), "input", c.input())); @@ -221,7 +353,10 @@ private void sendFrame(Map frame) { WebSocketSession session = wsSession.get(); if (session == null || !session.isOpen()) return; try { - session.sendMessage(new TextMessage(objectMapper.writeValueAsString(frame))); + String json = objectMapper.writeValueAsString(frame); + synchronized (sendLock) { + session.sendMessage(new TextMessage(json)); + } } catch (IOException e) { log.warn("WS push failed, dropping stream frame: {}", e.getMessage()); } diff --git a/app/src/main/java/ai/javaclaw/chat/ChatHtml.java b/app/src/main/java/ai/javaclaw/chat/ChatHtml.java index d355f405..9d285849 100644 --- a/app/src/main/java/ai/javaclaw/chat/ChatHtml.java +++ b/app/src/main/java/ai/javaclaw/chat/ChatHtml.java @@ -1,5 +1,7 @@ package ai.javaclaw.chat; +import ai.javaclaw.agent.ChatSessions; +import ai.javaclaw.agent.SessionChannel; import org.springframework.web.util.HtmlUtils; import java.time.Instant; @@ -64,11 +66,12 @@ public static String typingDots() { """.formatted(agentHead(null)); } - public static String chatInputArea(String conversationId) { - if ("web".equals(conversationId)) { + /** The composer for the web chat; a read-only notice for another channel's conversation. */ + public static String chatInputArea(boolean writable, String label) { + if (writable) { return """

+ hx-vals='{"type": "userMessage"}'> - -
- - + + {# Markup the streaming script clones; it fills in text with textContent only. #}