From 9d726042513479f1e59f14b5e9c1c1e77b719ea4 Mon Sep 17 00:00:00 2001 From: Ling Test Date: Tue, 1 Dec 2026 14:41:11 +0800 Subject: [PATCH 1/2] feat: add optional Inuyasha startup animation plugin host --- apps/web/public/illustrations/launch-hand.svg | 8 + apps/web/src/api/startup-animation.ts | 21 +++ .../src/features/launch/LaunchTransition.tsx | 117 +++++++++++-- .../src/styles/features/launch-transition.css | 156 ++++++++++++++++++ docs/design/clients/launch-animation.md | 14 +- .../inuyasha-startup-animation-plugin.md | 75 +++++++++ .../src/features/plugins/remote-package.ts | 2 +- .../daemon/src/features/plugins/routes.ts | 36 ++++ .../src/features/plugins/startup-animation.ts | 63 +++++++ packages/daemon/src/server/router.ts | 6 + .../test/plugin-startup-animation.test.ts | 96 +++++++++++ plugins/inuyasha-startup-animation/README.md | 7 + .../package/.ling-plugin/plugin.json | 19 +++ .../package/ui/startup-animation.json | 8 + scripts/ci/daemon-test-platforms.json | 1 + scripts/plugins/collect-official-releases.mjs | 32 +++- 16 files changed, 634 insertions(+), 27 deletions(-) create mode 100644 apps/web/public/illustrations/launch-hand.svg create mode 100644 apps/web/src/api/startup-animation.ts create mode 100644 docs/design/integrations/inuyasha-startup-animation-plugin.md create mode 100644 packages/daemon/src/features/plugins/startup-animation.ts create mode 100644 packages/daemon/test/plugin-startup-animation.test.ts create mode 100644 plugins/inuyasha-startup-animation/README.md create mode 100644 plugins/inuyasha-startup-animation/package/.ling-plugin/plugin.json create mode 100644 plugins/inuyasha-startup-animation/package/ui/startup-animation.json diff --git a/apps/web/public/illustrations/launch-hand.svg b/apps/web/public/illustrations/launch-hand.svg new file mode 100644 index 000000000..f4d5d65ac --- /dev/null +++ b/apps/web/public/illustrations/launch-hand.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/web/src/api/startup-animation.ts b/apps/web/src/api/startup-animation.ts new file mode 100644 index 000000000..444074fa9 --- /dev/null +++ b/apps/web/src/api/startup-animation.ts @@ -0,0 +1,21 @@ +import { getDaemonHealth } from "./control-plane.js"; +import { daemonBaseUrl } from "./client.js"; +import { readActiveWorkspaceCwd, readInitialWorkspaceCwd } from "../lib/local-storage.js"; + +export async function readStartupAnimationVideo(): Promise { + let cwd = readActiveWorkspaceCwd() || readInitialWorkspaceCwd(); + if (!cwd) { + const health = await Promise.race([ + getDaemonHealth(), + new Promise((resolve) => window.setTimeout(() => resolve(undefined), 500)), + ]); + cwd = health?.defaultWorkspaceCwd?.trim() ?? ""; + } + if (!cwd) return undefined; + const url = new URL("/plugins/startup-animation/media", daemonBaseUrl); + url.searchParams.set("cwd", cwd); + const response = await fetch(url, { signal: AbortSignal.timeout(1200), cache: "no-store" }); + if (response.status === 204) return undefined; + if (!response.ok || response.headers.get("content-type") !== "video/mp4") throw new Error("Startup animation video is unavailable."); + return await response.blob(); +} diff --git a/apps/web/src/features/launch/LaunchTransition.tsx b/apps/web/src/features/launch/LaunchTransition.tsx index 5c880839c..206f0d2ae 100644 --- a/apps/web/src/features/launch/LaunchTransition.tsx +++ b/apps/web/src/features/launch/LaunchTransition.tsx @@ -1,5 +1,6 @@ import { createPortal } from "react-dom"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { readStartupAnimationVideo } from "../../api/startup-animation.js"; import { createLaunchAnimation, LAUNCH_ANIMATION_FADE_DURATION, @@ -21,13 +22,63 @@ export function LaunchTransition({ const controllerRef = useRef(undefined); const objectUrlRef = useRef(undefined); const onFinishedRef = useRef(onFinished); + const finishedRef = useRef(false); + const fadeTimerRef = useRef(undefined); const [exiting, setExiting] = useState(false); const [visible, setVisible] = useState(true); + const [media, setMedia] = useState(undefined); + const [videoUrl, setVideoUrl] = useState(undefined); + const [introComplete, setIntroComplete] = useState(false); + const [handoff, setHandoff] = useState(false); + + const complete = (): void => { + if (finishedRef.current) return; + finishedRef.current = true; + setExiting(true); + fadeTimerRef.current = window.setTimeout(() => { + setVisible(false); + onFinishedRef.current?.(); + }, LAUNCH_ANIMATION_FADE_DURATION); + }; useEffect(() => { onFinishedRef.current = onFinished; }, [onFinished]); + useEffect(() => { + if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { + if (finishedRef.current) return undefined; + finishedRef.current = true; + setVisible(false); + onFinishedRef.current?.(); + return undefined; + } + const timeout = window.setTimeout(complete, 5000); + const introTimer = window.setTimeout(() => setIntroComplete(true), 720); + let cancelled = false; + void readStartupAnimationVideo() + .then((video) => { if (!cancelled) setMedia(video ?? null); }) + .catch(() => { if (!cancelled) setMedia(null); }); + return () => { + cancelled = true; + window.clearTimeout(timeout); + window.clearTimeout(introTimer); + }; + }, []); + + useEffect(() => { + if (!media) return undefined; + const url = URL.createObjectURL(media); + setVideoUrl(url); + return () => { + URL.revokeObjectURL(url); + }; + }, [media]); + + useEffect(() => () => { + if (fadeTimerRef.current !== undefined) window.clearTimeout(fadeTimerRef.current); + }, []); + useLayoutEffect(() => { if (!visible) return undefined; const roots = ["root", "ling-ui-overlay-root"] @@ -36,6 +87,7 @@ export function LaunchTransition({ .map((root) => ({ root, previousInert: root.inert })); for (const { root } of roots) root.inert = true; const blockKeyboard = (event: KeyboardEvent): void => { + if (event.key === "Escape") complete(); event.stopImmediatePropagation(); if (!event.metaKey && !event.ctrlKey) event.preventDefault(); }; @@ -44,27 +96,21 @@ export function LaunchTransition({ window.removeEventListener("keydown", blockKeyboard, true); for (const { root, previousInert } of roots) root.inert = previousInert; }; - }, [visible]); + }, [visible, media]); useEffect(() => { const canvas = canvasRef.current; - if (!canvas) return undefined; + if (!canvas || media !== null) return undefined; - let fadeTimer: number | undefined; let controller: LaunchAnimationController; try { controller = createLaunchAnimation(canvas, { - ...(referenceImageUrl !== undefined ? { referenceImageUrl } : {}), - onComplete: () => { - setExiting(true); - fadeTimer = window.setTimeout(() => { - setVisible(false); - onFinishedRef.current?.(); - }, LAUNCH_ANIMATION_FADE_DURATION); - }, + ...((objectUrlRef.current ?? referenceImageUrl) !== undefined ? { referenceImageUrl: objectUrlRef.current ?? referenceImageUrl } : {}), + onComplete: complete, }); } catch (error) { console.warn("Launch animation could not start.", error); + finishedRef.current = true; setVisible(false); onFinishedRef.current?.(); return undefined; @@ -74,9 +120,8 @@ export function LaunchTransition({ return () => { controller?.destroy(); controllerRef.current = undefined; - if (fadeTimer !== undefined) window.clearTimeout(fadeTimer); }; - }, [referenceImageUrl]); + }, [referenceImageUrl, media]); useEffect(() => { const referenceImage = resolved.manifest.launchAnimation?.referenceImage; @@ -103,14 +148,54 @@ export function LaunchTransition({ if (!visible) return null; + const showVideo = Boolean(media && videoUrl && introComplete); + const transition = ( ); diff --git a/apps/web/src/styles/features/launch-transition.css b/apps/web/src/styles/features/launch-transition.css index 6424a71aa..7eeeac63a 100644 --- a/apps/web/src/styles/features/launch-transition.css +++ b/apps/web/src/styles/features/launch-transition.css @@ -19,6 +19,162 @@ height: 100%; } +.ling-launch-transition[data-mode="video"], +.ling-launch-transition[data-mode="loading"] { + background: #fff; +} + +.ling-launch-transition[data-mode="video"] { + transition: background calc(var(--ling-motion-attention) * 0.7) var(--ling-ease-standard), opacity 220ms ease; +} + +@property --ling-launch-reveal { + syntax: ""; + inherits: false; + initial-value: -15%; +} + +.ling-launch-video-stage { + --ling-launch-reveal: -15%; + position: absolute; + inset: 0; + overflow: hidden; + mask-image: radial-gradient(circle at center, transparent var(--ling-launch-reveal), #000 calc(var(--ling-launch-reveal) + 15%)); + transition: --ling-launch-reveal calc(var(--ling-motion-attention) * 0.8) var(--ling-ease-enter); +} + +.ling-launch-transition video { + display: block; + width: 100%; + height: 100%; + object-fit: cover; +} + +.ling-launch-transition[data-handoff="true"] { + background: transparent; +} + +.ling-launch-transition[data-handoff="true"] .ling-launch-video-stage { + --ling-launch-reveal: 100%; +} + +.ling-launch-brand { + position: absolute; + inset: 0; + background: #fff; + pointer-events: none; +} + +.ling-launch-brand-emblem { + position: absolute; + top: 47%; + left: 50%; + display: grid; + place-items: center; + width: clamp(76px, 8vw, 100px); + aspect-ratio: 1; + border-radius: 22%; + background: #1c2030; + box-shadow: 0 18px 40px rgb(37 34 70 / 14%); + transform: translate(-50%, -50%); + animation: ling-launch-tap calc(var(--ling-motion-slow) * 3) var(--ling-ease-standard) both; +} + +.ling-launch-brand-emblem img { + width: 78%; + height: 78%; +} + +.ling-launch-hand { + position: absolute; + top: calc(47% + 8px); + left: calc(50% - 28px); + width: clamp(210px, 22vw, 300px); + height: auto; + transform-origin: 25% 18%; + animation: ling-launch-hand-tap calc(var(--ling-motion-slow) * 3) var(--ling-ease-standard) both; +} + +.ling-launch-brand-ripple { + position: absolute; + top: 47%; + left: 50%; + width: 110px; + aspect-ratio: 1; + border: 2px solid #a48af4; + border-radius: 50%; + transform: translate(-50%, -50%) scale(0.4); + animation: ling-launch-ripple calc(var(--ling-motion-slow) * 3) var(--ling-ease-exit) both; +} + +.ling-launch-transition[data-mode="video"] .ling-launch-brand { + animation: ling-launch-reveal calc(var(--ling-motion-attention) / 2) var(--ling-ease-enter) forwards; +} + +.ling-launch-skip { + position: absolute; + top: 24px; + right: 28px; + display: inline-flex; + align-items: center; + gap: 10px; + padding: 8px 12px; + border: 1px solid rgb(32 36 54 / 18%); + border-radius: 8px; + background: rgb(255 255 255 / 78%); + color: #24283a; + font: inherit; + font-size: 13px; + font-weight: 500; + cursor: pointer; + backdrop-filter: blur(8px); +} + +.ling-launch-skip kbd { + font: inherit; + opacity: 0.72; +} + +.ling-launch-skip:hover, +.ling-launch-skip:focus-visible { + background: #fff; +} + +.ling-launch-transition[data-mode="video"] .ling-launch-skip { + border-color: rgb(255 255 255 / 32%); + background: rgb(16 20 30 / 50%); + color: #fff; +} + +.ling-launch-transition[data-mode="video"] .ling-launch-skip:hover, +.ling-launch-transition[data-mode="video"] .ling-launch-skip:focus-visible { + background: rgb(16 20 30 / 76%); +} + +@keyframes ling-launch-reveal { + to { opacity: 0; visibility: hidden; } +} + +@keyframes ling-launch-hand-tap { + 0% { transform: translate(110px, 105px) rotate(9deg); opacity: 0; } + 25% { opacity: 1; } + 56% { transform: translate(2px, 2px) rotate(0); } + 68% { transform: translate(-7px, -5px) rotate(-3deg); } + 100% { transform: translate(0, 0) rotate(0); } +} + +@keyframes ling-launch-tap { + 0%, 56% { transform: translate(-50%, -50%) scale(1); } + 68% { transform: translate(-50%, -50%) scale(0.9); } + 100% { transform: translate(-50%, -50%) scale(1); } +} + +@keyframes ling-launch-ripple { + 0%, 60% { opacity: 0; transform: translate(-50%, -50%) scale(0.4); } + 68% { opacity: 0.65; } + 100% { opacity: 0; transform: translate(-50%, -50%) scale(2.3); } +} + @media (prefers-reduced-motion: reduce) { .ling-launch-transition { transition-duration: 180ms; diff --git a/docs/design/clients/launch-animation.md b/docs/design/clients/launch-animation.md index 255e1a965..011013647 100644 --- a/docs/design/clients/launch-animation.md +++ b/docs/design/clients/launch-animation.md @@ -1,5 +1,7 @@ # Start page animation design +The optional official MP4 startup animation plugin is specified in [犬夜叉开机动画插件](../integrations/inuyasha-startup-animation-plugin.md). This document describes the built-in Canvas fallback and theme reference image pipeline. + ## Target The startup animation is the first screen transition layer. The application shell is mounted normally first, and the Canvas animation is overlaid on the shell. After the animation is completed, it fades out and is uninstalled. In this way, the startup animation will not participate in routing, session or workspace state, nor will it block the initialization of the first-screen business UI. @@ -54,12 +56,12 @@ Theme designers only need to provide an in-package PNG/WebP reference image and ## life cycle 1. `App` mounts `AppShell` and `LaunchTransition`. -2. `LaunchTransition` Create a Canvas controller immediately and start playing using the built-in reference image. -3. If the current theme declares a startup animation reference image, the runtime reads the verified Blob asynchronously through the theme repository. -4. After the resource is read successfully, the controller updates the current windmill diagram through `setReferenceImageUrl` without resetting the timeline or replaying the animation. -5. The default windmill continues to be used when resources are missing, the theme repository is unavailable, Blob URL creation fails, or image decoding fails. -6. The animation completes and enters a fade-out state, at which point the overlay is unloaded and the blob URL is released. -7. `prefers-reduced-motion: reduce` directly renders the final state and completes the transition without entering a long animation loop. +2. `LaunchTransition` checks the enabled startup animation plugin in the current workspace. A verified video plays in the overlay; when no video is available, the Canvas controller plays the built-in windmill animation. The transition exits within five seconds plus the fade. +3. If the current theme declares a startup animation reference image, the runtime reads the verified Blob asynchronously through the theme repository for the Canvas path. +4. After the image is read successfully, the Canvas controller updates the current windmill diagram through `setReferenceImageUrl` without resetting the timeline or replaying the animation. +5. The default windmill continues to be used when the plugin is unavailable or video playback fails, or when theme resources are missing or cannot be decoded. +6. The animation completes and enters a fade-out state, at which point the overlay is unloaded and the Blob URLs are released. +7. `prefers-reduced-motion: reduce` directly completes the transition without entering a long animation loop. Intercept pointer events during overlay display, and set the application root node and independent pop-up window root node to `inert`. The window capture phase prevents keyboard events from being transmitted to the business processor, preventing the Escape listener of the hidden pop-up window or the global shortcut key from changing the application state; the browser default shortcut key with Ctrl/Meta can still be used. When exiting or uninstalling, restore the original status of each root node and remove the keyboard monitor. When Canvas initialization fails, the overlay is directly uninstalled and interaction is restored, and the application shell continues to run. After the topic repository restores the complete list, the startup resource configuration will be updated even if the topic name, ID, and token are consistent with the first screen snapshot. diff --git a/docs/design/integrations/inuyasha-startup-animation-plugin.md b/docs/design/integrations/inuyasha-startup-animation-plugin.md new file mode 100644 index 000000000..36f8a43e0 --- /dev/null +++ b/docs/design/integrations/inuyasha-startup-animation-plugin.md @@ -0,0 +1,75 @@ +# 犬夜叉开机动画插件 + +## 目标与边界 + +Ling 启动时可由已安装且已启用的官方插件播放一次犬夜叉主题短视频,随后淡出进入已经挂载的主界面。体验参考 [Dragon Codex Boot](https://github.com/yushua0808-cpu/dragon-codex-boot):从明亮的品牌开场进入角色动作画面,最后与已打开的应用界面交接。Ling 使用五秒以内的短片,不等待主界面就绪,也不做桌宠、任务状态联动、动态脚本、音频播放或主题替换。 + +本设计以 [独立插件分发](plugin-independent-packaging.md) 和 [现有启动动画](../clients/launch-animation.md) 为基础。默认 Canvas 风车动画继续作为未安装、停用、读取失败时的回退。插件包只提供静态资源及声明式配置;宿主负责选择、验证、播放和退出。 + +## 视觉与交互 + +参考片段不是单纯播放角色视频:它先以手指点击 Codex 图标启动叙事,角色在明亮舞台登场,最后将画面转成 Codex 窗口并交给真实应用。Ling 用自己的标志和独立绘制的手部插画完成对应叙事;不复制参考项目的视频帧或应用截图。已选定的犬夜叉镜头保持为“爆流破”挥刀段,不换用其他候选。 + +| 阶段 | 目标时间 | 画面与行为 | +| --- | ---: | --- | +| 品牌开场 | `0–0.4s` | 白色全屏舞台,Ling 标志位于中央偏上;手从右下向图标移动,主界面在背后同步挂载。 | +| 点击触发 | `0.4–0.72s` | 手指触碰图标,图标轻微压下并回弹,紫色光圈扩散;这一段由宿主的固定 SVG/CSS 绘制,不由插件运行脚本。 | +| 角色动作 | `约 0.72–4.5s` | 图标场景以 300ms 亮场溶解到已验证的静音犬夜叉 MP4;片段为 257–260.5 秒的正面与挥刀镜头,视频按 16:9 裁切填满窗口。只有开场动画和媒体都就绪才开始播放;读取稍慢时保持点击结束后的品牌画面。 | +| 界面交接 | `视频最后约 0.55s` | 视频尾段的亮场开始时,角色画面从中心向外擦除,让背后**真实挂载的 Ling AppShell**从画面中央展开;视频结束后覆盖层再用 220ms 淡出。不使用预录或伪造的 Ling 界面帧。 | + +体验总上限是启动后五秒加 220ms 退场。参考项目约 14 秒且可暂停等待 Codex 应用就绪;Ling 按此前确定的五秒体验压缩分镜,不等待下载或主界面就绪。已选短片长约 3.5 秒,开场和解码共留约 1.5 秒预算;来不及完整播放时五秒硬上限优先。正式素材按 16:9 构图,使用 `object-fit: cover`,窄窗口允许裁切边缘。没有标题、进度、加载说明或卡片;视频静音播放。 + +- 右上角有轻量“跳过 Esc”,点击舞台或按 `Escape` 也可以跳过。`prefers-reduced-motion: reduce` 直接进入主界面。 +- 视频失败、资源缺失、插件未启用、超时或 daemon 不可用时,进入现有风车动画;从启动开始计时,过场总时长最多五秒再淡出,任何故障均不阻塞主界面。 +- 安装与启用后从下次启动生效。停用或卸载后恢复默认动画。插件管理页复用现有安装和启用开关。 + +## 包协议 + +插件 ID:`official:inuyasha-startup-animation`。复用 manifest v2 的 `ui-feature` contribution,不允许插件自带 JavaScript、HTML、CSS 或 WASM。包内资源: + +```text +.ling-plugin/plugin.json +.ling-plugin/checksums.json +.ling-plugin/provenance.json +ui/startup-animation.json +assets/startup.mp4 +``` + +`plugin.json` 的唯一 `ui-feature` contribution ID 为 `startup-animation`,路径固定为 `ui/startup-animation.json`。资源声明为: + +```json +{ + "schemaVersion": 1, + "type": "startup-animation", + "video": "assets/startup.mp4", + "maxDurationMs": 5000, + "muted": true, + "fit": "cover" +} +``` + +运行时只接受这个固定 ID、路径、类型和字段组合。MP4 上限 12 MiB,所有资源必须在插件包 checksums 中且通过安装校验。正式资源用 H.264、24–30fps、720p 或 1080p、无音轨,视频时长不超过五秒。每个平台的 ZIP 遵循现有 catalog 的平台和架构选择规则,即使媒体字节相同也分别发布。 + +## 数据流与所有权 + +1. daemon 从当前工作区的插件记录确认包已安装且启用,再比对版本化缓存指针和包记录。 +2. daemon 对缓存包重新验证完整性,读取固定配置和视频资源,通过受同源及 daemon 鉴权保护的只读资源端点提供视频字节。Web 不接触插件文件路径。 +3. Web 在启动过场初始化时解析当前工作区,获取可用媒体;读取期间保留启动舞台,有限时间内无结果则运行默认动画。 +4. Web 创建仅在本次启动有效的 Blob URL,解码后检查媒体时长不超过五秒;播放结束或卸载组件时释放。切换工作区不会重播动画。 + +启动视频不是启动就绪判断。不得为了等待网络、catalog 或下载而延迟主界面挂载;启动时只使用已安装的本地缓存。 + +## 发布 + +使用现有 `.ling-plugin.zip` 打包脚本、GitHub Release 资产、Ed25519 catalog 签名和安装器。正式发布需提供最终视频、可再分发的授权来源记录和可复现的源 SHA。catalog 工作流已允许附加该插件的 Release 资产;只有资产真实发布并通过校验后,客户端才可从官方插件源看到并安装。当前官方 catalog 未上线时,开发测试可用现有本地 catalog fixture,不将其称为线上可用。 + +本地视觉验收候选为[《犬夜叉》“爆流破”战斗镜头](https://www.youtube.com/watch?v=3NjF568sJSY)的 257–260.5 秒段:犬夜叉正面、挥刀和亮色能量衔接。个人频道页面没有再分发授权说明;本机预览包保存在仓库外的临时目录,不进入源码、官方 Release 或 catalog。正式发布前需确定可发布的犬夜叉素材来源,并按同一镜头节奏重新制作最终短片。 + +## 验收 + +- 安装、启用、重启后播放视频,播放完、点击和 `Escape` 都进入已挂载的主界面。 +- 停用、卸载、缺失或篡改媒体资源时走默认风车动画;失败不阻塞主界面。 +- 减少动态效果时不播放视频。 +- macOS 和 Windows 安装包均能通过签名 catalog 安装插件,重启后离线播放,更新和回滚后播放对应版本。 +- 内置浏览器检查实际播放、跳过、回退和控制台错误,并保留截图。正式犬夜叉素材及官方源发布须单独核对实际 Release 和 catalog。 +- 对照参考的开场与交接截图,检查 Ling 的手指点击、图标反馈、角色画面与真实界面交接四个可见阶段;选定镜头必须能辨识犬夜叉本人。 diff --git a/packages/daemon/src/features/plugins/remote-package.ts b/packages/daemon/src/features/plugins/remote-package.ts index a98aa7042..c3bd570b3 100644 --- a/packages/daemon/src/features/plugins/remote-package.ts +++ b/packages/daemon/src/features/plugins/remote-package.ts @@ -455,7 +455,7 @@ function assertRemoteManifest(plugin: LoadedPluginPackage, artifact: LingPluginA } } -async function verifyPackageIntegrity(packageRoot: string, artifact: { readonly artifactId?: string }): Promise { +export async function verifyPackageIntegrity(packageRoot: string, artifact: { readonly artifactId?: string }): Promise { const root = await lstat(packageRoot); if (!root.isDirectory()) throw new Error("Plugin package must be a regular directory."); const actualFiles = await listPackageFiles(packageRoot); diff --git a/packages/daemon/src/features/plugins/routes.ts b/packages/daemon/src/features/plugins/routes.ts index 0682488cf..b138e7c47 100644 --- a/packages/daemon/src/features/plugins/routes.ts +++ b/packages/daemon/src/features/plugins/routes.ts @@ -1,4 +1,5 @@ import type { IncomingMessage, ServerResponse } from "node:http"; +import { readEnabledStartupAnimationVideo } from "./startup-animation.js"; import type { ManagedPluginDescriptor, ManagedPluginHealthSnapshot, @@ -250,6 +251,41 @@ export async function handleOfficialPluginCatalog( } } +export async function handleStartupAnimationMedia( + request: IncomingMessage, + response: ServerResponse, + config: ResolvedDaemonConfig, + storeRegistry: RunStoreRegistry, +): Promise { + const url = new URL(request.url ?? "/", `http://${request.headers.host ?? `${config.host}:${config.port}`}`); + const cwd = url.searchParams.get("cwd"); + if (!cwd) { + writeJson(response, 400, { error: "bad_request", message: "cwd query parameter is required" }); + return; + } + if (request.method !== "GET") { + writeJson(response, 405, { error: "method_not_allowed", message: "Only GET is supported for startup animation media." }); + return; + } + try { + const video = await readEnabledStartupAnimationVideo(storeRegistry.getStore(cwd)); + if (!video) { + response.writeHead(204, { "Cache-Control": "no-store" }); + response.end(); + return; + } + response.writeHead(200, { + "Content-Type": "video/mp4", + "Content-Length": String(video.byteLength), + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + }); + response.end(video); + } catch (error) { + writeRouteError(response, error); + } +} + export async function handlePluginsImport( request: IncomingMessage, response: ServerResponse, diff --git a/packages/daemon/src/features/plugins/startup-animation.ts b/packages/daemon/src/features/plugins/startup-animation.ts new file mode 100644 index 000000000..49b4e4f22 --- /dev/null +++ b/packages/daemon/src/features/plugins/startup-animation.ts @@ -0,0 +1,63 @@ +import { lstat, readFile } from "node:fs/promises"; +import { join, resolve, sep } from "node:path"; +import type { RunStore } from "@ling-stack/core"; +import { loadPluginPackageFromRoot } from "./manifest.js"; +import { readCurrentPluginPointer, verifyPackageIntegrity } from "./remote-package.js"; + +export const STARTUP_ANIMATION_PLUGIN_ID = "official:inuyasha-startup-animation"; +const contributionPath = "ui/startup-animation.json"; +const videoPath = "assets/startup.mp4"; +const maxVideoBytes = 12 * 1024 * 1024; + +interface StartupAnimationDescriptor { + readonly schemaVersion: 1; + readonly type: "startup-animation"; + readonly video: typeof videoPath; + readonly maxDurationMs: 5000; + readonly muted: true; + readonly fit: "cover"; +} + +/** Reads only the selected, enabled official startup video from a verified cache tree. */ +export async function readEnabledStartupAnimationVideo(store: RunStore): Promise { + const record = store.getManagedPlugin(STARTUP_ANIMATION_PLUGIN_ID); + const installed = store.getManagedPluginPackage(STARTUP_ANIMATION_PLUGIN_ID); + if (!record?.enabled || record.sourceKind !== "official-remote" + || !installed || installed.status !== "installed" || installed.sourceKind !== "official-remote") return undefined; + + const pointer = await readCurrentPluginPointer(store.paths, STARTUP_ANIMATION_PLUGIN_ID); + if (!pointer || pointer.pluginId !== STARTUP_ANIMATION_PLUGIN_ID + || pointer.cacheRef !== installed.cacheRef || pointer.packageHash !== installed.packageHash + || pointer.version !== installed.version || pointer.artifactId !== installed.artifactId) return undefined; + + const expectedPrefix = `official-remote/official-inuyasha-startup-animation/${installed.version}/${installed.platform}/${installed.arch}/`; + if (!installed.cacheRef.startsWith(expectedPrefix) + || !/^[a-f0-9]{12}$/u.test(installed.cacheRef.slice(expectedPrefix.length))) return undefined; + const cacheRoot = resolve(store.paths.pluginCacheDir); + const packageRoot = resolve(cacheRoot, installed.cacheRef); + if (!packageRoot.startsWith(`${cacheRoot}${sep}`)) return undefined; + + await verifyPackageIntegrity(packageRoot, { artifactId: installed.artifactId }); + const plugin = loadPluginPackageFromRoot(packageRoot); + if (!plugin.validation.ok || plugin.manifest.id !== STARTUP_ANIMATION_PLUGIN_ID + || plugin.manifest.version !== installed.version + || plugin.manifest.sourceKind !== "official-remote" || plugin.manifest.trustLevel !== "official" + || plugin.manifest.contributions.length !== 1 + || plugin.manifest.contributions[0]?.kind !== "ui-feature" + || plugin.manifest.contributions[0]?.id !== "startup-animation" + || plugin.manifest.contributions[0]?.path !== contributionPath) return undefined; + + const descriptor = JSON.parse(await readFile(join(packageRoot, contributionPath), "utf8")) as StartupAnimationDescriptor | null; + if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) + || descriptor.schemaVersion !== 1 || descriptor.type !== "startup-animation" + || descriptor.video !== videoPath + || descriptor.maxDurationMs !== 5000 || descriptor.muted !== true || descriptor.fit !== "cover" + || Object.keys(descriptor).some((key) => !["schemaVersion", "type", "video", "maxDurationMs", "muted", "fit"].includes(key))) return undefined; + + const video = join(packageRoot, videoPath); + const info = await lstat(video); + if (!info.isFile() || info.size < 12 || info.size > maxVideoBytes) return undefined; + const bytes = await readFile(video); + if (bytes.toString("ascii", 4, 8) !== "ftyp") return undefined; + return bytes; +} diff --git a/packages/daemon/src/server/router.ts b/packages/daemon/src/server/router.ts index 1a6897564..e0a44c09f 100644 --- a/packages/daemon/src/server/router.ts +++ b/packages/daemon/src/server/router.ts @@ -205,6 +205,7 @@ import { handlePluginItem, handlePluginPackageItem, handleOfficialPluginCatalog, + handleStartupAnimationMedia, handlePluginSourcesCollection, handlePluginsCollection, handlePluginsImport, @@ -1022,6 +1023,11 @@ export async function routeRequest( return; } + if (url.pathname === "/plugins/startup-animation/media") { + await handleStartupAnimationMedia(request, response, config, storeRegistry); + return; + } + if (url.pathname === "/plugins/import/preview" || url.pathname === "/plugins/import/apply") { await handlePluginsImport( request, diff --git a/packages/daemon/test/plugin-startup-animation.test.ts b/packages/daemon/test/plugin-startup-animation.test.ts new file mode 100644 index 000000000..34f541c8a --- /dev/null +++ b/packages/daemon/test/plugin-startup-animation.test.ts @@ -0,0 +1,96 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import type { RunStore } from "@ling-stack/core"; +import { readEnabledStartupAnimationVideo, STARTUP_ANIMATION_PLUGIN_ID } from "../dist/features/plugins/startup-animation.js"; + +const version = "1.0.0"; +const artifactId = `${STARTUP_ANIMATION_PLUGIN_ID}-${version}-darwin-arm64`; +const cacheRef = "official-remote/official-inuyasha-startup-animation/1.0.0/darwin/arm64/123456789abc"; +const packageHash = "123456789abc".repeat(5) + "1234"; +const video = Buffer.from([0, 0, 0, 16, 102, 116, 121, 112, 105, 115, 111, 109, 0, 0, 0, 0]); + +async function fixture(): Promise<{ + readonly store: RunStore; + readonly packageRoot: string; + readonly cleanup: () => Promise; + readonly setEnabled: (enabled: boolean) => void; +}> { + const root = await mkdtemp(join(tmpdir(), "ling-startup-animation-")); + const cacheRoot = join(root, "cache"); + const packageRoot = join(cacheRoot, cacheRef); + await mkdir(join(packageRoot, ".ling-plugin"), { recursive: true }); + await mkdir(join(packageRoot, "ui"), { recursive: true }); + await mkdir(join(packageRoot, "assets"), { recursive: true }); + const manifest = { + id: STARTUP_ANIMATION_PLUGIN_ID, + displayName: "犬夜叉启动动画", + version, + manifestVersion: 2, + lingInterfaceVersion: "2", + sourceKind: "official-remote", + trustLevel: "official", + trustSummary: "Official static animation", + artifactId, + platform: "darwin", + arch: "arm64", + contributions: [{ kind: "ui-feature", id: "startup-animation", path: "ui/startup-animation.json" }], + }; + const descriptor = { + schemaVersion: 1, type: "startup-animation", video: "assets/startup.mp4", + maxDurationMs: 5000, muted: true, fit: "cover", + }; + const files = { + ".ling-plugin/plugin.json": Buffer.from(JSON.stringify(manifest)), + "ui/startup-animation.json": Buffer.from(JSON.stringify(descriptor)), + "assets/startup.mp4": video, + }; + for (const [name, bytes] of Object.entries(files)) await writeFile(join(packageRoot, name), bytes); + await writeFile(join(packageRoot, ".ling-plugin/checksums.json"), JSON.stringify({ + algorithm: "sha256", + files: Object.fromEntries(Object.entries(files).map(([name, bytes]) => [name, createHash("sha256").update(bytes).digest("hex")])), + })); + await writeFile(join(packageRoot, ".ling-plugin/provenance.json"), JSON.stringify({ schemaVersion: 1, artifactId })); + await mkdir(join(cacheRoot, "current"), { recursive: true }); + await writeFile(join(cacheRoot, "current/official-inuyasha-startup-animation.json"), JSON.stringify({ + pluginId: STARTUP_ANIMATION_PLUGIN_ID, version, artifactId, cacheRef, packageHash, + })); + let enabled = true; + const store = { + paths: { pluginCacheDir: cacheRoot }, + getManagedPlugin: () => ({ enabled, sourceKind: "official-remote" }), + getManagedPluginPackage: () => ({ + status: "installed", sourceKind: "official-remote", version, artifactId, + cacheRef, packageHash, platform: "darwin", arch: "arm64", + }), + } as unknown as RunStore; + return { + store, packageRoot, + cleanup: () => rm(root, { recursive: true, force: true }), + setEnabled: (value) => { enabled = value; }, + }; +} + +test("enabled startup animation reads only the verified selected video", async () => { + const item = await fixture(); + try { + assert.deepEqual(await readEnabledStartupAnimationVideo(item.store), video); + item.setEnabled(false); + assert.equal(await readEnabledStartupAnimationVideo(item.store), undefined); + } finally { + await item.cleanup(); + } +}); + +test("startup animation refuses a changed video in the cached package", async () => { + const item = await fixture(); + try { + await writeFile(join(item.packageRoot, "assets/startup.mp4"), Buffer.from("bad video")); + await assert.rejects(readEnabledStartupAnimationVideo(item.store), /checksum verification failed/u); + } finally { + await item.cleanup(); + } +}); diff --git a/plugins/inuyasha-startup-animation/README.md b/plugins/inuyasha-startup-animation/README.md new file mode 100644 index 000000000..ea5335819 --- /dev/null +++ b/plugins/inuyasha-startup-animation/README.md @@ -0,0 +1,7 @@ +# 犬夜叉启动动画插件素材 + +此目录保存插件清单和播放配置。经典镜头方向见[设计文档](../../docs/design/integrations/inuyasha-startup-animation-plugin.md);正式 MP4 尚未取得可再分发的来源。将可发布的 H.264 MP4 放到临时打包目录的 `assets/startup.mp4`,不要把个人频道上传的片段提交到主仓库。 + +本地打包时,复制 `package/` 到临时目录,放入 `assets/startup.mp4`,再运行仓库现有的 `scripts/plugins/package-plugin.mjs --root <临时目录> --output <输出目录> --platform darwin --arch arm64 --version 1.0.0 --minLingVersion 0.1.0`。Windows x64 使用同一素材另打一个 ZIP。正式包另传 `--sourceSha <发布仓库提交 SHA> --repository ling-stack-org/ling-plugin-inuyasha-startup-animation --releaseTag v1.0.0`。打包前用 `ffprobe` 核对 H.264、无音轨、时长不超过五秒及文件大小不超过 12 MiB。 + +正式发布还需 Release 资产、来源 SHA、签名和官方 catalog 快照;本地开发 fixture 不能作为正式资源。 diff --git a/plugins/inuyasha-startup-animation/package/.ling-plugin/plugin.json b/plugins/inuyasha-startup-animation/package/.ling-plugin/plugin.json new file mode 100644 index 000000000..9037dfca6 --- /dev/null +++ b/plugins/inuyasha-startup-animation/package/.ling-plugin/plugin.json @@ -0,0 +1,19 @@ +{ + "id": "official:inuyasha-startup-animation", + "displayName": "犬夜叉启动动画", + "version": "1.0.0", + "manifestVersion": 2, + "lingInterfaceVersion": "2", + "sourceKind": "official-remote", + "trustLevel": "official", + "description": "Ling 启动时播放犬夜叉主题短动画。", + "trustSummary": "静态视频资源,由 Ling 宿主播放,不执行插件脚本。", + "contributions": [ + { + "kind": "ui-feature", + "id": "startup-animation", + "path": "ui/startup-animation.json" + } + ], + "rollbackAllowed": true +} diff --git a/plugins/inuyasha-startup-animation/package/ui/startup-animation.json b/plugins/inuyasha-startup-animation/package/ui/startup-animation.json new file mode 100644 index 000000000..08db80417 --- /dev/null +++ b/plugins/inuyasha-startup-animation/package/ui/startup-animation.json @@ -0,0 +1,8 @@ +{ + "schemaVersion": 1, + "type": "startup-animation", + "video": "assets/startup.mp4", + "maxDurationMs": 5000, + "muted": true, + "fit": "cover" +} diff --git a/scripts/ci/daemon-test-platforms.json b/scripts/ci/daemon-test-platforms.json index 5aed5970b..0810416d1 100644 --- a/scripts/ci/daemon-test-platforms.json +++ b/scripts/ci/daemon-test-platforms.json @@ -345,6 +345,7 @@ "test/plugin-import-normalize.test.mjs", "test/plugin-registry.test.mjs", "test/plugin-remote-distribution.test.mjs", + "test/plugin-startup-animation.test.ts", "test/post-compaction-undo-routes.test.mjs", "test/post-compaction-undo.test.mjs", "test/prepared-isolated.test.mjs", diff --git a/scripts/plugins/collect-official-releases.mjs b/scripts/plugins/collect-official-releases.mjs index 2c48709c9..1d5e898b0 100644 --- a/scripts/plugins/collect-official-releases.mjs +++ b/scripts/plugins/collect-official-releases.mjs @@ -22,7 +22,9 @@ const repositories = new Map([ ["official:chrome-browser", "ling-stack-org/ling-plugin-chrome-browser"], ["official:office-documents", "ling-stack-org/ling-plugin-office-documents"], ["official:cua-driver", "ling-stack-org/ling-plugin-cua-driver"], + ["official:inuyasha-startup-animation", "ling-stack-org/ling-plugin-inuyasha-startup-animation"], ]); +const requiredPluginIds = ["official:chrome-browser", "official:office-documents", "official:cua-driver"]; const targets = [["darwin", "arm64"], ["win32", "x64"]]; const manifestPath = ".ling-plugin/plugin.json"; const checksumsPath = ".ling-plugin/checksums.json"; @@ -30,9 +32,9 @@ const provenancePath = ".ling-plugin/provenance.json"; const sources = JSON.parse(process.env.LING_PLUGIN_RELEASE_SOURCES || "null"); if (sources === null || typeof sources !== "object" || Array.isArray(sources) - || Object.keys(sources).length !== repositories.size - || [...repositories.keys()].some((id) => !Object.hasOwn(sources, id))) { - throw new Error("Release sources must identify each of the three official plugins."); + || requiredPluginIds.some((id) => !Object.hasOwn(sources, id)) + || Object.keys(sources).some((id) => !repositories.has(id))) { + throw new Error("Release sources must identify the required official plugins and may include the startup animation plugin."); } const key = requireOfficialSigningKey(process.env.LING_PLUGIN_ARTIFACT_PRIVATE_KEY, OFFICIAL_PLUGIN_ARTIFACT_PUBLIC_KEY, "LING_PLUGIN_ARTIFACT_PRIVATE_KEY"); @@ -41,6 +43,7 @@ const root = await mkdtemp(join(tmpdir(), "ling-plugin-releases-")); try { const plugins = []; for (const [pluginId, repository] of repositories) { + if (!Object.hasOwn(sources, pluginId)) continue; const pin = sources[pluginId]; if (!pin || !/^v\d+\.\d+\.\d+$/u.test(pin.tag) || !/^[a-f0-9]{40}$/u.test(pin.sourceSha) || !pin.sha256 || targets.some(([platform, arch]) => !/^[a-f0-9]{64}$/u.test(pin.sha256[`${platform}-${arch}`]))) { @@ -141,7 +144,9 @@ async function verifyRuntimeMembers(zip, index, pluginId, platform) { const isWindows = platform === "win32"; const cuaRoot = `runtime/providers/cua-driver/${CUA_DRIVER_PACKAGE_REVISION}`; const cuaLayout = cuaDriverArtifactLayoutFor(cuaDriverArtifactPlatformForRuntime(platform)); - const required = pluginId === "official:chrome-browser" + const required = pluginId === "official:inuyasha-startup-animation" + ? ["ui/startup-animation.json", "assets/startup.mp4"] + : pluginId === "official:chrome-browser" ? ["runtime/ling-for-chrome.zip", `runtime/ling-browser-host${isWindows ? ".exe" : ""}`] : pluginId === "official:office-documents" ? isWindows ? ["runtime/office-driver/win32-x64/ling-office-driver.exe"] : [ @@ -170,6 +175,25 @@ async function verifyRuntimeMembers(zip, index, pluginId, platform) { throw new Error(`Plugin archive contains an unexpected member ${entry.name}.`); } } + if (pluginId === "official:inuyasha-startup-animation") { + const manifest = JSON.parse((await readMember(zip, manifestPath)).toString("utf8")); + const descriptor = JSON.parse((await readMember(zip, "ui/startup-animation.json")).toString("utf8")); + const video = await readMember(zip, "assets/startup.mp4"); + if (manifest.contributions?.length !== 1 + || manifest.contributions[0]?.kind !== "ui-feature" + || manifest.contributions[0]?.id !== "startup-animation" + || manifest.contributions[0]?.path !== "ui/startup-animation.json" + || descriptor.schemaVersion !== 1 || descriptor.type !== "startup-animation" + || descriptor.video !== "assets/startup.mp4" || descriptor.maxDurationMs !== 5000 + || descriptor.muted !== true || descriptor.fit !== "cover" + || Object.keys(descriptor).some((key) => !["schemaVersion", "type", "video", "maxDurationMs", "muted", "fit"].includes(key)) + || video.length < 12 || video.length > 12 * 1024 * 1024 + || video.toString("ascii", 4, 8) !== "ftyp" + || names.length !== 3 + || names.some((path) => ![manifestPath, "ui/startup-animation.json", "assets/startup.mp4"].includes(path))) { + throw new Error("Startup animation package must contain one static UI feature and a bounded MP4."); + } + } if (pluginId === "official:cua-driver") { const lockPath = `${cuaRoot}/provider-lock.json`; const lock = validateCuaDriverProviderLockContract(JSON.parse((await readMember(zip, lockPath)).toString("utf8")), { From 90367263c68cb6be804a47d489e36fd44542c682 Mon Sep 17 00:00:00 2001 From: Ling Test Date: Tue, 1 Dec 2026 15:01:06 +0800 Subject: [PATCH 2/2] test: keep startup animation fixture portable --- packages/daemon/test/plugin-startup-animation.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/daemon/test/plugin-startup-animation.test.ts b/packages/daemon/test/plugin-startup-animation.test.ts index 34f541c8a..bcf8847cb 100644 --- a/packages/daemon/test/plugin-startup-animation.test.ts +++ b/packages/daemon/test/plugin-startup-animation.test.ts @@ -8,8 +8,8 @@ import type { RunStore } from "@ling-stack/core"; import { readEnabledStartupAnimationVideo, STARTUP_ANIMATION_PLUGIN_ID } from "../dist/features/plugins/startup-animation.js"; const version = "1.0.0"; -const artifactId = `${STARTUP_ANIMATION_PLUGIN_ID}-${version}-darwin-arm64`; -const cacheRef = "official-remote/official-inuyasha-startup-animation/1.0.0/darwin/arm64/123456789abc"; +const artifactId = `${STARTUP_ANIMATION_PLUGIN_ID}-${version}-linux-x64`; +const cacheRef = "official-remote/official-inuyasha-startup-animation/1.0.0/linux/x64/123456789abc"; const packageHash = "123456789abc".repeat(5) + "1234"; const video = Buffer.from([0, 0, 0, 16, 102, 116, 121, 112, 105, 115, 111, 109, 0, 0, 0, 0]); @@ -35,8 +35,8 @@ async function fixture(): Promise<{ trustLevel: "official", trustSummary: "Official static animation", artifactId, - platform: "darwin", - arch: "arm64", + platform: "linux", + arch: "x64", contributions: [{ kind: "ui-feature", id: "startup-animation", path: "ui/startup-animation.json" }], }; const descriptor = { @@ -64,7 +64,7 @@ async function fixture(): Promise<{ getManagedPlugin: () => ({ enabled, sourceKind: "official-remote" }), getManagedPluginPackage: () => ({ status: "installed", sourceKind: "official-remote", version, artifactId, - cacheRef, packageHash, platform: "darwin", arch: "arm64", + cacheRef, packageHash, platform: "linux", arch: "x64", }), } as unknown as RunStore; return {