Skip to content

Commit 7d4b1af

Browse files
committed
feat: add session management with sidebar and markdown rendering
- Add SessionService for session list, history, and cleanup - Add GET /sessions and GET /session/{id}/history API endpoints - Add SessionList sidebar component with toggle and new session - Add /chat/:sessionId route for session-based navigation - Render chat messages with marked (GFM) instead of plain text - Add comprehensive markdown styles (code, tables, blockquotes, etc.) - Refactor ChatView layout to sidebar + main chat area
1 parent 031af5a commit 7d4b1af

17 files changed

Lines changed: 902 additions & 634 deletions

File tree

‎.gitattributes‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# 统一换行符为 LF,避免 Windows 下 CRLF/LF 冲突
2+
* text=auto eol=lf

‎data-agent-backend/src/main/java/io/github/malonetalk/agent/AgentService.java‎

Lines changed: 9 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,37 +23,35 @@
2323
import io.agentscope.core.memory.InMemoryMemory;
2424
import io.agentscope.core.message.Msg;
2525
import io.agentscope.core.session.Session;
26-
import io.agentscope.core.session.mysql.MysqlSession;
2726
import io.agentscope.core.tool.Toolkit;
2827
import io.github.malonetalk.agent.tools.MarkAgentTool;
2928
import io.github.malonetalk.convertor.EventConverter;
3029
import io.github.malonetalk.dto.ChatStreamEvent;
3130
import io.github.malonetalk.utils.MsgUtils;
3231
import jakarta.annotation.PostConstruct;
3332
import java.util.List;
34-
import java.util.Map;
35-
import java.util.concurrent.ConcurrentHashMap;
36-
import javax.sql.DataSource;
33+
import lombok.extern.slf4j.Slf4j;
3734
import org.springframework.stereotype.Service;
3835
import reactor.core.publisher.Flux;
3936
import reactor.core.scheduler.Schedulers;
4037

38+
@Slf4j
4139
@Service
4240
public class AgentService {
4341

4442
private final ModelFactory modelFactory;
45-
private final Map<String, Session> sessionCache = new ConcurrentHashMap<>();
43+
private final SessionService sessionService;
4644
private Toolkit toolkit;
4745

4846
private final List<MarkAgentTool> allToolBeans;
4947

50-
private final DataSource dataSource;
51-
5248
public AgentService(
53-
ModelFactory modelFactory, List<MarkAgentTool> allToolBeans, DataSource dataSource) {
49+
ModelFactory modelFactory,
50+
SessionService sessionService,
51+
List<MarkAgentTool> allToolBeans) {
5452
this.modelFactory = modelFactory;
53+
this.sessionService = sessionService;
5554
this.allToolBeans = allToolBeans;
56-
this.dataSource = dataSource;
5755
}
5856

5957
@PostConstruct
@@ -62,16 +60,10 @@ public void init() {
6260
allToolBeans.forEach(this.toolkit::registerTool);
6361
}
6462

65-
private Session getOrCreateSession(String sessionId) {
66-
return sessionCache.computeIfAbsent(
67-
sessionId,
68-
k -> new MysqlSession(dataSource, "data_agent", "agentscope_sessions", false));
69-
}
70-
7163
public String chat(String sessionId, String userInput) {
7264
ReActAgent agent = createAgent();
7365

74-
Session session = getOrCreateSession(sessionId);
66+
Session session = sessionService.getOrCreateSession(sessionId);
7567
agent.loadIfExists(session, sessionId);
7668

7769
Msg userMsg = Msg.builder().textContent(userInput).build();
@@ -86,7 +78,7 @@ public String chat(String sessionId, String userInput) {
8678
public Flux<ChatStreamEvent> chatStream(String sessionId, String userInput) {
8779
ReActAgent agent = createAgent();
8880

89-
Session session = getOrCreateSession(sessionId);
81+
Session session = sessionService.getOrCreateSession(sessionId);
9082
agent.loadIfExists(session, sessionId);
9183

9284
Msg userMsg = Msg.builder().textContent(userInput).build();
@@ -123,15 +115,4 @@ private ReActAgent createAgent() {
123115
.maxIters(10)
124116
.build();
125117
}
126-
127-
public void clearSession(String sessionId) {
128-
Session session = sessionCache.remove(sessionId);
129-
if (session != null) {
130-
session.delete(io.agentscope.core.state.SimpleSessionKey.of(sessionId));
131-
}
132-
}
133-
134-
public void clearAllSessions() {
135-
sessionCache.clear();
136-
}
137118
}
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.agent;
19+
20+
import io.agentscope.core.message.ContentBlock;
21+
import io.agentscope.core.message.Msg;
22+
import io.agentscope.core.message.MsgRole;
23+
import io.agentscope.core.message.TextBlock;
24+
import io.agentscope.core.message.ThinkingBlock;
25+
import io.agentscope.core.message.ToolResultBlock;
26+
import io.agentscope.core.message.ToolUseBlock;
27+
import io.agentscope.core.session.Session;
28+
import io.agentscope.core.session.mysql.MysqlSession;
29+
import io.agentscope.core.state.SessionKey;
30+
import io.agentscope.core.state.SimpleSessionKey;
31+
import io.github.malonetalk.dto.ChatStreamEvent;
32+
import io.github.malonetalk.dto.SessionInfo;
33+
import io.github.malonetalk.dto.TurnItem;
34+
import io.github.malonetalk.enums.ChatStreamEventType;
35+
import io.github.malonetalk.utils.MsgUtils;
36+
import lombok.extern.slf4j.Slf4j;
37+
import org.springframework.stereotype.Service;
38+
39+
import javax.sql.DataSource;
40+
import java.sql.Connection;
41+
import java.sql.PreparedStatement;
42+
import java.sql.ResultSet;
43+
import java.util.ArrayList;
44+
import java.util.Collections;
45+
import java.util.HashMap;
46+
import java.util.List;
47+
import java.util.Map;
48+
import java.util.Set;
49+
import java.util.concurrent.ConcurrentHashMap;
50+
import java.util.stream.Collectors;
51+
52+
@Slf4j
53+
@Service
54+
public class SessionService {
55+
56+
private final DataSource dataSource;
57+
private final Map<String, Session> sessionCache = new ConcurrentHashMap<>();
58+
59+
public SessionService(DataSource dataSource) {
60+
this.dataSource = dataSource;
61+
}
62+
63+
public Session getOrCreateSession(String sessionId) {
64+
return sessionCache.computeIfAbsent(
65+
sessionId,
66+
k -> new MysqlSession(dataSource, "data_agent", "agentscope_sessions", false));
67+
}
68+
69+
public List<Msg> getSessionDebug(String sessionId) {
70+
Session session = getOrCreateSession(sessionId);
71+
if (!session.exists(SimpleSessionKey.of(sessionId))) {
72+
return Collections.emptyList();
73+
}
74+
return session.getList(SimpleSessionKey.of(sessionId), "memory_messages", Msg.class);
75+
}
76+
77+
public List<TurnItem> getSessionHistory(String sessionId) {
78+
Session session = getOrCreateSession(sessionId);
79+
80+
if (!session.exists(SimpleSessionKey.of(sessionId))) {
81+
return Collections.emptyList();
82+
}
83+
84+
List<Msg> messages =
85+
session.getList(SimpleSessionKey.of(sessionId), "memory_messages", Msg.class);
86+
87+
List<TurnItem> turns = new ArrayList<>();
88+
List<ContentBlock> agentBlocks = null;
89+
90+
for (Msg msg : messages) {
91+
boolean isUser = msg.getRole() == MsgRole.USER;
92+
if (isUser) {
93+
if (agentBlocks != null) {
94+
turns.add(buildAgentTurn(agentBlocks));
95+
agentBlocks = null;
96+
}
97+
String text =
98+
msg.getContent().stream()
99+
.filter(block -> block instanceof TextBlock)
100+
.map(block -> ((TextBlock) block).getText())
101+
.filter(t -> t != null && !t.isEmpty())
102+
.collect(Collectors.joining());
103+
turns.add(new TurnItem(MsgRole.USER.name(), text, List.of()));
104+
} else {
105+
if (agentBlocks == null) {
106+
agentBlocks = new ArrayList<>();
107+
}
108+
agentBlocks.addAll(msg.getContent());
109+
}
110+
}
111+
if (agentBlocks != null) {
112+
turns.add(buildAgentTurn(agentBlocks));
113+
}
114+
115+
return turns;
116+
}
117+
118+
private TurnItem buildAgentTurn(List<ContentBlock> blocks) {
119+
StringBuilder content = new StringBuilder();
120+
List<ChatStreamEvent> traceSteps = new ArrayList<>();
121+
122+
for (ContentBlock block : blocks) {
123+
if (block instanceof TextBlock tb) {
124+
appendText(content, tb);
125+
} else if (block instanceof ThinkingBlock tb) {
126+
appendThinking(traceSteps, tb);
127+
} else if (block instanceof ToolUseBlock tub) {
128+
appendToolCall(traceSteps, tub);
129+
} else if (block instanceof ToolResultBlock trb) {
130+
appendToolResult(traceSteps, trb);
131+
}
132+
}
133+
134+
return new TurnItem(MsgRole.ASSISTANT.name(), content.toString(), traceSteps);
135+
}
136+
137+
private void appendText(StringBuilder content, TextBlock tb) {
138+
String text = tb.getText();
139+
if (text != null && !text.isEmpty()) {
140+
content.append(text);
141+
}
142+
}
143+
144+
private void appendThinking(List<ChatStreamEvent> traceSteps, ThinkingBlock tb) {
145+
String thinking = tb.getThinking();
146+
if (thinking == null || thinking.isEmpty()) {
147+
return;
148+
}
149+
int lastIdx = traceSteps.size() - 1;
150+
if (lastIdx >= 0 && traceSteps.get(lastIdx).type() == ChatStreamEventType.THINKING) {
151+
String merged =
152+
(traceSteps.get(lastIdx).content() != null
153+
? traceSteps.get(lastIdx).content()
154+
: "")
155+
+ thinking;
156+
traceSteps.set(lastIdx, thinkingEvent(merged));
157+
} else {
158+
traceSteps.add(thinkingEvent(thinking));
159+
}
160+
}
161+
162+
private void appendToolCall(List<ChatStreamEvent> traceSteps, ToolUseBlock tub) {
163+
traceSteps.add(
164+
new ChatStreamEvent(
165+
ChatStreamEventType.TOOL_CALL,
166+
null,
167+
false,
168+
null,
169+
new ChatStreamEvent.ToolCallInfo(
170+
tub.getId(), tub.getName(), tub.getInput()),
171+
null));
172+
}
173+
174+
private void appendToolResult(List<ChatStreamEvent> traceSteps, ToolResultBlock trb) {
175+
String outputText =
176+
trb.getOutput().stream()
177+
.filter(b -> b instanceof TextBlock)
178+
.map(b -> ((TextBlock) b).getText())
179+
.filter(t -> t != null && !t.isEmpty())
180+
.collect(Collectors.joining("\n"));
181+
traceSteps.add(
182+
new ChatStreamEvent(
183+
ChatStreamEventType.TOOL_RESULT,
184+
null,
185+
false,
186+
null,
187+
null,
188+
new ChatStreamEvent.ToolResultInfo(
189+
trb.getId(), trb.getName(), outputText)));
190+
}
191+
192+
private static ChatStreamEvent thinkingEvent(String thinking) {
193+
return new ChatStreamEvent(ChatStreamEventType.THINKING, null, false, thinking, null, null);
194+
}
195+
196+
public void clearSession(String sessionId) {
197+
Session session = sessionCache.remove(sessionId);
198+
if (session != null) {
199+
session.delete(SimpleSessionKey.of(sessionId));
200+
}
201+
}
202+
203+
public void clearAllSessions() {
204+
sessionCache.clear();
205+
}
206+
207+
public List<SessionInfo> listSessions() {
208+
MysqlSession session =
209+
new MysqlSession(dataSource, "data_agent", "agentscope_sessions", false);
210+
Set<SessionKey> keys = session.listSessionKeys();
211+
212+
if (keys == null || keys.isEmpty()) {
213+
return Collections.emptyList();
214+
}
215+
216+
Map<String, String[]> timestamps = new HashMap<>();
217+
try (Connection conn = dataSource.getConnection();
218+
PreparedStatement ps =
219+
conn.prepareStatement(
220+
"SELECT session_id, MIN(created_at), MAX(updated_at)"
221+
+ " FROM agentscope_sessions GROUP BY session_id");
222+
ResultSet rs = ps.executeQuery()) {
223+
while (rs.next()) {
224+
timestamps.put(rs.getString(1), new String[] {rs.getString(2), rs.getString(3)});
225+
}
226+
} catch (Exception e) {
227+
log.error("Error listing session timestamps", e);
228+
}
229+
230+
List<SessionInfo> result = new ArrayList<>();
231+
for (SessionKey key : keys) {
232+
String sid = key.toIdentifier();
233+
List<Msg> messages = session.getList(key, "memory_messages", Msg.class);
234+
235+
String title = "";
236+
if (messages != null) {
237+
for (Msg msg : messages) {
238+
if (msg.getRole() == MsgRole.USER) {
239+
title = MsgUtils.getTextContent(msg);
240+
if (title.length() > 30) {
241+
title = title.substring(0, 30);
242+
}
243+
break;
244+
}
245+
}
246+
}
247+
if (title.isEmpty()) {
248+
title = sid.length() > 20 ? sid.substring(0, 20) : sid;
249+
}
250+
251+
String[] times = timestamps.getOrDefault(sid, new String[] {"", ""});
252+
result.add(new SessionInfo(sid, title, times[0], times[1]));
253+
}
254+
255+
result.sort((a, b) -> b.lastActiveAt().compareTo(a.lastActiveAt()));
256+
return result;
257+
}
258+
}

0 commit comments

Comments
 (0)