Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
330 changes: 262 additions & 68 deletions app/src/main/java/ai/javaclaw/chat/ChatChannel.java

Large diffs are not rendered by default.

108 changes: 84 additions & 24 deletions app/src/main/java/ai/javaclaw/chat/ChatHtml.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -64,11 +66,12 @@ public static String typingDots() {
</div>""".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 """
<form id="chat-form" class="ar-composer" ws-send hx-boost="false"
hx-vals='js:{"type": "userMessage", "conversationId": document.getElementById("channel-select") ? document.getElementById("channel-select").value : "web"}'>
hx-vals='js:{"type": "userMessage", "sessionId": document.getElementById("chat-messages").getAttribute("data-session-id")}'>
<label for="message-input" class="is-sr-only">Message JavaClaw</label>
<textarea id="message-input" class="ar-composer__input" name="message" rows="1"
placeholder="Message JavaClaw…"
Expand All @@ -83,25 +86,89 @@ public static String chatInputArea(String conversationId) {
</button>
</form>""";
}
String label = HtmlUtils.htmlEscape(labelFor(conversationId));
String escaped = HtmlUtils.htmlEscape(label);
return """
<p class="chat-readonly-notice">This is a read-only view of <strong>%s</strong>. \
Open %s to continue the conversation.</p>""".formatted(label, label);
Open %s to continue the conversation.</p>""".formatted(escaped, escaped);
}

public static String conversationSelector(List<String> ids, String selectedId) {
StringBuilder sb = new StringBuilder();
sb.append("""
<select id="channel-select" name="conversationId" \
ws-send hx-trigger="change" \
hx-vals='{"type": "channelChanged"}'>""");
for (String id : ids) {
sb.append("<option value=\"").append(HtmlUtils.htmlEscape(id)).append("\"");
if (id.equals(selectedId)) sb.append(" selected");
sb.append(">").append(HtmlUtils.htmlEscape(labelFor(id))).append("</option>");
/**
* The header of the shown session: its title and channel and, for a web chat, a rename button
* that turns the title into a text field with Save and Cancel ({@code /chat/chat.js}).
*/
public static String chatHeader(ChatSessions.Summary session, boolean renamable) {
String title = HtmlUtils.htmlEscape(session.title());
StringBuilder html = new StringBuilder("""
<span class="ar-chat-head__label">%s</span>\
<h1 class="ar-chat-head__title" id="chat-title">%s</h1>""".formatted(
HtmlUtils.htmlEscape(channelLabel(session.channel())), title));
if (renamable) {
html.append("""
<button type="button" class="ar-chat-head__rename" id="rename-btn" title="Rename" aria-label="Rename chat">\
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" \
stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/>\
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg></button>\
<form id="rename-form" class="ar-rename" ws-send hx-boost="false" hx-vals='{"type": "renameSession"}' hidden>\
<input type="hidden" name="sessionId" value="%s">\
<label for="rename-input" class="is-sr-only">Chat title</label>\
<input id="rename-input" class="ar-rename__input" name="title" value="%s" data-title="%s" \
maxlength="%d" required autocomplete="off">\
<button type="submit" class="ar-rename__button ar-rename__button--save">Save</button>\
<button type="button" class="ar-rename__button" id="rename-cancel">Cancel</button>\
</form>""".formatted(HtmlUtils.htmlEscape(session.id()), title, title, ChatSessions.MAX_TITLE_LENGTH));
}
return html.toString();
}

/**
* The sidebar's lists: the web chat's sessions, each switching to it, and the other channels'
* conversations, each opening the read-only view of its active session.
*
* @param shownId the session the page shows, highlighted
*/
public static String sessionLists(List<ChatSessions.Summary> chats, List<ChatSessions.Summary> channels, String shownId) {
StringBuilder html = new StringBuilder("""
<h2 class="ar-side__heading">Chats</h2><ul class="ar-side__list" id="chat-list">""");
for (ChatSessions.Summary chat : chats) {
html.append(sessionItem("switchSession", chat, null, chat.id().equals(shownId)));
}
sb.append("</select>");
return sb.toString();
html.append("""
</ul><p class="ar-side__empty" id="chat-list-empty" hidden>No chats match.</p>""");
if (!channels.isEmpty()) {
html.append("""
<h2 class="ar-side__heading">Channels</h2><ul class="ar-side__list">""");
for (ChatSessions.Summary channel : channels) {
html.append(sessionItem("viewSession", channel, channelLabel(channel.channel()), channel.id().equals(shownId)));
}
html.append("</ul>");
}
return html.toString();
}

private static String sessionItem(String frameType, ChatSessions.Summary session, String label, boolean shown) {
return """
<li><button type="button" class="ar-side__item%s"%s ws-send hx-vals='{"type": "%s"}' \
name="sessionId" value="%s">%s<span class="ar-side__title">%s</span>%s</button></li>""".formatted(
shown ? " is-active" : "",
shown ? " aria-current=\"true\"" : "",
frameType,
HtmlUtils.htmlEscape(session.id()),
label == null ? "" : "<span class=\"ar-side__channel\">" + HtmlUtils.htmlEscape(label) + "</span>",
HtmlUtils.htmlEscape(session.title()),
timeTag(session.lastActivity()));
}

/** What a channel is called in the chat. */
public static String channelLabel(SessionChannel channel) {
if (channel == null) return "Chat";
return switch (channel) {
case WEB -> "Web";
case TELEGRAM -> "Telegram";
case DISCORD -> "Discord";
case WHATSAPP -> "WhatsApp";
case TEAMS -> "Teams";
case INTERNAL -> "JavaClaw";
};
}

private static String agentMessage(String modifiers, String attributes, Instant time, String content) {
Expand All @@ -123,11 +190,4 @@ private static String timeTag(Instant time) {
if (time == null) return "";
return "<time class=\"ar-msg__time\" datetime=\"" + time.truncatedTo(ChronoUnit.SECONDS) + "\"></time>";
}

private static String labelFor(String conversationId) {
if ("web".equals(conversationId)) return "Web Chat";
if (conversationId.startsWith("discord-")) return "Discord (" + conversationId.substring("discord-".length()) + ")";
if (conversationId.startsWith("telegram-")) return "Telegram (" + conversationId.substring("telegram-".length()) + ")";
return conversationId;
}
}
112 changes: 64 additions & 48 deletions app/src/main/java/ai/javaclaw/chat/ws/ChatWebSocketHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ai.javaclaw.chat.Htmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
Expand All @@ -14,9 +15,17 @@
import tools.jackson.databind.ObjectMapper;

import java.time.Instant;
import java.util.List;
import java.util.Map;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
* The web chat's WebSocket: one connection per browser tab. Frames from a tab name the chat
* session they are about; {@link ChatChannel} checks it is one of the web conversation's.
*
* <p>An answer runs on its own thread, so the tab can switch session, start a new chat or open a
* channel's view while it streams.
*/
@Component
@ConditionalOnProperty(name = "javaclaw.chat.transport", havingValue = "spring-websocket", matchIfMissing = true)
public class ChatWebSocketHandler extends TextWebSocketHandler {
Expand All @@ -25,33 +34,28 @@ public class ChatWebSocketHandler extends TextWebSocketHandler {

private final ChatChannel chatChannel;
private final ObjectMapper objectMapper;
private final Executor concurrentChatExecutor;

@Autowired
public ChatWebSocketHandler(ChatChannel chatChannel, ObjectMapper objectMapper) {
this(chatChannel, objectMapper, Executors.newVirtualThreadPerTaskExecutor());
}

ChatWebSocketHandler(ChatChannel chatChannel, ObjectMapper objectMapper, Executor concurrentChatExecutor) {
this.chatChannel = chatChannel;
this.objectMapper = objectMapper;
this.concurrentChatExecutor = concurrentChatExecutor;
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
chatChannel.setWsSession(session);
log.info("WebChat WebSocket connected: {}", session.getId());

List<String> ids = chatChannel.conversationIds();
String selectedId = ids.getFirst();

String conversationSelector = ChatHtml.conversationSelector(ids, selectedId);
String bubbles = String.join(System.lineSeparator(), chatChannel.loadHistoryAsHtml(selectedId));
String inputArea = ChatHtml.chatInputArea(selectedId);
chatChannel.sendHtml(
Htmx.oobInnerHtml("channel-selector", conversationSelector),
Htmx.oobInnerHtml("chat-messages", bubbles),
Htmx.oobInnerHtml("chat-input-area", inputArea));
chatChannel.flushPendingMessages();
chatChannel.open(session);
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
chatChannel.clearWsSession(session);
chatChannel.close(session);
log.info("WebChat WebSocket disconnected: {} ({})", session.getId(), status);
}

Expand All @@ -61,48 +65,60 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message)
Map<String, Object> payload = objectMapper.readValue(message.getPayload(), Map.class);
String type = (String) payload.get("type");

if ("channelChanged".equals(type)) {
handleChannelChanged(payload);
} else if ("userMessage".equals(type)) {
handleUserMessage(payload);
try {
switch (type == null ? "" : type) {
case "userMessage" -> handleUserMessage(session, payload);
case "newChat" -> chatChannel.newChat(session);
case "switchSession" -> chatChannel.switchTo(session, text(payload, "sessionId"));
case "viewSession" -> chatChannel.showChannel(session, text(payload, "sessionId"));
case "renameSession" -> chatChannel.rename(webSession(payload), text(payload, "title"));
default -> log.debug("Ignoring WebChat frame of type {}", type);
}
} catch (IllegalArgumentException e) {
// A session of another conversation, an unknown session or a blank title: nothing changes
log.warn("Refused WebChat {} request: {}", type, e.getMessage());
}
}

private void handleChannelChanged(Map<String, Object> payload) throws Exception {
String conversationId = (String) payload.get("conversationId");
if (conversationId == null || conversationId.isBlank()) return;
private static String text(Map<String, Object> payload, String name) {
Object value = payload.get(name);
if (!(value instanceof String text) || text.isBlank()) {
throw new IllegalArgumentException("No " + name);
}
return text;
}

String bubbles = String.join(System.lineSeparator(), chatChannel.loadHistoryAsHtml(conversationId));
String inputArea = ChatHtml.chatInputArea(conversationId);
chatChannel.sendHtml(
Htmx.oobInnerHtml("chat-messages", bubbles),
Htmx.oobInnerHtml("chat-input-area", inputArea));
/** The frame's session, which must be one of the web conversation's. */
private String webSession(Map<String, Object> payload) {
String sessionId = text(payload, "sessionId");
if (!chatChannel.isWebSession(sessionId)) {
throw new IllegalArgumentException("Session " + sessionId + " is not one of the web chat's");
}
return sessionId;
}

private void handleUserMessage(Map<String, Object> payload) throws Exception {
String conversationId = (String) payload.get("conversationId");
private void handleUserMessage(WebSocketSession session, Map<String, Object> payload) throws Exception {
String userMessage = (String) payload.get("message");

if (userMessage == null || userMessage.isBlank()) return;
userMessage = userMessage.trim();
if (conversationId == null || conversationId.isBlank()) conversationId = "web";

// Echo user message + show typing indicator
chatChannel.sendHtml(
Htmx.oobAppend("chat-messages", ChatHtml.userBubble(userMessage, Instant.now())),
String question = userMessage.trim();
// A command (/new) is answered here; it reaches neither the model nor the history
if (chatChannel.runCommand(session, question)) return;
String sessionId = webSession(payload);

// Echo the question and show the typing indicator in every tab showing the session
chatChannel.sendHtmlTo(sessionId,
Htmx.oobAppend("chat-messages", ChatHtml.userBubble(question, Instant.now())),
Htmx.oobReplace("typing-indicator", ChatHtml.typingDots()));

try {
// Call agent (blocking — the response is streamed to the client as JSON frames
// by ChatChannel while this call runs; background tasks may push messages too)
chatChannel.chat(conversationId, userMessage);
chatChannel.sendHtml(Htmx.oobReplace("typing-indicator", ""));
} catch (RuntimeException ex) {
log.warn("Chat request failed for conversation {}", conversationId, ex);
chatChannel.sendHtml(
Htmx.oobAppend("chat-messages", ChatHtml.agentError(genericUserFacingError(ex), Instant.now())),
Htmx.oobReplace("typing-indicator", ""));
}
concurrentChatExecutor.execute(() -> {
try {
chatChannel.chat(sessionId, question);
} catch (RuntimeException ex) {
log.warn("Chat request failed in session {}", sessionId, ex);
chatChannel.failed(sessionId, genericUserFacingError(ex));
}
});
}

private static String genericUserFacingError(RuntimeException ex) {
Expand All @@ -117,4 +133,4 @@ private static String summarizeError(Throwable ex) {

return message;
}
}
}
Loading
Loading