Merge branch 'main' into feat/base-service-delivery

This commit is contained in:
ztkkOip
2026-07-28 18:03:04 +08:00
committed by GitHub
8 changed files with 443 additions and 55 deletions
+46
View File
@@ -79,3 +79,49 @@ function parseResponseBody(text: string) {
return { error: text }
}
}
export interface TaskLogStreamCallbacks {
onInit?: (lines: TaskLogLine[]) => void
onUpdate?: (lines: TaskLogLine[]) => void
onFinished?: () => void
onError?: (error: string) => void
}
export function createTaskLogStream(taskId: string, callbacks: TaskLogStreamCallbacks): EventSource {
const token = getToken()
const url = `/auth/api/v1/task-logs/stream?task_id=${encodeURIComponent(taskId)}&access_token=${encodeURIComponent(token || '')}`
const es = new EventSource(url)
es.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
switch (data.type) {
case 'init':
callbacks.onInit?.(Array.isArray(data.lines) ? data.lines : [])
break
case 'update':
callbacks.onUpdate?.(Array.isArray(data.lines) ? data.lines : [])
break
case 'finished':
callbacks.onFinished?.()
es.close()
break
case 'error':
callbacks.onError?.(data.error || 'Unknown error')
break
}
} catch {
// ignore parse errors for heartbeat etc.
}
}
es.onerror = () => {
// EventSource will auto-reconnect, but we report connection errors
if (es.readyState === EventSource.CLOSED) {
callbacks.onError?.('Connection closed')
}
}
return es
}
+164 -6
View File
@@ -52,12 +52,40 @@
<h3>
<span>任务日志</span>
<span class="selected-name">{{ selectedTaskName }}</span>
<span v-if="isStreaming" class="streaming-indicator">● 实时更新中</span>
</h3>
<span class="meta">{{ selectedTaskMeta }}</span>
<div class="panel-actions">
<el-switch
v-model="autoScroll"
active-text="自动滚动"
class="auto-scroll-switch"
/>
<span class="meta">{{ selectedTaskMeta }}</span>
</div>
</div>
<div class="panel-body log-stream">
<div v-for="(log, index) in logs" :key="index" :class="['task-log-line', log.class]">
<span class="t">{{ log.time }}</span>{{ log.message }}
<div
ref="logContainerRef"
class="panel-body log-stream"
@scroll="handleScroll"
>
<!-- 虚拟滚动容器 -->
<div
:style="{ height: `${virtualizer.getTotalSize()}px`, position: 'relative' }"
>
<div
v-for="virtualRow in virtualizer.getVirtualItems()"
:key="String(virtualRow.key)"
:class="['task-log-line', logs[virtualRow.index].class]"
:style="{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}"
>
<span class="t">{{ logs[virtualRow.index].time }}</span>{{ logs[virtualRow.index].message }}
</div>
</div>
<div v-if="loadingLogs" class="task-log-line">
<span class="t">...</span>加载中
@@ -72,10 +100,11 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { taskLogApi, type TaskLogLine, type TaskLogSummary } from '@/api/taskLog'
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { taskLogApi, createTaskLogStream, type TaskLogLine, type TaskLogSummary } from '@/api/taskLog'
import { useBusinessLineStore } from '@/stores/businessLine'
import { useBusinessLineMockProfile } from '@/utils/businessLineMock'
import { useVirtualizer } from '@tanstack/vue-virtual'
const { currentName } = useBusinessLineMockProfile()
const businessLineStore = useBusinessLineStore()
@@ -87,6 +116,18 @@ const logs = ref<TaskLogLine[]>([])
const loadingTasks = ref(false)
const loadingLogs = ref(false)
const lastLoadedAt = ref<Date | null>(null)
const isStreaming = ref(false)
let eventSource: EventSource | null = null
const autoScroll = ref(true)
const logContainerRef = ref<HTMLDivElement | null>(null)
// 虚拟滚动配置
const virtualizer = useVirtualizer({
count: logs.value.length,
getScrollElement: () => logContainerRef.value,
estimateSize: () => 20,
overscan: 5,
})
const selectedTask = computed(() => tasks.value.find((task) => task.id === selectedTaskId.value))
const selectedTaskName = computed(() => selectedTask.value?.name || '未选择')
@@ -122,6 +163,8 @@ async function loadLogs(taskId: string) {
const data = await taskLogApi.get(taskId)
logs.value = data.lines
lastLoadedAt.value = new Date()
// 启动 SSE 流式更新
startStream(taskId)
} catch (error) {
logs.value = [{ time: formatTime(new Date()), message: error instanceof Error ? error.message : '任务日志加载失败', class: 'err' }]
} finally {
@@ -129,14 +172,99 @@ async function loadLogs(taskId: string) {
}
}
function startStream(taskId: string) {
stopStream() // 关闭之前的连接
eventSource = createTaskLogStream(taskId, {
onInit: (lines) => {
logs.value = lines
lastLoadedAt.value = new Date()
scrollToBottom()
},
onUpdate: (newLines) => {
logs.value = [...logs.value, ...newLines]
lastLoadedAt.value = new Date()
scrollToBottom()
},
onFinished: () => {
isStreaming.value = false
},
onError: (error) => {
console.error('SSE error:', error)
isStreaming.value = false
},
})
isStreaming.value = true
}
function stopStream() {
if (eventSource) {
eventSource.close()
eventSource = null
isStreaming.value = false
}
}
function scrollToBottom() {
if (!autoScroll.value) return
nextTick(() => {
if (logContainerRef.value) {
logContainerRef.value.scrollTop = logContainerRef.value.scrollHeight
}
})
}
function handleScroll() {
if (!logContainerRef.value) return
const { scrollTop, scrollHeight, clientHeight } = logContainerRef.value
const distanceFromBottom = scrollHeight - scrollTop - clientHeight
// 距离底部小于 50px 时认为在底部,恢复自动滚动
if (distanceFromBottom < 50) {
autoScroll.value = true
} else if (distanceFromBottom > 100) {
// 用户向上滚动超过 100px 时暂停自动滚动
autoScroll.value = false
}
}
function selectTask(taskId: string) {
if (selectedTaskId.value === taskId) {
return
}
stopStream() // 停止之前的流
selectedTaskId.value = taskId
void loadLogs(taskId)
}
function scrollToBottom() {
if (!autoScroll.value) return
nextTick(() => {
if (logContainerRef.value) {
logContainerRef.value.scrollTop = logContainerRef.value.scrollHeight
}
})
}
function handleScroll() {
if (!logContainerRef.value) return
const { scrollTop, scrollHeight, clientHeight } = logContainerRef.value
const distanceFromBottom = scrollHeight - scrollTop - clientHeight
// 距离底部小于 50px 时认为在底部,恢复自动滚动
if (distanceFromBottom < 50) {
autoScroll.value = true
} else if (distanceFromBottom > 100) {
// 用户向上滚动超过 100px 时暂停自动滚动
autoScroll.value = false
}
}
function refreshCurrent() {
void loadTasks()
}
@@ -155,6 +283,10 @@ watch(
onMounted(() => {
void loadTasks()
})
onUnmounted(() => {
stopStream()
})
</script>
<style scoped>
@@ -248,6 +380,7 @@ onMounted(() => {
.task-log-panel .panel-head {
gap: 14px;
flex-wrap: wrap;
}
.task-log-panel .panel-head h3 {
@@ -257,11 +390,36 @@ onMounted(() => {
gap: 10px;
}
.task-log-panel .panel-head .panel-actions {
margin-left: auto;
}
.selected-name {
color: var(--text-dim);
font-weight: 500;
}
.streaming-indicator {
font-size: 11px;
color: var(--accent);
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.panel-actions {
display: flex;
align-items: center;
gap: 12px;
}
.auto-scroll-switch {
--el-switch-on-color: var(--accent);
}
.log-stream {
max-height: calc(100vh - 210px);
min-height: 520px;