mirror of
https://gitee.com/mateos/mateclaw.git
synced 2026-09-13 11:13:43 +08:00
feat(memory): dream-v2 D3 — Diff viewer + SSE + Focused Dream dialog
This commit is contained in:
parent
30b9912ded
commit
bf4cebb7b3
@ -8,6 +8,8 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import vip.mate.common.result.R;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import vip.mate.memory.model.DreamReportEntity;
|
||||
import vip.mate.memory.repository.DreamReportMapper;
|
||||
import vip.mate.memory.service.MorningCardService;
|
||||
@ -32,6 +34,7 @@ public class DreamController {
|
||||
private final DreamReportMapper dreamReportMapper;
|
||||
private final MorningCardService morningCardService;
|
||||
private final MemoryHilService hilService;
|
||||
private final DreamEventBroadcaster eventBroadcaster;
|
||||
|
||||
@Operation(summary = "List dream reports (paginated, newest first)")
|
||||
@GetMapping("/reports")
|
||||
@ -72,6 +75,15 @@ public class DreamController {
|
||||
return R.ok(entity);
|
||||
}
|
||||
|
||||
// ==================== SSE Events ====================
|
||||
|
||||
@Operation(summary = "Subscribe to dream events (SSE)")
|
||||
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@RequireWorkspaceRole("viewer")
|
||||
public SseEmitter subscribeDreamEvents(@PathVariable Long agentId) {
|
||||
return eventBroadcaster.register(agentId);
|
||||
}
|
||||
|
||||
// ==================== Morning Card ====================
|
||||
|
||||
@Operation(summary = "Get morning card for current user + agent")
|
||||
|
||||
@ -0,0 +1,92 @@
|
||||
package vip.mate.memory.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import vip.mate.memory.event.DreamCompletedEvent;
|
||||
import vip.mate.memory.event.DreamFailedEvent;
|
||||
import vip.mate.memory.service.DreamReport;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Broadcasts dream events to connected SSE clients.
|
||||
* Clients subscribe per agentId via GET /dream/events.
|
||||
*
|
||||
* @author MateClaw Team
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DreamEventBroadcaster {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final List<EmitterEntry> emitters = new CopyOnWriteArrayList<>();
|
||||
|
||||
record EmitterEntry(Long agentId, SseEmitter emitter) {}
|
||||
|
||||
/**
|
||||
* Register a new SSE emitter for an agent.
|
||||
*/
|
||||
public SseEmitter register(Long agentId) {
|
||||
SseEmitter emitter = new SseEmitter(300_000L); // 5 min timeout
|
||||
EmitterEntry entry = new EmitterEntry(agentId, emitter);
|
||||
emitters.add(entry);
|
||||
emitter.onCompletion(() -> emitters.remove(entry));
|
||||
emitter.onTimeout(() -> emitters.remove(entry));
|
||||
emitter.onError(e -> emitters.remove(entry));
|
||||
log.debug("[DreamSSE] Client connected for agent={}, total={}", agentId, emitters.size());
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@Async
|
||||
@EventListener
|
||||
public void onDreamCompleted(DreamCompletedEvent event) {
|
||||
broadcast(event.report(), "dream.completed");
|
||||
}
|
||||
|
||||
@Async
|
||||
@EventListener
|
||||
public void onDreamFailed(DreamFailedEvent event) {
|
||||
broadcast(event.report(), "dream.failed");
|
||||
}
|
||||
|
||||
private void broadcast(DreamReport report, String eventType) {
|
||||
Long agentId = report.agentId();
|
||||
String json;
|
||||
try {
|
||||
json = objectMapper.writeValueAsString(Map.of(
|
||||
"type", eventType,
|
||||
"agentId", agentId,
|
||||
"mode", report.mode().name(),
|
||||
"topic", report.topic() != null ? report.topic() : "",
|
||||
"status", report.status().name(),
|
||||
"promotedCount", report.promotedCount(),
|
||||
"rejectedCount", report.rejectedCount()
|
||||
));
|
||||
} catch (Exception e) {
|
||||
log.warn("[DreamSSE] Failed to serialize event: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> dead = new java.util.ArrayList<>();
|
||||
for (EmitterEntry entry : emitters) {
|
||||
if (!entry.agentId().equals(agentId)) continue;
|
||||
try {
|
||||
entry.emitter().send(SseEmitter.event()
|
||||
.name(eventType)
|
||||
.data(json));
|
||||
} catch (Exception e) {
|
||||
dead.add(entry);
|
||||
}
|
||||
}
|
||||
emitters.removeAll(dead);
|
||||
log.debug("[DreamSSE] Broadcast {} to {} clients for agent={}", eventType, emitters.size(), agentId);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,11 @@
|
||||
package vip.mate.memory.event;
|
||||
|
||||
import vip.mate.memory.service.DreamReport;
|
||||
|
||||
/**
|
||||
* Published when a dream consolidation completes successfully.
|
||||
*
|
||||
* @param report the structured dream report
|
||||
* @author MateClaw Team
|
||||
*/
|
||||
public record DreamCompletedEvent(DreamReport report) {}
|
||||
@ -0,0 +1,11 @@
|
||||
package vip.mate.memory.event;
|
||||
|
||||
import vip.mate.memory.service.DreamReport;
|
||||
|
||||
/**
|
||||
* Published when a dream consolidation fails.
|
||||
*
|
||||
* @param report the structured dream report (status=FAILED)
|
||||
* @author MateClaw Team
|
||||
*/
|
||||
public record DreamFailedEvent(DreamReport report) {}
|
||||
@ -11,6 +11,8 @@ import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.stereotype.Service;
|
||||
import vip.mate.memory.event.DreamCompletedEvent;
|
||||
import vip.mate.memory.event.DreamFailedEvent;
|
||||
import vip.mate.memory.event.MemoryWriteEvent;
|
||||
import vip.mate.agent.AgentGraphBuilder;
|
||||
import vip.mate.agent.prompt.PromptLoader;
|
||||
@ -384,6 +386,12 @@ public class MemoryEmergenceService {
|
||||
dreamReportMapper.insert(entity);
|
||||
log.debug("[Memory] DreamReport persisted: agent={}, mode={}, status={}",
|
||||
report.agentId(), report.mode(), report.status());
|
||||
// Publish event for SSE broadcast
|
||||
if (report.status() == DreamStatus.SUCCESS) {
|
||||
eventPublisher.publishEvent(new DreamCompletedEvent(report));
|
||||
} else if (report.status() == DreamStatus.FAILED) {
|
||||
eventPublisher.publishEvent(new DreamFailedEvent(report));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("[Memory] Failed to persist DreamReport for agent={}: {}", report.agentId(), e.getMessage());
|
||||
}
|
||||
|
||||
@ -1818,5 +1818,17 @@ export default {
|
||||
confirmed: 'Confirmed',
|
||||
saved: 'Saved to MEMORY.md',
|
||||
},
|
||||
focused: {
|
||||
btn: 'Think Now',
|
||||
title: 'Focused Dream',
|
||||
desc: 'Let the Agent re-organize memories around a specific topic. It will prioritize consolidating information related to your theme.',
|
||||
placeholder: 'Enter a topic, e.g. "architecture decisions", "user preferences"...',
|
||||
trigger: 'Start',
|
||||
success: 'Dream completed, timeline updated',
|
||||
skipped: 'Nothing to consolidate',
|
||||
},
|
||||
diff: {
|
||||
title: 'Change Summary',
|
||||
},
|
||||
},
|
||||
} as const
|
||||
|
||||
@ -1828,5 +1828,17 @@ export default {
|
||||
confirmed: '已确认',
|
||||
saved: '已保存到 MEMORY.md',
|
||||
},
|
||||
focused: {
|
||||
btn: '现在想一想',
|
||||
title: 'Focused Dream',
|
||||
desc: '围绕一个主题让 Agent 重新整理记忆。Agent 会优先提炼该主题相关的信息。',
|
||||
placeholder: '输入主题,如"项目架构决策"、"用户偏好"...',
|
||||
trigger: '开始整理',
|
||||
success: 'Dream 完成,时间线已更新',
|
||||
skipped: '没有需要整合的内容',
|
||||
},
|
||||
diff: {
|
||||
title: '变更摘要',
|
||||
},
|
||||
},
|
||||
} as const
|
||||
|
||||
@ -25,6 +25,7 @@ export const useMemoryStore = defineStore('memory', () => {
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const currentReport = ref<DreamReportItem | null>(null)
|
||||
let eventSource: EventSource | null = null
|
||||
|
||||
async function fetchReports(agentId: number, page = 1, size = 20) {
|
||||
loading.value = true
|
||||
@ -49,5 +50,42 @@ export const useMemoryStore = defineStore('memory', () => {
|
||||
}
|
||||
}
|
||||
|
||||
return { reports, total, loading, currentReport, fetchReports, fetchReport }
|
||||
/**
|
||||
* Subscribe to dream SSE events for an agent.
|
||||
* Automatically refreshes the report list on new dream events.
|
||||
*/
|
||||
function subscribeEvents(agentId: number) {
|
||||
unsubscribeEvents()
|
||||
const token = localStorage.getItem('token')
|
||||
const url = `/api/v1/memory/${agentId}/dream/events`
|
||||
eventSource = new EventSource(url)
|
||||
|
||||
eventSource.addEventListener('dream.completed', (e) => {
|
||||
// Refresh the report list to show the new dream
|
||||
fetchReports(agentId, 1, 20)
|
||||
})
|
||||
|
||||
eventSource.addEventListener('dream.failed', (e) => {
|
||||
fetchReports(agentId, 1, 20)
|
||||
})
|
||||
|
||||
eventSource.onerror = () => {
|
||||
// Reconnect after 5s on error
|
||||
unsubscribeEvents()
|
||||
setTimeout(() => subscribeEvents(agentId), 5000)
|
||||
}
|
||||
}
|
||||
|
||||
function unsubscribeEvents() {
|
||||
if (eventSource) {
|
||||
eventSource.close()
|
||||
eventSource = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
reports, total, loading, currentReport,
|
||||
fetchReports, fetchReport,
|
||||
subscribeEvents, unsubscribeEvents,
|
||||
}
|
||||
})
|
||||
|
||||
44
mateclaw-ui/src/views/Memory/components/DreamDiffViewer.vue
Normal file
44
mateclaw-ui/src/views/Memory/components/DreamDiffViewer.vue
Normal file
@ -0,0 +1,44 @@
|
||||
<template>
|
||||
<div class="diff-viewer" v-if="diff">
|
||||
<div class="diff-header">
|
||||
<span class="diff-icon">📝</span>
|
||||
<span class="diff-label">{{ t('memory.diff.title') }}</span>
|
||||
</div>
|
||||
<pre class="diff-content">{{ diff }}</pre>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n'
|
||||
const { t } = useI18n()
|
||||
defineProps<{ diff: string | null }>()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.diff-viewer {
|
||||
margin-top: 12px;
|
||||
padding: 12px 16px;
|
||||
background: var(--el-fill-color-lighter);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--el-border-color-extra-light);
|
||||
}
|
||||
.diff-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
.diff-icon { font-size: 14px; }
|
||||
.diff-content {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
font-family: 'SF Mono', 'Menlo', monospace;
|
||||
color: var(--el-text-color-regular);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,75 @@
|
||||
<template>
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
:title="t('memory.focused.title')"
|
||||
width="420px"
|
||||
:close-on-click-modal="false"
|
||||
>
|
||||
<div class="focused-form">
|
||||
<p class="focused-desc">{{ t('memory.focused.desc') }}</p>
|
||||
<el-input
|
||||
v-model="topic"
|
||||
:placeholder="t('memory.focused.placeholder')"
|
||||
:rows="3"
|
||||
type="textarea"
|
||||
maxlength="200"
|
||||
show-word-limit
|
||||
/>
|
||||
</div>
|
||||
<template #footer>
|
||||
<el-button @click="visible = false">{{ t('memory.hil.cancel') }}</el-button>
|
||||
<el-button type="primary" :loading="running" :disabled="!topic.trim()" @click="trigger">
|
||||
{{ t('memory.focused.trigger') }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { http } from '@/api'
|
||||
|
||||
const props = defineProps<{ agentId: number }>()
|
||||
const emit = defineEmits<{ triggered: []; 'update:modelValue': [val: boolean] }>()
|
||||
const { t } = useI18n()
|
||||
|
||||
const visible = defineModel<boolean>({ default: false })
|
||||
const topic = ref('')
|
||||
const running = ref(false)
|
||||
|
||||
async function trigger() {
|
||||
if (!topic.value.trim()) return
|
||||
running.value = true
|
||||
try {
|
||||
const res = await http.post(`/memory/${props.agentId}/dreaming/focused`, {
|
||||
topic: topic.value.trim(),
|
||||
})
|
||||
if (res.data?.status === 'SUCCESS') {
|
||||
ElMessage.success(t('memory.focused.success'))
|
||||
} else {
|
||||
ElMessage.info(t('memory.focused.skipped'))
|
||||
}
|
||||
emit('triggered')
|
||||
visible.value = false
|
||||
topic.value = ''
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || 'Focused dream failed')
|
||||
} finally {
|
||||
running.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.focused-form {
|
||||
padding: 4px 0;
|
||||
}
|
||||
.focused-desc {
|
||||
margin: 0 0 12px;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
@ -21,6 +21,13 @@
|
||||
<!-- Morning Card -->
|
||||
<MorningCard v-if="selectedAgentId" :agent-id="selectedAgentId" />
|
||||
|
||||
<!-- Action bar -->
|
||||
<div v-if="selectedAgentId" class="memory-actions">
|
||||
<el-button size="small" type="primary" plain @click="showFocusedDialog = true">
|
||||
{{ t('memory.focused.btn') }}
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<!-- Tab navigation: minimal, no borders -->
|
||||
<div class="memory-nav">
|
||||
<button
|
||||
@ -45,23 +52,35 @@
|
||||
<p>Coming soon</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Focused Dream Dialog -->
|
||||
<FocusedDreamDialog
|
||||
v-if="selectedAgentId"
|
||||
v-model="showFocusedDialog"
|
||||
:agent-id="selectedAgentId"
|
||||
@triggered="onDreamTriggered"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useAgentStore } from '@/stores/useAgentStore'
|
||||
import { useMemoryStore } from '@/stores/useMemoryStore'
|
||||
import DreamTimeline from './components/DreamTimeline.vue'
|
||||
import MorningCard from './components/MorningCard.vue'
|
||||
import FocusedDreamDialog from './components/FocusedDreamDialog.vue'
|
||||
|
||||
const { t } = useI18n()
|
||||
const agentStore = useAgentStore()
|
||||
const memoryStore = useMemoryStore()
|
||||
const agents = ref<any[]>([])
|
||||
const selectedAgentId = ref<number | null>(null)
|
||||
const activeTab = ref('timeline')
|
||||
const showFocusedDialog = ref(false)
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ key: 'timeline', label: t('memory.tabTimeline'), disabled: false },
|
||||
@ -78,9 +97,26 @@ onMounted(async () => {
|
||||
}
|
||||
})
|
||||
|
||||
// SSE subscription management
|
||||
watch(selectedAgentId, (id) => {
|
||||
if (id) memoryStore.subscribeEvents(id)
|
||||
else memoryStore.unsubscribeEvents()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
memoryStore.unsubscribeEvents()
|
||||
})
|
||||
|
||||
function onAgentChange() {
|
||||
activeTab.value = 'timeline'
|
||||
}
|
||||
|
||||
function onDreamTriggered() {
|
||||
// Refresh timeline after focused dream
|
||||
if (selectedAgentId.value) {
|
||||
memoryStore.fetchReports(selectedAgentId.value, 1, 20)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@ -131,6 +167,9 @@ function onAgentChange() {
|
||||
.memory-content {
|
||||
min-height: 300px;
|
||||
}
|
||||
.memory-actions {
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
.empty-state {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user