diff --git a/README.md b/README.md index f05f070f..ec9f25b5 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,14 @@ 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. + ### Telegram Configure during onboarding or by setting: diff --git a/app/build.gradle b/app/build.gradle index e70be469..ca599ba9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -46,11 +46,14 @@ 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' testImplementation 'org.springframework.boot:spring-boot-starter-websocket-test' testImplementation 'org.springframework.boot:spring-boot-testcontainers' + testImplementation 'org.awaitility:awaitility' testImplementation 'org.testcontainers:testcontainers-junit-jupiter' testImplementation libs.spring.modulith.starter.test testImplementation libs.archunit.junit5 diff --git a/app/src/main/java/ai/javaclaw/chat/ChatChannel.java b/app/src/main/java/ai/javaclaw/chat/ChatChannel.java index 964dfcf9..a2640864 100644 --- a/app/src/main/java/ai/javaclaw/chat/ChatChannel.java +++ b/app/src/main/java/ai/javaclaw/chat/ChatChannel.java @@ -3,19 +3,26 @@ 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.event.EventListener; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.util.HtmlUtils; import tools.jackson.databind.ObjectMapper; import java.io.IOException; @@ -25,13 +32,21 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicReference; /** - * 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. + * GUI channel for the web chat interface, in any number of browser tabs. + * + *

Each tab (WebSocket session) shows one chat session of its own: a session of the web + * conversation, which it continues, or another channel's conversation, read-only. A new tab opens + * the web conversation's active session. Every view sends the header, the sidebar, the messages + * and the composer together, and marks the messages with the shown session's id. + * + *

An answer is streamed as JSON frames that carry the session id of the turn and go only to the + * tabs showing that session. Background messages go to every tab, or are buffered for REST polling + * while no tab is open. */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) @@ -42,69 +57,114 @@ 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<>(); + /** Every open tab, by its WebSocket session's id. */ + private final Map tabs = new ConcurrentHashMap<>(); - 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); log.info("Started Web Chat channel"); } + /** + * One browser tab: its WebSocket session and the chat session it shows. + * + * @param sessionId the shown chat session; null until the first view is sent + * @param readOnly whether that is another channel's conversation + */ + private record Tab(WebSocketSession socket, String sessionId, boolean readOnly) { + + Tab showing(String sessionId, boolean readOnly) { + return new Tab(socket, sessionId, readOnly); + } + } + @Override public String getName() { return "Web Chat Channel"; } - /** - * Called by the WebSocket handler when a client connects. - */ - public void setWsSession(WebSocketSession session) { - wsSession.set(session); + // --- Tabs ---------------------------------------------------------------------------------- + + /** A tab connected: it shows the web conversation's active session. */ + public void open(WebSocketSession socket) throws IOException { + tabs.put(socket.getId(), new Tab(socket, null, false)); + showWebSession(socket, activeWebSession()); + flushPendingMessages(); } - /** - * Called by the WebSocket handler when the client disconnects. - */ - public void clearWsSession(WebSocketSession session) { - wsSession.compareAndSet(session, null); + /** A tab disconnected. */ + public void close(WebSocketSession socket) { + tabs.remove(socket.getId()); } - /** - * Sends a raw HTML fragment to the active WebSocket session. - * Used by the WebSocket handler to push user/agent bubbles and typing indicators. - */ - 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))); + /** Whether the session is one of the web conversation's, which a tab may continue. */ + public boolean isWebSession(String sessionId) { + return chatSessions.isSessionOf(WEB, sessionId); + } + + /** Sends a raw HTML fragment to one tab, such as the echo of the question it sent. */ + public void sendHtml(WebSocketSession socket, String... html) throws IOException { + send(socket, String.join(System.lineSeparator(), html)); + } + + /** Sends a raw HTML fragment to every tab that shows the session, such as the echo of a question. */ + public void sendHtmlTo(String sessionId, String... html) { + String payload = String.join(System.lineSeparator(), html); + for (Tab tab : tabs.values()) { + if (!sessionId.equals(tab.sessionId())) { + continue; + } + try { + send(tab.socket(), payload); + } catch (IOException e) { + log.warn("WS push failed: {}", e.getMessage()); + } } } /** - * Delivers a background-task message. Pushes directly to WebSocket if a session - * is open, otherwise buffers for REST polling. + * Delivers a background-task message to every open tab, or buffers it for REST polling when + * no tab is open. */ @Override public void sendMessage(String message) { - try { - sendHtml(buildBackgroundMessageHtml(message)); - } catch (IOException e) { - log.warn("WS push failed, buffering message: {}", e.getMessage()); + String html = Htmx.oobAppend("chat-messages", ChatHtml.agentBubble(message, Instant.now())); + boolean delivered = false; + for (Tab tab : tabs.values()) { + try { + send(tab.socket(), html); + delivered = true; + } catch (IOException e) { + log.warn("WS push failed: {}", e.getMessage()); + } + } + if (!delivered) { pendingMessages.add(message); } } /** - * Delivers messages buffered while no WebSocket session was active. + * Delivers messages buffered while no tab was open. * Each buffered message is attempted once; a failed push re-buffers it. */ public void flushPendingMessages() { @@ -115,30 +175,141 @@ public void flushPendingMessages() { } } + // --- Views --------------------------------------------------------------------------------- + + /** + * Shows a session of the web conversation in one tab, which then continues it. + * + * @param notices agent messages shown below the history that are not part of it, such as the + * reply to a command + * @throws IllegalArgumentException if it is not a session of the web conversation + */ + public void showWebSession(WebSocketSession socket, String sessionId, String... notices) throws IOException { + ChatSessions.Summary session = chatSessions.summary(WEB, sessionId); + List bubbles = new ArrayList<>(notices.length == 0 ? loadHistoryAsHtml(sessionId) : history(sessionId)); + for (String notice : notices) { + bubbles.add(ChatHtml.agentBubble(notice, Instant.now())); + } + Tab tab = show(socket, sessionId, false); + sendView(tab, ChatHtml.chatHeader(session, true), bubbles, ChatHtml.chatInputArea(true, null)); + } + + /** Shows another channel's conversation in one tab, read-only, by the id of its active session. */ + public void showChannel(WebSocketSession socket, String sessionId) throws IOException { + ChatSessions.Summary session = chatSessions.summary(sessionId); + String label = ChatHtml.channelLabel(session.channel()) + " · " + session.title(); + Tab tab = show(socket, sessionId, true); + sendView(tab, ChatHtml.chatHeader(session, false), loadHistoryAsHtml(sessionId), ChatHtml.chatInputArea(false, label)); + } + + /** Starts a new web chat session, which becomes active, and shows it in this tab. */ + public void newChat(WebSocketSession socket) throws IOException { + String sessionId = chatSessions.create(WEB, SessionKind.CHAT, SessionChannel.WEB, null); + showWebSession(socket, sessionId); + refreshSidebars(); + } + /** - * Returns all known conversation IDs, always with "web" first. + * Makes an earlier web chat session active and shows it in this tab. + * + * @throws IllegalArgumentException if it is not a web chat session */ - 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 switchTo(WebSocketSession socket, String sessionId) throws IOException { + chatSessions.switchTo(WEB, sessionId); + showWebSession(socket, sessionId); + refreshSidebars(); } /** - * 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. + * Renames a web chat session; the header and the sidebar of every tab follow. + * + * @throws IllegalArgumentException if the title is blank or 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 rename(String sessionId, String title) throws IOException { + chatSessions.rename(WEB, sessionId, title); + refreshSidebars(); + } + + /** + * Runs a chat command ({@link ChatCommands}) typed in a tab, and shows the result there; other + * tabs keep what they show. + * + * @return whether {@code message} was a command; if not, it is for the agent + */ + public boolean runCommand(WebSocketSession socket, String message) throws IOException { + Optional reply = chatCommands.handle(WEB, SessionChannel.WEB, message); + if (reply.isEmpty()) { + return false; + } + // The command made its new session the active one + showWebSession(socket, activeWebSession(), reply.get()); + refreshSidebars(); + return true; + } + + /** A session got its title in the background: the sidebar and the header of every tab show it. */ + @EventListener + void onSessionTitled(SessionTitles.SessionTitled event) { + refreshSidebars(); + } + + /** Sends every tab the header and the sidebar of what it shows, leaving its messages alone. */ + private void refreshSidebars() { + for (Tab tab : tabs.values()) { + if (tab.sessionId() == null) { + continue; + } + try { + String header = tab.readOnly() + ? ChatHtml.chatHeader(chatSessions.summary(tab.sessionId()), false) + : ChatHtml.chatHeader(chatSessions.summary(WEB, tab.sessionId()), true); + sendHtml(tab.socket(), + Htmx.oobInnerHtml("chat-header", header), + Htmx.oobInnerHtml("chat-sessions", sessionLists(tab.sessionId()))); + } catch (IOException | RuntimeException e) { + log.warn("Could not refresh the sidebar of tab {}: {}", tab.socket().getId(), e.getMessage()); + } } + } + + private Tab show(WebSocketSession socket, String sessionId, boolean readOnly) { + return tabs.compute(socket.getId(), (_, tab) -> tab == null + ? new Tab(socket, sessionId, readOnly) + : tab.showing(sessionId, readOnly)); + } + + /** The messages carry the shown session's id, so the page ignores stream frames of any other. */ + private void sendView(Tab tab, String header, List bubbles, String inputArea) throws IOException { + sendHtml(tab.socket(), + Htmx.oobInnerHtml("chat-header", header), + Htmx.oobInnerHtml("chat-sessions", sessionLists(tab.sessionId())), + "

" + 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 activeWebSession() { + return chatSessions.active(WEB, SessionKind.CHAT, SessionChannel.WEB); + } + + /** + * 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())); } @@ -149,6 +320,8 @@ public List loadHistoryAsHtml(String conversationId) { return bubbles; } + // --- Answers ------------------------------------------------------------------------------- + /** * The tool calls as {@code chat.js} renders them: the fields of a live {@code toolCall} and * {@code toolResult} frame, plus the times of the call and the result. A call without a result @@ -180,26 +353,37 @@ private String toolsJson(List toolCalls) { } /** - * Handles a chat message from the web UI for the given conversationId. - * The response is streamed to the WebSocket session as JSON frames + * Handles a chat message sent from a tab: it goes to the web chat session that tab shows, not + * necessarily the active one. The response is streamed 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. + * session id and the time it was sent, to the tabs showing that session; the page shows the + * first frame's time as the time of the answer. + * + * @throws IllegalArgumentException if the session is not one of the web conversation's */ - public void chat(String conversationId, String message) { + public void chat(String sessionId, String message) { + if (!isWebSession(sessionId)) { + throw new IllegalArgumentException("Session " + sessionId + " is not one of the web chat's"); + } channelRegistry.publishMessageReceivedEvent(new ChannelMessageReceivedEvent(getName(), message)); - agent.respondTo(AgentRequest.chat(conversationId, 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, + agent.respondTo(AgentRequest.chat(WEB, sessionId, SessionChannel.WEB, message), event -> sendFrame(sessionId, switch (event) { + case AgentEvent.Token t -> frame(StreamFrameType.CHUNK, sessionId, t.text()); + case AgentEvent.ToolCall c -> frame(StreamFrameType.TOOL_CALL, sessionId, toolData(c.id(), c.name(), "input", c.input())); - case AgentEvent.ToolResult r -> frame(StreamFrameType.TOOL_RESULT, conversationId, + case AgentEvent.ToolResult r -> frame(StreamFrameType.TOOL_RESULT, sessionId, toolData(r.id(), r.name(), "output", r.output())); - case AgentEvent.Done ignored -> frame(StreamFrameType.DONE, conversationId, null); - case AgentEvent.Failed f -> frame(StreamFrameType.ERROR, conversationId, + case AgentEvent.Done ignored -> frame(StreamFrameType.DONE, sessionId, null); + case AgentEvent.Failed f -> frame(StreamFrameType.ERROR, sessionId, f.message() == null ? "Unknown error" : f.message()); })); } + /** Reports a turn that failed before it could stream, to the tabs showing its session. */ + public void failed(String sessionId, String message) { + sendFrame(sessionId, frame(StreamFrameType.ERROR, sessionId, message)); + } + private static Map toolData(String id, String name, String payloadKey, String payload) { Map data = new LinkedHashMap<>(); data.put("id", id); @@ -208,26 +392,36 @@ private static Map toolData(String id, String name, String paylo return data; } - private static Map frame(StreamFrameType type, String conversationId, Object payload) { + private static Map frame(StreamFrameType type, String sessionId, Object payload) { Map frame = new LinkedHashMap<>(); frame.put("type", type.type()); if (payload != null) frame.put("data", payload); - frame.put("conversationId", conversationId); + frame.put("sessionId", sessionId); frame.put("time", Instant.now().truncatedTo(ChronoUnit.SECONDS).toString()); return frame; } - private void sendFrame(Map frame) { - WebSocketSession session = wsSession.get(); - if (session == null || !session.isOpen()) return; - try { - session.sendMessage(new TextMessage(objectMapper.writeValueAsString(frame))); - } catch (IOException e) { - log.warn("WS push failed, dropping stream frame: {}", e.getMessage()); + /** Sends a stream frame to the tabs that show its session now; the others never see it. */ + private void sendFrame(String sessionId, Map frame) { + String json = objectMapper.writeValueAsString(frame); + for (Tab tab : tabs.values()) { + if (!sessionId.equals(tab.sessionId())) { + continue; + } + try { + send(tab.socket(), json); + } catch (IOException e) { + log.warn("WS push failed, dropping stream frame: {}", e.getMessage()); + } } } - private static String buildBackgroundMessageHtml(String text) { - return Htmx.oobAppend("chat-messages", ChatHtml.agentBubble(text, Instant.now())); + /** A WebSocket session takes one message at a time; streaming, titles and tasks all send. */ + private static void send(WebSocketSession socket, String payload) throws IOException { + synchronized (socket) { + if (socket.isOpen()) { + socket.sendMessage(new TextMessage(payload)); + } + } } } diff --git a/app/src/main/java/ai/javaclaw/chat/ChatHtml.java b/app/src/main/java/ai/javaclaw/chat/ChatHtml.java index d355f405..5ebd41bb 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='js:{"type": "userMessage", "sessionId": document.getElementById("chat-messages").getAttribute("data-session-id")}'> - -
- - +
+
+
+ + + +
+
+
+ {# Markup the streaming script clones; it fills in text with textContent only. #}