chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,105 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { DOMParser } from '@xmldom/xmldom'
|
||||
import { vStableHtml } from './stableHtml.ts'
|
||||
import { clearProtectedFileFailureCache, hydrateProtectedFileImages } from '../utils/security.ts'
|
||||
|
||||
// Use real parsed trees and the complete directive. Adapt the small browser
|
||||
// surface absent from xmldom rather than extracting the morph implementation.
|
||||
function parse(html: string): any {
|
||||
const root = new DOMParser().parseFromString(`<div>${html}</div>`, 'text/xml').documentElement!
|
||||
function adapt(el: any) {
|
||||
const tag = el.tagName.toUpperCase()
|
||||
Object.defineProperties(el, {
|
||||
tagName: { value: tag },
|
||||
children: { get: () => Array.from(el.childNodes).filter((child: any) => child.nodeType === 1) },
|
||||
firstElementChild: { get: () => el.children[0] ?? null },
|
||||
parentElement: { get: () => el.parentNode?.nodeType === 1 ? el.parentNode : null },
|
||||
src: { get: () => el.getAttribute('src'), set: value => el.setAttribute('src', value) },
|
||||
alt: { get: () => el.getAttribute('alt') },
|
||||
})
|
||||
el.complete = true
|
||||
el.naturalWidth = 1
|
||||
el.classList = { contains: (name: string) => (el.getAttribute('class') || '').split(/\s+/).includes(name) }
|
||||
el.dataset = new Proxy({}, {
|
||||
get: (_, key: string) => el.getAttribute(`data-${key.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`)}`),
|
||||
set: (_, key: string, value) => {
|
||||
el.setAttribute(`data-${key.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`)}`, value)
|
||||
return true
|
||||
},
|
||||
})
|
||||
el.style = {
|
||||
get display() { return el.getAttribute('style')?.match(/(?:^|;)\s*display:\s*([^;]+)/)?.[1] || '' },
|
||||
set display(value: string) {
|
||||
const rest = (el.getAttribute('style') || '').replace(/(?:^|;)\s*display:[^;]*;?/g, '')
|
||||
el.setAttribute('style', `${rest}${value ? `;display:${value}` : ''}`)
|
||||
},
|
||||
}
|
||||
el.querySelectorAll = (selector: string) => Array.from(el.getElementsByTagName('img'))
|
||||
.filter((img: any) => selector.includes('src^=') || img.hasAttribute('data-protected-src'))
|
||||
for (const child of el.children) adapt(child)
|
||||
}
|
||||
adapt(root)
|
||||
return root
|
||||
}
|
||||
|
||||
test('missing image and paragraph stay hidden across streaming morphs, then recover without new HTML', async t => {
|
||||
const previous = {
|
||||
Node: (globalThis as any).Node, HTMLImageElement: (globalThis as any).HTMLImageElement,
|
||||
document: (globalThis as any).document, window: (globalThis as any).window, fetch: globalThis.fetch,
|
||||
}
|
||||
Object.assign(globalThis, {
|
||||
Node: { ELEMENT_NODE: 1, TEXT_NODE: 3, COMMENT_NODE: 8 },
|
||||
HTMLImageElement: class { static [Symbol.hasInstance](el: any) { return el?.tagName === 'IMG' } },
|
||||
document: {
|
||||
createElement(tag: string) {
|
||||
assert.equal(tag, 'template')
|
||||
return { content: null, set innerHTML(html: string) { this.content = parse(html) } }
|
||||
},
|
||||
},
|
||||
window: { location: { origin: 'http://localhost' }, addEventListener() {} },
|
||||
})
|
||||
t.after(() => { Object.assign(globalThis, previous); clearProtectedFileFailureCache() })
|
||||
const source = 'local://2/exports/morph-hidden.png'
|
||||
const imageHTML = `<p><img src="${source}" data-protected-src="${source}" style="max-width:80%" /></p>`
|
||||
const root = parse(`${imageHTML}<p>first</p>`)
|
||||
const img = root.children[0].firstElementChild
|
||||
const paragraph = img.parentElement
|
||||
const access = { mode: 'message', sessionId: 'session', messageId: 'assistant' } as const
|
||||
let persisted = false
|
||||
globalThis.fetch = async () => persisted
|
||||
? new Response(new Blob(['png'], { type: 'image/png' })) : new Response(null, { status: 404 })
|
||||
await hydrateProtectedFileImages(root, access)
|
||||
assert.equal(img.style.display, 'none')
|
||||
assert.equal(paragraph.style.display, 'none')
|
||||
let previousHTML = `${imageHTML}<p>first</p>`
|
||||
for (const text of ['first second', 'first second third']) {
|
||||
const html = `${imageHTML}<p>${text}</p>`
|
||||
;(vStableHtml.updated as Function)(root, { value: html, oldValue: previousHTML })
|
||||
// Assert BEFORE another onUpdated/hydrate pass can mask a flicker.
|
||||
assert.equal(root.children[0].firstElementChild, img)
|
||||
assert.equal(img.style.display, 'none')
|
||||
assert.equal(paragraph.style.display, 'none')
|
||||
previousHTML = html
|
||||
}
|
||||
persisted = true
|
||||
clearProtectedFileFailureCache()
|
||||
await hydrateProtectedFileImages(root, access)
|
||||
assert.match(img.src, /^blob:/)
|
||||
assert.equal(img.style.display, '')
|
||||
assert.equal(paragraph.style.display, '')
|
||||
assert.equal(img.hasAttribute('data-protected-hidden'), false)
|
||||
assert.equal(paragraph.hasAttribute('data-protected-hidden'), false)
|
||||
|
||||
// A new source occupying the same paragraph must not inherit hidden state.
|
||||
persisted = false
|
||||
const other = 'local://2/exports/morph-other.png'
|
||||
const otherHTML = imageHTML.replaceAll(source, other)
|
||||
;(vStableHtml.updated as Function)(root, { value: `${otherHTML}<p>changed</p>`, oldValue: previousHTML })
|
||||
await hydrateProtectedFileImages(root, access)
|
||||
assert.equal(img.style.display, 'none')
|
||||
;(vStableHtml.updated as Function)(root, { value: `${imageHTML}<p>restored</p>`, oldValue: `${otherHTML}<p>changed</p>` })
|
||||
assert.notEqual(img.style.display, 'none')
|
||||
assert.notEqual(paragraph.style.display, 'none')
|
||||
assert.equal(img.hasAttribute('data-protected-hidden'), false)
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { ObjectDirective } from 'vue';
|
||||
|
||||
function imageIdentity(img: HTMLImageElement): string {
|
||||
return (img.getAttribute('data-protected-src') || img.currentSrc || img.src || '').trim();
|
||||
}
|
||||
|
||||
function canMorph(current: Node, next: Node): boolean {
|
||||
if (current.nodeType !== next.nodeType) return false;
|
||||
if (current.nodeType !== Node.ELEMENT_NODE) return true;
|
||||
return (current as Element).tagName === (next as Element).tagName;
|
||||
}
|
||||
|
||||
function syncAttributes(current: Element, next: Element, preserved: Set<string> = new Set()): void {
|
||||
Array.from(current.attributes).forEach(({ name }) => {
|
||||
if (!preserved.has(name) && !next.hasAttribute(name)) current.removeAttribute(name);
|
||||
});
|
||||
Array.from(next.attributes).forEach(({ name, value }) => {
|
||||
if (!preserved.has(name) && current.getAttribute(name) !== value) {
|
||||
current.setAttribute(name, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function morphImage(current: HTMLImageElement, next: HTMLImageElement): void {
|
||||
const sameProtectedSource = Boolean(
|
||||
current.getAttribute('data-protected-src')
|
||||
&& current.getAttribute('data-protected-src') === next.getAttribute('data-protected-src'),
|
||||
);
|
||||
const sameIdentity = imageIdentity(current) === imageIdentity(next);
|
||||
const sameProtectedAlt = Boolean(
|
||||
current.getAttribute('data-protected-src')
|
||||
&& next.getAttribute('data-protected-src')
|
||||
&& current.alt
|
||||
&& current.alt === next.alt,
|
||||
);
|
||||
const keepDecodedImage = current.complete
|
||||
&& current.naturalWidth > 1
|
||||
&& (sameProtectedSource || sameIdentity || sameProtectedAlt);
|
||||
|
||||
if (sameProtectedSource && current.hasAttribute('data-protected-hidden')) {
|
||||
// The authenticated loader keeps missing images addressable for the final
|
||||
// retry. Do not reveal their 1px placeholder between streaming patches.
|
||||
syncAttributes(current, next, new Set(['style', 'data-protected-hidden']));
|
||||
return;
|
||||
}
|
||||
|
||||
if (keepDecodedImage) {
|
||||
// Never write the placeholder src (or loading flags) over an image Chrome
|
||||
// has already decoded. More importantly, leave this exact DOM node attached
|
||||
// to the document so Chromium keeps its painted image layer.
|
||||
syncAttributes(current, next, new Set([
|
||||
'src',
|
||||
'data-protected-src',
|
||||
'data-img-loading',
|
||||
'data-auth-hydrated',
|
||||
]));
|
||||
return;
|
||||
}
|
||||
|
||||
syncAttributes(current, next);
|
||||
}
|
||||
|
||||
function isMermaidCanvas(el: Element): boolean {
|
||||
return el.classList.contains('chat-mermaid-block__canvas')
|
||||
|| (el.tagName === 'PRE' && el.classList.contains('mermaid'));
|
||||
}
|
||||
|
||||
function mermaidCanvasHasSvg(el: Element): boolean {
|
||||
return !!el.querySelector('svg');
|
||||
}
|
||||
|
||||
function morphMermaidCanvas(current: Element, next: Element): void {
|
||||
// Incoming HTML from marked still has mermaid source. Keep a diagram that
|
||||
// was already painted so typewriter / stream ticks cannot flash it back
|
||||
// into a fenced code block.
|
||||
if (mermaidCanvasHasSvg(current) && !mermaidCanvasHasSvg(next)) {
|
||||
syncAttributes(current, next, new Set(['data-mermaid']));
|
||||
return;
|
||||
}
|
||||
syncAttributes(current, next);
|
||||
morphChildren(current, next);
|
||||
}
|
||||
|
||||
function morphNode(current: Node, next: Node): void {
|
||||
if (current.nodeType === Node.TEXT_NODE || current.nodeType === Node.COMMENT_NODE) {
|
||||
if (current.nodeValue !== next.nodeValue) current.nodeValue = next.nodeValue;
|
||||
return;
|
||||
}
|
||||
|
||||
const currentElement = current as Element;
|
||||
const nextElement = next as Element;
|
||||
if (currentElement instanceof HTMLImageElement && nextElement instanceof HTMLImageElement) {
|
||||
morphImage(currentElement, nextElement);
|
||||
return;
|
||||
}
|
||||
if (isMermaidCanvas(currentElement) && isMermaidCanvas(nextElement)) {
|
||||
morphMermaidCanvas(currentElement, nextElement);
|
||||
return;
|
||||
}
|
||||
|
||||
// Standalone missing images hide their empty paragraph as well. Preserve it
|
||||
// only while the next paragraph still contains that exact image and no text.
|
||||
const currentImage = currentElement.firstElementChild;
|
||||
const nextImage = nextElement.firstElementChild;
|
||||
const keepHiddenParagraph = currentElement.tagName === 'P'
|
||||
&& currentElement.hasAttribute('data-protected-hidden')
|
||||
&& nextElement.children.length === 1 && !nextElement.textContent?.trim()
|
||||
&& nextImage?.tagName === 'IMG'
|
||||
&& Boolean(currentImage?.getAttribute('data-protected-src'))
|
||||
&& currentImage?.getAttribute('data-protected-src') === nextImage?.getAttribute('data-protected-src');
|
||||
syncAttributes(currentElement, nextElement,
|
||||
keepHiddenParagraph ? new Set(['style', 'data-protected-hidden']) : undefined);
|
||||
morphChildren(currentElement, nextElement);
|
||||
}
|
||||
|
||||
function morphChildren(currentParent: ParentNode, nextParent: ParentNode): void {
|
||||
const desiredChildren = Array.from(nextParent.childNodes);
|
||||
let current = currentParent.firstChild;
|
||||
|
||||
for (const desired of desiredChildren) {
|
||||
if (current && canMorph(current, desired)) {
|
||||
const following = current.nextSibling;
|
||||
morphNode(current, desired);
|
||||
current = following;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Insert only the new/mismatched subtree. Existing matching ancestors and
|
||||
// their image descendants remain connected throughout streaming updates.
|
||||
currentParent.insertBefore(desired.cloneNode(true), current);
|
||||
}
|
||||
|
||||
while (current) {
|
||||
const following = current.nextSibling;
|
||||
currentParent.removeChild(current);
|
||||
current = following;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch sanitized streaming HTML in place.
|
||||
*
|
||||
* Replacing innerHTML — or moving decoded images through a detached template —
|
||||
* makes Chromium briefly drop the image's painted layer on every typewriter
|
||||
* frame. This directive morphs text and surrounding markup without detaching a
|
||||
* matching loaded <img> node.
|
||||
*/
|
||||
export const vStableHtml: ObjectDirective<HTMLElement, string> = {
|
||||
beforeMount(el, binding) {
|
||||
el.innerHTML = binding.value || '';
|
||||
},
|
||||
updated(el, binding) {
|
||||
const html = binding.value || '';
|
||||
if (html === binding.oldValue) return;
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = html;
|
||||
morphChildren(el, template.content);
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user