Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(debug): add global development tools and queue diagnostics
Timothy Yin2efd5d60a57e
diff --git a/app/app.vue b/app/app.vueindex 2fdd2dc1..d2a2a4f3 100644--- a/app/app.vue+++ b/app/app.vue@@ -3,6 +3,10 @@ import dayjsLocale_zhCN from 'dayjs/locale/zh-cn'import dayjsLocale_zhTW from 'dayjs/locale/zh-tw'import dayjsLocale_zhHK from 'dayjs/locale/zh-hk'+const DebugPanel = import.meta.dev+ ? defineAsyncComponent(() => import('~/components/debug/Panel.vue'))+ : null+const router = useRouter()const dayjs = useDayjs()const colorMode = useColorMode()@@ -69,8 +73,14 @@ const handleIndexChange = (newIndex: number) => {switchToIndex(newIndex)const photoId = viewerPhotos.value[newIndex]?.idif (!photoId) return- if (returnRoute.value?.startsWith('/albums/') && route.path === returnRoute.value) {- router.replace({ path: route.path, query: { ...route.query, photo: photoId } })+ if (+ returnRoute.value?.startsWith('/albums/') &&+ route.path === returnRoute.value+ ) {+ router.replace({+ path: route.path,+ query: { ...route.query, photo: photoId },+ })} else {router.replace(`/${photoId}`)}@@ -132,6 +142,10 @@ provide(<NuxtPage /></NuxtLayout><ClientOnly>+ <component+ :is="DebugPanel"+ v-if="DebugPanel"+ /><PhotoViewer:photos="viewerPhotos":current-index="currentPhotoIndex"diff --git a/app/components/debug/Control.vue b/app/components/debug/Control.vuenew file mode 100644index 00000000..b37bcd74--- /dev/null+++ b/app/components/debug/Control.vue@@ -0,0 +1,81 @@+<script setup lang="ts">+import type { DebugControl, DebugValue } from '~/types/debug'+const props = defineProps<{ control: DebugControl }>()+const store = useDebugStore()+const value = computed(() =>+ store.get(props.control.key, props.control.default ?? ''),+)+function update(next: DebugValue) {+ store.set(props.control.key, next)+}+</script>+<template>+ <div class="flex min-h-8 min-w-0 items-center justify-between gap-3">+ <span class="text-xs text-muted">{{ control.label }}</span>+ <USwitch+ v-if="control.type === 'switch'"+ :model-value="Boolean(value)"+ :aria-label="control.label"+ :disabled="control.disabled"+ size="sm"+ @update:model-value="update"+ />+ <USelect+ v-else-if="control.type === 'select'"+ :model-value="value as string | number"+ :items="control.options"+ :ui="{ content: 'z-[10010]' }"+ :aria-label="control.label"+ :disabled="control.disabled"+ class="w-40"+ size="xs"+ @update:model-value="update"+ />+ <UInput+ v-else-if="control.type === 'number'"+ :model-value="value as number"+ type="number"+ :min="control.min"+ :max="control.max"+ :step="control.step"+ :aria-label="control.label"+ :disabled="control.disabled"+ class="w-28"+ size="xs"+ @update:model-value="+ (next) => {+ const n = Number(next)+ if (Number.isFinite(n))+ update(+ Math.max(+ control.min ?? -Infinity,+ Math.min(control.max ?? Infinity, n),+ ),+ )+ }+ "+ />+ <UInput+ v-else-if="control.type === 'text'"+ :model-value="String(value)"+ :aria-label="control.label"+ :disabled="control.disabled"+ class="w-40"+ size="xs"+ @update:model-value="update"+ />+ <UButton+ v-else-if="control.type === 'action'"+ :label="control.label"+ size="xs"+ variant="soft"+ :disabled="control.disabled"+ @click="control.action?.()"+ />+ <span+ v-else+ class="max-w-[60%] break-all text-xs font-mono"+ >{{ control.value ?? value }}</span+ >+ </div>+</template>diff --git a/app/components/debug/Panel.vue b/app/components/debug/Panel.vuenew file mode 100644index 00000000..6516dc78--- /dev/null+++ b/app/components/debug/Panel.vue@@ -0,0 +1,454 @@+<script setup lang="ts">+import FloatingWindow from '~/components/ui/FloatingWindow/FloatingWindow.vue'+const store = useDebugStore()+const route = useRoute()+const colorMode = useColorMode()+const { locale } = useI18n()+store.initialize()+const available = import.meta.dev+const open = useDebugValue<boolean>('ui:open', false)+const viewport = ref({ width: 1, height: 1 })+const launcher = reactive({ x: 0, y: 0 })+const preferredLauncher = reactive({ x: 0, y: 0 })+const launcherDragging = ref(false)+const ogImageUrl = ref('')+const ogImageLoading = ref(false)+const ogImageError = ref(false)+let headObserver: MutationObserver | undefined+let headFrame: number | undefined+let ogRequest: AbortController | undefined+let routeOgMetadata = false+function readOgImage(head: ParentNode = document.head) {+ const content = head+ .querySelector<HTMLMetaElement>(+ 'meta[property="og:image"], meta[name="og:image"], meta[property="og:image:url"]',+ )+ ?.content?.trim()+ let next = ''+ if (content) {+ try {+ const url = new URL(content, document.baseURI)+ if (url.protocol === 'http:' || url.protocol === 'https:') next = url.href+ } catch {+ /* Ignore malformed page metadata. */+ }+ }+ if (next !== ogImageUrl.value) {+ ogImageUrl.value = next+ ogImageLoading.value = Boolean(next)+ ogImageError.value = false+ }+}+async function refreshRouteOgImage() {+ ogRequest?.abort()+ const request = new AbortController()+ ogRequest = request+ // Reused page instances can retain their initial OG tags. Read the same+ // server-rendered metadata that a social crawler sees for the current URL.+ routeOgMetadata = true+ ogImageUrl.value = ''+ ogImageLoading.value = false+ ogImageError.value = false+ try {+ const response = await fetch(+ new URL(route.fullPath, window.location.origin),+ {+ signal: request.signal,+ headers: { Accept: 'text/html' },+ },+ )+ if (!response.ok) return+ const html = await response.text()+ if (request.signal.aborted || ogRequest !== request) return+ readOgImage(new DOMParser().parseFromString(html, 'text/html').head)+ } catch {+ // Keep the preview empty when the current page cannot be resolved.+ }+}+watch(+ () => route.fullPath,+ () => {+ if (import.meta.client) void refreshRouteOgImage()+ },+ { flush: 'post' },+)+function handleOgImageError() {+ ogImageLoading.value = false+ ogImageError.value = true+}+function scheduleOgImageRead() {+ if (headFrame !== undefined) cancelAnimationFrame(headFrame)+ headFrame = requestAnimationFrame(() => {+ headFrame = undefined+ if (!routeOgMetadata) readOgImage()+ })+}+const launcherSize = 40+const windowCreated = ref(false)+const launcherReady = ref(false)+const initialWindow = computed(() => {+ const margin = 24+ const width = Math.max(1, Math.min(400, viewport.value.width - margin * 2))+ const height = Math.max(1, Math.min(520, viewport.value.height - margin * 2))+ return {+ width,+ height,+ x: Math.max(+ margin,+ Math.min(launcher.x, viewport.value.width - width - margin),+ ),+ y: Math.max(+ margin,+ Math.min(launcher.y, viewport.value.height - height - margin),+ ),+ }+})+watch(open, (value) => {+ if (value && launcherReady.value) windowCreated.value = true+})+const sections = computed(() =>+ Object.values(store.sections).filter(+ (section) => section.route === route.path && section.active !== false,+ ),+)+const globalControls = computed(() => [+ {+ key: 'global:outline',+ type: 'switch' as const,+ label: $t('debug.outline'),+ default: false,+ },+])+watchEffect(() => {+ if (import.meta.client)+ document.documentElement.classList.toggle(+ 'debug-outline',+ available && store.get('global:outline', false),+ )+})+watch(+ () => route.query.queueDebug,+ (value) => {+ if (value === '1') {+ store.set('dashboard:queue:enabled', true)+ open.value = true+ }+ },+ { immediate: true },+)+watch(+ () => route.query.debug,+ (value) => {+ if (value === '1') open.value = true+ },+ { immediate: true },+)+function persistLauncher() {+ store.set('ui:launcherX', launcher.x)+ store.set('ui:launcherY', launcher.y)+}+function snap(commit = false) {+ const margin = 24+ const right = Math.max(margin, viewport.value.width - launcherSize - margin)+ const bottom = Math.max(margin, viewport.value.height - launcherSize - margin)+ launcher.x = Math.max(+ margin,+ Math.min(right, commit ? launcher.x : preferredLauncher.x),+ )+ launcher.y = Math.max(+ margin,+ Math.min(bottom, commit ? launcher.y : preferredLauncher.y),+ )+ const distances = [+ launcher.x - margin,+ right - launcher.x,+ launcher.y - margin,+ bottom - launcher.y,+ ]+ const nearest = distances.indexOf(Math.min(...distances))+ if (nearest === 0) launcher.x = margin+ if (nearest === 1) launcher.x = right+ if (nearest === 2) launcher.y = margin+ if (nearest === 3) launcher.y = bottom+ if (launcher.x - margin < 40) launcher.x = margin+ else if (right - launcher.x < 40) launcher.x = right+ if (launcher.y - margin < 40) launcher.y = margin+ else if (bottom - launcher.y < 40) launcher.y = bottom+ if (commit) {+ Object.assign(preferredLauncher, launcher)+ persistLauncher()+ }+}+function resizeViewport() {+ viewport.value = { width: window.innerWidth, height: window.innerHeight }+ snap()+}+let dragged = false+let cleanupDrag: (() => void) | undefined+function drag(event: PointerEvent) {+ if (event.button !== 0) return+ cleanupDrag?.()+ launcherDragging.value = true+ dragged = false+ const target = event.currentTarget as HTMLElement+ target.setPointerCapture(event.pointerId)+ const initial = { ...launcher },+ x = event.clientX,+ y = event.clientY+ const move = (e: PointerEvent) => {+ if (e.pointerId !== event.pointerId) return+ const dx = e.clientX - x,+ dy = e.clientY - y+ if (Math.hypot(dx, dy) > 4) dragged = true+ if (!dragged) return+ launcher.x = Math.max(+ 0,+ Math.min(viewport.value.width - launcherSize, initial.x + dx),+ )+ launcher.y = Math.max(+ 0,+ Math.min(viewport.value.height - launcherSize, initial.y + dy),+ )+ }+ const stop = () => {+ target.removeEventListener('pointermove', move)+ target.removeEventListener('pointerup', stop)+ target.removeEventListener('pointercancel', stop)+ target.removeEventListener('lostpointercapture', stop)+ if (target.hasPointerCapture(event.pointerId))+ target.releasePointerCapture(event.pointerId)+ cleanupDrag = undefined+ launcherDragging.value = false+ snap(dragged)+ }+ target.addEventListener('pointermove', move)+ target.addEventListener('pointerup', stop)+ target.addEventListener('pointercancel', stop)+ target.addEventListener('lostpointercapture', stop)+ cleanupDrag = stop+}+function openWindow(event: MouseEvent) {+ if (!dragged || event.detail === 0) open.value = true+}+function reset() {+ store.reset()+}+function reload() {+ window.location.reload()+}+function refreshPage() {+ refreshNuxtData()+}+onMounted(() => {+ readOgImage()+ headObserver = new MutationObserver(scheduleOgImageRead)+ headObserver.observe(document.head, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['content', 'property', 'name'],+ })+ viewport.value = { width: window.innerWidth, height: window.innerHeight }+ preferredLauncher.x = store.get(+ 'ui:launcherX',+ viewport.value.width - launcherSize - 16,+ )+ preferredLauncher.y = store.get(+ 'ui:launcherY',+ Math.round(viewport.value.height * 0.7),+ )+ snap()+ launcherReady.value = true+ windowCreated.value = open.value+ window.addEventListener('resize', resizeViewport)+})+onBeforeUnmount(() => {+ ogRequest?.abort()+ headObserver?.disconnect()+ if (headFrame !== undefined) cancelAnimationFrame(headFrame)+ cleanupDrag?.()+ window.removeEventListener('resize', resizeViewport)+ document.documentElement.classList.remove('debug-outline')+})+</script>++<template>+ <template v-if="available">+ <Teleport to="body">+ <button+ v-if="!open"+ type="button"+ :aria-label="$t('debug.open')"+ :title="$t('debug.open')"+ class="debug-launcher fixed z-[10000] flex size-10 touch-none select-none items-center justify-center rounded-full border border-default bg-default text-muted shadow-lg hover:text-primary focus-visible:outline-2 focus-visible:outline-primary"+ :class="{ 'is-dragging': launcherDragging }"+ :style="{ left: launcher.x + 'px', top: launcher.y + 'px' }"+ @pointerdown="drag"+ @click="openWindow"+ >+ <UIcon+ name="tabler:bug"+ class="size-6"+ />+ </button>+ </Teleport>+ <FloatingWindow+ v-if="windowCreated"+ id="global-debug"+ v-model="open"+ :title="$t('debug.title')"+ :allow-overflow="false"+ :min-width="Math.min(320, initialWindow.width)"+ :min-height="Math.min(260, initialWindow.height)"+ :initial-width="initialWindow.width"+ :initial-height="initialWindow.height"+ :initial-x="initialWindow.x"+ :initial-y="initialWindow.y"+ >+ <div class="space-y-4 p-4">+ <section>+ <h3 class="mb-2 text-xs font-semibold">{{ $t('debug.info') }}</h3>+ <dl+ class="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 rounded-lg bg-elevated/50 p-3 text-xs"+ >+ <dt class="text-muted">{{ $t('debug.route') }}</dt>+ <dd class="break-all font-mono">{{ route.fullPath }}</dd>+ <dt class="text-muted">{{ $t('debug.version') }}</dt>+ <dd>{{ $config.public.VERSION }}</dd>+ <dt class="text-muted">{{ $t('debug.viewport') }}</dt>+ <dd class="tabular-nums">+ {{ viewport.width }} × {{ viewport.height }}+ </dd>+ <dt class="text-muted">{{ $t('debug.locale') }}</dt>+ <dd>{{ locale }}</dd>+ <dt class="text-muted">{{ $t('debug.theme') }}</dt>+ <dd>{{ colorMode.value }}</dd>+ </dl>+ <div+ v-if="ogImageUrl"+ class="mt-3 space-y-2"+ >+ <div class="flex items-center justify-between gap-2">+ <span class="text-xs text-muted">{{ $t('debug.ogImage') }}</span>+ <a+ :href="ogImageUrl"+ target="_blank"+ rel="noopener noreferrer"+ class="text-xs text-muted hover:text-primary"+ :aria-label="$t('debug.openOgImage')"+ >+ <UIcon+ name="tabler:external-link"+ class="size-4"+ />+ </a>+ </div>+ <div+ class="relative aspect-[2/1] overflow-hidden rounded-lg bg-elevated/50"+ >+ <img+ :key="ogImageUrl"+ :src="ogImageUrl"+ :alt="$t('debug.ogImage')"+ class="absolute inset-0 block h-full w-full object-cover"+ :class="{ hidden: ogImageError }"+ @load="ogImageLoading = false"+ @error="handleOgImageError"+ />+ <div+ v-if="ogImageLoading"+ class="absolute inset-0 flex items-center justify-center bg-elevated/50 py-6"+ >+ <UIcon+ name="tabler:loader-2"+ class="size-5 animate-spin text-muted"+ />+ </div>+ <p+ v-if="ogImageError"+ class="absolute inset-0 flex items-center justify-center px-3 text-center text-xs text-muted"+ >+ {{ $t('debug.ogImageError') }}+ </p>+ </div>+ </div>+ </section>+ <section class="border-t border-default pt-3">+ <h3 class="text-xs font-semibold">{{ $t('debug.general') }}</h3>+ <DebugControl+ v-for="control in globalControls"+ :key="control.key"+ :control="control"+ />+ <div class="mt-2 flex flex-wrap gap-2">+ <UButton+ size="xs"+ variant="soft"+ color="neutral"+ icon="tabler:refresh"+ @click="refreshPage"+ >{{ $t('debug.refresh') }}</UButton+ >+ <UButton+ size="xs"+ variant="soft"+ color="neutral"+ @click="reload"+ >{{ $t('debug.reload') }}</UButton+ >+ <UButton+ size="xs"+ variant="ghost"+ color="neutral"+ @click="reset"+ >{{ $t('debug.reset') }}</UButton+ >+ </div>+ </section>+ <section class="border-t border-default pt-3">+ <h3 class="mb-2 text-xs font-semibold">{{ $t('debug.page') }}</h3>+ <p+ v-if="!sections.length"+ class="text-xs text-muted"+ >+ {{ $t('debug.empty') }}+ </p>+ <div+ v-for="section in sections"+ :key="section.id"+ class="rounded-lg border border-default p-3"+ >+ <h4 class="mb-2 text-xs font-medium">{{ section.title }}</h4>+ <div class="flex flex-col gap-2">+ <DebugControl+ v-for="control in section.controls"+ :key="control.key"+ :control="control"+ />+ </div>+ </div>+ </section>+ </div>+ </FloatingWindow>+ </template>+</template>++<style>+.debug-launcher {+ transition:+ left 240ms cubic-bezier(0.22, 1, 0.36, 1),+ top 240ms cubic-bezier(0.22, 1, 0.36, 1);+}+.debug-launcher.is-dragging {+ transition: none;+}+@media (prefers-reduced-motion: reduce) {+ .debug-launcher {+ transition: none;+ }+}++.debug-outline body *:not([role='dialog']):not([role='dialog'] *) {+ outline: 1px solid rgb(239 68 68 / 25%);+}+</style>diff --git a/app/components/photo/ProgressiveImage.vue b/app/components/photo/ProgressiveImage.vueindex e3d4484f..a645399c 100644--- a/app/components/photo/ProgressiveImage.vue+++ b/app/components/photo/ProgressiveImage.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { WebGLImageViewer } from '@chronoframe/webgl-image'+import { LoadingState, WebGLImageViewer } from '@chronoframe/webgl-image'import type { LoadingIndicatorRef } from './LoadingIndicator.vue'import type { ImageLoaderManager } from '~/libs/image-loader-manager'@@ -55,7 +55,7 @@ const currentSrc = ref<string | null>()const { loggedIn } = useUserSession()const webglImageViewerDebug = useSettingRef('system:webglImageViewerDebug')const isDev = computed(() => import.meta.env.DEV)-const showDebugInfo = computed(() => {+const configuredDebugInfo = computed(() => {if (webglImageViewerDebug.value === true) {return !!loggedIn.value}@@ -63,6 +63,99 @@ const showDebugInfo = computed(() => {return isDev.value && import.meta.env.VITE_SHOW_DEBUG_INFO === 'true'})+const debugOverride = useDebugValue<string>('viewer:webgl:visibility', 'system')+const debugDelay = useDebugValue<number>('viewer:image:delay', 0)+const debugFailure = useDebugValue<boolean>('viewer:image:failure', false)+const showDebugInfo = computed(() => {+ if (import.meta.dev && debugOverride.value === 'show') return true+ if (import.meta.dev && debugOverride.value === 'hide') return false+ return configuredDebugInfo.value+})+const loadStage = ref('idle')+const debugSectionId = 'viewer:image:' + useId()+const route = useRoute()+useDebugSection(() => ({+ id: debugSectionId,+ route: route.path,+ active: props.isCurrentImage,+ title: $t('debug.viewer.title'),+ controls: [+ {+ key: 'viewer:webgl:visibility',+ label: $t('debug.viewer.visibility'),+ type: 'select',+ default: 'system',+ options: ['system', 'show', 'hide'].map((value) => ({+ value,+ label: $t('debug.viewer.' + value),+ })),+ },+ {+ key: 'viewer:image:delay',+ label: $t('debug.viewer.delay'),+ type: 'number',+ default: 0,+ min: 0,+ max: 30000,+ step: 500,+ },+ {+ key: 'viewer:image:failure',+ label: $t('debug.viewer.failure'),+ type: 'switch',+ default: false,+ },+ {+ key: 'viewer:image:reload',+ label: $t('debug.viewer.reload'),+ type: 'action',+ action: reloadImage,+ },+ {+ key: 'viewer:webgl:systemValue',+ label: $t('debug.viewer.systemValue'),+ type: 'status',+ value: webglImageViewerDebug.value === true,+ },+ {+ key: 'viewer:webgl:effective',+ label: $t('debug.viewer.effective'),+ type: 'status',+ value: showDebugInfo.value,+ },+ {+ key: 'viewer:image:stage',+ label: $t('debug.viewer.stage'),+ type: 'status',+ value: $t('debug.viewer.stages.' + loadStage.value),+ },+ ],+}))+let loadGeneration = 0+let debugTimer: ReturnType<typeof setTimeout> | undefined+function cancelDebugTimer() {+ loadGeneration+++ clearTimeout(debugTimer)+ debugTimer = undefined+}+function reloadImage() {+ cancelDebugTimer()+ loaderManagerRef.value?.cleanup()+ loaderManagerRef.value = null+ highResLoaded.value = false+ highResRendered.value = false+ hasError.value = false+ currentSrc.value = null+ props.onBlobSrcChange?.(null)+ props.loadingIndicatorRef?.resetLoadingState()+ loadStage.value = 'idle'+ if (props.isCurrentImage) loadImage()+}+if (import.meta.dev)+ watch([debugDelay, debugFailure], () => {+ if (props.isCurrentImage) reloadImage()+ })+// 使用 WebGLImageViewer 的引用const webglViewerRef = ref()const loaderManagerRef = ref<ImageLoaderManager | null>(null)@@ -80,7 +173,38 @@ const showWebGLViewer = computed(() => {)})-const loadImage = () => {+const loadImage = (afterDelay = false) => {+ if (!props.isCurrentImage || highResLoaded.value || hasError.value) return+ if (import.meta.dev) {+ const delay = Math.min(30000, Math.max(0, debugDelay.value))+ if (!afterDelay && delay > 0) {+ cancelDebugTimer()+ loadStage.value = 'delay'+ props.loadingIndicatorRef?.updateLoadingState({+ isVisible: true,+ isError: false,+ message: $t('debug.viewer.waiting'),+ })+ debugTimer = setTimeout(() => {+ debugTimer = undefined+ loadImage(true)+ }, delay)+ return+ }+ if (debugFailure.value) {+ loadStage.value = 'error'+ hasError.value = true+ props.onError?.()+ props.loadingIndicatorRef?.updateLoadingState({+ isVisible: true,+ isError: true,+ message: $t('photo.image.loadError'),+ })+ return+ }+ }+ loadStage.value = 'image'+ const generation = loadGenerationloaderManagerRef.value = useImageLoader(props.src,props.isCurrentImage,@@ -91,9 +215,13 @@ const loadImage = () => {props.onError,(src) => (currentSrc.value = src),(loaded) => (highResLoaded.value = loaded),- (error) => (hasError.value = error),+ (error) => {+ hasError.value = error+ if (error) loadStage.value = 'error'+ },(rendered) => (highResRendered.value = rendered),props.onImageLoaded,+ () => generation === loadGeneration && props.isCurrentImage,)}@@ -102,6 +230,7 @@ watch(() => props.isCurrentImage,(isCurrent, wasCurrent) => {if (!isCurrent && wasCurrent) {+ cancelDebugTimer()// 当图片不再是当前图片时,中断加载loaderManagerRef.value?.cleanup()loaderManagerRef.value = null@@ -123,6 +252,7 @@ watch(() => props.src,(newSrc, oldSrc) => {if (newSrc !== oldSrc) {+ cancelDebugTimer()// 中断之前的加载loaderManagerRef.value?.cleanup()loaderManagerRef.value = null@@ -145,7 +275,26 @@ watch(// 初始加载loadImage()-const handleWebGLStateChange = useWebGLWorkState(props.loadingIndicatorRef)+const updateWebGLState = useWebGLWorkState(props.loadingIndicatorRef)+const handleWebGLStateChange = (+ isLoading: boolean,+ state?: LoadingState,+ quality?: 'high' | 'medium' | 'low' | 'unknown',+) => {+ loadStage.value =+ state === LoadingState.ERROR+ ? 'error'+ : state === LoadingState.IDLE+ ? 'idle'+ : !isLoading+ ? 'ready'+ : state === LoadingState.TEXTURE_LOADING+ ? 'texture'+ : state === LoadingState.TILE_LOADING+ ? 'tile'+ : 'image'+ updateWebGLState(isLoading, state, quality)+}// 处理缩放状态变化const handleZoomChange = (originalScale: number, relativeScale: number) => {@@ -157,6 +306,7 @@ const handleZoomChange = (originalScale: number, relativeScale: number) => {// 组件卸载时清理onUnmounted(() => {+ cancelDebugTimer()loaderManagerRef.value?.cleanup()loaderManagerRef.value = null})diff --git a/app/components/ui/FloatingWindow/FloatingWindow.vue b/app/components/ui/FloatingWindow/FloatingWindow.vuenew file mode 100644index 00000000..c4aaec77--- /dev/null+++ b/app/components/ui/FloatingWindow/FloatingWindow.vue@@ -0,0 +1,353 @@+<script setup lang="ts">+import {+ constrainFloatingRect,+ resizeFloatingRect,+} from '~/utils/floatingWindow'+import type { FloatingRect } from '~/utils/floatingWindow'+const props = withDefaults(+ defineProps<{+ id?: string+ title?: string+ allowOverflow?: boolean+ minWidth?: number+ minHeight?: number+ maxWidth?: number+ maxHeight?: number+ initialWidth?: number+ initialHeight?: number+ initialX?: number+ initialY?: number+ }>(),+ {+ allowOverflow: true,+ minWidth: 240,+ minHeight: 160,+ maxWidth: Infinity,+ maxHeight: Infinity,+ initialWidth: 420,+ initialHeight: 480,+ initialX: 24,+ initialY: 24,+ },+)+const open = defineModel<boolean>({ default: true })+const rect = ref<FloatingRect>({+ x: props.initialX,+ y: props.initialY,+ width: props.initialWidth,+ height: props.initialHeight,+})+const preferredRect = ref({ ...rect.value })+const ready = ref(false)+const interacting = ref(false)+const maximized = ref(false)+const viewport = ref({ width: 1, height: 1 })+const edges = ['n', 'e', 's', 'w', 'ne', 'nw', 'se', 'sw']+const style = computed(() => {+ const r = maximized.value+ ? { x: 0, y: 0, width: viewport.value.width, height: viewport.value.height }+ : rect.value+ return {+ left: `${r.x}px`,+ top: `${r.y}px`,+ width: `${r.width}px`,+ height: `${r.height}px`,+ }+})+function normalize() {+ rect.value = constrainFloatingRect(+ preferredRect.value,+ viewport.value,+ props.minWidth,+ props.minHeight,+ props.maxWidth,+ props.maxHeight,+ props.allowOverflow,+ )+}+function save() {+ if (!props.id) return+ try {+ localStorage.setItem(+ `chronoframe:window:${props.id}`,+ JSON.stringify({ rect: preferredRect.value, maximized: maximized.value }),+ )+ } catch {+ /* Optional persistence. */+ }+}+function resizeViewport() {+ viewport.value = { width: window.innerWidth, height: window.innerHeight }+ normalize()+}+function toggleMaximize() {+ maximized.value = !maximized.value+ save()+}+let stopGesture: (() => void) | undefined+function startGesture(event: PointerEvent, edge?: string) {+ if (+ event.button !== 0 ||+ maximized.value ||+ (!edge && (event.target as HTMLElement).closest('button,input,select,a'))+ )+ return+ event.preventDefault()+ stopGesture?.()+ interacting.value = true+ const target = event.currentTarget as HTMLElement+ target.setPointerCapture(event.pointerId)+ const initial = { ...rect.value },+ x = event.clientX,+ y = event.clientY+ const move = (e: PointerEvent) => {+ if (e.pointerId !== event.pointerId) return+ const dx = e.clientX - x,+ dy = e.clientY - y+ preferredRect.value = edge+ ? resizeFloatingRect(+ initial,+ edge,+ dx,+ dy,+ viewport.value,+ props.minWidth,+ props.minHeight,+ props.maxWidth,+ props.maxHeight,+ props.allowOverflow,+ )+ : { ...initial, x: initial.x + dx, y: initial.y + dy }+ normalize()+ preferredRect.value = { ...rect.value }+ }+ const stop = () => {+ target.removeEventListener('pointermove', move)+ target.removeEventListener('pointerup', stop)+ target.removeEventListener('pointercancel', stop)+ target.removeEventListener('lostpointercapture', stop)+ if (target.hasPointerCapture(event.pointerId))+ target.releasePointerCapture(event.pointerId)+ interacting.value = false+ stopGesture = undefined+ save()+ }+ target.addEventListener('pointermove', move)+ target.addEventListener('pointerup', stop)+ target.addEventListener('pointercancel', stop)+ target.addEventListener('lostpointercapture', stop)+ stopGesture = stop+}+function handleKey(event: KeyboardEvent) {+ if (open.value && event.key === 'Escape' && !event.defaultPrevented)+ open.value = false+}+onMounted(() => {+ viewport.value = { width: window.innerWidth, height: window.innerHeight }+ if (props.id) {+ try {+ const saved = JSON.parse(+ localStorage.getItem(`chronoframe:window:${props.id}`) || 'null',+ )+ if (+ saved?.rect &&+ ['x', 'y', 'width', 'height'].every((key) =>+ Number.isFinite(saved.rect[key]),+ )+ ) {+ preferredRect.value = saved.rect+ maximized.value = saved.maximized === true+ }+ } catch {+ /* Ignore invalid saved geometry. */+ }+ }+ normalize()+ ready.value = true+ window.addEventListener('resize', resizeViewport)+ window.addEventListener('keydown', handleKey)+})+watch(+ () => [+ props.allowOverflow,+ props.minWidth,+ props.minHeight,+ props.maxWidth,+ props.maxHeight,+ ],+ () => {+ normalize()+ },+)+watch(open, (value) => {+ if (!value) stopGesture?.()+})+onBeforeUnmount(() => {+ stopGesture?.()+ window.removeEventListener('resize', resizeViewport)+ window.removeEventListener('keydown', handleKey)+})+</script>++<template>+ <Teleport to="body">+ <Transition+ name="floating-window"+ appear+ >+ <section+ v-if="open && ready"+ role="dialog"+ tabindex="-1"+ :aria-label="title"+ class="floating-window fixed z-[10000] flex flex-col overflow-hidden border-default bg-default"+ :class="[+ maximized+ ? 'border-0 rounded-none shadow-none'+ : 'border rounded-xl shadow-2xl',+ { 'is-interacting': interacting },+ ]"+ :style="style"+ >+ <header+ class="flex h-11 shrink-0 touch-none select-none items-center gap-2 border-b border-default px-3"+ :class="maximized ? '' : 'cursor-move'"+ @pointerdown="startGesture($event)"+ @dblclick="toggleMaximize"+ >+ <div class="min-w-0 flex-1 truncate text-sm font-semibold">+ <slot name="title">{{ title }}</slot>+ </div>+ <slot name="actions" />+ <UButton+ :icon="+ maximized ? 'tabler:arrows-minimize' : 'tabler:arrows-maximize'+ "+ :aria-label="+ maximized+ ? $t('debug.window.restore')+ : $t('debug.window.maximize')+ "+ size="xs"+ variant="ghost"+ color="neutral"+ @dblclick.stop+ @click="toggleMaximize"+ />+ <UButton+ icon="tabler:x"+ :aria-label="$t('debug.window.close')"+ size="xs"+ variant="ghost"+ color="neutral"+ @dblclick.stop+ @click="open = false"+ />+ </header>+ <div class="min-h-0 flex-1 overflow-auto">+ <slot :maximized="maximized" />+ </div>+ <div+ v-if="$slots.footer"+ class="shrink-0 border-t border-default"+ >+ <slot name="footer" />+ </div>+ <template v-if="!maximized">+ <div+ v-for="edge in edges"+ :key="edge"+ class="resize-handle absolute touch-none"+ :class="'resize-' + edge"+ aria-hidden="true"+ @pointerdown.stop="startGesture($event, edge)"+ />+ </template>+ </section>+ </Transition>+ </Teleport>+</template>++<style scoped>+.floating-window {+ transition:+ left 220ms ease,+ top 220ms ease,+ width 220ms ease,+ height 220ms ease,+ border-radius 220ms ease,+ opacity 160ms ease,+ transform 160ms ease;+}+.floating-window.is-interacting {+ transition: none;+}+.floating-window-enter-from,+.floating-window-leave-to {+ opacity: 0;+ transform: translateY(8px) scale(0.97);+}+@media (prefers-reduced-motion: reduce) {+ .floating-window {+ transition: none;+ }+ .floating-window-enter-from,+ .floating-window-leave-to {+ transform: none;+ }+}++.resize-n,+.resize-s {+ height: 6px;+ left: 10px;+ right: 10px;+ cursor: ns-resize;+}+.resize-n {+ top: 0;+}+.resize-s {+ bottom: 0;+}+.resize-e,+.resize-w {+ width: 6px;+ top: 10px;+ bottom: 10px;+ cursor: ew-resize;+}+.resize-e {+ right: 0;+}+.resize-w {+ left: 0;+}+.resize-ne,+.resize-nw,+.resize-se,+.resize-sw {+ width: 12px;+ height: 12px;+}+.resize-ne {+ top: 0;+ right: 0;+ cursor: nesw-resize;+}+.resize-nw {+ top: 0;+ left: 0;+ cursor: nwse-resize;+}+.resize-se {+ bottom: 0;+ right: 0;+ cursor: nwse-resize;+}+.resize-sw {+ bottom: 0;+ left: 0;+ cursor: nesw-resize;+}+</style>diff --git a/app/composables/useDebugSection.ts b/app/composables/useDebugSection.tsnew file mode 100644index 00000000..fd715475--- /dev/null+++ b/app/composables/useDebugSection.ts@@ -0,0 +1,31 @@+import type { DebugSection, DebugValue } from '~/types/debug'++/** Register route-specific controls; values survive navigation, controls do not. */+export function useDebugSection(section: MaybeRefOrGetter<DebugSection>) {+ if (!import.meta.dev) return+ const store = useDebugStore()+ const id = toValue(section).id+ let registered: DebugSection+ watch(+ () => toValue(section),+ (value) => {+ registered = value+ store.register(value)+ },+ { immediate: true, deep: true },+ )+ onScopeDispose(() => {+ if (store.sections[id] === registered) store.unregister(id)+ })+}++/** All debug features read and write through the same persistent store. */+export function useDebugValue<T extends DebugValue>(key: string, fallback: T) {+ if (!import.meta.dev)+ return computed({ get: () => fallback, set: (_value: T) => {} })+ const store = useDebugStore()+ return computed({+ get: () => store.get(key, fallback),+ set: (value) => store.set(key, value),+ })+}diff --git a/app/composables/useImageLoader.ts b/app/composables/useImageLoader.tsindex 33793b3b..ec6bbed9 100644--- a/app/composables/useImageLoader.ts+++ b/app/composables/useImageLoader.ts@@ -14,6 +14,7 @@ export const useImageLoader = (updateError?: (error: boolean) => void,updateHighResImageRendered?: (isRendered: boolean) => void,onImageLoaded?: () => void,+ shouldApply: () => boolean = () => true,) => {// useImageLoader() is invoked from loadImage(), which also runs inside watch// callbacks (outside the synchronous setup context) — useI18n() would throw@@ -36,17 +37,24 @@ export const useImageLoader = (const loadImage = async () => {try {const loadResult = await loaderManager.loadImage(src, {- onProgress,- onError,+ onProgress: (progress) => {+ if (shouldApply()) onProgress?.(progress)+ },+ onError: () => {+ if (shouldApply()) onError?.()+ },onUpdateLoadingState: (state) => {+ if (!shouldApply()) returnloadingIndicatorRef?.updateLoadingState(state)},})+ if (!shouldApply()) returnupdateBlobSrc?.(loadResult.blobSrc)updateHighResLoaded?.(true)onImageLoaded?.() // 通知图片加载完成} catch {+ if (!shouldApply()) returnupdateError?.(true)loadingIndicatorRef?.updateLoadingState({isVisible: true,diff --git a/app/pages/dashboard/index.vue b/app/pages/dashboard/index.vueindex 78fa83d4..b708b0e9 100644--- a/app/pages/dashboard/index.vue+++ b/app/pages/dashboard/index.vue@@ -51,20 +51,167 @@ const systemStatus = computed(() => {return 'healthy'})+const queueDebugEnabled = useDebugValue<boolean>(+ 'dashboard:queue:enabled',+ false,+)+const queueDebugScenario = useDebugValue(+ 'dashboard:queue:scenario',+ 'processing',+)+const queueDebugScenarios = {+ empty: {+ activeWorkers: 0,+ totalWorkers: 5,+ totalProcessed: 0,+ totalErrors: 0,+ isActive: true,+ pending: 0,+ failed: 0,+ oldestWaitSeconds: 0,+ },+ processing: {+ activeWorkers: 3,+ totalWorkers: 5,+ totalProcessed: 128,+ totalErrors: 2,+ isActive: true,+ pending: 24,+ failed: 0,+ oldestWaitSeconds: 40,+ },+ backlog: {+ activeWorkers: 0,+ totalWorkers: 5,+ totalProcessed: 80,+ totalErrors: 5,+ isActive: true,+ pending: 156,+ failed: 0,+ oldestWaitSeconds: 720,+ },+ stopped: {+ activeWorkers: 0,+ totalWorkers: 5,+ totalProcessed: 42,+ totalErrors: 3,+ isActive: false,+ pending: 18,+ failed: 0,+ oldestWaitSeconds: 120,+ },+ failures: {+ activeWorkers: 1,+ totalWorkers: 5,+ totalProcessed: 12,+ totalErrors: 8,+ isActive: true,+ pending: 4,+ failed: 8,+ oldestWaitSeconds: 30,+ },+ allFailed: {+ activeWorkers: 0,+ totalWorkers: 5,+ totalProcessed: 0,+ totalErrors: 6,+ isActive: true,+ pending: 0,+ failed: 6,+ oldestWaitSeconds: 0,+ },+}+const queueDebugOptions = computed(() =>+ Object.keys(queueDebugScenarios).map((value) => ({+ value,+ label: $t('dashboard.overview.section.queue.debug.scenarios.' + value),+ })),+)+useDebugSection(() => ({+ id: 'dashboard:queue',+ route: '/dashboard',+ title: $t('dashboard.overview.section.queue.title'),+ controls: [+ {+ key: 'dashboard:queue:enabled',+ label: $t('dashboard.overview.section.queue.debug.label'),+ type: 'switch',+ default: false,+ },+ {+ key: 'dashboard:queue:scenario',+ label: $t('debug.scenario'),+ type: 'select',+ default: 'processing',+ options: queueDebugOptions.value,+ disabled: !queueDebugEnabled.value,+ },+ ],+}))++const queueDisplayStats = computed(() => {+ if (!import.meta.dev || !queueDebugEnabled.value) return dashboardStats.value+ const mock =+ queueDebugScenarios[+ queueDebugScenario.value as keyof typeof queueDebugScenarios+ ]+ if (!mock) return dashboardStats.value+ const attempts = mock.totalProcessed + mock.totalErrors+ return {+ workerPool: {+ ...mock,+ averageSuccessRate: attempts ? (mock.totalProcessed / attempts) * 100 : 0,+ },+ queue: {+ pending: mock.pending,+ failed: mock.failed,+ oldestWaitSeconds: mock.oldestWaitSeconds,+ },+ }+})++const queueState = computed(() => {+ if (!queueDisplayStats.value) return 'unknown'+ const pool = queueDisplayStats.value.workerPool+ if (!pool?.isActive || pool.totalWorkers === 0) return 'stopped'+ if (pool.activeWorkers > 0) return 'processing'+ if ((queueDisplayStats.value.queue?.oldestWaitSeconds || 0) >= 300)+ return 'attention'+ return 'idle'+})++const queueNotice = computed(() => {+ const queue = queueDisplayStats.value?.queue+ if (!queue) return ''+ if (queue.pending > 0 && queueState.value === 'stopped')+ return $t('dashboard.overview.section.queue.stoppedNotice', {+ count: queue.pending,+ })+ if (queue.oldestWaitSeconds >= 300)+ return $t('dashboard.overview.section.queue.waitNotice', {+ minutes: Math.floor(queue.oldestWaitSeconds / 60),+ })+ if (queue.failed > 0)+ return $t('dashboard.overview.section.queue.failedNotice', {+ count: queue.failed,+ })+ return ''+})+const hasQueueActivity = computed(() => {- const pool = dashboardStats.value?.workerPool+ const pool = queueDisplayStats.value?.workerPoolreturn (pool?.totalProcessed || 0) > 0 || (pool?.totalErrors || 0) > 0})const queueSuccessRate = computed(() =>Math.min(100,- Math.max(0, dashboardStats.value?.workerPool?.averageSuccessRate || 0),+ Math.max(0, queueDisplayStats.value?.workerPool?.averageSuccessRate || 0),),)const queueSuccessColor = computed(() => {- const pool = dashboardStats.value?.workerPool+ const pool = queueDisplayStats.value?.workerPoolif (!pool || !hasQueueActivity.value) return 'neutral'if (pool.averageSuccessRate > 90) return 'success'if (pool.averageSuccessRate > 70) return 'warning'@@ -433,7 +580,25 @@ const onShareSite = () => {<DashboardSectionHeader:title="$t('dashboard.overview.section.queue.title')"icon="tabler:list-check"- />+ >+ <span class="flex items-center gap-1.5 text-xs text-muted">+ <span+ class="size-1.5 rounded-full"+ :class="{+ 'bg-success': queueState === 'processing',+ 'bg-warning': queueState === 'attention',+ 'bg-error': queueState === 'stopped',+ 'bg-neutral-400':+ queueState === 'idle' || queueState === 'unknown',+ }"+ />+ {{+ $t(+ 'dashboard.overview.section.queue.states.' + queueState,+ )+ }}+ </span>+ </DashboardSectionHeader></template><div@@ -495,24 +660,26 @@ const onShareSite = () => {class="size-4 shrink-0 text-muted"/><span class="min-w-0 flex-1 text-xs text-muted">{{- $t('dashboard.overview.section.queue.activeWorkers')+ $t('dashboard.overview.section.queue.workers')}}</span><span class="text-base font-semibold tabular-nums">{{- dashboardStats?.workerPool?.activeWorkers || 0+ (queueDisplayStats?.workerPool?.activeWorkers || 0) ++ '/' ++ (queueDisplayStats?.workerPool?.totalWorkers || 0)}}</span></div><divclass="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 bg-default px-3 py-2.5"><UIcon- name="tabler:cpu"+ name="tabler:hourglass"class="size-4 shrink-0 text-muted"/><span class="min-w-0 flex-1 text-xs text-muted">{{- $t('dashboard.overview.section.queue.totalWorkers')+ $t('dashboard.overview.section.queue.pending')}}</span><span class="text-base font-semibold tabular-nums">{{- dashboardStats?.workerPool?.totalWorkers || 0+ queueDisplayStats?.queue?.pending || 0}}</span></div><div@@ -526,7 +693,7 @@ const onShareSite = () => {$t('dashboard.overview.section.queue.totalProcessed')}}</span><span class="text-base font-semibold tabular-nums">{{- dashboardStats?.workerPool?.totalProcessed || 0+ queueDisplayStats?.workerPool?.totalProcessed || 0}}</span></div><div@@ -543,13 +710,30 @@ const onShareSite = () => {class="text-base font-semibold tabular-nums":class="{'text-error':- (dashboardStats?.workerPool?.totalErrors || 0) > 0,+ (queueDisplayStats?.workerPool?.totalErrors || 0) > 0,}"- >{{ dashboardStats?.workerPool?.totalErrors || 0 }}</span+ >{{+ queueDisplayStats?.workerPool?.totalErrors || 0+ }}</span></div></div></div>+ <NuxtLink+ v-if="queueNotice"+ to="/dashboard/queue"+ class="mt-3 flex items-start gap-2 text-xs text-muted hover:text-default"+ >+ <UIcon+ name="tabler:alert-circle"+ class="size-4 shrink-0 text-warning"+ />+ <span>{{ queueNotice }}</span>+ <UIcon+ name="tabler:arrow-right"+ class="ml-auto size-4 shrink-0"+ />+ </NuxtLink></UCard></div></div>diff --git a/app/stores/debug.ts b/app/stores/debug.tsnew file mode 100644index 00000000..e641d394--- /dev/null+++ b/app/stores/debug.ts@@ -0,0 +1,74 @@+import { defineStore } from 'pinia'+import type { DebugSection, DebugValue } from '~/types/debug'++const storageKey = 'chronoframe:debug:v1'+export const useDebugStore = defineStore('debug', () => {+ const values = ref<Record<string, DebugValue>>({})+ const sections = shallowRef<Record<string, DebugSection>>({})+ const initialized = ref(false)+ function get<T extends DebugValue>(key: string, fallback: T): T {+ if (!import.meta.dev) return fallback+ const value = values.value[key]+ return value != null && typeof value === typeof fallback+ ? (value as T)+ : fallback+ }+ function set(key: string, value: DebugValue) {+ if (!import.meta.dev) return+ values.value = { ...values.value, [key]: value }+ }+ function reset() {+ values.value = {}+ }+ function initialize() {+ if (!import.meta.dev || !import.meta.client || initialized.value) return+ try {+ const saved = JSON.parse(localStorage.getItem(storageKey) || '{}')+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) {+ values.value = Object.fromEntries(+ Object.entries(saved).filter(+ ([, value]) =>+ value === null ||+ typeof value === 'string' ||+ typeof value === 'boolean' ||+ (typeof value === 'number' && Number.isFinite(value)),+ ),+ ) as Record<string, DebugValue>+ }+ } catch {+ /* A corrupt or unavailable storage must not block the app. */+ }+ initialized.value = true+ watch(+ values,+ (value) => {+ try {+ localStorage.setItem(storageKey, JSON.stringify(value))+ } catch {+ /* Storage may be disabled. */+ }+ },+ { deep: true },+ )+ }+ function register(section: DebugSection) {+ if (!import.meta.dev) return+ sections.value = { ...sections.value, [section.id]: section }+ }+ function unregister(id: string) {+ const next = { ...sections.value }+ delete next[id]+ sections.value = next+ }+ return {+ values,+ sections,+ initialized,+ get,+ set,+ reset,+ initialize,+ register,+ unregister,+ }+})diff --git a/app/types/debug.ts b/app/types/debug.tsnew file mode 100644index 00000000..e96c64f2--- /dev/null+++ b/app/types/debug.ts@@ -0,0 +1,21 @@+export type DebugValue = string | number | boolean | null+export type DebugControl = {+ key: string+ label: string+ type: 'switch' | 'select' | 'number' | 'text' | 'status' | 'action'+ default?: DebugValue+ options?: { label: string; value: string | number }[]+ min?: number+ max?: number+ step?: number+ value?: DebugValue+ action?: () => void+ disabled?: boolean+}+export type DebugSection = {+ active?: boolean+ id: string+ route: string+ title: string+ controls: DebugControl[]+}diff --git a/app/utils/floatingWindow.ts b/app/utils/floatingWindow.tsnew file mode 100644index 00000000..a807673d--- /dev/null+++ b/app/utils/floatingWindow.ts@@ -0,0 +1,87 @@+export type FloatingRect = {+ x: number+ y: number+ width: number+ height: number+}+export type FloatingBounds = { width: number; height: number }+export function constrainFloatingRect(+ rect: FloatingRect,+ viewport: FloatingBounds,+ minWidth: number,+ minHeight: number,+ maxWidth: number,+ maxHeight: number,+ allowOverflow: boolean,+): FloatingRect {+ const upperWidth = Math.max(+ 1,+ Math.min(maxWidth, allowOverflow ? Infinity : viewport.width),+ )+ const upperHeight = Math.max(+ 1,+ Math.min(maxHeight, allowOverflow ? Infinity : viewport.height),+ )+ const width = Math.min(+ upperWidth,+ Math.max(Math.min(minWidth, upperWidth), rect.width),+ )+ const height = Math.min(+ upperHeight,+ Math.max(Math.min(minHeight, upperHeight), rect.height),+ )+ return {+ width,+ height,+ x: allowOverflow+ ? rect.x+ : Math.max(0, Math.min(viewport.width - width, rect.x)),+ y: allowOverflow+ ? rect.y+ : Math.max(0, Math.min(viewport.height - height, rect.y)),+ }+}+export function resizeFloatingRect(+ rect: FloatingRect,+ edge: string,+ dx: number,+ dy: number,+ viewport: FloatingBounds,+ minWidth: number,+ minHeight: number,+ maxWidth: number,+ maxHeight: number,+ allowOverflow: boolean,+): FloatingRect {+ const west = edge.includes('w'),+ north = edge.includes('n')+ const widthLimit = allowOverflow+ ? maxWidth+ : Math.min(maxWidth, west ? rect.x + rect.width : viewport.width - rect.x)+ const heightLimit = allowOverflow+ ? maxHeight+ : Math.min(+ maxHeight,+ north ? rect.y + rect.height : viewport.height - rect.y,+ )+ const width =+ edge.includes('w') || edge.includes('e')+ ? Math.max(+ Math.min(minWidth, widthLimit),+ Math.min(widthLimit, rect.width + (west ? -dx : dx)),+ )+ : rect.width+ const height =+ edge.includes('n') || edge.includes('s')+ ? Math.max(+ Math.min(minHeight, heightLimit),+ Math.min(heightLimit, rect.height + (north ? -dy : dy)),+ )+ : rect.height+ return {+ width,+ height,+ x: west ? rect.x + rect.width - width : rect.x,+ y: north ? rect.y + rect.height - height : rect.y,+ }+}diff --git a/docs/development/debug-tools.md b/docs/development/debug-tools.mdnew file mode 100644index 00000000..a7d77ccd--- /dev/null+++ b/docs/development/debug-tools.md@@ -0,0 +1,67 @@+# Development debug tools++The floating debug entry appears globally under `pnpm dev`. Production builds+remove the panel import and disable debug reads, writes, and registrations.+`?debug=1` opens the panel; the previous `?queueDebug=1` link also enables the+queue preview in development. Neither parameter activates production debugging.++Drag the entry to dock it against the nearest edge; near a corner it docks to+both edges. Drag a window header to move it, and its edges/corners to resize it.+The header buttons maximize/restore and close the window. Double-clicking the+header also maximizes/restores. Escape closes the window.++## Register page controls++```ts+const enabled = useDebugValue<boolean>('feature:enabled', false)+const count = useDebugValue<number>('feature:count', 10)++useDebugSection(() => ({+ id: 'my-feature',+ route: '/my-page',+ title: 'My feature',+ controls: [+ {+ key: 'feature:enabled',+ label: 'Enable preview',+ type: 'switch',+ default: false,+ },+ {+ key: 'feature:count',+ label: 'Count',+ type: 'number',+ default: 10,+ min: 0,+ max: 100,+ },+ {+ key: 'feature:status',+ label: 'Status',+ type: 'status',+ value: enabled.value ? 'Enabled' : 'Disabled',+ },+ ],+}))+```++Supported controls: `switch`, `select` (with `options`), `number`, `text`,+`status` (read-only `value`), and `action` (with an `action` callback).+Use `useDebugValue` for reactive reads/writes, or `useDebugStore().get/set`+for imperative access. Configuration persists in local storage. Route controls+are scoped to their page lifecycle and filtered by exact route path.+In production reads return the supplied defaults and writes are ignored.+Wrap expensive mock generation in `if (import.meta.dev)` for build removal.++## Reuse the floating window++`app/components/ui/FloatingWindow/FloatingWindow.vue` is independent of the+store. Use `v-model` for visibility. An optional stable `id` persists geometry+and maximized state. `allowOverflow` defaults to `true`; set it to `false` to+keep the window inside the viewport. Configure `minWidth`, `minHeight`,+`maxWidth`, `maxHeight`, `initialX`, `initialY`, `initialWidth`, and+`initialHeight`. Viewport limits take precedence over minimum dimensions on+small screens. Maximization fills the viewport and preserves the normal rect.+Slots: default content, `title`, `actions`, and `footer`.++Validation: `node --test tests/debug-tools.test.mjs`.diff --git a/i18n/locales/en.json b/i18n/locales/en.jsonindex a1032c0e..052af166 100644--- a/i18n/locales/en.json+++ b/i18n/locales/en.json@@ -999,7 +999,30 @@"totalWorkers": "Total Workers","totalProcessed": "Processed","totalFailed": "Failure count",- "avgSuccessRate": "Success rate"+ "avgSuccessRate": "Success rate",+ "pending": "Pending",+ "workers": "Workers",+ "states": {+ "unknown": "Unknown",+ "stopped": "Stopped",+ "processing": "Processing",+ "attention": "Needs attention",+ "idle": "Idle"+ },+ "stoppedNotice": "{count} tasks are waiting while workers are stopped.",+ "waitNotice": "Oldest task has waited {minutes} minutes.",+ "failedNotice": "{count} failed tasks need review.",+ "debug": {+ "label": "Mock preview",+ "scenarios": {+ "empty": "No tasks",+ "processing": "Processing",+ "backlog": "Backlog",+ "stopped": "Stopped",+ "failures": "Failures",+ "allFailed": "All failed"+ }+ }},"recentActivity": {"title": "Recent Activity",@@ -1647,5 +1670,54 @@"image": {"loadError": "Failed to load image"}+ },+ "debug": {+ "title": "Debug tools",+ "open": "Open debug tools",+ "info": "Basic information",+ "route": "Route",+ "version": "Version",+ "viewport": "Viewport",+ "locale": "Language",+ "theme": "Theme",+ "general": "General tools",+ "outline": "Show element outlines",+ "refresh": "Refresh data",+ "reload": "Reload page",+ "reset": "Reset debug settings",+ "page": "Current page",+ "empty": "No debug options on this page.",+ "scenario": "Scenario",+ "window": {+ "maximize": "Maximize",+ "restore": "Restore",+ "close": "Close"+ },+ "viewer": {+ "title": "Image viewer",+ "visibility": "WebGL diagnostics",+ "system": "Follow system setting",+ "show": "Force show",+ "hide": "Force hide",+ "delay": "Load delay (ms)",+ "failure": "Simulate load failure",+ "reload": "Reload current image",+ "systemValue": "System setting",+ "effective": "Effective visibility",+ "stage": "Load stage",+ "waiting": "Simulated loading delay",+ "stages": {+ "idle": "Idle",+ "delay": "Simulated delay",+ "image": "Loading image",+ "texture": "Loading texture",+ "ready": "Ready",+ "error": "Failed",+ "tile": "Loading tiles"+ }+ },+ "ogImage": "Page OG image",+ "openOgImage": "Open OG image",+ "ogImageError": "Could not load the OG image."}}diff --git a/i18n/locales/ja.json b/i18n/locales/ja.jsonindex a035fc71..c8606766 100644--- a/i18n/locales/ja.json+++ b/i18n/locales/ja.json@@ -924,7 +924,30 @@"totalWorkers": "総 Workers","totalProcessed": "処理","totalFailed": "障害カウント",- "avgSuccessRate": "成功率"+ "avgSuccessRate": "成功率",+ "pending": "待機中",+ "workers": "ワーカー",+ "states": {+ "unknown": "不明",+ "stopped": "停止中",+ "processing": "処理中",+ "attention": "要確認",+ "idle": "待機中"+ },+ "stoppedNotice": "ワーカーが停止中です。{count} 件のタスクが待機しています。",+ "waitNotice": "最も古いタスクは {minutes} 分待機しています。",+ "failedNotice": "{count} 件の失敗タスクを確認してください。",+ "debug": {+ "label": "模擬プレビュー",+ "scenarios": {+ "empty": "処理履歴なし",+ "processing": "処理中",+ "backlog": "滞留",+ "stopped": "停止中",+ "failures": "一部失敗",+ "allFailed": "すべて失敗"+ }+ }},"recentActivity": {"title": "最近のアクティビティ",@@ -1656,5 +1679,54 @@"image": {"loadError": "画像の読み込み失敗"}+ },+ "debug": {+ "title": "デバッグツール",+ "open": "デバッグツールを開く",+ "info": "基本情報",+ "route": "ルート",+ "version": "バージョン",+ "viewport": "画面サイズ",+ "locale": "言語",+ "theme": "テーマ",+ "general": "共通操作",+ "outline": "要素の輪郭を表示",+ "refresh": "データ更新",+ "reload": "ページ再読み込み",+ "reset": "設定をリセット",+ "page": "現在のページ",+ "empty": "このページにデバッグ設定はありません。",+ "scenario": "シナリオ",+ "window": {+ "maximize": "最大化",+ "restore": "元に戻す",+ "close": "閉じる"+ },+ "viewer": {+ "title": "写真ビューア",+ "visibility": "WebGL 診断表示",+ "system": "システム設定に従う",+ "show": "強制表示",+ "hide": "強制非表示",+ "delay": "読込遅延(ms)",+ "failure": "読込失敗を模擬",+ "reload": "現在の画像を再読込",+ "systemValue": "システム設定",+ "effective": "実際の表示",+ "stage": "読込段階",+ "waiting": "模擬遅延中",+ "stages": {+ "idle": "待機",+ "delay": "模擬遅延",+ "image": "画像読込",+ "texture": "テクスチャ読込",+ "ready": "準備完了",+ "error": "失敗",+ "tile": "タイル読込"+ }+ },+ "ogImage": "ページの OG 画像",+ "openOgImage": "OG 画像を開く",+ "ogImageError": "OG 画像を読み込めませんでした。"}}diff --git a/i18n/locales/ru.json b/i18n/locales/ru.jsonindex c889b50f..d1e048f3 100644--- a/i18n/locales/ru.json+++ b/i18n/locales/ru.json@@ -999,7 +999,30 @@"totalWorkers": "Всего обработчиков","totalProcessed": "Обработано","totalFailed": "Ошибок",- "avgSuccessRate": "Доля успешных задач"+ "avgSuccessRate": "Доля успешных задач",+ "pending": "В очереди",+ "workers": "Обработчики",+ "states": {+ "unknown": "Неизвестно",+ "stopped": "Остановлено",+ "processing": "Обработка",+ "attention": "Требует внимания",+ "idle": "Простой"+ },+ "stoppedNotice": "Обработчики остановлены, ожидают {count} задач.",+ "waitNotice": "Самая старая задача ожидает {minutes} мин.",+ "failedNotice": "Необходимо проверить {count} неудачных задач.",+ "debug": {+ "label": "Предпросмотр",+ "scenarios": {+ "empty": "Нет задач",+ "processing": "Обработка",+ "backlog": "Накопление",+ "stopped": "Остановлено",+ "failures": "Частичные ошибки",+ "allFailed": "Все неудачны"+ }+ }},"recentActivity": {"title": "Недавняя активность",@@ -1647,5 +1670,54 @@"image": {"loadError": "Не удалось загрузить изображение"}+ },+ "debug": {+ "title": "Отладка",+ "open": "Открыть отладку",+ "info": "Основная информация",+ "route": "Маршрут",+ "version": "Версия",+ "viewport": "Размер окна",+ "locale": "Язык",+ "theme": "Тема",+ "general": "Общие действия",+ "outline": "Показать контуры",+ "refresh": "Обновить данные",+ "reload": "Перезагрузить",+ "reset": "Сбросить настройки",+ "page": "Текущая страница",+ "empty": "На этой странице нет настроек отладки.",+ "scenario": "Сценарий",+ "window": {+ "maximize": "Развернуть",+ "restore": "Восстановить",+ "close": "Закрыть"+ },+ "viewer": {+ "title": "Просмотр фото",+ "visibility": "Диагностика WebGL",+ "system": "Системная настройка",+ "show": "Показать",+ "hide": "Скрыть",+ "delay": "Задержка (мс)",+ "failure": "Имитировать ошибку",+ "reload": "Перезагрузить изображение",+ "systemValue": "Системная настройка",+ "effective": "Фактическое значение",+ "stage": "Этап загрузки",+ "waiting": "Искусственная задержка",+ "stages": {+ "idle": "Ожидание",+ "delay": "Задержка",+ "image": "Загрузка изображения",+ "texture": "Загрузка текстуры",+ "ready": "Готово",+ "error": "Ошибка",+ "tile": "Загрузка тайлов"+ }+ },+ "ogImage": "OG-изображение страницы",+ "openOgImage": "Открыть OG-изображение",+ "ogImageError": "Не удалось загрузить OG-изображение."}}diff --git a/i18n/locales/zh-Hans.json b/i18n/locales/zh-Hans.jsonindex ade1d2d0..a34d2de8 100644--- a/i18n/locales/zh-Hans.json+++ b/i18n/locales/zh-Hans.json@@ -999,7 +999,30 @@"totalWorkers": "总 Workers","totalProcessed": "已处理","totalFailed": "失败计数",- "avgSuccessRate": "成功率"+ "avgSuccessRate": "成功率",+ "pending": "待处理",+ "workers": "Workers",+ "states": {+ "unknown": "未知",+ "stopped": "已停止",+ "processing": "处理中",+ "attention": "需要关注",+ "idle": "空闲"+ },+ "stoppedNotice": "Workers 已停止,仍有 {count} 项任务等待处理。",+ "waitNotice": "最早任务已等待 {minutes} 分钟。",+ "failedNotice": "有 {count} 项失败任务待检查。",+ "debug": {+ "label": "模拟预览",+ "scenarios": {+ "empty": "无处理记录",+ "processing": "处理中",+ "backlog": "任务积压",+ "stopped": "已停止",+ "failures": "部分失败",+ "allFailed": "全部失败"+ }+ }},"recentActivity": {"title": "最近动态",@@ -1521,7 +1544,7 @@"admin": "管理员账户","site": "站点信息","storage": "存储配置",- "map": "地图服务",+ "map": "地图服务","complete": "完成"},"tips": "不用担心填错,后续可在管理后台进行修改",@@ -1647,5 +1670,54 @@"image": {"loadError": "图片加载失败"}+ },+ "debug": {+ "title": "调试工具",+ "open": "打开调试工具",+ "info": "基础信息",+ "route": "当前路由",+ "version": "版本",+ "viewport": "视口尺寸",+ "locale": "语言",+ "theme": "主题",+ "general": "通用操作",+ "outline": "显示元素轮廓",+ "refresh": "刷新数据",+ "reload": "重新加载页面",+ "reset": "重置调试配置",+ "page": "当前页面",+ "empty": "此页面暂无调试配置。",+ "scenario": "模拟场景",+ "window": {+ "maximize": "最大化",+ "restore": "恢复",+ "close": "关闭"+ },+ "viewer": {+ "title": "照片查看器",+ "visibility": "WebGL 诊断显示",+ "system": "遵循系统设置",+ "show": "强制显示",+ "hide": "强制隐藏",+ "delay": "加载延迟(毫秒)",+ "failure": "模拟加载失败",+ "reload": "重新加载当前图片",+ "systemValue": "系统设置值",+ "effective": "最终生效值",+ "stage": "加载阶段",+ "waiting": "模拟加载延迟中",+ "stages": {+ "idle": "空闲",+ "delay": "模拟延迟",+ "image": "加载图片",+ "texture": "加载纹理",+ "ready": "已就绪",+ "error": "加载失败",+ "tile": "加载分块"+ }+ },+ "ogImage": "页面 OG 图",+ "openOgImage": "打开 OG 图",+ "ogImageError": "OG 图加载失败。"}}diff --git a/i18n/locales/zh-Hant-HK.json b/i18n/locales/zh-Hant-HK.jsonindex d18f4a46..5387912f 100644--- a/i18n/locales/zh-Hant-HK.json+++ b/i18n/locales/zh-Hant-HK.json@@ -924,7 +924,30 @@"totalWorkers": "總 Workers","totalProcessed": "已處理","totalFailed": "失敗計數",- "avgSuccessRate": "成功率"+ "avgSuccessRate": "成功率",+ "pending": "待處理",+ "workers": "Workers",+ "states": {+ "unknown": "未知",+ "stopped": "已停止",+ "processing": "處理中",+ "attention": "需要關注",+ "idle": "閒置"+ },+ "stoppedNotice": "Workers 已停止,仍有 {count} 項任務等待處理。",+ "waitNotice": "最早任務已等待 {minutes} 分鐘。",+ "failedNotice": "有 {count} 項失敗任務待檢查。",+ "debug": {+ "label": "模擬預覽",+ "scenarios": {+ "empty": "無處理記錄",+ "processing": "處理中",+ "backlog": "任務積壓",+ "stopped": "已停止",+ "failures": "部分失敗",+ "allFailed": "全部失敗"+ }+ }},"recentActivity": {"title": "最近動態",@@ -1647,5 +1670,54 @@"image": {"loadError": "圖片載入失敗"}+ },+ "debug": {+ "title": "偵錯工具",+ "open": "開啟偵錯工具",+ "info": "基本資訊",+ "route": "目前路由",+ "version": "版本",+ "viewport": "視窗尺寸",+ "locale": "語言",+ "theme": "主題",+ "general": "通用操作",+ "outline": "顯示元素輪廓",+ "refresh": "重新整理資料",+ "reload": "重新載入頁面",+ "reset": "重設偵錯設定",+ "page": "目前頁面",+ "empty": "此頁面暫無偵錯設定。",+ "scenario": "模擬情境",+ "window": {+ "maximize": "最大化",+ "restore": "還原",+ "close": "關閉"+ },+ "viewer": {+ "title": "相片檢視器",+ "visibility": "WebGL 診斷顯示",+ "system": "遵循系統設定",+ "show": "強制顯示",+ "hide": "強制隱藏",+ "delay": "載入延遲(毫秒)",+ "failure": "模擬載入失敗",+ "reload": "重新載入目前圖片",+ "systemValue": "系統設定值",+ "effective": "最終生效值",+ "stage": "載入階段",+ "waiting": "模擬載入延遲中",+ "stages": {+ "idle": "閒置",+ "delay": "模擬延遲",+ "image": "載入圖片",+ "texture": "載入紋理",+ "ready": "已就緒",+ "error": "載入失敗",+ "tile": "載入分塊"+ }+ },+ "ogImage": "頁面 OG 圖",+ "openOgImage": "開啟 OG 圖",+ "ogImageError": "OG 圖載入失敗。"}}diff --git a/i18n/locales/zh-Hant-TW.json b/i18n/locales/zh-Hant-TW.jsonindex f7da7ce3..21f218bc 100644--- a/i18n/locales/zh-Hant-TW.json+++ b/i18n/locales/zh-Hant-TW.json@@ -924,7 +924,30 @@"totalWorkers": "總 Workers","totalProcessed": "已處理","totalFailed": "失敗計數",- "avgSuccessRate": "成功率"+ "avgSuccessRate": "成功率",+ "pending": "待處理",+ "workers": "Workers",+ "states": {+ "unknown": "未知",+ "stopped": "已停止",+ "processing": "處理中",+ "attention": "需要關注",+ "idle": "閒置"+ },+ "stoppedNotice": "Workers 已停止,仍有 {count} 項任務等待處理。",+ "waitNotice": "最早任務已等待 {minutes} 分鐘。",+ "failedNotice": "有 {count} 項失敗任務待檢查。",+ "debug": {+ "label": "模擬預覽",+ "scenarios": {+ "empty": "無處理紀錄",+ "processing": "處理中",+ "backlog": "任務積壓",+ "stopped": "已停止",+ "failures": "部分失敗",+ "allFailed": "全部失敗"+ }+ }},"recentActivity": {"title": "最近動態",@@ -1647,5 +1670,54 @@"image": {"loadError": "圖片載入失敗"}+ },+ "debug": {+ "title": "偵錯工具",+ "open": "開啟偵錯工具",+ "info": "基本資訊",+ "route": "目前路由",+ "version": "版本",+ "viewport": "視窗尺寸",+ "locale": "語言",+ "theme": "主題",+ "general": "通用操作",+ "outline": "顯示元素輪廓",+ "refresh": "重新整理資料",+ "reload": "重新載入頁面",+ "reset": "重設偵錯設定",+ "page": "目前頁面",+ "empty": "此頁面暫無偵錯設定。",+ "scenario": "模擬情境",+ "window": {+ "maximize": "最大化",+ "restore": "還原",+ "close": "關閉"+ },+ "viewer": {+ "title": "相片檢視器",+ "visibility": "WebGL 診斷顯示",+ "system": "遵循系統設定",+ "show": "強制顯示",+ "hide": "強制隱藏",+ "delay": "載入延遲(毫秒)",+ "failure": "模擬載入失敗",+ "reload": "重新載入目前圖片",+ "systemValue": "系統設定值",+ "effective": "最終生效值",+ "stage": "載入階段",+ "waiting": "模擬載入延遲中",+ "stages": {+ "idle": "閒置",+ "delay": "模擬延遲",+ "image": "載入圖片",+ "texture": "載入紋理",+ "ready": "已就緒",+ "error": "載入失敗",+ "tile": "載入分塊"+ }+ },+ "ogImage": "頁面 OG 圖",+ "openOgImage": "開啟 OG 圖",+ "ogImageError": "OG 圖載入失敗。"}}diff --git a/server/api/system/stats.get.ts b/server/api/system/stats.get.tsindex ac4bcb42..75b63cee 100644--- a/server/api/system/stats.get.ts+++ b/server/api/system/stats.get.ts@@ -4,7 +4,9 @@ import { readFileSync } from 'node:fs'async function getQueueStats() {const workerPool = globalThis.__workerPool- return workerPool ? workerPool.getPoolStats() : null+ return workerPool+ ? { ...workerPool.getPoolStats(), isActive: workerPool.isActive() }+ : null}async function checkIfDocker(): Promise<boolean> {@@ -120,6 +122,17 @@ function mapSystemInfo(distribution: string): string {export default eventHandler(async (event) => {await requireUserSession(event)+ const queue = await useDB()+ .select({+ pending: sql<number>`COALESCE(SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END), 0)`,+ failed: sql<number>`COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0)`,+ oldestPendingAt: sql<+ number | null+ >`MIN(CASE WHEN status = 'pending' THEN created_at END)`,+ })+ .from(tables.pipelineQueue)+ .get()+// 获取基础统计const totalPhotos = await useDB().select({ count: sql<number>`count(*)` })@@ -228,6 +241,14 @@ export default eventHandler(async (event) => {thisMonth: monthPhotos?.count || 0,},workerPool: (await getQueueStats()) || null,+ queue: {+ pending: queue?.pending || 0,+ failed: queue?.failed || 0,+ oldestWaitSeconds:+ queue?.oldestPendingAt != null+ ? Math.max(0, Math.floor(Date.now() / 1000) - queue.oldestPendingAt)+ : 0,+ },storage: {totalSize: storageStats?.totalSize || 0,averageSize: storageStats?.avgSize || 0,diff --git a/server/services/pipeline-queue/worker-pool.ts b/server/services/pipeline-queue/worker-pool.tsindex 6f46a3fd..1a776c07 100644--- a/server/services/pipeline-queue/worker-pool.ts+++ b/server/services/pipeline-queue/worker-pool.ts@@ -154,17 +154,9 @@ export class WorkerPool {(stats) => stats.isProcessing,).length- // 只计算已执行过操作的worker的平均成功率- const workersWithActivity = workerStats.filter(- (stats) => stats.processedCount > 0,- )+ const totalAttempts = totalProcessed + totalErrorsconst averageSuccessRate =- workersWithActivity.length > 0- ? workersWithActivity.reduce(- (sum, stats) => sum + stats.successRate,- 0,- ) / workersWithActivity.length- : 0+ totalAttempts > 0 ? (totalProcessed / totalAttempts) * 100 : 0return {totalWorkers: this.workers.length,