diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 51c8dfbf..ea95d8b7 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -93,6 +93,11 @@ function closeTimeline() { timelineDrawerVisible.value = false; } +// Exposed so the parent's three-dot menu can jump straight into the +// trace drawer for a card without forcing the user to click the +// detail drawer header link manually. +defineExpose({ openTimeline }); + marked.use({ breaks: true, // 启用单行换行转
gfm: true, // 启用 GitHub Flavored Markdown @@ -129,14 +134,14 @@ const viewMode = ref<'chunks' | 'merged' | 'preview'>('merged'); */ const mergeChunks = (chunks: any[]): string => { if (!chunks || chunks.length === 0) return ''; - + // 按 start_at 排序 const sortedChunks = [...chunks].sort((a, b) => { const startA = a.start_at ?? a.chunk_index ?? 0; const startB = b.start_at ?? b.chunk_index ?? 0; return startA - startB; }); - + // 初始化合并结果,第一个 chunk 直接加入 const mergedChunks: Array<{ content: string; @@ -147,16 +152,16 @@ const mergeChunks = (chunks: any[]): string => { start_at: sortedChunks[0].start_at ?? 0, end_at: sortedChunks[0].end_at ?? 0 }]; - + // 从第二个 chunk 开始遍历 for (let i = 1; i < sortedChunks.length; i++) { const currentChunk = sortedChunks[i]; const lastChunk = mergedChunks[mergedChunks.length - 1]; - + const currentStartAt = currentChunk.start_at ?? 0; const currentEndAt = currentChunk.end_at ?? 0; const currentContent = currentChunk.content || ''; - + // 如果当前 chunk 的起始位置在最后一个 chunk 的结束位置之后,直接添加 if (currentStartAt > lastChunk.end_at) { mergedChunks.push({ @@ -166,23 +171,23 @@ const mergeChunks = (chunks: any[]): string => { }); continue; } - + // 合并重叠的 chunks if (currentEndAt > lastChunk.end_at) { // 将内容转换为字符数组以正确处理多字节字符 const contentRunes = Array.from(currentContent); const contentLength = contentRunes.length; - + // 计算偏移量:内容长度 - (当前结束位置 - 上一个结束位置) const offset = contentLength - (currentEndAt - lastChunk.end_at); - + // 拼接非重叠部分 const newContent = contentRunes.slice(offset).join(''); lastChunk.content = lastChunk.content + newContent; lastChunk.end_at = currentEndAt; } } - + // 合并所有段落,用双换行符连接 return mergedChunks.map(chunk => chunk.content).join('\n\n'); }; @@ -233,7 +238,7 @@ const checkImage = (url) => { img.src = url; }); }; -renderer.image = function ({href, title, text}) { +renderer.image = function ({ href, title, text }) { if (!isValidImageURL(href)) { return `

${t('error.invalidImageLink')}

`; } @@ -246,7 +251,7 @@ renderer.image = function ({href, title, text}) { }; // 自定义代码块渲染器,只显示语言标签 -renderer.code = function ({text, lang}) { +renderer.code = function ({ text, lang }) { // 空值校验:防止 text 为 undefined 或 null if (!text || typeof text !== 'string') { text = ''; @@ -494,7 +499,7 @@ const processMarkdown = (markdownText) => { // 最终安全清理 let result = sanitizeHTML(html); - + return result; }; const handleClose = () => { @@ -671,7 +676,7 @@ const handleDeleteQuestion = async (item: any, chunkIndex: number, question: Gen try { await deleteGeneratedQuestion(item.id, question.id); MessagePlugin.success(t('common.deleteSuccess')); - + // 更新本地数据 const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata) : item.metadata; if (metadata && metadata.generated_questions) { @@ -681,7 +686,7 @@ const handleDeleteQuestion = async (item: any, chunkIndex: number, question: Gen } item.metadata = typeof item.metadata === 'string' ? JSON.stringify(metadata) : metadata; } - + // 通知父组件刷新数据 emit('questionDeleted', { chunkId: item.id, questionId: question.id }); } catch (error: any) { @@ -716,7 +721,7 @@ const toggleParentContext = async (item: any, index: number) => { parentContextExpanded.value = new Set(parentContextExpanded.value); return; } - + const parentId = item.parent_chunk_id; if (!parentContextCache.value.has(parentId)) { parentContextLoading.value.add(index); @@ -735,7 +740,7 @@ const toggleParentContext = async (item: any, index: number) => { parentContextLoading.value = new Set(parentContextLoading.value); } } - + parentContextExpanded.value.add(index); parentContextExpanded.value = new Set(parentContextExpanded.value); await runMarkdownPostRenderPipeline(); @@ -807,7 +812,8 @@ const handleDetailsScroll = () => { @@ -1124,7 +1068,7 @@ const handleDetailsScroll = () => { border-radius: 6px; background: var(--td-bg-color-container); overflow: hidden; - box-shadow: 0 1px 2px rgba(0,0,0,0.05); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); .code-block-header { display: flex; @@ -1144,6 +1088,7 @@ const handleDetailsScroll = () => { overflow: auto; font-size: 13px; line-height: 1.5; + code { background: transparent; padding: 0; @@ -1167,7 +1112,7 @@ const handleDetailsScroll = () => { display: flex; align-items: center; gap: 8px; - + .header-title { flex: 1; font-size: 16px; @@ -1185,7 +1130,9 @@ const handleDetailsScroll = () => { margin-bottom: 16px; } -.doc_box, .url_box, .manual_box { +.doc_box, +.url_box, +.manual_box { .info_panel(); } @@ -1198,33 +1145,48 @@ const handleDetailsScroll = () => { } /* ============== Trace entry (header inline link) ============== - Compact, lives in the drawer titlebar next to the file-type tag. - Replaces the previous big card-style trigger which dominated the - doc body. Reads as a quiet secondary action — colored dot + label - + duration + chevron — at the same visual weight as a t-link or - the file-type t-tag, so it doesn't compete with 文件名 / 摘要. */ + Sits in the drawer titlebar next to the file-type tag. Status-aware + tinted pill: success-green when the trace finished cleanly, + amber-stripe when still in flight, error-red on failure. The + duration is shown in mono digits to the right; the trace icon + anchors the meaning so the button reads as "open the trace" even + without the word "查看". */ .kp-trace-link { display: inline-flex; align-items: center; gap: 6px; - height: 24px; - padding: 0 10px; + height: 26px; + padding: 0 10px 0 8px; border: 1px solid var(--td-component-stroke); - border-radius: 999px; - background: transparent; + border-radius: var(--td-radius-default); + background: var(--td-bg-color-container); color: var(--td-text-color-secondary); font-family: var(--app-font-family); font-size: 12px; + line-height: 1; cursor: pointer; - transition: border-color 150ms ease, color 150ms ease, background 150ms ease; + transition: border-color 150ms ease, color 150ms ease, + background 150ms ease, box-shadow 150ms ease; } .kp-trace-link:hover { - border-color: var(--td-brand-color); - color: var(--td-brand-color); - background: var(--td-brand-color-light); + border-color: var(--td-text-color-secondary); + color: var(--td-text-color-primary); + background: var(--td-bg-color-container-hover); +} + +.kp-trace-link-icon { + display: inline-flex; + align-items: center; + justify-content: center; + color: var(--td-text-color-placeholder); + margin-right: -2px; + transition: color 150ms ease; +} + +.kp-trace-link:hover .kp-trace-link-icon { + color: var(--td-text-color-secondary); } -.kp-trace-link:hover .kp-trace-link-arrow { transform: translateX(2px); } .kp-trace-link-dot { width: 6px; @@ -1233,37 +1195,130 @@ const handleDetailsScroll = () => { background: var(--td-text-color-placeholder); flex-shrink: 0; } -.kp-trace-link-dot-done, -.kp-trace-link-dot-completed { background: var(--td-success-color); } -.kp-trace-link-dot-failed { background: var(--td-error-color); } -.kp-trace-link-dot-running, -.kp-trace-link-dot-processing, -.kp-trace-link-dot-pending { - background: var(--td-brand-color); - animation: kpTriggerPulse 1.6s ease-in-out infinite; -} -.kp-trace-link-text { font-weight: 500; } +.kp-trace-link-text { + font-weight: 500; + letter-spacing: 0.02em; +} .kp-trace-link-meta { font-family: var(--app-font-family-mono); font-size: 11px; color: var(--td-text-color-placeholder); + font-weight: 500; + padding-left: 2px; + border-left: 1px solid var(--td-component-stroke); + margin-left: 2px; + padding-left: 8px; letter-spacing: 0; } -.kp-trace-link-arrow { - color: var(--td-text-color-placeholder); - transition: transform 150ms ease, color 150ms ease; - margin-left: 2px; +/* Status tints — done / failed / running each get a soft palette + pull. Lets a glance at the pill tell you the trace's outcome + without needing to look at the colored dot. */ +.kp-trace-link-done, +.kp-trace-link-completed { + border-color: var(--td-success-color-3); + background: var(--td-success-color-1); + color: var(--td-success-color-7); } -.kp-trace-link:hover .kp-trace-link-arrow { - color: var(--td-brand-color); + +.kp-trace-link-done .kp-trace-link-dot, +.kp-trace-link-completed .kp-trace-link-dot { + background: var(--td-success-color); +} + +.kp-trace-link-done .kp-trace-link-icon, +.kp-trace-link-completed .kp-trace-link-icon { + color: var(--td-success-color-6); +} + +.kp-trace-link-done .kp-trace-link-meta, +.kp-trace-link-completed .kp-trace-link-meta { + color: var(--td-success-color-7); + border-color: var(--td-success-color-3); +} + +.kp-trace-link-done:hover, +.kp-trace-link-completed:hover { + border-color: var(--td-success-color-5); + background: var(--td-success-color-2); + color: var(--td-success-color-8); +} + +.kp-trace-link-failed { + border-color: var(--td-error-color-3); + background: var(--td-error-color-1); + color: var(--td-error-color-7); +} + +.kp-trace-link-failed .kp-trace-link-dot { + background: var(--td-error-color); +} + +.kp-trace-link-failed .kp-trace-link-icon { + color: var(--td-error-color-6); +} + +.kp-trace-link-failed .kp-trace-link-meta { + color: var(--td-error-color-7); + border-color: var(--td-error-color-3); +} + +.kp-trace-link-failed:hover { + border-color: var(--td-error-color-5); + background: var(--td-error-color-2); + color: var(--td-error-color-8); +} + +.kp-trace-link-running, +.kp-trace-link-processing, +.kp-trace-link-pending { + border-color: var(--td-warning-color-3); + background: var(--td-warning-color-1); + color: var(--td-warning-color-7); +} + +.kp-trace-link-running .kp-trace-link-dot, +.kp-trace-link-processing .kp-trace-link-dot, +.kp-trace-link-pending .kp-trace-link-dot { + background: var(--td-warning-color); + animation: kpTriggerPulse 1.4s ease-in-out infinite; +} + +.kp-trace-link-running .kp-trace-link-icon, +.kp-trace-link-processing .kp-trace-link-icon, +.kp-trace-link-pending .kp-trace-link-icon { + color: var(--td-warning-color-6); +} + +.kp-trace-link-running .kp-trace-link-meta, +.kp-trace-link-processing .kp-trace-link-meta, +.kp-trace-link-pending .kp-trace-link-meta { + color: var(--td-warning-color-7); + border-color: var(--td-warning-color-3); +} + +.kp-trace-link-running:hover, +.kp-trace-link-processing:hover, +.kp-trace-link-pending:hover { + border-color: var(--td-warning-color-5); + background: var(--td-warning-color-2); + color: var(--td-warning-color-8); } @keyframes kpTriggerPulse { - 0%, 100% { box-shadow: 0 0 0 0 var(--td-brand-color-light); } - 50% { box-shadow: 0 0 0 4px transparent; } + + 0%, + 100% { + transform: scale(1); + opacity: 1; + } + + 50% { + transform: scale(0.6); + opacity: 0.5; + } } /* Hidden mount keeps fetcher live without showing UI */ @@ -1351,7 +1406,7 @@ const handleDetailsScroll = () => { position: relative; } -.kp-drawer-body > :deep(.kp-timeline) { +.kp-drawer-body> :deep(.kp-timeline) { width: 100%; height: 100%; } @@ -1485,20 +1540,20 @@ const handleDetailsScroll = () => { border-radius: 4px; background: var(--td-bg-color-container-hover); padding: 8px 12px; - + .url_link { display: flex; align-items: center; gap: 8px; color: var(--td-brand-color); text-decoration: none; - + .url_text { flex: 1; font-size: 13px; word-break: break-all; } - + .jump-icon { flex-shrink: 0; color: var(--td-brand-color); @@ -1511,7 +1566,7 @@ const handleDetailsScroll = () => { flex: 1; display: flex; align-items: center; - + .manual_title { color: var(--td-text-color-primary); font-size: 13px; @@ -1539,7 +1594,7 @@ const handleDetailsScroll = () => { display: flex; align-items: center; gap: 8px; - + .label { margin: 0; font-size: 14px; @@ -1556,7 +1611,7 @@ const handleDetailsScroll = () => { flex-wrap: wrap; gap: 12px; } - + .meta-left { display: flex; align-items: center; @@ -1579,7 +1634,7 @@ const handleDetailsScroll = () => { .view-mode-buttons { display: flex; gap: 4px; - + .view-mode-btn { height: 28px; min-width: 60px; @@ -1623,20 +1678,20 @@ const handleDetailsScroll = () => { margin-bottom: 8px; padding-bottom: 6px; border-bottom: 1px solid var(--td-component-stroke); - + .chunk-index { color: var(--td-text-color-placeholder); font-size: 12px; font-weight: 600; letter-spacing: 0.5px; } - + .chunk-header-right { display: flex; align-items: center; gap: 8px; } - + .chunk-meta { color: var(--td-text-color-disabled); font-size: 11px; @@ -1667,7 +1722,7 @@ const handleDetailsScroll = () => { background: var(--td-brand-color-light); border-radius: 4px; border-left: 3px solid var(--td-brand-color); - + .md-content { color: var(--td-text-color-secondary); font-size: 13px; @@ -1708,29 +1763,29 @@ const handleDetailsScroll = () => { font-size: 13px; color: var(--td-text-color-primary); line-height: 1.5; - + &:hover { .delete-question-btn { opacity: 1; } } - + .question-icon { color: var(--td-brand-color-active); flex-shrink: 0; margin-top: 2px; } - + .question-text { flex: 1; word-break: break-word; } - + .delete-question-btn { opacity: 0; flex-shrink: 0; color: var(--td-text-color-placeholder); - + &:hover { color: var(--td-error-color); } diff --git a/frontend/src/components/knowledge-processing-timeline.vue b/frontend/src/components/knowledge-processing-timeline.vue index 23650e2a..4766e819 100644 --- a/frontend/src/components/knowledge-processing-timeline.vue +++ b/frontend/src/components/knowledge-processing-timeline.vue @@ -39,12 +39,23 @@ interface SpansResponse { last_error?: LastError | null } -const props = defineProps<{ - knowledgeId: string - parseStatus?: string - autoPoll?: boolean - compact?: boolean -}>() +// IMPORTANT: Vue 3 coerces missing Boolean props to `false`, NOT +// `undefined` — so an optional boolean parent omits is indistinguishable +// from one explicitly set to false. That bit us: every parent that +// didn't pass auto-poll silently got polling disabled. Use withDefaults +// to make the intent explicit: polling is ON unless a parent opts out. +const props = withDefaults( + defineProps<{ + knowledgeId: string + parseStatus?: string + autoPoll?: boolean + compact?: boolean + }>(), + { + autoPoll: true, + compact: false, + }, +) const emit = defineEmits<{ (e: 'update:hasSpans', has: boolean): void @@ -66,11 +77,18 @@ const expandedJsonKeys = ref>(new Set()) const nowTick = ref(Date.now()) const detailTab = ref<'overview' | 'input' | 'output' | 'metadata' | 'raw'>('overview') const lastFetchedAt = ref(0) -// Tracks whether we've completed our FIRST successful fetch for the -// current knowledgeId. After that, the user owns expandedRows — we -// don't re-auto-expand on every poll (would un-collapse rows the user -// intentionally collapsed mid-parse). -let firstLoadDone = false +// Stages the user has explicitly toggled (in either direction). Once +// a stage is in this set, the auto-expand-when-children-appear rule +// stops applying to it — the user's last action wins forever. +// +// Why this beats the old "firstLoadDone once" approach: +// - Old logic only auto-expanded on the very first fetch. If a stage +// had no subspans yet at that moment, it'd stay collapsed even +// after children arrived later, forcing a manual click. +// - New logic re-evaluates on every fetch: stages with children get +// expanded unless the user has spoken. Discoverability + respect +// for manual collapse, both. +const userToggledStages = ref>(new Set()) // Tracks consecutive fetch failures so the "更新于" caption can surface // staleness. When the parse_status is mid-flight but every fetch is // hitting an error, the loop keeps going silently — without this @@ -81,11 +99,27 @@ const lastFetchOk = ref(true) const attemptStatuses = reactive>(new Map()) +// ===== Polling, take N+1: brutally simple ===== +// +// Prior incarnations tried "smart" polling (self-rescheduling chains, +// watchers, watchdogs, fetchInFlight gates routing through tick +// callbacks). They all had edge cases where the loop silently died +// while the LIVE badge kept showing. +// +// New design: ONE setInterval that fires every tick for the entire +// lifetime of the component. The tick callback checks state and +// either calls fetchSpans or no-ops. No re-arming, no clearing, no +// watchers, no chains. The interval cannot get "stranded" because +// nothing ever stops it until unmount. +// +// A 2-second no-op (3 ref reads) is free. The simplicity is the win. let pollTimer: ReturnType | null = null let nowTimer: ReturnType | null = null let unmounted = false -// Guard against overlapping fetches when a previous poll is still -// in flight (e.g. slow backend) and the next interval tick fires. +// Drops overlapping fetches. Does NOT gate the polling decision — +// the tick callback owns scheduling. If fetchInFlight is stuck (e.g. +// network black hole), the worst case is one stuck request blocking +// retries until axios timeout (30s); the loop itself stays alive. let fetchInFlight = false const stages = computed(() => { @@ -134,45 +168,37 @@ function isPolling(status?: string): boolean { return status === 'pending' || status === 'processing' } -const isLive = computed(() => isPolling(data.value?.parse_status)) - -function clearTimer() { - if (pollTimer) { - clearInterval(pollTimer) - pollTimer = null +// True if any node in the trace is still running/pending. Crucial for +// postprocess — its subspans (summary/question/graph.chunk[*]) run +// asynchronously AFTER the main pipeline closes, so parse_status +// flips to 'completed' while there's plenty of work still happening. +// Without checking the tree we'd stop polling at that moment and +// strand the user staring at half-rendered postprocess until they +// manually refresh. +function spanTreeActive(node?: SpanNode): boolean { + if (!node) return false + const s = node.status + if (s === 'running' || s === 'pending') return true + const kids = node.children || [] + for (let i = 0; i < kids.length; i++) { + if (spanTreeActive(kids[i])) return true } + return false } -// Set up the auto-poll interval if it's not already running. Cheap -// to call repeatedly — does nothing if already armed. -function ensurePolling() { - if (unmounted) return - if (props.autoPoll === false) return - if (pollTimer) return - console.debug('[KnowledgeTimeline] arming poll interval', { knowledgeId: props.knowledgeId, every: POLL_INTERVAL_MS }) - pollTimer = setInterval(() => { - // Guard against overlapping fetches AND state changes that have - // since flipped status out of polling. Keeps the loop conservative. - if (unmounted) { - clearTimer() - return - } - if (fetchInFlight) return - const status = data.value?.parse_status - if (!status) { - // First fetch hasn't completed yet — give it another tick to - // settle. Common when the drawer opens against a slow network. - return - } - if (!isPolling(status)) { - // Terminal state: stop the interval. The watcher will re-arm - // it if status flips back to polling (e.g. user triggers reparse). - clearTimer() - return - } - fetchSpans() - }, POLL_INTERVAL_MS) -} +const traceActive = computed(() => spanTreeActive(data.value?.trace)) + +// Drives BOTH the LIVE badge AND polling. Single source of truth: +// 1. If we have data: still live while parse_status is polling +// OR the span tree has any running descendant. +// 2. If we don't have data yet (initial paint): trust the parent's +// parseStatus hint so the UI shows LIVE immediately. +const isLive = computed(() => { + if (data.value) { + return isPolling(data.value.parse_status) || traceActive.value + } + return isPolling(props.parseStatus) +}) async function fetchSpans(opts: { manual?: boolean } = {}) { if (!props.knowledgeId) return @@ -189,21 +215,23 @@ async function fetchSpans(opts: { manual?: boolean } = {}) { if (selectedAttempt.value === undefined) { selectedAttempt.value = data.value.attempt } - // First-load auto-expand: surface any stage that already has - // subspans (multimodal.image[i], postprocess.summary, etc.) so - // users don't have to click ▸ on every stage to discover them. - // Only runs once per (knowledgeId × attempt) — subsequent polls - // honor whatever the user has collapsed. - if (!firstLoadDone) { - const expanded = new Set(['__root__']) - for (const stage of data.value.trace?.children || []) { - if ((stage.children || []).length > 0) { - expanded.add(stage.span_id || `stage:${stage.name}`) - } + // Auto-expand rule, applied on EVERY fetch: + // - Stage has children + user hasn't toggled it → expand + // - Stage has no children → leave whatever state it was in + // - User has toggled the stage (either direction) → don't touch + // This way subspans that arrive mid-parse surface themselves + // without forcing a click, but a user who explicitly collapsed + // a noisy stage stays in control. + const expanded = new Set(expandedRows.value) + expanded.add('__root__') + for (const stage of data.value.trace?.children || []) { + const key = stage.span_id || `stage:${stage.name}` + if (userToggledStages.value.has(key)) continue + if ((stage.children || []).length > 0) { + expanded.add(key) } - expandedRows.value = expanded - firstLoadDone = true } + expandedRows.value = expanded const traceStatus = data.value.trace?.status || data.value.parse_status || 'running' attemptStatuses.set(data.value.attempt, traceStatus) ensureAttemptStatuses() @@ -232,18 +260,6 @@ async function fetchSpans(opts: { manual?: boolean } = {}) { loading.value = false refreshing.value = false fetchInFlight = false - // Arm the polling loop if the freshly-fetched status is mid-flight. - // ensurePolling is idempotent so calling it from every fetchSpans - // is safe — keeps the loop alive even after manual refreshes that - // happen during in-flight parsing. The actual decision to fetch on - // each tick is made inside the interval based on current state, so - // status changing from 'processing' to 'completed' between ticks - // simply stops the next fetch and clears the timer. - if (data.value?.parse_status && isPolling(data.value.parse_status)) { - ensurePolling() - } else { - clearTimer() - } } } @@ -258,7 +274,7 @@ function ensureAttemptStatuses() { attemptStatuses.set(n, res.data.trace.status || res.data.parse_status || 'running') } }) - .catch(() => {}) + .catch(() => { }) } } @@ -314,8 +330,10 @@ function onAttemptChange(n: number) { if (Number.isNaN(n)) return selectedAttempt.value = n selectedSpanId.value = null - // Re-trigger auto-expand on the new attempt's stages. - firstLoadDone = false + // New attempt: forget per-stage user choices so the auto-expand + // rule re-evaluates cleanly against the new attempt's tree. + userToggledStages.value = new Set() + expandedRows.value = new Set(['__root__']) fetchSpans() } @@ -327,30 +345,11 @@ watch( expandedRows.value = new Set(['__root__']) selectedSpanId.value = null attemptStatuses.clear() - firstLoadDone = false + userToggledStages.value = new Set() fetchSpans() }, ) -// Watchdog: re-arm the polling interval whenever parse_status enters -// a polling state (pending/processing). Idempotent — ensurePolling -// is a no-op if the interval is already running. This is the safety -// net that catches the "first fetch returns 'processing' but the loop -// somehow never re-fires" case the user originally reported. -watch( - () => data.value?.parse_status, - (status) => { - if (unmounted) return - if (!status) return - if (props.autoPoll === false) return - if (isPolling(status)) { - ensurePolling() - } else { - clearTimer() - } - }, -) - function onKeydown(ev: KeyboardEvent) { if (ev.key === 'Escape' && selectedSpanId.value) { selectedSpanId.value = null @@ -359,14 +358,21 @@ function onKeydown(ev: KeyboardEvent) { onMounted(() => { fetchSpans() - // Arm the polling interval unconditionally — the per-tick callback - // decides whether to actually fetch based on current parse_status. - // This way the loop can never get stranded waiting on a status - // transition that already happened. The callback self-clears when - // status reaches a terminal state, and the watcher re-arms if it - // flips back to polling. - ensurePolling() - // Tick at 1Hz; running bars and "next refresh" countdown depend on it. + // One permanent interval for the entire component lifetime. The + // tick decides whether to actually fetch — no clearing, no + // re-arming, no watchers wired into it. If this interval ever + // stops firing, the entire JS event loop is wedged (in which case + // nothing else would work either). + if (props.autoPoll) { + pollTimer = setInterval(() => { + if (unmounted) return + if (fetchInFlight) return + // Reuse the same isLive logic that drives the badge — so what + // the user sees and what we actually fetch can never disagree. + if (!isLive.value) return + fetchSpans() + }, POLL_INTERVAL_MS) + } nowTimer = setInterval(() => { nowTick.value = Date.now() }, 1000) @@ -375,7 +381,10 @@ onMounted(() => { onBeforeUnmount(() => { unmounted = true - clearTimer() + if (pollTimer) { + clearInterval(pollTimer) + pollTimer = null + } if (nowTimer) { clearInterval(nowTimer) nowTimer = null @@ -457,7 +466,11 @@ const tEnd = computed(() => { const max = Math.max(...all) candidate = candidate === null ? max : Math.max(candidate, max) } - if (isPolling(data.value?.parse_status)) { + // Extend the right edge to "now" whenever the trace is still + // actively producing spans — this covers both parse_status mid-flight + // AND the postprocess-async case where the top-level status closes + // but subspans keep ticking. Both conditions are captured by isLive. + if (isLive.value) { const now = nowTick.value candidate = candidate === null ? now : Math.max(candidate, now) } @@ -576,7 +589,13 @@ function barStyle(node: SpanNode): Record { if (!total || t0.value === null) return { display: 'none' } const start = nodeStart(node) if (start === null) return { display: 'none' } - const end = nodeEnd(node) ?? (isPolling(data.value?.parse_status) ? nowTick.value : start) + // For a span with no recorded finished_at, use "now" as the end + // whenever it's plausibly still running — either the trace overall + // is live, or this individual span's status says it's in flight. + // Without the second clause, postprocess subspans that survived past + // parse_status='completed' would collapse to zero width. + const liveBar = isLive.value || node.status === 'running' || node.status === 'pending' + const end = nodeEnd(node) ?? (liveBar ? nowTick.value : start) const leftPct = ((start - t0.value) / total) * 100 const widthPct = Math.max(0.4, ((end - start) / total) * 100) return { @@ -658,6 +677,15 @@ function toggleTree(row: FlatRow, ev?: MouseEvent) { if (next.has(row.key)) next.delete(row.key) else next.add(row.key) expandedRows.value = next + // Once the user toggles a stage row, opt it out of further + // auto-management so subsequent polls don't override their choice. + // Deeper rows (subspans of subspans) aren't auto-managed anyway, + // so we only need to track stage-level intent here. + if (row.isStage) { + const touched = new Set(userToggledStages.value) + touched.add(row.key) + userToggledStages.value = touched + } } function selectRow(row: FlatRow) { @@ -972,13 +1000,8 @@ const stageBreakdown = computed(() => { ========================================================= -->