Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(shell): play a user-supplied video as the startup animation

vastsa201eb8735ff4
diff --git a/apps/desktop/electron/main/bootstrap/main-state.ts b/apps/desktop/electron/main/bootstrap/main-state.ts
index 4e602c13d..bcb0fa787 100644
--- a/apps/desktop/electron/main/bootstrap/main-state.ts
+++ b/apps/desktop/electron/main/bootstrap/main-state.ts
@@ -20,6 +20,7 @@ import type { PlanRuntimeState } from "../runtime/plans";
import type { StartupState } from "./startup";
import type { ShutdownState } from "./shutdown";
import type { HostProcess } from "../host-process";
+import type { ResolvedStartupAnimation } from "../startup-animation";
import type { AgentSidecar } from "../agent-sidecar";
import type { AgentHostBridge } from "../agent-host-bridge";
import type { McpControlController, McpControlServer } from "../mcp-control";
@@ -85,6 +86,13 @@ export class MainProcessState {
* preference can only turn it off.
*/
macosWindowTranslucency = true;
+ /**
+ * Boot animation resolved from the data directory for this launch (D679).
+ * Null — the default — keeps the brand splash, which is what every
+ * installation without a `startup/` directory gets.
+ */
+ startupAnimation: ResolvedStartupAnimation | null = null;
+ startupAnimationPlayed = false;
updaterLocale = "en";
pluginPanelTheme: PluginPanelTheme = nativeTheme.shouldUseDarkColors ? "dark" : "light";
@@ -261,6 +269,18 @@ export class MainProcessState {
set macosWindowTranslucency(value) {
self.macosWindowTranslucency = value;
},
+ get startupAnimation() {
+ return self.startupAnimation;
+ },
+ set startupAnimation(value) {
+ self.startupAnimation = value;
+ },
+ get startupAnimationPlayed() {
+ return self.startupAnimationPlayed;
+ },
+ set startupAnimationPlayed(value) {
+ self.startupAnimationPlayed = value;
+ },
get pluginLauncherWindow() {
return self.pluginLauncherWindow;
},
@@ -361,6 +381,12 @@ export class MainProcessState {
set applicationBooted(value) {
self.applicationBooted = value;
},
+ get startupAnimation() {
+ return self.startupAnimation;
+ },
+ set startupAnimation(value) {
+ self.startupAnimation = value;
+ },
get closeBehavior() {
return self.closeBehavior;
},
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index 15950a8a3..25e4c4e2d 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -16,6 +16,11 @@ import { installGenUiProtocol } from "../gen-ui-protocol";
import { installPluginAssetProtocol } from "../plugin-asset-protocol";
import { installPluginRendererProtocol } from "../plugin-renderer-protocol";
import { registerPluginSchemes } from "../plugin-schemes";
+import {
+ resolveStartupAnimation,
+ type ResolvedStartupAnimation,
+} from "../startup-animation";
+import { installStartupAnimationProtocol } from "../startup-animation-protocol";
import { applyNetworkProxyFromAppSettings } from "../network-proxy";
import { readCloseBehavior } from "../window-preferences";
import { createAgentHostBridge, type AgentHostBridge } from "../agent-host-bridge";
@@ -64,6 +69,11 @@ function formatRemoteLogData(data: unknown): string | undefined {
export type StartupState = {
applicationBooted: boolean;
closeBehavior: CloseBehavior;
+ /**
+ * Boot animation this launch resolved, which the `pi-startup:` handler reads
+ * per request. Null — the default and every failure — keeps the brand splash.
+ */
+ startupAnimation: ResolvedStartupAnimation | null;
agentHostBridge: AgentHostBridge | null;
backendRouter: BackendRouter | null;
desktopControl: McpControlController | null;
@@ -203,6 +213,10 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
plugins.resolveRendererSource(pluginId, generation, requestPath),
);
installGenUiProtocol({ getHost });
+ // The animation itself is resolved later, once settings are readable; the
+ // handler is installed here so it is already in place when the first
+ // window's `<video>` asks for the bytes.
+ installStartupAnimationProtocol(() => state.startupAnimation);
// Load the close-behavior preference before the first window exists: the
// close handler reads `closeBehavior` synchronously, and a window created
// while it still held the "ask" default would prompt a user who already
@@ -327,6 +341,10 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
});
}
const host = getHost();
+ // Preferences for the boot animation, when settings were readable. An
+ // unreadable backend leaves this null and discovery falls back to the
+ // defaults, so a launch with no host still plays what the user dropped in.
+ let storedStartupAnimationSettings: { startupAnimation?: unknown } | null = null;
if (host) {
try {
const stored = (await host.call("settings.get")) as {
@@ -336,6 +354,7 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
developerMode?: unknown;
fontScale?: unknown;
macosWindowTranslucency?: unknown;
+ startupAnimation?: unknown;
preventScreenSleep?: unknown;
keepAwakeWhileRunning?: unknown;
} | null;
@@ -344,6 +363,7 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
applyMacosWindowTranslucency(stored);
applyPreventScreenSleep(stored);
applyKeepAwakeWhileRunning(stored);
+ storedStartupAnimationSettings = stored;
await applyNetworkProxyFromAppSettings(stored);
} catch {
// Keep the OS-locale menu until settings can be read again, while
@@ -357,6 +377,26 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
applyPluginLauncherShortcut();
applyToggleWindowShortcut();
}
+ // Resolve the boot animation before the window exists: the descriptor is a
+ // renderer creation argument, so it has to be known by `new BrowserWindow`.
+ // The capture rig compares deterministic frames, so a user's animation in
+ // front of them would break every scene; it is skipped outright. The E2E
+ // harnesses need no guard — each runs against a throwaway
+ // `PI_DESKTOP_DATA_DIR`, which has no `startup/` directory to find.
+ if (process.env.PI_DESKTOP_CAPTURE !== "1") {
+ state.startupAnimation = await resolveStartupAnimation({
+ dataDir,
+ settings: storedStartupAnimationSettings,
+ });
+ if (state.startupAnimation) {
+ logger.app("lifecycle", "info", "startup animation resolved", {
+ data: JSON.stringify({
+ fileName: state.startupAnimation.descriptor.fileName,
+ byteLength: state.startupAnimation.descriptor.byteLength,
+ }),
+ });
+ }
+ }
await ensureWindow();
if (process.env.PI_DESKTOP_MCP_CONTROL === "1") {
try {
diff --git a/apps/desktop/electron/main/bootstrap/window.ts b/apps/desktop/electron/main/bootstrap/window.ts
index 8e04e3efa..82739262a 100644
--- a/apps/desktop/electron/main/bootstrap/window.ts
+++ b/apps/desktop/electron/main/bootstrap/window.ts
@@ -6,10 +6,12 @@ import { getModuleDirectory } from "../module-path";
import {
APP_NAME,
builtinWindowBackground,
+ encodeStartupAnimationArgument,
IPC,
MAC_TRAFFIC_LIGHT_POSITION,
type CloseBehavior,
} from "@pi-desktop/shared";
+import type { ResolvedStartupAnimation } from "../startup-animation";
import type { BrowserHost } from "../browser-host";
import type { HostProcess } from "../host-process";
import type { Logger } from "../logger";
@@ -88,6 +90,20 @@ export type WindowLifecycleState = {
* `settings.macosWindowTranslucency` is.
*/
macosWindowTranslucency: boolean;
+ /**
+ * Boot animation this launch resolved from the data directory, or null to
+ * keep the brand splash. Held for the whole process because the
+ * `pi-startup:` handler reads it per request, not once.
+ */
+ startupAnimation: ResolvedStartupAnimation | null;
+ /**
+ * Whether a window has already been created with the animation.
+ *
+ * The animation is a launch moment, so it plays for the first window of the
+ * process only: reopening from the tray or the Dock after the window was
+ * closed replays nothing.
+ */
+ startupAnimationPlayed: boolean;
pluginLauncherWindow: BrowserWindow | null;
host: HostProcess | null;
};
@@ -185,6 +201,13 @@ export async function createWindow({
const initialWindowBackground = builtinWindowBackground(
nativeTheme.shouldUseDarkColors ? "dark" : "light",
);
+ // Only the first window of the process plays the animation (D679). Claiming
+ // it here, before `new BrowserWindow`, is what keeps a reopened window — and
+ // a second window racing this one — on the brand splash instead.
+ const startupAnimation = windowState.startupAnimationPlayed
+ ? null
+ : windowState.startupAnimation;
+ if (startupAnimation) windowState.startupAnimationPlayed = true;
const windows11NativeCorners = usesWindows11NativeCorners(
process.platform,
process.getSystemVersion(),
@@ -241,7 +264,15 @@ export async function createWindow({
// Preload runs in a sandbox and cannot import Electron's main-only `app`
// module. Pass the display locale at process creation so it remains
// available synchronously before the renderer's first paint.
- additionalArguments: [`--pi-desktop-locale=${app.getLocale()}`],
+ additionalArguments: [
+ `--pi-desktop-locale=${app.getLocale()}`,
+ // The boot animation has to be on screen in the renderer's first
+ // frame, so the descriptor travels as a creation argument like the
+ // locale does; an IPC round-trip would land after the first paint.
+ ...(startupAnimation
+ ? [encodeStartupAnimationArgument(startupAnimation.descriptor)]
+ : []),
+ ],
},
});
const window = windowState.mainWindow;
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index a382f0a41..7cf1f16ad 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -10,6 +10,7 @@ import { readNpmPath, writeNpmPath } from "../npm-preferences";
import { registerAgentIpc } from "./agent-ipc";
import { registerAppIpc } from "./app-ipc";
import { registerDiagnosticsIpc } from "./diagnostics-ipc";
+import { registerStartupAnimationIpc } from "./startup-animation-ipc";
import { registerMarketIpc } from "./market-ipc";
import { registerMcpIpc } from "./mcp-ipc";
import type { McpOAuthManager } from "../mcp-oauth";
@@ -547,6 +548,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getMainWindow,
});
+ registerStartupAnimationIpc({ registrar, dataDir, stripWinLongPrefix });
+
return async (channel: string, args: readonly unknown[] = []) => {
const handler = ipcHandlers.get(channel);
diff --git a/apps/desktop/electron/main/ipc/startup-animation-ipc.ts b/apps/desktop/electron/main/ipc/startup-animation-ipc.ts
new file mode 100644
index 000000000..5618a9ca4
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/startup-animation-ipc.ts
@@ -0,0 +1,55 @@
+import { shell } from "electron";
+import { mkdir } from "node:fs/promises";
+import { IPC } from "@pi-desktop/shared";
+import type { StartupAnimationStatus } from "@pi-desktop/shared";
+import {
+ resolveStartupAnimation,
+ startupAnimationDirectory,
+} from "../startup-animation";
+import type { IpcRegistrar } from "./types";
+
+export type StartupAnimationIpcDependencies = {
+ registrar: IpcRegistrar;
+ dataDir: string;
+ stripWinLongPrefix: (path: string) => string;
+};
+
+/**
+ * Channels behind the Appearance row for the boot animation (D679).
+ *
+ * The status is re-scanned per call rather than reported from the launch's own
+ * resolution, because the row's job is to say what the *next* launch will play:
+ * a user who just dropped a file in has not restarted yet, and a row that
+ * reported the running launch would call their new file missing.
+ *
+ * Neither channel returns a filesystem path. "Open folder" hands the directory
+ * to the OS from the main process, so the renderer learns the file's name at
+ * most — never where the data directory is.
+ */
+export function registerStartupAnimationIpc({
+ registrar,
+ dataDir,
+ stripWinLongPrefix,
+}: StartupAnimationIpcDependencies): void {
+ registrar.handle(IPC.invoke.startupAnimationStatus, async () => {
+ // Discovery only: the enabled preference belongs to the toggle beside this
+ // row, and a disabled animation must still report the file it would play.
+ const resolved = await resolveStartupAnimation({ dataDir, settings: null });
+ const status: StartupAnimationStatus = {
+ directoryName: startupAnimationDirectory(dataDir).split(/[/\\]/).pop() ?? "",
+ fileName: resolved?.descriptor.fileName ?? null,
+ byteLength: resolved?.descriptor.byteLength ?? null,
+ };
+ return status;
+ });
+
+ registrar.handle(IPC.invoke.startupAnimationOpenFolder, async () => {
+ const directory = startupAnimationDirectory(dataDir);
+ // Created on demand so the action always lands somewhere: an installation
+ // that never used the feature has no such directory, and sending the user
+ // to a missing path is worse than making it.
+ await mkdir(directory, { recursive: true });
+ await shell.openPath(stripWinLongPrefix(directory));
+ return { ok: true };
+ });
+}
diff --git a/apps/desktop/electron/main/plugin-schemes.ts b/apps/desktop/electron/main/plugin-schemes.ts
index a4ebcf242..1f11c66dd 100644
--- a/apps/desktop/electron/main/plugin-schemes.ts
+++ b/apps/desktop/electron/main/plugin-schemes.ts
@@ -2,10 +2,11 @@ import { protocol } from "electron";
import { GEN_UI_SCHEME_PRIVILEGES } from "./gen-ui-protocol";
import { PLUGIN_ASSET_SCHEME_PRIVILEGES } from "./plugin-asset-protocol";
import { PLUGIN_RENDERER_SCHEME_PRIVILEGES } from "./plugin-renderer-protocol";
+import { STARTUP_ANIMATION_SCHEME_PRIVILEGES } from "./startup-animation-protocol";
/**
* Reserve every host-owned scheme before the app is ready: the plugin
- * schemes and the GenUI visualization scheme.
+ * schemes, the GenUI visualization scheme, and the startup animation.
*
* Electron accepts `registerSchemesAsPrivileged` once per process: a second
* call replaces the secure/fetch/CORS scheme lists that child processes
@@ -18,5 +19,6 @@ export function registerPluginSchemes(): void {
PLUGIN_ASSET_SCHEME_PRIVILEGES,
PLUGIN_RENDERER_SCHEME_PRIVILEGES,
GEN_UI_SCHEME_PRIVILEGES,
+ STARTUP_ANIMATION_SCHEME_PRIVILEGES,
]);
}
diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.ts
index 065ba1a00..4c48580ec 100644
--- a/apps/desktop/electron/main/runtime/provider-catalog.ts
+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts
@@ -205,6 +205,7 @@ export function createProviderCatalogRuntime({
lastNotifiedUpdateVersion?: unknown;
networkProxy?: unknown;
macosWindowTranslucency?: unknown;
+ startupAnimation?: unknown;
transcriptDisplayMode?: unknown;
radialMenu?: unknown;
};
@@ -266,6 +267,23 @@ export function createProviderCatalogRuntime({
errorCode: ErrorCodes.INVALID_PARAMS,
});
}
+ if (Object.prototype.hasOwnProperty.call(value, "startupAnimation")) {
+ const startupAnimation = value.startupAnimation;
+ if (
+ !startupAnimation ||
+ typeof startupAnimation !== "object" ||
+ Array.isArray(startupAnimation) ||
+ Object.entries(startupAnimation).some(
+ ([key, field]) =>
+ (key !== "enabled" && key !== "skipWhenReady") ||
+ typeof field !== "boolean",
+ )
+ ) {
+ throw Object.assign(new Error("startupAnimation is invalid"), {
+ errorCode: ErrorCodes.INVALID_PARAMS,
+ });
+ }
+ }
const radialMenuProblem = radialMenuWriteError(value.radialMenu);
if (radialMenuProblem) {
throw Object.assign(new Error(radialMenuProblem), {
diff --git a/apps/desktop/electron/main/startup-animation-protocol.ts b/apps/desktop/electron/main/startup-animation-protocol.ts
new file mode 100644
index 000000000..6679e1701
--- /dev/null
+++ b/apps/desktop/electron/main/startup-animation-protocol.ts
@@ -0,0 +1,102 @@
+import { createReadStream } from "node:fs";
+import { stat } from "node:fs/promises";
+import { Readable } from "node:stream";
+import { protocol, type CustomScheme } from "electron";
+import {
+ parseByteRange,
+ STARTUP_ANIMATION_MAX_BYTES,
+ STARTUP_ANIMATION_MIME_TYPES,
+ STARTUP_ANIMATION_SCHEME,
+} from "@pi-desktop/shared";
+import type { ResolvedStartupAnimation } from "./startup-animation";
+
+/**
+ * Serve the user's boot animation over a host-owned scheme (ADR 0338).
+ *
+ * The renderer is sandboxed and its CSP admits no `file:` source, so the video
+ * cannot be referenced by path — and should not be: a path in the page would
+ * disclose the data directory to anything that later runs there. This handler
+ * is the narrowest shape that solves it. There is exactly one URL, it carries
+ * no path, host, or query the caller controls, and the bytes come from the
+ * single file the main process resolved at boot. Nothing the renderer sends can
+ * select a different file, so there is no traversal surface to confine.
+ *
+ * Media playback is range-driven, so the handler answers `Range` as well; a
+ * `<video>` that cannot get a 206 falls back to buffering the whole response.
+ */
+
+/**
+ * Privileges reserved before the app is ready, by `registerPluginSchemes`.
+ *
+ * `stream` is the one that matters for media: without it the response is
+ * buffered whole before the first frame decodes, which is the opposite of what
+ * a boot surface needs. `standard` and `secure` keep the URL parseable and
+ * free of mixed-content treatment; no CORS privileges, because a `<video>`
+ * `src` is a no-cors fetch and nothing else may read these bytes.
+ */
+export const STARTUP_ANIMATION_SCHEME_PRIVILEGES: CustomScheme = {
+ scheme: STARTUP_ANIMATION_SCHEME,
+ privileges: {
+ standard: true,
+ secure: true,
+ stream: true,
+ },
+};
+
+function notFound(): Response {
+ return new Response("not found", {
+ status: 404,
+ headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
+ });
+}
+
+/**
+ * Install the request handler. Call once, after the app is ready.
+ *
+ * The resolution is read per request rather than captured, so a window created
+ * later in the process life answers from whatever the current launch resolved,
+ * and a cleared resolution stops serving immediately.
+ */
+export function installStartupAnimationProtocol(
+ current: () => ResolvedStartupAnimation | null,
+): void {
+ protocol.handle(STARTUP_ANIMATION_SCHEME, async (request) => {
+ const resolved = current();
+ if (!resolved) return notFound();
+ const mime = STARTUP_ANIMATION_MIME_TYPES[resolved.descriptor.extension];
+ if (!mime) return notFound();
+ // Re-stat instead of trusting the boot-time size: the user may have
+ // replaced the file while the app was running, and the range math has to
+ // match the bytes this read will actually see.
+ let size: number;
+ try {
+ const stats = await stat(resolved.filePath);
+ if (!stats.isFile() || stats.size <= 0) return notFound();
+ size = stats.size;
+ } catch {
+ return notFound();
+ }
+ if (size > STARTUP_ANIMATION_MAX_BYTES) return notFound();
+ const range = parseByteRange(request.headers.get("range"), size);
+ const start = range?.start ?? 0;
+ const end = range?.end ?? size - 1;
+ const stream = Readable.toWeb(
+ createReadStream(resolved.filePath, { start, end }),
+ ) as ReadableStream<Uint8Array>;
+ return new Response(stream, {
+ status: range ? 206 : 200,
+ headers: {
+ "content-type": mime,
+ "content-length": String(end - start + 1),
+ "accept-ranges": "bytes",
+ ...(range
+ ? { "content-range": `bytes ${start}-${end}/${size}` }
+ : {}),
+ // The user can swap the file between launches, so a cached copy would
+ // outlive the animation it came from.
+ "cache-control": "no-store",
+ "x-content-type-options": "nosniff",
+ },
+ });
+ });
+}
diff --git a/apps/desktop/electron/main/startup-animation.ts b/apps/desktop/electron/main/startup-animation.ts
new file mode 100644
index 000000000..67ce8d7a2
--- /dev/null
+++ b/apps/desktop/electron/main/startup-animation.ts
@@ -0,0 +1,138 @@
+import { readdir, realpath, stat } from "node:fs/promises";
+import { join, sep } from "node:path";
+import {
+ chooseStartupAnimation,
+ STARTUP_ANIMATION_DIR_NAME,
+ STARTUP_ANIMATION_MAX_BYTES,
+ startupAnimationExtensionOf,
+ type StartupAnimationCandidate,
+ type StartupAnimationDescriptor,
+} from "@pi-desktop/shared";
+
+/**
+ * Discover the user's boot animation in `<dataDir>/startup/` (D679 / ADR 0338).
+ *
+ * The directory is the whole configuration surface: a user drops one video in
+ * and the next launch plays it. Nothing is created here — an installation that
+ * never uses the feature keeps a data directory without the folder, and the
+ * boot surface stays the brand splash.
+ *
+ * The resolved file path never leaves the main process. The renderer is handed
+ * a descriptor and plays the single-file `pi-startup:` URL, so the page never
+ * learns where the user's data directory is.
+ */
+
+/** A playable animation and the file behind it, which only main may know. */
+export type ResolvedStartupAnimation = {
+ descriptor: StartupAnimationDescriptor;
+ /** Realpath of the chosen file, confined to the startup directory. */
+ filePath: string;
+};
+
+export type StartupAnimationInput = {
+ /** Installation data directory, as `desktopDataDir()` resolved it. */
+ dataDir: string;
+ /** Stored preferences; absent or unreadable settings use the defaults. */
+ settings?: { startupAnimation?: unknown } | null;
+};
+
+function readPreferences(settings: StartupAnimationInput["settings"]): {
+ enabled: boolean;
+ skipWhenReady: boolean;
+} {
+ const value = settings?.startupAnimation;
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return { enabled: true, skipWhenReady: false };
+ }
+ const preferences = value as { enabled?: unknown; skipWhenReady?: unknown };
+ return {
+ // Absent means on: the feature is dormant without a file, so defaulting to
+ // off would make dropping one in look broken.
+ enabled: preferences.enabled !== false,
+ skipWhenReady: preferences.skipWhenReady === true,
+ };
+}
+
+/**
+ * Entries of the startup directory that are confined to it.
+ *
+ * Confinement is by realpath rather than by name: a symlink in the directory
+ * resolves wherever it points, and following one would let an animation serve
+ * an arbitrary file over the host-owned scheme. Entries that escape, that are
+ * not regular files, or that cannot be stat'd are dropped silently — a boot
+ * surface is the wrong place to report a filesystem detail.
+ */
+async function confinedCandidates(
+ directory: string,
+): Promise<{ candidates: StartupAnimationCandidate[]; paths: Map<string, string> }> {
+ const root = await realpath(directory);
+ const prefix = root.endsWith(sep) ? root : `${root}${sep}`;
+ const names = await readdir(root);
+ const candidates: StartupAnimationCandidate[] = [];
+ const paths = new Map<string, string>();
+ for (const name of names) {
+ // Cheap rejection before two syscalls per entry; the chooser re-checks.
+ if (name.startsWith(".") || !startupAnimationExtensionOf(name)) continue;
+ let resolved: string;
+ try {
+ resolved = await realpath(join(root, name));
+ } catch {
+ continue;
+ }
+ if (!resolved.startsWith(prefix)) continue;
+ let size: number;
+ try {
+ const stats = await stat(resolved);
+ if (!stats.isFile()) continue;
+ size = stats.size;
+ } catch {
+ continue;
+ }
+ candidates.push({ fileName: name, byteLength: size });
+ paths.set(name, resolved);
+ }
+ return { candidates, paths };
+}
+
+/**
+ * The animation this launch should play, or null to keep the brand splash.
+ *
+ * Null covers every ordinary case as well as every failure: the setting is
+ * off, the directory does not exist, it holds nothing playable, or the
+ * filesystem refused the read. The caller treats them identically, which is
+ * what keeps a broken animation from being a broken launch.
+ */
+export async function resolveStartupAnimation(
+ input: StartupAnimationInput,
+): Promise<ResolvedStartupAnimation | null> {
+ const preferences = readPreferences(input.settings);
+ if (!preferences.enabled) return null;
+ const directory = join(input.dataDir, STARTUP_ANIMATION_DIR_NAME);
+ let found: Awaited<ReturnType<typeof confinedCandidates>>;
+ try {
+ found = await confinedCandidates(directory);
+ } catch {
+ return null;
+ }
+ const chosen = chooseStartupAnimation(
+ found.candidates,
+ STARTUP_ANIMATION_MAX_BYTES,
+ );
+ if (!chosen) return null;
+ const filePath = found.paths.get(chosen.fileName);
+ if (!filePath) return null;
+ return {
+ descriptor: {
+ fileName: chosen.fileName,
+ extension: chosen.extension,
+ byteLength: chosen.byteLength,
+ skipWhenReady: preferences.skipWhenReady,
+ },
+ filePath,
+ };
+}
+
+/** Absolute path of the directory a user drops the animation into. */
+export function startupAnimationDirectory(dataDir: string): string {
+ return join(dataDir, STARTUP_ANIMATION_DIR_NAME);
+}
diff --git a/apps/desktop/electron/preload/index.ts b/apps/desktop/electron/preload/index.ts
index 591b5aafe..e04c1e1c3 100644
--- a/apps/desktop/electron/preload/index.ts
+++ b/apps/desktop/electron/preload/index.ts
@@ -1,5 +1,8 @@
import { contextBridge, ipcRenderer, webUtils } from "electron";
import { IPC, IPC_WHITELIST } from "@pi-desktop/shared/protocol";
+// Narrow subpath, not the package barrel: the preload is a single bundled file
+// for a sandboxed renderer, so it must not pull the whole shared surface in.
+import { decodeStartupAnimationArgument } from "@pi-desktop/shared/startup-animation";
const LOCALE_ARGUMENT_PREFIX = "--pi-desktop-locale=";
@@ -46,6 +49,11 @@ const api = {
// creation argument. This keeps the locale available before first paint
// without importing Electron's main-only `app` module in the sandbox.
locale: readOsLocale(),
+ // The boot animation must be on screen in the renderer's first frame, so it
+ // arrives the same way the locale does: resolved in main, passed as a
+ // creation argument, read synchronously here (D679). Null — no file, the
+ // setting off, a later window of the same process — means the brand splash.
+ startupAnimation: decodeStartupAnimationArgument(process.argv),
/** Resolve a real dropped File without exposing Node or Electron to the page. */
getDroppedFilePath: (file: File): string | null => {
try {
diff --git a/apps/desktop/index.html b/apps/desktop/index.html
index 2160d7ab5..93bd3bbe4 100644
--- a/apps/desktop/index.html
+++ b/apps/desktop/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
- content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset:; media-src 'self' data: blob: https:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:; frame-src pi-genui:;"
+ content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: plugin-renderer:; style-src 'self' 'unsafe-inline' plugin-renderer:; img-src 'self' data: blob: https: plugin-asset: plugin-renderer:; font-src 'self' data: plugin-asset:; media-src 'self' data: blob: https: pi-startup:; connect-src 'self' ws://localhost:* http://localhost:* ws://127.0.0.1:* http://127.0.0.1:* plugin-renderer:; frame-src pi-genui:;"
/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PI-Desktop</title>
diff --git a/apps/desktop/src/components/StartupAnimation.tsx b/apps/desktop/src/components/StartupAnimation.tsx
new file mode 100644
index 000000000..012d6c92a
--- /dev/null
+++ b/apps/desktop/src/components/StartupAnimation.tsx
@@ -0,0 +1,67 @@
+import { useTranslation } from "react-i18next";
+import { STARTUP_ANIMATION_URL } from "@pi-desktop/shared";
+import type { StartupAnimationEndReason } from "../lib/startup-animation";
+import { cx } from "./ui";
+
+/**
+ * Full-window boot surface playing the user's own animation (D679 / ADR 0338).
+ *
+ * The layer is opaque black for its whole life, including the reveal: the video
+ * sits on it, and when the video is gone the same black is the mask the shell
+ * fades in from. One element rather than two means there is no seam between the
+ * last frame and the mask for a frame of shell to show through.
+ *
+ * The file is referenced only as the host-owned `pi-startup:` URL — the page
+ * never learns a path — and the element is inert: no controls, no picture in
+ * picture, not focusable, and muted, because an unmuted autoplay is both
+ * blocked by Chromium and a poor thing to do to someone opening an app.
+ */
+export function StartupAnimation({
+ playing,
+ revealing,
+ holdingLong,
+ onFirstFrame,
+ onAnimationEnd,
+}: {
+ playing: boolean;
+ revealing: boolean;
+ holdingLong: boolean;
+ onFirstFrame: () => void;
+ onAnimationEnd: (reason: StartupAnimationEndReason) => void;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <div
+ className={cx("startup-animation", revealing && "is-revealing")}
+ role="status"
+ aria-live="polite"
+ aria-busy={!revealing}
+ data-testid="startup-animation"
+ >
+ {playing ? (
+ <video
+ className="startup-animation-video"
+ src={STARTUP_ANIMATION_URL}
+ autoPlay
+ muted
+ playsInline
+ preload="auto"
+ controls={false}
+ disablePictureInPicture
+ tabIndex={-1}
+ aria-hidden
+ onLoadedData={onFirstFrame}
+ onEnded={() => onAnimationEnd("ended")}
+ onError={() => onAnimationEnd("error")}
+ />
+ ) : null}
+ {holdingLong ? (
+ <div className="startup-animation-track" aria-hidden>
+ <span className="startup-animation-bar" />
+ </div>
+ ) : null}
+ <span className="sr-only">{t("app.starting")}</span>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/settings/StartupAnimationRows.tsx b/apps/desktop/src/components/settings/StartupAnimationRows.tsx
new file mode 100644
index 000000000..7456a79bb
--- /dev/null
+++ b/apps/desktop/src/components/settings/StartupAnimationRows.tsx
@@ -0,0 +1,127 @@
+/**
+ * Appearance rows for the user-supplied boot animation (D679 / ADR 0338).
+ *
+ * The animation is a file, not a value, so the first job of these rows is to
+ * make the folder findable: the status line names what the next launch will
+ * play — or says nothing is there — and the action opens the folder, creating
+ * it on the way. Without that, a feature configured by dropping a file into a
+ * hidden directory is undiscoverable.
+ *
+ * Neither row can change the running window. The descriptor is a window
+ * creation argument, so like the translucency switch beside it, a change lands
+ * on the next launch; the copy says so rather than implying a live preview.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { AppSettings, StartupAnimationStatus } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { SettingsRow } from "../../features/settings/primitives";
+import { SettingsToggle } from "../ui";
+
+export function StartupAnimationRows({
+ settings,
+ saveSettings,
+}: {
+ settings: AppSettings;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ // Absent means on: the feature is dormant without a file, so a default of
+ // off would make dropping one in look broken.
+ const enabled = settings.startupAnimation?.enabled !== false;
+ const skipWhenReady = settings.startupAnimation?.skipWhenReady === true;
+ // `null` until the scan answers; an unreadable folder keeps the status line
+ // empty rather than claiming no file is there.
+ const [status, setStatus] = useState<StartupAnimationStatus | null>(null);
+
+ // Both the mount scan and the post-open rescan resolve after an await, so
+ // neither may publish into an unmounted row.
+ const mountedRef = useRef(true);
+ const refresh = useCallback(() => {
+ void api
+ .startupAnimationStatus()
+ .then((next) => {
+ if (mountedRef.current) setStatus(next);
+ })
+ .catch(() => undefined);
+ }, []);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ refresh();
+ return () => {
+ mountedRef.current = false;
+ };
+ }, [refresh]);
+
+ const openFolder = useCallback(() => {
+ void api
+ .openStartupAnimationFolder()
+ // A user opens the folder to put a file in it, so re-scan when they come
+ // back instead of leaving a status line that predates the drop.
+ .then(() => {
+ refresh();
+ })
+ .catch(() => undefined);
+ }, [refresh]);
+
+ return (
+ <>
+ <SettingsRow
+ title={t("settings.startupAnimation")}
+ description={t("settings.startupAnimationDesc")}
+ detail={
+ <span className="startup-animation-status">
+ <span className="startup-animation-status-file">
+ {status
+ ? (status.fileName ?? t("settings.startupAnimationNone"))
+ : ""}
+ </span>
+ <button
+ type="button"
+ className="settings-inline-action"
+ onClick={openFolder}
+ >
+ {t("settings.startupAnimationFolder")}
+ </button>
+ </span>
+ }
+ >
+ <SettingsToggle
+ checked={enabled}
+ label={t("settings.startupAnimation")}
+ onChange={() =>
+ void saveSettings({
+ startupAnimation: { ...settings.startupAnimation, enabled: !enabled },
+ })
+ }
+ />
+ </SettingsRow>
+ {/*
+ Gated by the master switch, and kept out of the tree entirely while the
+ animation is off: it describes a moment that cannot happen then. The
+ stored value survives, so turning the animation back on restores the
+ previous choice instead of resetting it.
+ */}
+ {enabled ? (
+ <SettingsRow
+ title={t("settings.startupAnimationSkipWhenReady")}
+ description={t("settings.startupAnimationSkipWhenReadyDesc")}
+ >
+ <SettingsToggle
+ checked={skipWhenReady}
+ label={t("settings.startupAnimationSkipWhenReady")}
+ onChange={() =>
+ void saveSettings({
+ startupAnimation: {
+ ...settings.startupAnimation,
+ skipWhenReady: !skipWhenReady,
+ },
+ })
+ }
+ />
+ </SettingsRow>
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 4be556a57..236fc447d 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -13,6 +13,7 @@ import {
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { installRendererApi } from "../../capture/renderer-api";
+import { StartupAnimation } from "../../components/StartupAnimation";
import { StartupSplash } from "../../components/StartupSplash";
import { api } from "../../lib/api";
import { composerSuggestion } from "../chat/composer/plugins/suggestion-bridge";
@@ -37,6 +38,7 @@ import {
} from "../../lib/work-panel-tabs";
import { useAppStore } from "../../stores/app-store";
import { useSidebarTransition } from "./useSidebarTransition";
+import { useStartupAnimation } from "./useStartupAnimation";
import { useStartupWatchdog } from "./useStartupWatchdog";
import { useTraySessions } from "./useTraySessions";
import { runLiveVoiceShortcut } from "../voice/live/live-voice-shortcuts";
@@ -1019,14 +1021,35 @@ export function useAppShellRuntime() {
retry: retryStartup,
retrying: startupRetrying,
} = useStartupWatchdog(ready);
- const showSplash = splashPhase !== "done";
- // The splash and the recovery surface answer the same question ("nothing to
- // show yet"), and on macOS the shell hides every child except the splash while
- // it animates. Exactly one of them is mounted, so neither has to fight the
- // other's layering.
- const splash = showSplash && startupPhase === "starting" ? (
- <StartupSplash exiting={splashPhase === "exiting"} />
- ) : null;
+ const startupAnimation = useStartupAnimation(ready);
+ // Whether a boot surface still stands between the user and the shell. The
+ // reveal is deliberately outside it: the mask is already transparent to input
+ // by then, so the window controls and the shell chrome come back for the
+ // whole fade rather than snapping in at the end of it.
+ const showSplash = startupAnimation.active
+ ? startupAnimation.phase !== "reveal"
+ : splashPhase !== "done";
+ // Three surfaces answer the same question ("nothing to show yet") and exactly
+ // one is ever mounted, so none has to fight the others' layering. The
+ // recovery surface outranks both boot surfaces — a stalled launch must not be
+ // left behind an opaque animation — and a user's animation outranks the brand
+ // splash, which is what it was dropped in to replace.
+ const splash =
+ startupPhase !== "starting"
+ ? null
+ : startupAnimation.active
+ ? (
+ <StartupAnimation
+ playing={startupAnimation.playing}
+ revealing={startupAnimation.phase === "reveal"}
+ holdingLong={startupAnimation.holdingLong}
+ onFirstFrame={startupAnimation.onFirstFrame}
+ onAnimationEnd={startupAnimation.onAnimationEnd}
+ />
+ )
+ : splashPhase !== "done"
+ ? <StartupSplash exiting={splashPhase === "exiting"} />
+ : null;
const shortcutPlatform = platform as ShortcutPlatform;
const toggleSidebarShortcut = KEYBOARD_SHORTCUTS.find(
diff --git a/apps/desktop/src/features/app/useStartupAnimation.ts b/apps/desktop/src/features/app/useStartupAnimation.ts
new file mode 100644
index 000000000..bba54471b
--- /dev/null
+++ b/apps/desktop/src/features/app/useStartupAnimation.ts
@@ -0,0 +1,214 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ STARTUP_ANIMATION_FIRST_FRAME_TIMEOUT_MS,
+ STARTUP_ANIMATION_HOLD_HINT_MS,
+ STARTUP_ANIMATION_MAX_DURATION_MS,
+} from "@pi-desktop/shared";
+import {
+ INITIAL_STARTUP_ANIMATION_STATE,
+ REVEAL_MS,
+ reduceStartupAnimation,
+ shouldPlayStartupAnimation,
+ STARTUP_ANIMATION_PLAYED_KEY,
+ type StartupAnimationEndReason,
+ type StartupAnimationPhase,
+} from "../../lib/startup-animation";
+
+/**
+ * Drive the user's boot animation (D679 / ADR 0338).
+ *
+ * The decision to play is made once, during the first render, because the
+ * descriptor is already on `window.piDesktop` before the first paint and the
+ * surface must be in that paint. Everything after that is bounded: the first
+ * frame, the whole playback, and the reveal each have a timer, so no state the
+ * video element can get into leaves the window behind an opaque mask.
+ */
+
+export type StartupAnimationState = {
+ /** The animation owns the boot surface; the brand splash stays unmounted. */
+ active: boolean;
+ phase: StartupAnimationPhase;
+ /** True while the `<video>` should be mounted and playing. */
+ playing: boolean;
+ /** The hold has outlasted its quiet bound; show the progress affordance. */
+ holdingLong: boolean;
+ /** Attach to the element: the first decoded frame cancels its own bound. */
+ onFirstFrame: () => void;
+ /** Attach to `ended`; also the error and skip path. */
+ onAnimationEnd: (reason: StartupAnimationEndReason) => void;
+};
+
+function prefersReducedMotion(): boolean {
+ return (
+ typeof window !== "undefined" &&
+ typeof window.matchMedia === "function" &&
+ window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ );
+}
+
+/**
+ * Whether this window already spent its animation.
+ *
+ * `sessionStorage` rather than a module variable: a renderer reload re-runs the
+ * module but keeps the storage, which is exactly the boundary wanted here — one
+ * animation per window, not one per script evaluation.
+ */
+function readPlayed(): boolean {
+ try {
+ return window.sessionStorage.getItem(STARTUP_ANIMATION_PLAYED_KEY) === "1";
+ } catch {
+ // A renderer without storage access is still allowed to play; the main
+ // process has already limited the descriptor to the first window.
+ return false;
+ }
+}
+
+function markPlayed(): void {
+ try {
+ window.sessionStorage.setItem(STARTUP_ANIMATION_PLAYED_KEY, "1");
+ } catch {
+ // Non-fatal: the worst case is a replay after a manual reload.
+ }
+}
+
+/**
+ * This page load's verdict, decided once.
+ *
+ * The decision has a side effect — it marks the animation as spent — so it
+ * cannot be re-evaluated. `StrictMode` invokes a `useState` initializer twice
+ * in development and keeps the second result, which without this memo would
+ * read back the mark the first invocation just wrote and answer "already
+ * played": the animation would never appear in a development build.
+ *
+ * Module scope is the right lifetime. It is reset by a reload, and a reload is
+ * exactly what the `sessionStorage` mark is there to catch.
+ */
+let pageLoadVerdict: boolean | null = null;
+
+function decidePlayback(
+ descriptor: ReturnType<typeof readDescriptor>,
+): boolean {
+ if (pageLoadVerdict !== null) return pageLoadVerdict;
+ const surface = new URLSearchParams(window.location.search).get("surface");
+ const play = shouldPlayStartupAnimation({
+ descriptor,
+ surface,
+ reduceMotion: prefersReducedMotion(),
+ played: readPlayed(),
+ });
+ if (play) markPlayed();
+ pageLoadVerdict = play;
+ return play;
+}
+
+function readDescriptor() {
+ if (typeof window === "undefined") return null;
+ return window.piDesktop?.startupAnimation ?? null;
+}
+
+export function useStartupAnimation(ready: boolean): StartupAnimationState {
+ const descriptor = useMemo(readDescriptor, []);
+ const [active] = useState(() => decidePlayback(descriptor));
+ const skipWhenReady = descriptor?.skipWhenReady === true;
+ const [state, setState] = useState(INITIAL_STARTUP_ANIMATION_STATE);
+ const [holdingLong, setHoldingLong] = useState(false);
+ // `ready` is read inside the reducer rules, which the event callbacks close
+ // over; a ref keeps those callbacks stable without going stale.
+ const readyRef = useRef(ready);
+ readyRef.current = ready;
+
+ const dispatch = useCallback(
+ (event: Parameters<typeof reduceStartupAnimation>[1]) => {
+ setState((current) =>
+ reduceStartupAnimation(current, event, {
+ skipWhenReady,
+ ready: readyRef.current,
+ }),
+ );
+ },
+ [skipWhenReady],
+ );
+
+ const onAnimationEnd = useCallback(
+ (reason: StartupAnimationEndReason) => {
+ dispatch({ kind: "animation-ended", reason });
+ },
+ [dispatch],
+ );
+
+ // The first decoded frame retires the only bound that can fire before the
+ // animation is visible at all.
+ const firstFrameRef = useRef(false);
+ const onFirstFrame = useCallback(() => {
+ firstFrameRef.current = true;
+ }, []);
+
+ // A file that is readable but not playable leaves `<video>` silent: no
+ // `ended`, no `error`. Without this bound the window sits on an empty black
+ // surface until the watchdog's 180s recovery bound, which is three minutes of
+ // nothing for what is really a bad export.
+ useEffect(() => {
+ if (!active || state.phase !== "video") return;
+ const firstFrame = window.setTimeout(() => {
+ if (!firstFrameRef.current) onAnimationEnd("no-first-frame");
+ }, STARTUP_ANIMATION_FIRST_FRAME_TIMEOUT_MS);
+ const maxDuration = window.setTimeout(() => {
+ onAnimationEnd("max-duration");
+ }, STARTUP_ANIMATION_MAX_DURATION_MS);
+ return () => {
+ window.clearTimeout(firstFrame);
+ window.clearTimeout(maxDuration);
+ };
+ }, [active, state.phase, onAnimationEnd]);
+
+ useEffect(() => {
+ if (!active || !ready) return;
+ dispatch({ kind: "shell-ready" });
+ }, [active, ready, dispatch]);
+
+ useEffect(() => {
+ if (!active || state.phase !== "reveal") return;
+ const timer = window.setTimeout(() => {
+ dispatch({ kind: "reveal-finished" });
+ }, REVEAL_MS);
+ return () => window.clearTimeout(timer);
+ }, [active, state.phase, dispatch]);
+
+ // An opaque mask is indistinguishable from a hang, so a hold that outlasts
+ // its quiet bound earns the splash's progress affordance. The real failure
+ // bounds stay with the startup watchdog.
+ useEffect(() => {
+ if (!active || state.phase !== "hold") {
+ setHoldingLong(false);
+ return;
+ }
+ const timer = window.setTimeout(
+ () => setHoldingLong(true),
+ STARTUP_ANIMATION_HOLD_HINT_MS,
+ );
+ return () => window.clearTimeout(timer);
+ }, [active, state.phase]);
+
+ // Escape is the escape hatch for a long animation someone has seen enough
+ // times. It jumps to the reveal rather than cutting to the shell, so the
+ // transition is the same one every launch ends with.
+ useEffect(() => {
+ if (!active || state.phase === "done") return;
+ const onKey = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ onAnimationEnd("skipped");
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [active, state.phase, onAnimationEnd]);
+
+ return {
+ active: active && state.phase !== "done",
+ phase: state.phase,
+ playing: active && state.phase === "video",
+ holdingLong,
+ onFirstFrame,
+ onAnimationEnd,
+ };
+}
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index e90138a43..59f8262c2 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -44,6 +44,7 @@ import { LanguageRow } from "../../components/settings/LanguageRow";
import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
import { ThemeRow } from "../../components/settings/ThemeRow";
import { MacosWindowTranslucencyRow } from "../../components/settings/MacosWindowTranslucencyRow";
+import { StartupAnimationRows } from "../../components/settings/StartupAnimationRows";
import { NetworkProxySection } from "../../components/settings/NetworkProxySection";
import { ProjectsPage } from "../../pages/ProjectsPage";
import { AgentSkillsPage } from "../../components/settings/AgentSkillsPage";
@@ -419,6 +420,7 @@ export function SettingsPage() {
{platform === "darwin" && (
<MacosWindowTranslucencyRow settings={settings} saveSettings={saveSettings} />
)}
+ <StartupAnimationRows settings={settings} saveSettings={saveSettings} />
</SettingsCard>
<SettingsCard title={t("settings.sidebar")}>
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 30ba3fb4c..cb003fc31 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -31,6 +31,8 @@ import type {
PendingInteractiveRequests,
AgentInstructionFile,
AppSettings,
+ StartupAnimationDescriptor,
+ StartupAnimationStatus,
JevKeyCheckResult,
CommandShellCatalog,
AppVersionInfo,
@@ -338,6 +340,11 @@ declare global {
platform: NodeJS.Platform;
/** Authoritative OS locale passed from the main process at window creation. */
locale?: string;
+ /**
+ * Boot animation the main process resolved for this window, or null to
+ * keep the brand splash. Available before the first paint (D679).
+ */
+ startupAnimation?: StartupAnimationDescriptor | null;
/** Resolve a native dropped File to its source path. */
getDroppedFilePath?: (file: File) => string | null;
};
@@ -585,6 +592,23 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
errorCode: "INVALID_PARAMS",
});
}
+ if (Object.prototype.hasOwnProperty.call(value, "startupAnimation")) {
+ const startupAnimation = value.startupAnimation;
+ if (
+ !startupAnimation ||
+ typeof startupAnimation !== "object" ||
+ Array.isArray(startupAnimation) ||
+ Object.entries(startupAnimation).some(
+ ([key, field]) =>
+ (key !== "enabled" && key !== "skipWhenReady") ||
+ typeof field !== "boolean",
+ )
+ ) {
+ throw Object.assign(new Error("startupAnimation is invalid"), {
+ errorCode: "INVALID_PARAMS",
+ });
+ }
+ }
for (const key of [
"sidebarRunningIndicators",
"sidebarRunningBadge",
@@ -1607,6 +1631,12 @@ export const api = {
executeCommand: (commandId: string) =>
invoke(IPC.invoke.commandPaletteExecute, commandId),
openLogs: () => invoke(IPC.invoke.logOpenFolder),
+ /** What the next launch would play as its boot animation (D679). */
+ startupAnimationStatus: () =>
+ invoke<StartupAnimationStatus>(IPC.invoke.startupAnimationStatus),
+ /** Reveal the folder a startup animation is dropped into, creating it first. */
+ openStartupAnimationFolder: () =>
+ invoke(IPC.invoke.startupAnimationOpenFolder),
/**
* Quit the application. Used by the surfaces that own the window before the
* shell has data; the main process runs the same ordered shutdown as the Quit
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index 3a7365bf1..f8d0456cd 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -97,6 +97,10 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.sidebarSessionTime",
"settings.windowTranslucency",
"settings.windowTranslucencyDesc",
+ "settings.startupAnimation",
+ "settings.startupAnimationDesc",
+ "settings.startupAnimationSkipWhenReady",
+ "settings.startupAnimationSkipWhenReadyDesc",
"settings.radialMenu",
"settings.radialMenuDesc",
"settings.radialMenuEnable",
diff --git a/apps/desktop/src/lib/startup-animation.ts b/apps/desktop/src/lib/startup-animation.ts
new file mode 100644
index 000000000..a0c3c8708
--- /dev/null
+++ b/apps/desktop/src/lib/startup-animation.ts
@@ -0,0 +1,134 @@
+/**
+ * Phase machine for the user-supplied boot animation (D679 / ADR 0338).
+ *
+ * The animation replaces the brand splash as the boot surface, so the one
+ * question it has to answer correctly is *when the shell becomes visible*. Two
+ * independent things end: the video reaches its last frame, and the shell
+ * receives its initial state. The reveal waits for both, which is what makes
+ * the sequence the user asked for — play, then black, then fade — rather than a
+ * fade that lands on a half-built window.
+ *
+ * Kept free of React and of the clock so every transition is testable without
+ * a renderer: the hook supplies the events, this decides the phase.
+ */
+
+import {
+ STARTUP_ANIMATION_REVEAL_MS,
+ type StartupAnimationDescriptor,
+} from "@pi-desktop/shared";
+
+/**
+ * - `video`: the animation is playing over black.
+ * - `hold`: the animation finished, the shell has no state yet, the mask is
+ * opaque black.
+ * - `reveal`: the mask is fading out; the shell underneath already takes input.
+ * - `done`: the surface is gone.
+ */
+export type StartupAnimationPhase = "video" | "hold" | "reveal" | "done";
+
+/** Why the animation stopped; carried for diagnostics, not for rendering. */
+export type StartupAnimationEndReason =
+ | "ended"
+ | "error"
+ | "no-first-frame"
+ | "max-duration"
+ | "skipped"
+ | "ready";
+
+export type StartupAnimationState = {
+ phase: StartupAnimationPhase;
+ /** Set once the animation stops, whichever bound stopped it. */
+ endReason: StartupAnimationEndReason | null;
+};
+
+export type StartupAnimationEvent =
+ | { kind: "animation-ended"; reason: StartupAnimationEndReason }
+ | { kind: "shell-ready" }
+ | { kind: "reveal-finished" };
+
+export const INITIAL_STARTUP_ANIMATION_STATE: StartupAnimationState = {
+ phase: "video",
+ endReason: null,
+};
+
+export type StartupAnimationRules = {
+ /** `descriptor.skipWhenReady`: a fast boot may cut the playback short. */
+ skipWhenReady: boolean;
+ /** The shell already published its initial state. */
+ ready: boolean;
+};
+
+/**
+ * Advance the phase.
+ *
+ * Deliberately total and monotonic: every phase only ever moves forward, so a
+ * late `animation-ended` from a video element that was already abandoned, or a
+ * second `shell-ready` from a re-render, cannot pull the surface back over a
+ * shell the user is already using.
+ */
+export function reduceStartupAnimation(
+ state: StartupAnimationState,
+ event: StartupAnimationEvent,
+ rules: StartupAnimationRules,
+): StartupAnimationState {
+ if (state.phase === "done") return state;
+ switch (event.kind) {
+ case "animation-ended": {
+ if (state.phase !== "video") return state;
+ const endReason = state.endReason ?? event.reason;
+ // Already-ready boots skip the black hold entirely; there is nothing left
+ // to wait for, and a mandatory beat of black would read as a stutter.
+ return { phase: rules.ready ? "reveal" : "hold", endReason };
+ }
+ case "shell-ready": {
+ if (state.phase === "hold") {
+ return { phase: "reveal", endReason: state.endReason };
+ }
+ if (state.phase === "video" && rules.skipWhenReady) {
+ return { phase: "reveal", endReason: state.endReason ?? "ready" };
+ }
+ return state;
+ }
+ case "reveal-finished": {
+ if (state.phase !== "reveal") return state;
+ return { phase: "done", endReason: state.endReason };
+ }
+ }
+}
+
+/**
+ * Whether this renderer should play the animation at all.
+ *
+ * `played` is the reload guard: the descriptor rides on a window creation
+ * argument, so it survives a renderer reload that the user triggered long after
+ * the launch. Replaying a cinematic over a window someone was working in would
+ * be worse than skipping it.
+ *
+ * Reduced motion drops the animation rather than shortening it. A boot video is
+ * motion the user cannot opt out of once it starts, and the OS-level request is
+ * exactly that opt-out.
+ */
+export function shouldPlayStartupAnimation(input: {
+ descriptor: StartupAnimationDescriptor | null | undefined;
+ /** Renderer surface query parameter; only the main window plays it. */
+ surface: string | null;
+ reduceMotion: boolean;
+ played: boolean;
+}): boolean {
+ if (!input.descriptor) return false;
+ if (input.surface) return false;
+ if (input.reduceMotion) return false;
+ return !input.played;
+}
+
+/** `sessionStorage` key marking the animation as spent for this window. */
+export const STARTUP_ANIMATION_PLAYED_KEY = "pi-desktop.startup-animation.played";
+
+/**
+ * Milliseconds the reveal fade takes, matching the CSS transition.
+ *
+ * Re-exported so the hook and the stylesheet are read from one number; the
+ * surface unmounts on this timer rather than on `transitionend`, which never
+ * fires if the element is hidden mid-fade.
+ */
+export const REVEAL_MS = STARTUP_ANIMATION_REVEAL_MS;
diff --git a/apps/desktop/src/styles/chrome.css b/apps/desktop/src/styles/chrome.css
index e337552cb..8e4ebae42 100644
--- a/apps/desktop/src/styles/chrome.css
+++ b/apps/desktop/src/styles/chrome.css
@@ -1,6 +1,7 @@
/*
- App chrome — startup splash, sidebar frame (header/body/brand), titlebar and
- native window controls, the conversation top bar, and the notification center.
+ App chrome — startup splash and boot animation, sidebar frame
+ (header/body/brand), titlebar and native window controls, the conversation
+ top bar, and the notification center.
*/
/*
@@ -165,7 +166,99 @@
}
}
+/*
+ * Boot animation (D679) — the user's own video as the boot surface.
+ *
+ * Opaque black for its whole life, including the fade: the video sits on this
+ * layer, and once the video is gone the same black is the mask the shell fades
+ * in from. One layer rather than two means no seam between the last frame and
+ * the mask. The fill is literal black, not `--ds-bg-primary`, so a video's own
+ * letterboxing and fades meet the same colour under either theme.
+ *
+ * No macOS counterpart to the splash's child-hiding rule is needed: that rule
+ * exists because the splash is glass and the mounted shell bleeds through its
+ * tint. This layer is opaque, so there is nothing to bleed.
+ */
+.startup-animation {
+ position: fixed;
+ inset: 0;
+ z-index: 100;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ background: #000;
+ opacity: 1;
+ /* The window has no chrome yet, so the surface itself has to be draggable. */
+ -webkit-app-region: drag;
+ transition: opacity var(--motion-startup-reveal) var(--motion-ease-out);
+}
+
+.startup-animation.is-revealing {
+ opacity: 0;
+ /* The shell underneath takes input for the whole fade, not after it. */
+ pointer-events: none;
+}
+
+/*
+ * `cover` (D679): a user's export almost never matches the window aspect, and
+ * a filled frame is what reads as a launch sequence. The trade is that the
+ * edges are cropped, which is why the setting copy says to keep the subject
+ * centred.
+ */
+.startup-animation-video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ /* Safari/Chromium paint a 1px seam at the edges of a scaled video. */
+ transform: scale(1.002);
+ pointer-events: none;
+}
+
+/*
+ * Progress affordance for a boot that outlasted the video. Absent for the
+ * first `STARTUP_ANIMATION_HOLD_HINT_MS` of black so a normal launch stays a
+ * clean cut, and borrowed from the splash so a slow boot looks the same
+ * whichever surface covered it.
+ */
+.startup-animation-track {
+ position: absolute;
+ bottom: 48px;
+ width: 120px;
+ height: 3px;
+ overflow: hidden;
+ border-radius: var(--radius-full);
+ background: color-mix(in oklab, #fff 8%, transparent);
+ animation: startup-splash-in var(--motion-duration-slow) var(--motion-ease-out) both;
+}
+
+.startup-animation-bar {
+ display: block;
+ width: 40%;
+ height: 100%;
+ border-radius: inherit;
+ background: color-mix(in oklab, #fff 55%, transparent);
+ animation: startup-bar 1.1s var(--motion-ease-standard) infinite;
+}
+
@media (prefers-reduced-motion: reduce) {
+ /*
+ * The animation is not played at all under reduced motion (the renderer
+ * never mounts this surface), so these rules only cover a preference that
+ * changes mid-boot: the reveal becomes instant and the bar stops.
+ */
+ .startup-animation {
+ transition-duration: 0.01ms;
+ }
+ .startup-animation-track {
+ animation: none;
+ }
+ .startup-animation-bar {
+ animation: none;
+ width: 100%;
+ transform: none;
+ opacity: 0.55;
+ }
.startup-splash,
.startup-splash.is-exiting,
.startup-splash-mark,
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index deafacb47..5fdf62f97 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -1153,6 +1153,42 @@
line-height: var(--leading-body);
}
+/*
+ * Boot animation status line (D679). The file name and the folder action sit
+ * in the detail slot rather than the control slot: the control slot is capped
+ * at 240px and already holds the switch, and this is row metadata plus the one
+ * action that makes the folder findable.
+ */
+.startup-animation-status {
+ display: inline-flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 4px 10px;
+}
+
+.startup-animation-status-file {
+ /* A user's file name can be arbitrarily long; the row must not grow with it. */
+ overflow: hidden;
+ max-width: 28ch;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.settings-inline-action {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--ds-text-link, var(--ds-text-primary));
+ font: inherit;
+ cursor: pointer;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+}
+
+.settings-inline-action:hover {
+ color: var(--ds-text-primary);
+}
+
.settings-row-control {
flex: 0 0 auto;
min-width: 0;
diff --git a/apps/desktop/src/styles/tokens.css b/apps/desktop/src/styles/tokens.css
index bc74a6109..7ea3e6457 100644
--- a/apps/desktop/src/styles/tokens.css
+++ b/apps/desktop/src/styles/tokens.css
@@ -211,6 +211,12 @@
--motion-duration-fast: 150ms;
--motion-duration-normal: 200ms;
--motion-duration-slow: 300ms;
+ /* The one duration outside the ramp above (D679): the boot animation's
+ reveal is the end of a cinematic, not a control answering a click, so it
+ is sized in that register instead of the in-flow feedback register. It is
+ used only by .startup-animation and must stay matched to
+ STARTUP_ANIMATION_REVEAL_MS in @pi-desktop/shared. */
+ --motion-startup-reveal: 1000ms;
--motion-ease-out: cubic-bezier(0.22, 1, 0.36, 1);
--motion-ease-in: cubic-bezier(0.4, 0, 1, 1);
--motion-ease-standard: cubic-bezier(0.2, 0, 0, 1);
diff --git a/apps/desktop/test/bounded-history-mutations.test.mjs b/apps/desktop/test/bounded-history-mutations.test.mjs
index 54af13852..9bfa18109 100644
--- a/apps/desktop/test/bounded-history-mutations.test.mjs
+++ b/apps/desktop/test/bounded-history-mutations.test.mjs
@@ -174,6 +174,8 @@ test("the real store/API/preload/IPC path uploads bounded ids with more than 64
assert.ok(["sessionDeleteMessage", "sessionRetractPendingPrompt", "sessionActivateRevision"].includes(key));
return { ok: true, data: await ipc.invoke(key, input) };
} } }, "@pi-desktop/shared": shared, "@pi-desktop/shared/protocol": shared,
+ // Boot-animation descriptor decoding (D679); no argument, nothing to read.
+ "@pi-desktop/shared/startup-animation": { decodeStartupAnimationArgument: () => null },
});
const { api } = load("../src/lib/api.ts", {
"@pi-desktop/shared": shared, "./plan-history": {}, "./remote-session-safety": safety,
diff --git a/apps/desktop/test/gen-ui-protocol.test.mjs b/apps/desktop/test/gen-ui-protocol.test.mjs
index b0c4f1406..e600aefdd 100644
--- a/apps/desktop/test/gen-ui-protocol.test.mjs
+++ b/apps/desktop/test/gen-ui-protocol.test.mjs
@@ -292,7 +292,7 @@ test("scheme privileges: standard + secure only, registered in the single privil
const schemes = await readMainModule("plugin-schemes.ts");
assert.match(
schemes,
- /registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*GEN_UI_SCHEME_PRIVILEGES,\s*\]\)/,
+ /registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*GEN_UI_SCHEME_PRIVILEGES,\s*STARTUP_ANIMATION_SCHEME_PRIVILEGES,\s*\]\)/,
);
const startup = await readMainModule("bootstrap/startup.ts");
const install = startup.indexOf("installGenUiProtocol({ getHost });");
diff --git a/apps/desktop/test/plugin-renderer-protocol.test.mjs b/apps/desktop/test/plugin-renderer-protocol.test.mjs
index d8bb83816..0e83efd57 100644
--- a/apps/desktop/test/plugin-renderer-protocol.test.mjs
+++ b/apps/desktop/test/plugin-renderer-protocol.test.mjs
@@ -11,7 +11,7 @@ test("plugin schemes are reserved together, in the only privileged registration"
const schemes = await readMainModule("plugin-schemes.ts");
assert.match(
schemes,
- /registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*GEN_UI_SCHEME_PRIVILEGES,\s*\]\)/,
+ /registerSchemesAsPrivileged\(\[\s*PLUGIN_ASSET_SCHEME_PRIVILEGES,\s*PLUGIN_RENDERER_SCHEME_PRIVILEGES,\s*GEN_UI_SCHEME_PRIVILEGES,\s*STARTUP_ANIMATION_SCHEME_PRIVILEGES,\s*\]\)/,
);
const startup = await readMainModule("bootstrap/startup.ts");
assert.ok(
diff --git a/apps/desktop/test/session-collaboration-ipc.test.mjs b/apps/desktop/test/session-collaboration-ipc.test.mjs
index bb17049d9..5f8752cbf 100644
--- a/apps/desktop/test/session-collaboration-ipc.test.mjs
+++ b/apps/desktop/test/session-collaboration-ipc.test.mjs
@@ -87,6 +87,11 @@ function rendererApi(invoke) {
},
"@pi-desktop/shared": shared,
"@pi-desktop/shared/protocol": shared,
+ // The preload reads the boot-animation descriptor from its own argv
+ // (D679); with no such argument there is nothing to decode.
+ "@pi-desktop/shared/startup-animation": {
+ decodeStartupAnimationArgument: () => null,
+ },
});
const { api } = load("../src/lib/api.ts", {
"@pi-desktop/shared": shared,
diff --git a/apps/desktop/test/startup-animation.test.mjs b/apps/desktop/test/startup-animation.test.mjs
new file mode 100644
index 000000000..7c5d2abb0
--- /dev/null
+++ b/apps/desktop/test/startup-animation.test.mjs
@@ -0,0 +1,465 @@
+/**
+ * D679 / ADR 0338: a user's own video as the boot surface.
+ *
+ * The animation owns the first paint of a released app, so these tests are
+ * weighted towards the ways it must *not* work: a missing folder, a file that
+ * escapes it, a video that never ends, a stalled boot behind an opaque mask,
+ * and a reload replaying a cinematic over a window someone was using. The happy
+ * path is one transition; the bounds are the feature.
+ */
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import {
+ parseByteRange,
+ STARTUP_ANIMATION_FIRST_FRAME_TIMEOUT_MS,
+ STARTUP_ANIMATION_HOLD_HINT_MS,
+ STARTUP_ANIMATION_MAX_BYTES,
+ STARTUP_ANIMATION_MAX_DURATION_MS,
+ STARTUP_ANIMATION_REVEAL_MS,
+ STARTUP_ANIMATION_SCHEME,
+ STARTUP_ANIMATION_URL,
+} from "@pi-desktop/shared";
+import { STARTUP_STALLED_MS } from "../src/lib/startup-watchdog.ts";
+import {
+ INITIAL_STARTUP_ANIMATION_STATE,
+ reduceStartupAnimation,
+ shouldPlayStartupAnimation,
+} from "../src/lib/startup-animation.ts";
+import {
+ resolveStartupAnimation,
+ startupAnimationDirectory,
+} from "../electron/main/startup-animation.ts";
+import { readAppSource } from "./helpers/source-contracts.mjs";
+import { loadStyles } from "./helpers/styles.mjs";
+
+const read = (path) => readFile(new URL(path, import.meta.url), "utf8");
+
+const [shell, surface, hook, css, english, chinese, settingsRow, html, preload, windowBoot, startupBoot] =
+ await Promise.all([
+ readAppSource(),
+ read("../src/components/StartupAnimation.tsx"),
+ read("../src/features/app/useStartupAnimation.ts"),
+ loadStyles(),
+ read("../../../packages/i18n/src/locales/en/index.ts"),
+ read("../../../packages/i18n/src/locales/zh-CN/index.ts"),
+ read("../src/components/settings/StartupAnimationRows.tsx"),
+ read("../index.html"),
+ read("../electron/preload/index.ts"),
+ read("../electron/main/bootstrap/window.ts"),
+ read("../electron/main/bootstrap/startup.ts"),
+ ]);
+
+async function withDataDir(run) {
+ const root = await mkdtemp(join(tmpdir(), "pi-startup-animation-"));
+ try {
+ return await run(root);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}
+
+const RULES = { skipWhenReady: false, ready: false };
+
+// ---------------------------------------------------------------------------
+// Bounds
+// ---------------------------------------------------------------------------
+
+test("every bound is ordered so no single one can hold the window", () => {
+ // The first-frame bound must fire long before the playback bound, or a file
+ // that never decodes waits out the whole animation budget.
+ assert.ok(
+ STARTUP_ANIMATION_FIRST_FRAME_TIMEOUT_MS < STARTUP_ANIMATION_MAX_DURATION_MS,
+ );
+ // The hold hint is a hint, not a bound: it has to arrive while the user is
+ // still looking at black, not after the watchdog has taken over.
+ assert.ok(STARTUP_ANIMATION_HOLD_HINT_MS < STARTUP_ANIMATION_MAX_DURATION_MS);
+ // And the whole animation must end well inside the watchdog's stalled bound,
+ // so the recovery surface is never racing a mask that is still up.
+ assert.ok(
+ STARTUP_ANIMATION_MAX_DURATION_MS + STARTUP_ANIMATION_REVEAL_MS <
+ STARTUP_STALLED_MS,
+ );
+ // The reveal the feature was asked for: about a second, not a UI transition.
+ assert.equal(STARTUP_ANIMATION_REVEAL_MS, 1000);
+});
+
+test("the reveal duration is one number, shared by the timer and the stylesheet", () => {
+ assert.match(css, /--motion-startup-reveal:\s*1000ms;/);
+ assert.match(
+ css,
+ /\.startup-animation \{[\s\S]*transition: opacity var\(--motion-startup-reveal\)/,
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Phase machine
+// ---------------------------------------------------------------------------
+
+test("the reveal waits for both the video and the shell", () => {
+ // The order the feature was specified in: play, then black, then fade.
+ const held = reduceStartupAnimation(
+ INITIAL_STARTUP_ANIMATION_STATE,
+ { kind: "animation-ended", reason: "ended" },
+ RULES,
+ );
+ assert.equal(held.phase, "hold");
+ const revealing = reduceStartupAnimation(held, { kind: "shell-ready" }, RULES);
+ assert.equal(revealing.phase, "reveal");
+ assert.equal(
+ reduceStartupAnimation(revealing, { kind: "reveal-finished" }, RULES).phase,
+ "done",
+ );
+});
+
+test("a boot that finished first skips the black hold entirely", () => {
+ const rules = { skipWhenReady: false, ready: true };
+ assert.equal(
+ reduceStartupAnimation(
+ INITIAL_STARTUP_ANIMATION_STATE,
+ { kind: "animation-ended", reason: "ended" },
+ rules,
+ ).phase,
+ "reveal",
+ );
+});
+
+test("readiness cuts the playback short only when the user asked it to", () => {
+ const playedOut = reduceStartupAnimation(
+ INITIAL_STARTUP_ANIMATION_STATE,
+ { kind: "shell-ready" },
+ { skipWhenReady: false, ready: true },
+ );
+ assert.equal(playedOut.phase, "video", "the default plays to the last frame");
+ const cutShort = reduceStartupAnimation(
+ INITIAL_STARTUP_ANIMATION_STATE,
+ { kind: "shell-ready" },
+ { skipWhenReady: true, ready: true },
+ );
+ assert.equal(cutShort.phase, "reveal");
+ assert.equal(cutShort.endReason, "ready");
+});
+
+test("every failure path ends the animation the same way a clean finish does", () => {
+ for (const reason of ["error", "no-first-frame", "max-duration", "skipped"]) {
+ const next = reduceStartupAnimation(
+ INITIAL_STARTUP_ANIMATION_STATE,
+ { kind: "animation-ended", reason },
+ RULES,
+ );
+ assert.equal(next.phase, "hold", `${reason} must not strand the surface`);
+ assert.equal(next.endReason, reason);
+ }
+});
+
+test("the phase only moves forward, so a late event cannot re-cover the shell", () => {
+ // A `<video>` that was abandoned on a timeout can still fire `ended`, and a
+ // re-render can republish readiness. Neither may pull the mask back over a
+ // window the user is already working in.
+ const done = { phase: "done", endReason: "ended" };
+ for (const event of [
+ { kind: "animation-ended", reason: "ended" },
+ { kind: "shell-ready" },
+ { kind: "reveal-finished" },
+ ]) {
+ assert.equal(reduceStartupAnimation(done, event, RULES).phase, "done");
+ }
+ const revealing = { phase: "reveal", endReason: "ended" };
+ assert.equal(
+ reduceStartupAnimation(
+ revealing,
+ { kind: "animation-ended", reason: "error" },
+ RULES,
+ ).phase,
+ "reveal",
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Whether to play at all
+// ---------------------------------------------------------------------------
+
+test("the animation plays only for a first-paint main window that wants motion", () => {
+ const descriptor = {
+ fileName: "intro.webm",
+ extension: "webm",
+ byteLength: 10,
+ skipWhenReady: false,
+ };
+ const base = { descriptor, surface: null, reduceMotion: false, played: false };
+ assert.equal(shouldPlayStartupAnimation(base), true);
+ assert.equal(
+ shouldPlayStartupAnimation({ ...base, descriptor: null }),
+ false,
+ "no file, no animation",
+ );
+ assert.equal(
+ shouldPlayStartupAnimation({ ...base, surface: "plugin-launcher" }),
+ false,
+ "a secondary renderer surface is not a launch",
+ );
+ assert.equal(
+ shouldPlayStartupAnimation({ ...base, reduceMotion: true }),
+ false,
+ "reduced motion drops the animation rather than shortening it",
+ );
+ assert.equal(
+ shouldPlayStartupAnimation({ ...base, played: true }),
+ false,
+ "a reload must not replay a cinematic over a window in use",
+ );
+});
+
+test("the reload guard survives module re-evaluation", () => {
+ // A module-level flag would reset on reload, which is the exact case the
+ // guard exists for; it has to live in storage the window keeps.
+ assert.match(hook, /sessionStorage/);
+ assert.match(hook, /STARTUP_ANIMATION_PLAYED_KEY/);
+});
+
+test("deciding to play is idempotent, so StrictMode cannot cancel the animation", () => {
+ // The decision writes the spent mark, so a second evaluation would read its
+ // own write and answer "already played". `StrictMode` invokes a `useState`
+ // initializer twice in development and keeps the second result, which would
+ // mean the animation never appears in a development build.
+ assert.match(hook, /let pageLoadVerdict: boolean \| null = null;/);
+ assert.match(hook, /if \(pageLoadVerdict !== null\) return pageLoadVerdict;/);
+ assert.match(hook, /useState\(\(\) => decidePlayback\(descriptor\)\)/);
+});
+
+// ---------------------------------------------------------------------------
+// Discovery
+// ---------------------------------------------------------------------------
+
+test("discovery finds a video dropped into the startup folder", async () => {
+ await withDataDir(async (dataDir) => {
+ const directory = startupAnimationDirectory(dataDir);
+ assert.equal(directory, join(dataDir, "startup"));
+ await mkdir(directory, { recursive: true });
+ await writeFile(join(directory, "intro.mp4"), Buffer.alloc(64, 1));
+ const resolved = await resolveStartupAnimation({ dataDir, settings: null });
+ assert.equal(resolved?.descriptor.fileName, "intro.mp4");
+ assert.equal(resolved?.descriptor.byteLength, 64);
+ // The served path is a realpath (that is what confines it to the folder),
+ // so it can differ from the path that was written — on macOS `/var` is a
+ // link to `/private/var`.
+ assert.equal(resolved?.filePath, await realpath(join(directory, "intro.mp4")));
+ assert.equal(resolved?.descriptor.skipWhenReady, false);
+ });
+});
+
+test("an installation that never used the feature resolves nothing", async () => {
+ await withDataDir(async (dataDir) => {
+ // No folder is created on the discovery path: a data directory must not
+ // grow a folder just because the app booted.
+ assert.equal(await resolveStartupAnimation({ dataDir, settings: null }), null);
+ await mkdir(startupAnimationDirectory(dataDir), { recursive: true });
+ assert.equal(
+ await resolveStartupAnimation({ dataDir, settings: null }),
+ null,
+ "an empty folder is the same as no folder",
+ );
+ });
+});
+
+test("the setting can silence a file that is present", async () => {
+ await withDataDir(async (dataDir) => {
+ const directory = startupAnimationDirectory(dataDir);
+ await mkdir(directory, { recursive: true });
+ await writeFile(join(directory, "intro.webm"), Buffer.alloc(8, 1));
+ assert.equal(
+ await resolveStartupAnimation({
+ dataDir,
+ settings: { startupAnimation: { enabled: false } },
+ }),
+ null,
+ );
+ // Absent means on, so dropping a file in is all it takes.
+ for (const settings of [null, {}, { startupAnimation: {} }, { startupAnimation: null }]) {
+ assert.ok(
+ await resolveStartupAnimation({ dataDir, settings }),
+ `settings ${JSON.stringify(settings)} should still play`,
+ );
+ }
+ });
+});
+
+test("skipWhenReady reaches the descriptor the renderer reads", async () => {
+ await withDataDir(async (dataDir) => {
+ const directory = startupAnimationDirectory(dataDir);
+ await mkdir(directory, { recursive: true });
+ await writeFile(join(directory, "intro.webm"), Buffer.alloc(8, 1));
+ const resolved = await resolveStartupAnimation({
+ dataDir,
+ settings: { startupAnimation: { skipWhenReady: true } },
+ });
+ assert.equal(resolved?.descriptor.skipWhenReady, true);
+ });
+});
+
+test("a symlink out of the folder is not served", async () => {
+ await withDataDir(async (dataDir) => {
+ const directory = startupAnimationDirectory(dataDir);
+ await mkdir(directory, { recursive: true });
+ const outside = join(dataDir, "secrets.webm");
+ await writeFile(outside, Buffer.alloc(16, 1));
+ await symlink(outside, join(directory, "intro.webm"));
+ assert.equal(
+ await resolveStartupAnimation({ dataDir, settings: null }),
+ null,
+ "the host-owned scheme must not become a reader for arbitrary files",
+ );
+ });
+});
+
+test("a directory named like a video is not mistaken for one", async () => {
+ await withDataDir(async (dataDir) => {
+ const directory = startupAnimationDirectory(dataDir);
+ await mkdir(join(directory, "nested.webm"), { recursive: true });
+ assert.equal(await resolveStartupAnimation({ dataDir, settings: null }), null);
+ // The real file beside it still wins, and its size is what the cap is
+ // applied to (the cap itself is covered in the shared unit tests).
+ await writeFile(join(directory, "intro.webm"), Buffer.alloc(1024));
+ const resolved = await resolveStartupAnimation({ dataDir, settings: null });
+ assert.equal(resolved?.descriptor.fileName, "intro.webm");
+ assert.ok(resolved.descriptor.byteLength < STARTUP_ANIMATION_MAX_BYTES);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Protocol
+// ---------------------------------------------------------------------------
+
+test("media range requests are answered, and a nonsense range is not", () => {
+ assert.deepEqual(parseByteRange("bytes=0-", 100), { start: 0, end: 99 });
+ assert.deepEqual(parseByteRange("bytes=10-19", 100), { start: 10, end: 19 });
+ // A range past the end is clamped rather than refused; Chromium asks for one.
+ assert.deepEqual(parseByteRange("bytes=90-999", 100), { start: 90, end: 99 });
+ assert.deepEqual(parseByteRange("bytes=-20", 100), { start: 80, end: 99 });
+ assert.equal(parseByteRange(null, 100), null, "no header means a plain 200");
+ assert.equal(parseByteRange("bytes=100-", 100), null, "a start past the end");
+ assert.equal(parseByteRange("bytes=20-10", 100), null, "an inverted range");
+ assert.equal(parseByteRange("items=0-10", 100), null, "a non-byte unit");
+ assert.equal(parseByteRange("bytes=0-10,20-30", 100), null, "a multi-range");
+});
+
+test("the renderer references the animation by URL, never by path", () => {
+ assert.equal(STARTUP_ANIMATION_URL, `${STARTUP_ANIMATION_SCHEME}://animation`);
+ assert.match(surface, /src=\{STARTUP_ANIMATION_URL\}/);
+ // A single pathless URL means nothing the page sends can select another file.
+ assert.doesNotMatch(surface, /filePath|dataDir/);
+ assert.match(html, /media-src [^;]*pi-startup:/);
+});
+
+// ---------------------------------------------------------------------------
+// Wiring
+// ---------------------------------------------------------------------------
+
+test("the descriptor reaches the renderer before its first paint", () => {
+ // An IPC round-trip would land after the first frame, which is the one frame
+ // the animation exists to own; it travels as a creation argument like the
+ // locale does.
+ assert.match(windowBoot, /additionalArguments: \[[\s\S]*encodeStartupAnimationArgument/);
+ assert.match(preload, /startupAnimation: decodeStartupAnimationArgument\(process\.argv\)/);
+ // Narrow subpath, not the package barrel: the preload is one bundled file.
+ assert.match(preload, /from "@pi-desktop\/shared\/startup-animation"/);
+});
+
+test("only the first window of the process plays the animation", () => {
+ assert.match(
+ windowBoot,
+ /windowState\.startupAnimationPlayed\s*\?\s*null\s*:\s*windowState\.startupAnimation/,
+ );
+ // Claimed before the window is constructed, so a second window racing this
+ // one cannot also take it.
+ assert.ok(
+ windowBoot.indexOf("windowState.startupAnimationPlayed = true") <
+ windowBoot.indexOf("windowState.mainWindow = new BrowserWindow("),
+ );
+});
+
+test("the capture rig never sees a user's animation", () => {
+ // Every capture scene is a frame comparison; an animation in front of them
+ // would break all of them.
+ assert.match(
+ startupBoot,
+ /PI_DESKTOP_CAPTURE !== "1"[\s\S]*resolveStartupAnimation\(/,
+ );
+});
+
+test("the animation is resolved before the window and served after app ready", () => {
+ const install = startupBoot.indexOf("installStartupAnimationProtocol(");
+ const resolve = startupBoot.indexOf("resolveStartupAnimation({");
+ const ensure = startupBoot.indexOf("await ensureWindow()");
+ assert.ok(install > 0 && resolve > install, "the handler is in place first");
+ assert.ok(resolve < ensure, "the descriptor exists before the window does");
+});
+
+test("a stalled launch is never left behind the opaque mask", () => {
+ // The watchdog's surfaces outrank both boot surfaces, so the phase is the
+ // first thing the splash expression tests.
+ assert.match(shell, /const splash =\s*startupPhase !== "starting"\s*\? null/);
+ assert.match(shell, /startupAnimation\.active\s*\?\s*\(\s*<StartupAnimation/);
+ // Exactly one of the three surfaces is ever mounted.
+ assert.equal((shell.match(/<StartupAnimation/g) ?? []).length, 1);
+ assert.equal((shell.match(/<StartupSplash/g) ?? []).length, 1);
+});
+
+test("the shell becomes operable for the whole fade, not after it", () => {
+ assert.match(
+ shell,
+ /const showSplash = startupAnimation\.active\s*\?\s*startupAnimation\.phase !== "reveal"/,
+ );
+ assert.match(css, /\.startup-animation\.is-revealing \{[\s\S]*pointer-events: none;/);
+});
+
+// ---------------------------------------------------------------------------
+// Surface
+// ---------------------------------------------------------------------------
+
+test("the surface is opaque black and the video is inert and silent", () => {
+ assert.match(css, /\.startup-animation \{[\s\S]*background: #000;/);
+ assert.match(css, /\.startup-animation-video \{[\s\S]*object-fit: cover;/);
+ // Muted: an unmuted autoplay is blocked by Chromium and hostile besides.
+ assert.match(surface, /\bmuted\b/);
+ assert.match(surface, /\bplaysInline\b/);
+ assert.match(surface, /controls=\{false\}/);
+ assert.match(surface, /tabIndex=\{-1\}/);
+ assert.match(surface, /data-testid="startup-animation"/);
+});
+
+test("a boot that outlasts the video stops looking like a hang", () => {
+ assert.match(surface, /holdingLong \? \(/);
+ assert.match(hook, /STARTUP_ANIMATION_HOLD_HINT_MS/);
+ assert.match(css, /\.startup-animation-track \{/);
+});
+
+test("reduced motion is handled in the renderer and in the stylesheet", () => {
+ assert.match(hook, /prefers-reduced-motion: reduce/);
+ assert.match(
+ css,
+ /@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\.startup-animation \{\s*transition-duration: 0\.01ms;/,
+ );
+});
+
+test("the settings rows make the folder findable and name the next launch's file", () => {
+ assert.match(settingsRow, /startupAnimationStatus\(\)/);
+ assert.match(settingsRow, /openStartupAnimationFolder\(\)/);
+ assert.match(settingsRow, /settings\.startupAnimationNone/);
+ // The sub-switch is gated by the master switch, as the sidebar rows are.
+ assert.match(settingsRow, /enabled \? \(/);
+ for (const key of [
+ "startupAnimation",
+ "startupAnimationDesc",
+ "startupAnimationNone",
+ "startupAnimationFolder",
+ "startupAnimationSkipWhenReady",
+ "startupAnimationSkipWhenReadyDesc",
+ ]) {
+ assert.match(english, new RegExp(`${key}:`), `en is missing ${key}`);
+ assert.match(chinese, new RegExp(`${key}:`), `zh-CN is missing ${key}`);
+ }
+});
diff --git a/apps/desktop/test/startup-watchdog.test.mjs b/apps/desktop/test/startup-watchdog.test.mjs
index 9c613218d..a6f2fb640 100644
--- a/apps/desktop/test/startup-watchdog.test.mjs
+++ b/apps/desktop/test/startup-watchdog.test.mjs
@@ -217,8 +217,14 @@ test("the shell watches the wait and renders the recovery surface", () => {
assert.match(shell, /<StartupRecovery[\s\S]*onRetry=\{retryStartup\}/);
assert.match(shell, /<StartupRecovery[\s\S]*retrying=\{startupRetrying\}/);
assert.match(shell, /startupPhase !== "starting"/);
- // Exactly one boot surface is mounted: the splash yields to the recovery.
- assert.match(shell, /const splash = showSplash && startupPhase === "starting"/);
+ // Exactly one boot surface is mounted, and the recovery outranks both of the
+ // others: the phase is the first thing the splash expression tests, so a
+ // stalled launch can never be left behind the brand splash or behind an
+ // opaque startup animation (D679).
+ assert.match(
+ shell,
+ /const splash =\s*startupPhase !== "starting"\s*\? null/,
+ );
});
test("the boot surfaces keep the window controls, so a stuck launch is closable", () => {
diff --git a/docs/adr/0338-user-supplied-startup-animation.md b/docs/adr/0338-user-supplied-startup-animation.md
new file mode 100644
index 000000000..69a75ad59
--- /dev/null
+++ b/docs/adr/0338-user-supplied-startup-animation.md
@@ -0,0 +1,174 @@
+# ADR 0338: a user-supplied video owns the boot surface, served over a host-owned scheme
+
+- Status: Accepted
+- Date: 2026-11-03
+- Deciders: PI-Desktop maintainers
+- Related: D679, D348, D665, ADR 0248 (theme assets and window background),
+ ADR 0332 (macOS window surface), issue #831 (startup watchdog),
+ `docs/spec/04-ux/09-interaction-patterns.md`,
+ `docs/spec/06-delivery/04-e2e-test-plan.md` (E2E-076)
+
+## Context
+
+The window has always shown one boot surface: `StartupSplash`, a brand mark
+with a tagline and an indeterminate bar, mounted until the shell publishes its
+initial state and then faded out over 280ms after a 420ms minimum dwell. Issue
+#831 added the two bounds that keep it from being permanent — a slow hint at
+30s and a recovery surface at 180s.
+
+Users asked to put their own launch video there. That request touches three
+boundaries at once, and each has a wrong answer that looks easy:
+
+- **The file.** The renderer is sandboxed, `contextIsolation` is on, and the
+ page CSP has no `file:` source. A video cannot be referenced by path, and
+ should not be: a path in the page discloses the user's data directory to
+ anything that later runs in that renderer, including plugin renderer
+ extensions.
+- **The timing.** The animation has to be in the renderer's *first* frame or
+ the user sees the splash flash before it. Anything fetched over IPC lands
+ after that frame.
+- **The failure modes.** A splash is code the product controls; a video is a
+ file a user produced. It can be unplayable, truncated, 2 GB, or an infinite
+ loop, and `<video>` reports none of those uniformly — a bad export fires
+ neither `ended` nor `error`. A boot surface that waits for an event that
+ never comes is a launch that never finishes.
+
+## Decision
+
+A video in `<dataDir>/startup/` replaces the brand splash for that launch,
+plays to its last frame, then holds the window under the same opaque black it
+played on until the shell is ready, then fades that black out over one second.
+
+**Discovery is filesystem-only and creates nothing.** `resolveStartupAnimation`
+reads `<dataDir>/startup/`, keeps entries whose extension is in
+`STARTUP_ANIMATION_EXTENSIONS`, confines each by realpath to that directory,
+and picks deterministically: most-decodable container first (`webm`, then
+`mp4`, `m4v`, `mov`), ties broken by file name. Dot-prefixed entries, non-files,
+empty files, and files over `STARTUP_ANIMATION_MAX_BYTES` (64 MB) drop out. No
+directory is created on this path, so an installation that never uses the
+feature is unchanged on disk and keeps the brand splash.
+
+**The bytes travel over `pi-startup:`, a host-owned scheme with exactly one
+URL.** `pi-startup://animation` carries no path, host, or query the caller
+controls; the handler streams the single file the main process resolved at boot
+and answers `Range` so media playback is not buffered whole. Because the URL
+selects nothing, there is no traversal surface to confine — the realpath check
+at discovery is the only place a file is chosen. The scheme is reserved in
+`registerPluginSchemes`, the one `registerSchemesAsPrivileged` call, with
+`standard`, `secure`, and `stream` and no CORS privileges: a `<video>` `src` is
+a no-cors fetch and nothing else may read these bytes. `media-src pi-startup:`
+is the only CSP change.
+
+**The descriptor reaches the renderer as a window creation argument**, the same
+mechanism the display locale already uses, so `window.piDesktop.startupAnimation`
+is readable synchronously before the first paint. The descriptor carries the
+file's name, extension, byte length, and the `skipWhenReady` preference — never
+a path. The preload re-validates every field, because the argument vector is
+process input.
+
+**Three bounds make the surface recoverable**, and each is below the next:
+first frame (2s), whole animation (15s), and the watchdog's stalled bound
+(180s), which the animation plus its reveal must finish well inside. `Escape`
+is a fourth, user-driven bound. Every one of them ends the animation through
+the same transition a clean finish uses, so there is no failure-specific
+rendering path.
+
+**Three boot surfaces exist and exactly one is mounted**, ranked: the recovery
+surface outranks both (a stalled launch must never sit behind an opaque mask),
+and the animation outranks the brand splash it was dropped in to replace. The
+mask stops taking input the moment the fade starts, so the shell and its window
+controls are operable for the whole second rather than after it.
+
+**The animation plays once per launch, for the first window of the process.**
+Main claims it before `new BrowserWindow`, so reopening from the tray or the
+Dock replays nothing; the renderer marks `sessionStorage`, so a manual reload
+does not replay a cinematic over a window someone is working in. Reduced motion
+drops the animation entirely rather than shortening it — a boot video is motion
+the user cannot opt out of once it starts. The capture rig is skipped outright,
+since every scene it records is a frame comparison.
+
+`AppSettings.startupAnimation` holds the only two choices discovery cannot make:
+`enabled` (absent means on, so dropping a file in is sufficient) and
+`skipWhenReady` (absent means play it out). Both are read before the window is
+created, so like ADR 0332's translucency switch a change lands on the next
+launch.
+
+## Consequences
+
+- An installation with no `startup/` directory behaves exactly as before: same
+ splash, same dwell, same fade, same watchdog bounds. The feature is dormant
+ rather than defaulted off, which is what makes dropping a file in work with
+ no further configuration.
+- A launch with an animation is slower to reach the shell by design: the video
+ plays to its last frame unless the user turns on `skipWhenReady`. This is the
+ trade the feature asks for, and the bounds cap it at 15s.
+- The host now owns a fourth privileged scheme. Its attack surface is smaller
+ than the plugin schemes': no caller-supplied path, no CORS, and one file per
+ process chosen by main.
+- `--motion-startup-reveal: 1000ms` is the one duration outside the motion ramp
+ (150/200/300ms). It is used only by `.startup-animation` and is documented as
+ an exception rather than a new scale.
+- The surface is literal `#000`, not `--ds-bg-primary`, so a video's own
+ letterboxing and fades meet the same colour under either theme. It is opaque,
+ so unlike the glass splash it needs no macOS rule hiding the shell beneath it.
+- Settings gains a status line that names the resolved file and an action that
+ opens (and creates) the folder. Without it, a feature configured by dropping
+ a file into a hidden directory would be undiscoverable.
+
+## Alternatives rejected
+
+- **A dedicated splash `BrowserWindow`.** It would let the video appear before
+ the main renderer boots at all, but it adds a second window with its own
+ focus, z-order, Dock, and vibrancy behaviour; it conflicts with the main
+ window's `ready-to-show` gate; and it cannot express what was asked for — a
+ mask *over the main interface* that fades away — without cross-window
+ choreography. One surface inside the existing shell keeps the watchdog and
+ recovery contracts intact.
+- **`file://` or a `data:`/`blob:` URL.** `file:` is not in the page CSP and
+ would disclose the data directory; a `data:` URL means base64 (a third larger)
+ for a file capped at 64 MB, read into memory before the first frame.
+- **Reusing `plugin-asset:`.** That scheme takes a plugin id and an asset path
+ from the URL, so it exists to serve a caller-selected file. Reusing it would
+ widen a confined resolver for an unrelated owner; a pathless scheme has no
+ such surface.
+- **Letting a plugin contribute the startup animation.** This hands an
+ untrusted source the full-window first paint before any UI exists. It is a
+ different security level from a file the user placed in their own data
+ directory and needs its own ADR, not an extension of this one.
+- **Unmuted audio.** Chromium blocks unmuted autoplay without a user gesture;
+ allowing it needs a process-wide `autoplayPolicy` that also affects plugin
+ webviews. A launch jingle on every start is also poor default behaviour. The
+ element is `muted` and the setting does not exist.
+- **`object-fit: contain`.** Letterboxing is safer for a centred logo, but a
+ filled frame is what reads as a launch sequence, and a user's export almost
+ never matches the window aspect. `cover` is fixed, and the settings copy says
+ to keep the subject centred.
+- **Cutting the video short as soon as the shell is ready, by default.** This
+ makes the animation feel truncated on a fast machine, which is the common
+ case. It is offered as `skipWhenReady` for users who want the file to be a
+ ceiling rather than a duration.
+- **Shortening the animation under reduced motion.** A shorter cinematic is
+ still a cinematic. The OS-level request is an opt-out, so the animation is
+ not played.
+
+## Evidence
+
+- `packages/shared/src/startup-animation.test.ts` — the chooser, the container
+ and MIME tables, the range parser, and the creation-argument codec including
+ every malformed-descriptor rejection.
+- `apps/desktop/test/startup-animation.test.mjs` — bound ordering against the
+ watchdog, the phase machine (including monotonicity), the play/skip decision,
+ discovery against temporary data directories (missing folder, empty folder,
+ symlink escape, directory named like a video, the setting off), the surface
+ and stylesheet contracts, and the boot-surface ranking.
+- `pnpm test:e2e:startup-animation` (`scripts/e2e-startup-animation.mjs`) — the
+ two properties no source assertion can reach: a real launch decodes a
+ generated VP9 clip over `pi-startup:` under the page CSP (`readyState` 4,
+ advancing `currentTime`) and then reveals an interactive shell, and an
+ unplayable file of the same name yields the shell in about a second instead
+ of holding the window.
+- `apps/desktop/test/startup-watchdog.test.mjs` — the recovery surface still
+ outranks both boot surfaces.
+- `apps/desktop/test/plugin-renderer-protocol.test.mjs`,
+ `apps/desktop/test/gen-ui-protocol.test.mjs` — the scheme is reserved in the
+ single privileged registration.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 07ca0ca51..8f3d83276 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -395,5 +395,6 @@ Each ADR includes:
| 0332 | [macOS keeps its translucent window surface with an opaque opt-out](0332-macos-opaque-window-surface.md) | Accepted (D665, amended by D666 and D667; supersedes the macOS vibrancy window backing from D348; issue #1064) |
| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Accepted (D671) |
| 0337 | [Keep the request prefix stable across delegation settlements](0337-stable-prompt-prefix-across-delegation.md) | Accepted (supersedes ADR 0279 §9) |
+| 0338 | [A user-supplied video owns the boot surface, served over a host-owned scheme](0338-user-supplied-startup-animation.md) | Accepted (D679) |
| model-reasoning-effort-override | [Model reasoning effort override](model-reasoning-effort-override.md) | Proposed |
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index fb1679a3a..8c421cc13 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -168,6 +168,16 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
created, so the row shows a restart hint while the stored value differs from
the surface this process launched with instead of pretending to change the
live window. Other platforms do not render the row.
+ - **Startup animation** (D679 / ADR 0338): one switch, plus an **End early
+ when ready** sub-switch gated by it. The animation itself is a file, not a
+ value, so the row's other job is making the folder findable: its detail line
+ names the video the next launch would play — or says none was found — and
+ carries the action that opens `<dataDir>/startup/`, creating it on the way.
+ Both preferences persist under `AppSettings.startupAnimation` (`enabled`
+ absent means on, so dropping a file in is sufficient; `skipWhenReady` absent
+ plays the video out) and are read before the main window is created, so like
+ the row above they apply on the next launch. The status is re-scanned per
+ open, because a user who just dropped a file in has not restarted yet.
- **Auto language detection** resolves the OS locale through the main process
(`app.getLocale()`) rather than the renderer's `navigator.language`, and the
Auto option shows the detected language inline (e.g. "Currently 简体中文")
diff --git a/docs/spec/04-ux/07-ui-design-system.md b/docs/spec/04-ux/07-ui-design-system.md
index 52d246d08..5ad12b6d6 100644
--- a/docs/spec/04-ux/07-ui-design-system.md
+++ b/docs/spec/04-ux/07-ui-design-system.md
@@ -724,6 +724,18 @@ CSS custom properties on `:root` (D146):
Interactive surfaces should reference these variables instead of hard-coded
millisecond literals when practical.
+One duration sits outside this scale, and only one:
+
+| Token | CSS variable | Duration | Usage |
+|---|---|---|---|
+| `startup-reveal` | `--motion-startup-reveal` | 1000ms | Boot-animation reveal only (§8.3.1, D679) |
+
+The scale above is sized for in-flow UI feedback — a control answering a
+click. The reveal is the end of a cinematic the user supplied, so it is sized
+in that register instead. It is used by `.startup-animation` and nothing else,
+and it must stay matched to `STARTUP_ANIMATION_REVEAL_MS` in
+`@pi-desktop/shared`. New surfaces do not reference it.
+
### 8.2 Easing
CSS custom properties on `:root` (D146):
@@ -763,6 +775,32 @@ plain status text:
This is boot-state feedback, not decorative chrome.
+#### 8.3.1 User-supplied startup animation (D679 / ADR 0338)
+
+A video in `<dataDir>/startup/` replaces the splash above for that launch
+(`StartupAnimation`, `data-testid="startup-animation"`). Without such a file
+the splash is unchanged, which is what every existing installation gets.
+
+- One layer, opaque `#000` for its whole life: the video sits on it, and once
+ the video is gone the same black is the mask the shell fades in from, so there
+ is no seam between the last frame and the mask. Literal black rather than
+ `--ds-bg-primary` so a video's own letterboxing and fades meet the same colour
+ under either theme.
+- `object-fit: cover`; the frame is filled and the edges are cropped, so the
+ settings copy tells the user to keep the subject centred.
+- The element is inert and silent: `muted`, `playsInline`, no controls, no
+ picture-in-picture, not focusable, `aria-hidden`. Accessible status copy comes
+ from `app.starting`, as the splash's does.
+- Sequence: play → opaque black hold until `ready` → `--motion-startup-reveal`
+ (1000ms) opacity fade with `pointer-events: none`, so the shell takes input
+ for the whole fade rather than after it.
+- A hold longer than 3s adds the splash's indeterminate bar, so an opaque mask
+ is not mistaken for a hang.
+- Reduced motion does not play it at all — a shorter cinematic is still a
+ cinematic, and the OS request is the opt-out.
+- Unlike the glass splash, this surface is opaque, so it needs no macOS rule
+ hiding the mounted shell beneath it.
+
### 8.4 Overlay / floating surface enter
Dialogs, search spotlight, and modal backdrops use shared enter keyframes:
diff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.md
index 7a75caa64..46e3671e9 100644
--- a/docs/spec/04-ux/09-interaction-patterns.md
+++ b/docs/spec/04-ux/09-interaction-patterns.md
@@ -723,6 +723,42 @@ may be retained while exactly one workspace supplies the visible shell context.
writes naming an unknown action are rejected by both the renderer and
Electron Main.
+### 1.12 User-supplied startup animation (D679, ADR 0338)
+
+- A video in `<dataDir>/startup/` becomes the boot surface for that launch,
+ replacing the brand splash. An installation without that directory is
+ unchanged: same splash, same 420ms dwell, same 280ms fade.
+- The sequence is **play → black → reveal**. The video plays over opaque black
+ (`#000`, `object-fit: cover`, muted, no controls, not focusable); when it
+ ends, the same black layer stays as an opaque mask; once the shell has its
+ initial state, that mask fades out over 1000ms
+ (`--motion-startup-reveal`). The reveal waits for both the video and the
+ shell, so it never lands on a half-built window.
+- The mask stops taking input the moment the fade starts, so the shell, its
+ chrome, and the renderer-drawn window controls are operable for the whole
+ second rather than after it.
+- A boot that outlasts the video shows the splash's indeterminate bar after 3s
+ of black, so an opaque mask is not mistaken for a hang.
+- Four bounds end the animation, and each runs the same reveal: no first frame
+ within 2s, 15s of total playback, a `<video>` `error`, or `Escape`. The
+ startup watchdog's bounds are unchanged and outrank it — at 30s the boot
+ surface gains logs and diagnostics, and at 180s the recovery surface replaces
+ the animation, so a stalled launch is never left behind the mask.
+- Exactly one boot surface is mounted, ranked recovery > animation > brand
+ splash.
+- The animation plays once per launch, for the first window of the process:
+ reopening from the tray or the Dock replays nothing, and a renderer reload
+ does not replay it.
+- Settings → General → Appearance carries the switch (absent means on, so
+ dropping a file in is enough), a `skipWhenReady` sub-switch gated by it
+ (absent plays the video out), a status line naming the file the next launch
+ would play — or saying none was found — and an action that opens the folder,
+ creating it if needed. Both preferences are read before the window is
+ created, so a change applies on the next launch.
+- Discovery is deterministic: `webm` > `mp4` > `m4v` > `mov`, file name as the
+ tie-break, with dot-prefixed entries, non-files, empty files, files over
+ 64 MB, and anything that resolves outside the directory excluded.
+
## 2. Streaming message behavior
### 2.1 Token rendering
@@ -1780,6 +1816,7 @@ This does not prevent state changes — it makes them instant.
| Tool card expand/collapse | 200ms transition | instant toggle |
| Hover state transition | 150ms background change | instant color change |
| Startup splash | Brand splash + progress, min dwell then fade out | Instant static splash, no bar motion, instant reveal |
+| Startup animation (D679) | User's video, then a black mask, then a 1000ms reveal | Not played at all; the brand splash's reduced-motion path is used |
| Dialog / search enter | overlay-in + surface-in via motion tokens | Near-zero duration enter |
| Scroll-to-bottom button fade-in | 150ms opacity | instant appear |
| Toast slide-in | 200ms slide | instant appear |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index cfb1086fb..0d7e3406f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -7067,7 +7067,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- Escape and outside click dismiss the menu without creating anything.
#### E2E-076: Startup splash appears then yields to the main shell
-- **Status**: Partially automated (`startup-splash-motion.test.mjs` covers splash markup, motion tokens, reduced-motion, and catalog keys; `macos-sidebar-vibrancy.test.mjs` covers the darwin glass splash and shell cross-fade; full window timing remains Draft)
+- **Status**: Partially automated (`startup-splash-motion.test.mjs` covers splash markup, motion tokens, reduced-motion, and catalog keys; `macos-sidebar-vibrancy.test.mjs` covers the darwin glass splash and shell cross-fade; `startup-animation.test.mjs` and `packages/shared/src/startup-animation.test.ts` cover the D679 animation's bounds, phase machine, discovery, surface, and boot-surface ranking; `pnpm test:e2e:startup-animation` boots the real app against a generated video and asserts `pi-startup:` decoding, advancing playback, the reveal, and that an unplayable file still yields the shell; full window timing remains Draft)
- **Priority**: P1
- **Covers**: A, Quality / US-UI shell polish
- **Preconditions**: App launch path available (dev or packaged).
@@ -7078,11 +7078,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
4. Repeat with OS `prefers-reduced-motion: reduce` when available.
5. On macOS, compare the splash surface with the sidebar glass after the shell appears.
6. Repeat with `bootstrap` held unanswered past the watchdog bounds, and observe the boot surface at 30s and after 180s (issue #831).
+ 7. Drop a short playable video into `<dataDir>/startup/` and relaunch (D679).
+ 8. Replace it with an unplayable file (for example a renamed text file) and relaunch.
+ 9. With the animation present, relaunch under `prefers-reduced-motion: reduce`, then reload the renderer, then close the window and reopen it from the tray or Dock.
- **Expected**:
- Before ready: full-window splash with brand mark, shell name, tagline, and accessible starting status (`data-testid="startup-splash"`).
- After ready: splash exits with a short fade (or instantly under reduced motion) and the main shell (or settings page) is interactive underneath.
- If the initial state never arrives, the splash is replaced rather than held: the boot surface gains logs, diagnostics, and quit at 30s (`STARTUP_SLOW_HINT_MS`) without reporting a failure, and at 180s (`STARTUP_STALLED_MS`) becomes the recovery surface, which also offers a retry (`data-testid="startup-recovery"`); every action works without a backend, the renderer-drawn window controls stay above the surface on Windows/Linux, and quit goes through `pi-desktop/app/quit`.
- On macOS the splash uses the same glass tint and sheen as the sidebar over native `sidebar` vibrancy; the mounted shell stays hidden until the splash exit fade, then cross-fades in. Other platforms keep the opaque `--ds-bg-primary` fill.
+ - With a video in `<dataDir>/startup/` (D679): `data-testid="startup-animation"` replaces the splash in the first painted frame, plays over opaque black with no controls and no audio, then holds the same black until bootstrap finishes, then fades out over about a second with the shell already clickable during the fade. A boot slower than the video shows an indeterminate bar after 3s of black. `Escape` jumps straight to that fade.
+ - An unplayable file never holds the launch: the animation ends within 2s (no first frame) or on `error`, and the reveal runs exactly as it does after a clean finish.
+ - The animation is not played under reduced motion, on a renderer reload, or on a window reopened from the tray or Dock; the brand splash is used instead. Settings → General → Appearance names the resolved file, offers the folder, and applies a toggled switch on the next launch only.
+ - A boot held past the watchdog bounds replaces the animation with the recovery surface — it is never left behind the opaque mask.
- No plain unbranded “Starting…” centered text as the only boot UI.
- Overlay/dialog enter motion uses shared tokens; reduced motion keeps state changes without decorative duration.
- If a non-settings bootstrap request fails while the settings read is still
@@ -7090,7 +7097,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
settings request itself fails, the active section shows a loading/failure
state and retry action rather than a blank content pane; retrying after the
local service recovers restores the controls without leaving Settings.
-- **Specs linked**: `04-ux/07-ui-design-system.md` §8, `04-ux/02-i18n-english-first.md`, decisions-log D146 / D304 / D348
+- **Specs linked**: `04-ux/07-ui-design-system.md` §8, `04-ux/02-i18n-english-first.md`, `04-ux/09-interaction-patterns.md` §1.12, ADR 0338, decisions-log D146 / D304 / D348 / D679
- **Acceptance**: A (app startup), Quality
- **Milestone**: M5
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index a67792c37..c6701e9f4 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -8101,3 +8101,50 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
check `pnpm test:e2e:radial-menu`, and capture scenes `pi-radial` /
`pi-radial-dark`. See `04-ux/09-interaction-patterns.md` §1.11 and
E2E-CHAT-radial-background-menu.
+
+## 2026-11-03 — User-supplied startup animation (D679)
+
+- D679 lets a user own the boot surface. A video in `<dataDir>/startup/`
+ replaces the brand splash for that launch: it plays to its last frame, holds
+ the window under the same opaque black it played on until the shell has its
+ initial state, then fades that black out over 1000ms
+ (`--motion-startup-reveal`, the one duration outside the motion ramp). The
+ mask stops taking input when the fade starts, so the shell and its window
+ controls are operable for the whole second.
+- Discovery is filesystem-only and creates nothing: entries are confined to
+ the directory by realpath, ranked `webm` > `mp4` > `m4v` > `mov` with file
+ name as the tie-break, and dot-prefixed, non-file, empty, or over-64 MB
+ entries drop out. An installation with no such directory is unchanged — same
+ splash, same dwell, same watchdog bounds.
+- The bytes are served over `pi-startup://animation`, a host-owned scheme with
+ one pathless URL (`standard`, `secure`, `stream`, no CORS) reserved in the
+ single `registerSchemesAsPrivileged` call; `media-src pi-startup:` is the only
+ CSP change. No filesystem path reaches the renderer. The descriptor arrives
+ as a window creation argument, like the display locale, so it is readable
+ before the first paint.
+- Three bounds keep the surface recoverable, each below the next: first frame
+ 2s, whole animation 15s, and the watchdog's stalled bound 180s. `Escape`
+ skips. Every end — clean, error, timeout, skip — runs the same reveal.
+- Exactly one boot surface is mounted, ranked recovery > animation > brand
+ splash. The animation plays once per launch for the process's first window
+ (a tray or Dock reopen replays nothing; `sessionStorage` blocks a reload
+ replay), is dropped entirely under `prefers-reduced-motion: reduce`, and is
+ skipped under `PI_DESKTOP_CAPTURE=1`.
+- `AppSettings.startupAnimation` holds the two choices discovery cannot make:
+ `enabled` (absent means on) and `skipWhenReady` (absent plays it out). Both
+ are read before the window is created, so a change lands on the next launch.
+ General → Appearance gains the switch, the gated `skipWhenReady` switch, a
+ status line naming the file the next launch would play, and an action that
+ opens and creates the folder.
+- Not changed: the brand splash, its 420ms dwell and 280ms fade, the watchdog
+ bounds and recovery surface, window creation options, and plugin contracts.
+ Plugin-contributed animations are explicitly out of scope — that hands an
+ untrusted source the first paint and needs its own ADR.
+- Covered by `packages/shared/src/startup-animation.test.ts` and
+ `apps/desktop/test/startup-animation.test.mjs`. See ADR 0338,
+ `04-ux/09-interaction-patterns.md` §1.12 and E2E-076.
+- `pnpm test:e2e:startup-animation` boots the real app against a generated
+ VP9 clip and asserts what no source check can: Chromium decodes bytes served
+ over `pi-startup:` under the page CSP, playback advances, the reveal hands
+ over an interactive shell, and an unplayable file yields the shell in about a
+ second rather than holding the window.
diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.md
index c2db6b7f7..49b9d997a 100644
--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md
+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md
@@ -75,6 +75,13 @@
渲染器在根元素设置 `--font-scale`,全部 `--text-*` 阶和共享 Lucide 图标
按比例缩放,无需重载。窗口放大/缩小/重置仍独立。界面不出现 px 输入
(D343 / ADR 0180)
+ - **启动动画**(D679 / ADR 0338):一个总开关,外加受其管辖的**就绪后提前结束**
+ 子开关。动画本身是文件而不是取值,因此该行的另一项职责是让文件夹可被找到:它的
+ 详情行说明下次启动将播放哪个视频(或提示未找到),并带上打开
+ `<dataDir>/startup/` 的动作(必要时顺手创建)。两个偏好都持久化在
+ `AppSettings.startupAnimation` 下(`enabled` 缺省为开,所以放进文件即可;
+ `skipWhenReady` 缺省会把视频播完),并且在创建主窗口之前读取,因此与上面那行一样
+ 在下次启动生效。状态每次打开都重新扫描,因为刚放进文件的用户还没重启。
- **自动语言检测**通过主进程解析操作系统区域设置
(`app.getLocale()`) 而不是渲染器的 `navigator.language`,并且
「跟随系统」选项内嵌显示检测到的语言(例如“当前:简体中文”)
diff --git a/docs/zh-CN/spec/04-ux/07-ui-design-system.md b/docs/zh-CN/spec/04-ux/07-ui-design-system.md
index 49ffc124f..2852ce780 100644
--- a/docs/zh-CN/spec/04-ux/07-ui-design-system.md
+++ b/docs/zh-CN/spec/04-ux/07-ui-design-system.md
@@ -639,6 +639,16 @@ D419。主题专属取值应写在 `styles/tokens.css` 的标记块里,两套
交互式表面应该引用这些变量而不是硬编码
实用时为毫秒文字。
+有且只有一个时长在该梯度之外:
+
+| 令牌 | CSS 变量 | 时长 | 用途 |
+|---|---|---|---|
+| `startup-reveal` | `--motion-startup-reveal` | 1000毫秒 | 仅用于启动动画的渐显(第 8.3.1 节,D679) |
+
+上面的梯度是按「控件回应一次点击」这种界面内反馈来定尺的。渐显是用户自备影片的收尾,
+因此按另一种语境定尺。它只被 `.startup-animation` 使用,且必须与
+`@pi-desktop/shared` 中的 `STARTUP_ANIMATION_REVEAL_MS` 保持一致。新界面不引用它。
+
### 8. 2 宽松
`:root` (D146) 上的 CSS 自定义属性:
@@ -674,6 +684,25 @@ D419。主题专属取值应写在 `styles/tokens.css` 的标记块里,两套
这是启动状态反馈,而不是装饰性镀铬。
+#### 8.3.1 用户自备启动动画(D679 / ADR 0338)
+
+`<dataDir>/startup/` 中的视频会替代上面的启动画面(`StartupAnimation`、
+`data-testid="startup-animation"`)。没有该文件时启动画面完全不变,这也是每个既有
+安装得到的结果。
+
+- 只有一层,全程不透明 `#000`:视频叠在它上面,视频消失后同一层黑色就是外壳渐显所
+ 依托的遮罩,因此最后一帧与遮罩之间没有缝。用字面黑而不是 `--ds-bg-primary`,这样
+ 视频自带的黑边与淡入淡出在两种主题下都能对上同一个颜色。
+- `object-fit: cover`;画面铺满、边缘被裁,因此设置文案提示用户让主体居中。
+- 元素是惰性且静音的:`muted`、`playsInline`、无控件、无画中画、不可聚焦、
+ `aria-hidden`。可访问状态文案与启动画面一样来自 `app.starting`。
+- 时序:播放 → 不透明黑幕直到 `ready` → `--motion-startup-reveal`(1000毫秒)
+ 不透明度淡出,期间 `pointer-events: none`,所以外壳在整段淡出中都能接收输入,而不是
+ 等淡出结束。
+- 黑幕超过 3 秒会加上启动画面那条不确定进度条,避免把不透明遮罩误读成卡死。
+- 减少运动下完全不播放——缩短的影片仍然是影片,而操作系统的这项请求本身就是退出口。
+- 与玻璃态启动画面不同,这一层是不透明的,因此不需要 macOS 上那条隐藏其下外壳的规则。
+
### 8. 4 覆盖/浮动表面输入
对话框、搜索聚光灯和模态背景使用共享输入关键帧:
diff --git a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
index 83f782fc7..d6ec243cb 100644
--- a/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
+++ b/docs/zh-CN/spec/04-ux/09-interaction-patterns.md
@@ -519,6 +519,31 @@
右:全选对话文本;下:回到最新;左:跳到顶部)。写入未知动作会被渲染器和 Electron
Main 两侧拒绝。
+### 1. 12 用户自备启动动画(D679、ADR 0338)
+
+- `<dataDir>/startup/` 中的视频会成为该次启动的启动界面,替代品牌启动画面。没有该
+ 目录的安装行为不变:同样的启动画面、同样的 420ms 最短停留、同样的 280ms 淡出。
+- 时序是**播放 → 黑幕 → 渐显**。视频在不透明黑底上播放(`#000`、
+ `object-fit: cover`、静音、无控件、不可聚焦);播放结束后同一层黑色继续作为不透明
+ 遮罩;外壳拿到首批状态后,该遮罩在 1000ms 内淡出(`--motion-startup-reveal`)。
+ 渐显同时等待视频与外壳两件事,因此绝不会落在一个只构建了一半的窗口上。
+- 淡出一开始遮罩就不再接收事件,所以主界面、其窗口装饰以及渲染器自绘的窗口控件在整
+ 整一秒里都可操作,而不是等淡出结束才可用。
+- 启动比视频更慢时,黑幕满 3s 后显示启动画面那条不确定进度条,避免把不透明遮罩误读
+ 成卡死。
+- 有四个边界会结束动画,并且都走同一套渐显:2s 内没有首帧、总播放 15s、`<video>`
+ 触发 `error`,以及按下 `Escape`。启动看门狗的边界不变且优先级更高——30s 时启动界面
+ 获得日志与诊断,180s 时恢复界面取代动画,因此卡死的启动绝不会被留在遮罩后面。
+- 任何时刻只挂载一个启动界面,优先级为 恢复界面 > 启动动画 > 品牌启动画面。
+- 动画每次启动只播一次,且只给进程的第一个窗口:从托盘或 Dock 重新打开不会重播,渲
+ 染器重载也不会重播。
+- 设置 → 常规 → 外观 提供总开关(缺省为开,所以放进文件即可生效)、受其管辖的
+ `skipWhenReady` 子开关(缺省会把视频播完)、一行说明下次启动将播放哪个文件(或提示
+ 未找到),以及一个打开该文件夹的动作(必要时创建)。两个偏好都在创建窗口之前读取,
+ 因此改动在下次启动生效。
+- 选片是确定性的:`webm` > `mp4` > `m4v` > `mov`,同类按文件名排序决定;点号开头的
+ 条目、非普通文件、空文件、超过 64 MB 的文件,以及解析后落在目录之外的条目都会排除。
+
## 2. 流消息行为
### 2. 1 Token渲染
@@ -1218,6 +1243,7 @@ Mode/provider/model/permission/shell 配置和新提示仍然存在
| 工具卡 expand/collapse | 200ms 过渡 | 即时切换 |
| 悬停状态转换 | 150ms背景变化 | 瞬间变色 |
| 启动水花 | 品牌启动 + 进度,最短停留时间然后淡出 | 即时静态飞溅,无条形运动,即时显示 |
+| 启动动画(D679) | 用户视频,随后黑色遮罩,再 1000ms 渐显 | 完全不播放;改走品牌启动画面的减少运动路径 |
| 对话框/搜索输入 | 通过运动令牌覆盖-in + 表面-in | 接近零持续时间输入 |
| 滚动到底部按钮淡入 | 150ms 不透明度 | 即时出现 |
| Toast滑入式 | 200毫秒幻灯片 | 即时出现 |
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 252d0d742..f06c35687 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -3683,7 +3683,7 @@ IPC 请求无法关闭。
- 退出并外部单击关闭菜单而不创建任何内容。
#### E2E-076:出现启动画面,然后返回主 shell
-- **状态**:部分自动化(`startup-splash-motion.test.mjs` 涵盖启动标记、运动标记、简化运动和目录键;`macos-sidebar-vibrancy.test.mjs` 覆盖 darwin 玻璃启动页与 shell 交叉淡入;全窗口计时仍为草稿)
+- **状态**:部分自动化(`startup-splash-motion.test.mjs` 涵盖启动标记、运动标记、简化运动和目录键;`macos-sidebar-vibrancy.test.mjs` 覆盖 darwin 玻璃启动页与 shell 交叉淡入;`startup-animation.test.mjs` 与 `packages/shared/src/startup-animation.test.ts` 覆盖 D679 动画的边界、状态机、选片、界面与启动界面优先级;`pnpm test:e2e:startup-animation` 用生成的视频启动真实应用,断言 `pi-startup:` 解码、播放推进、渐显,以及不可播放文件仍会交出主界面;全窗口计时仍为草稿)
- **优先级**:P1
- **封面**:A,品质/US-UI 外壳抛光
- **先决条件**:应用程序启动路径可用(开发或打包)。
@@ -3694,14 +3694,21 @@ IPC 请求无法关闭。
4. 如果可用,请对 OS `prefers-reduced-motion: reduce` 重复此操作。
5. 在 macOS 上,将启动面与 shell 出现后的侧边栏玻璃态对比。
6. 在 `bootstrap` 一直被搁置、超过看门狗界限时重复一次,在 30 秒与超过 180 秒时观察启动表面(issue #831)。
+ 7. 把一个可播放的短视频放进 `<dataDir>/startup/` 后重新启动(D679)。
+ 8. 换成不可播放的文件(例如改名的文本文件)后重新启动。
+ 9. 保留该动画,分别在 `prefers-reduced-motion: reduce` 下启动、重载渲染器、以及关闭窗口后从托盘或 Dock 重新打开。
- **预期**:
- 准备之前:带有品牌标志、外壳名称、标语和可访问的启动状态 (`data-testid="startup-splash"`) 的全窗口启动画面。
- 准备好后:启动画面会短暂淡出(或立即减少运动)退出,并且主外壳(或设置页面)在下面是交互式的。
- 如果初始状态始终没有到达,启动画面不是被一直保留而是被替换:启动表面在 30 秒(`STARTUP_SLOW_HINT_MS`)时加上日志、诊断与退出且不报告失败,在 180 秒(`STARTUP_STALLED_MS`)时变成恢复表面,并额外提供重试(`data-testid="startup-recovery"`);每个操作都不依赖后端,Windows/Linux 上渲染器绘制的窗口控制按钮保持在该表面之上,退出走 `pi-desktop/app/quit`。
- macOS 上启动页与侧边栏使用同一套玻璃 tint/sheen,叠在原生 `sidebar` vibrancy 之上;已挂载的 shell 在退出淡出前保持隐藏,再交叉淡入。其他平台仍为不透明的 `--ds-bg-primary`。
+ - `<dataDir>/startup/` 中有视频时(D679):首个绘制帧里 `data-testid="startup-animation"` 取代启动画面,在不透明黑底上播放,无控件无声音,播完后同一层黑色继续遮住窗口直到引导完成,然后在约一秒内淡出,淡出期间主界面已可点击。启动比视频慢时,黑幕满 3 秒后出现不确定进度条。`Escape` 直接跳到该淡出。
+ - 不可播放的文件绝不会劫持启动:动画在 2 秒内(无首帧)或 `error` 时结束,渐显与正常播完完全一致。
+ - 减少运动、渲染器重载,以及从托盘或 Dock 重新打开的窗口都不播放动画,改用品牌启动画面。设置 → 常规 → 外观 会显示选中的文件、提供打开文件夹的动作,开关改动只在下次启动生效。
+ - 启动被搁置超过看门狗边界时,恢复界面取代动画——绝不会被留在不透明遮罩后面。
- 没有简单的无品牌“开始...”居中文本作为唯一的启动 UI。
- Overlay/dialog 输入动作使用共享令牌;减少的运动可以保持状态变化,而无需装饰持续时间。
-- **链接规格**:`04-ux/07-ui-design-system.md` §8、`04-ux/02-i18n-english-first.md`、决策日志 D146 / D304 / D348
+- **链接规格**:`04-ux/07-ui-design-system.md` §8、`04-ux/02-i18n-english-first.md`、`04-ux/09-interaction-patterns.md` 第 1.12 节、ADR 0338、决策日志 D146 / D304 / D348 / D679
- **验收**:A(应用程序启动),质量
- **里程碑**:M5
#### E2E-099:品牌标志遵循活跃主题
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 82ef77ee8..acc04f3ee 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -5653,3 +5653,38 @@ Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编
- 由 `apps/desktop/test/radial-menu.test.mjs`、Chromium 组件检查
`pnpm test:e2e:radial-menu`,以及截图场景 `pi-radial`、`pi-radial-dark` 覆盖。见
`04-ux/09-interaction-patterns.md` 第 1.11 节与 E2E-CHAT-radial-background-menu。
+
+## 2026-11-03 — 用户自备启动动画(D679)
+
+- D679 把启动界面交给用户。`<dataDir>/startup/` 中的视频会替代该次启动的品牌启动
+ 画面:先播到最后一帧,再用播放时那同一层不透明黑色遮住窗口,直到外壳拿到首批状态,
+ 然后在 1000ms 内把黑色淡出(`--motion-startup-reveal`,运动梯度之外唯一的时长)。
+ 淡出一开始遮罩就不再接收事件,所以主界面与窗口控件在整整一秒里都可操作。
+- 选片只读文件系统且不创建任何目录:条目按 realpath 限制在该目录内,排序为
+ `webm` > `mp4` > `m4v` > `mov`,同类按文件名决定;点号开头、非普通文件、空文件以及
+ 超过 64 MB 的条目都会排除。没有该目录的安装行为不变——同样的启动画面、同样的最短
+ 停留、同样的看门狗边界。
+- 字节通过 `pi-startup://animation` 提供:host 自有协议,只有一个不带路径的 URL
+ (`standard`、`secure`、`stream`,不开 CORS),在唯一一次
+ `registerSchemesAsPrivileged` 调用中注册;CSP 只新增 `media-src pi-startup:`。没有
+ 任何文件系统路径到达渲染器。描述符随窗口创建参数传递(与界面语言同一机制),因此首帧
+ 之前就可同步读取。
+- 三个边界让界面始终可恢复,且逐级小于下一级:首帧 2s、整段动画 15s、看门狗的卡死边界
+ 180s。`Escape` 可跳过。无论正常结束、出错、超时还是跳过,都走同一套渐显。
+- 任何时刻只挂载一个启动界面,优先级为 恢复界面 > 启动动画 > 品牌启动画面。动画每次
+ 启动只播一次,且只给进程的第一个窗口(托盘或 Dock 重新打开不重播;`sessionStorage`
+ 阻止重载重播);`prefers-reduced-motion: reduce` 下完全不播放;
+ `PI_DESKTOP_CAPTURE=1` 下直接跳过。
+- `AppSettings.startupAnimation` 只存选片无法决定的两个选择:`enabled`(缺省为开)和
+ `skipWhenReady`(缺省把视频播完)。两者都在创建窗口之前读取,因此改动在下次启动生效。
+ 常规 → 外观 新增该开关、受其管辖的 `skipWhenReady` 开关、一行说明下次启动将播放哪个
+ 文件,以及一个打开并创建该文件夹的动作。
+- 未改动:品牌启动画面及其 420ms 停留与 280ms 淡出、看门狗边界与恢复界面、窗口创建
+ 选项、插件契约。插件提供启动动画明确不在范围内——那等于把首帧交给不可信来源,需要
+ 单独立 ADR。
+- 由 `packages/shared/src/startup-animation.test.ts` 与
+ `apps/desktop/test/startup-animation.test.mjs` 覆盖。见 ADR 0338、
+ `04-ux/09-interaction-patterns.md` 第 1.12 节与 E2E-076。
+- `pnpm test:e2e:startup-animation` 用生成的 VP9 片段启动真实应用,断言源码检查无法
+ 覆盖的部分:Chromium 能在页面 CSP 下解码经 `pi-startup:` 提供的字节、播放会推进、
+ 渐显会交出可交互的主界面,以及不可播放的文件会在约一秒内交出主界面而不是占住窗口。
diff --git a/package.json b/package.json
index 1a848febc..509c3ea7b 100644
--- a/package.json
+++ b/package.json
@@ -60,6 +60,7 @@
"test:e2e:hosted-search": "node scripts/e2e-hosted-search.mjs",
"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs",
"test:e2e:boot": "node scripts/e2e-electron-boot.mjs",
+ "test:e2e:startup-animation": "node scripts/e2e-startup-animation.mjs",
"test:e2e:todos": "node scripts/e2e-todo-checklist.mjs",
"test:e2e:provider-model-layout": "node scripts/e2e-provider-model-layout.mjs",
"test:e2e:settings-scroll": "node scripts/e2e-settings-scroll.mjs",
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 34e530f7a..07d3f3ddc 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1506,6 +1506,12 @@ sklm: {
"windowTranslucency": "Transparentes Fenster",
"windowTranslucencyDesc": "Hält das macOS-Fenster über der Unschärfe des Schreibtischs transparent; das ist die Voreinstellung. Kostet mehr GPU, solange das Fenster sichtbar ist; für die geringste Leerlauflast ausschalten. Die Änderung greift nach einem Neustart.",
"windowTranslucencyRestart": "Zum Anwenden neu starten",
+ "startupAnimation": "Startanimation",
+ "startupAnimationDesc": "Spielt beim Start ein eigenes Video anstelle des Marken-Startbildschirms. Legen Sie ein Video in den Ordner „startup“; es füllt das Fenster aus, halten Sie das Motiv daher zentriert. Mit Escape überspringen. Wird beim nächsten Start angewendet.",
+ "startupAnimationNone": "Kein Video gefunden",
+ "startupAnimationFolder": "Ordner „startup“ öffnen",
+ "startupAnimationSkipWhenReady": "Bei Bereitschaft früher beenden",
+ "startupAnimationSkipWhenReadyDesc": "Beendet die Animation, sobald die App fertig gestartet ist, anstatt sie bis zum letzten Bild abzuspielen.",
"linkOpenTarget": "Ziel für Link-Öffnung",
"linkOpenTargetWorkpanel": "Arbeitsbereich-Browser",
"linkOpenTargetExternal": "Standard-Betriebssystem-Browser",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 789ab662a..615a82399 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1520,6 +1520,12 @@ sklm: {
windowTranslucency: "Translucent window",
windowTranslucencyDesc: "Keep the macOS window translucent over the desktop blur, which is the default. It costs more GPU while the window is visible; turn it off for an opaque window with the lowest idle load. A change applies after a restart.",
windowTranslucencyRestart: "Restart to apply",
+ startupAnimation: "Startup animation",
+ startupAnimationDesc: "Play your own video while the app starts, instead of the brand splash. Drop one video into the startup folder; it fills the window, so keep the subject centred. Press Escape to skip it. Takes effect on the next launch.",
+ startupAnimationNone: "No video found",
+ startupAnimationFolder: "Open startup folder",
+ startupAnimationSkipWhenReady: "End early when ready",
+ startupAnimationSkipWhenReadyDesc: "Cut the animation short as soon as the app has finished starting, instead of letting it play to the last frame.",
linkOpenTarget: "Link open destination",
linkOpenTargetWorkpanel: "Work panel browser",
linkOpenTargetExternal: "Default OS browser",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 16164263b..364aaa259 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1506,6 +1506,12 @@ sklm: {
"windowTranslucency": "Ventana translúcida",
"windowTranslucencyDesc": "Mantiene la ventana de macOS translúcida sobre el desenfoque del escritorio; es el valor predeterminado. Usa más GPU mientras la ventana está visible; desactívalo para una ventana opaca con la menor carga en reposo. El cambio se aplica tras reiniciar.",
"windowTranslucencyRestart": "Reinicia para aplicar",
+ "startupAnimation": "Animación de inicio",
+ "startupAnimationDesc": "Reproduce tu propio vídeo durante el inicio, en lugar de la pantalla de bienvenida. Coloca un vídeo en la carpeta «startup»; llena la ventana, así que mantén el motivo centrado. Pulsa Escape para omitirla. Se aplica en el próximo inicio.",
+ "startupAnimationNone": "No se encontró ningún vídeo",
+ "startupAnimationFolder": "Abrir la carpeta «startup»",
+ "startupAnimationSkipWhenReady": "Terminar antes cuando esté lista",
+ "startupAnimationSkipWhenReadyDesc": "Corta la animación en cuanto la aplicación termina de iniciarse, en lugar de dejarla llegar al último fotograma.",
"linkOpenTarget": "Destino al abrir enlaces",
"linkOpenTargetWorkpanel": "Navegador del panel de trabajo",
"linkOpenTargetExternal": "Navegador predeterminado del sistema",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index b7691e6da..9f6c303e5 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1506,6 +1506,12 @@ sklm: {
"windowTranslucency": "Fenêtre translucide",
"windowTranslucencyDesc": "Garde la fenêtre macOS translucide sur le flou du bureau ; c'est le réglage par défaut. Consomme plus de GPU tant que la fenêtre est visible ; désactivez pour une fenêtre opaque et une charge au repos minimale. Le changement s'applique après un redémarrage.",
"windowTranslucencyRestart": "Redémarrer pour appliquer",
+ "startupAnimation": "Animation de démarrage",
+ "startupAnimationDesc": "Lit votre propre vidéo au démarrage, à la place de l'écran de lancement. Déposez une vidéo dans le dossier « startup » ; elle remplit la fenêtre, gardez donc le sujet centré. Appuyez sur Échap pour la passer. Prend effet au prochain démarrage.",
+ "startupAnimationNone": "Aucune vidéo trouvée",
+ "startupAnimationFolder": "Ouvrir le dossier « startup »",
+ "startupAnimationSkipWhenReady": "Terminer dès que l'app est prête",
+ "startupAnimationSkipWhenReadyDesc": "Interrompt l'animation dès que l'application a fini de démarrer, au lieu de la laisser aller jusqu'à la dernière image.",
"linkOpenTarget": "Destination d'ouverture des liens",
"linkOpenTargetWorkpanel": "Navigateur du panneau de travail",
"linkOpenTargetExternal": "Navigateur par défaut du système",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index f71e3aee0..62cb57500 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1516,6 +1516,12 @@ sklm: {
windowTranslucency: "반투명 창",
windowTranslucencyDesc: "macOS 창을 데스크톱 흐림 위에 반투명하게 유지합니다(기본값). 창이 보이는 동안 GPU를 더 사용하므로, 유휴 부하를 가장 낮추려면 끄세요. 변경 사항은 재시작 후 적용됩니다.",
windowTranslucencyRestart: "적용하려면 재시작",
+ startupAnimation: "시작 애니메이션",
+ startupAnimationDesc: "브랜드 스플래시 대신 앱이 시작되는 동안 직접 준비한 영상을 재생합니다. startup 폴더에 영상 하나를 넣으면 됩니다. 화면을 가득 채우므로 피사체를 가운데에 두세요. Escape 키로 건너뛸 수 있습니다. 다음 실행부터 적용됩니다.",
+ startupAnimationNone: "영상을 찾을 수 없음",
+ startupAnimationFolder: "startup 폴더 열기",
+ startupAnimationSkipWhenReady: "준비되면 일찍 종료",
+ startupAnimationSkipWhenReadyDesc: "영상을 마지막 프레임까지 재생하지 않고, 앱 시작이 끝나는 즉시 애니메이션을 중단합니다.",
linkOpenTarget: "링크 열기 위치",
linkOpenTargetWorkpanel: "작업 패널 브라우저",
linkOpenTargetExternal: "시스템 기본 브라우저",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 3e10fabf8..81a32b845 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1479,6 +1479,12 @@ export const ptBR = {
windowTranslucency: "Janela translúcida",
windowTranslucencyDesc: "Mantém a janela do macOS translúcida sobre o desfoque da área de trabalho, que é o padrão. Usa mais GPU enquanto a janela está visível; desative para uma janela opaca com a menor carga ociosa. A alteração vale após reiniciar.",
windowTranslucencyRestart: "Reiniciar para aplicar",
+ startupAnimation: "Animação de inicialização",
+ startupAnimationDesc: "Reproduz seu próprio vídeo durante a inicialização, em vez da tela de abertura da marca. Coloque um vídeo na pasta \"startup\"; ele preenche a janela, então mantenha o assunto centralizado. Pressione Escape para pular. Entra em vigor na próxima inicialização.",
+ startupAnimationNone: "Nenhum vídeo encontrado",
+ startupAnimationFolder: "Abrir a pasta \"startup\"",
+ startupAnimationSkipWhenReady: "Encerrar antes quando estiver pronto",
+ startupAnimationSkipWhenReadyDesc: "Interrompe a animação assim que o aplicativo termina de iniciar, em vez de deixá-la chegar ao último quadro.",
linkOpenTarget: "Destino ao abrir links",
linkOpenTargetWorkpanel: "Navegador do painel de trabalho",
linkOpenTargetExternal: "Navegador padrão do sistema",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 7a9f1319c..ec4f6b65c 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1510,6 +1510,12 @@ sklm: {
windowTranslucency: "Saydam pencere",
windowTranslucencyDesc: "macOS penceresini masaüstü bulanıklığı üzerinde saydam tutar; varsayılan budur. Pencere görünürken daha fazla GPU kullanır; en düşük boşta yük için kapatın. Değişiklik yeniden başlatmadan sonra uygulanır.",
windowTranslucencyRestart: "Uygulamak için yeniden başlatın",
+ startupAnimation: "Başlangıç animasyonu",
+ startupAnimationDesc: "Uygulama açılırken marka açılış ekranı yerine kendi videonuzu oynatır. \"startup\" klasörüne bir video bırakmanız yeterli; pencereyi tamamen doldurur, bu yüzden konuyu ortada tutun. Atlamak için Escape'e basın. Bir sonraki açılışta etkili olur.",
+ startupAnimationNone: "Video bulunamadı",
+ startupAnimationFolder: "\"startup\" klasörünü aç",
+ startupAnimationSkipWhenReady: "Hazır olunca erken bitir",
+ startupAnimationSkipWhenReadyDesc: "Animasyonu son kareye kadar oynatmak yerine, uygulamanın açılışı tamamlandığı anda kes.",
linkOpenTarget: "Bağlantı açma hedefi",
linkOpenTargetWorkpanel: "Çalışma paneli tarayıcısı",
linkOpenTargetExternal: "Varsayılan sistem tarayıcısı",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 7575052e8..6d72b69c5 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1500,6 +1500,12 @@ sklm: {
windowTranslucency: "窗口透明效果",
windowTranslucencyDesc: "让 macOS 窗口保持透明并显示桌面模糊背景(默认开启)。窗口可见时会占用更多 GPU;关闭后使用不透明窗口,空闲占用最低。修改后需重启生效。",
windowTranslucencyRestart: "重启后生效",
+ startupAnimation: "启动动画",
+ startupAnimationDesc: "启动时播放你自己的视频,替代品牌启动画面。把一个视频放进 startup 文件夹即可;画面会铺满窗口,请让主体居中。按 Escape 可跳过。下次启动生效。",
+ startupAnimationNone: "未找到视频",
+ startupAnimationFolder: "打开 startup 文件夹",
+ startupAnimationSkipWhenReady: "就绪后提前结束",
+ startupAnimationSkipWhenReadyDesc: "应用启动完成后立即结束动画,而不是等它播到最后一帧。",
linkOpenTarget: "链接打开位置",
linkOpenTargetWorkpanel: "工作区浏览器",
linkOpenTargetExternal: "系统默认浏览器",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 6615ea19d..4a5e77068 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1500,6 +1500,12 @@ sklm: {
windowTranslucency: "視窗透明效果",
windowTranslucencyDesc: "讓 macOS 視窗保持透明並顯示桌面模糊背景(預設開啟)。視窗可見時會佔用更多 GPU;關閉後使用不透明視窗,閒置佔用最低。修改後需重新啟動生效。",
windowTranslucencyRestart: "重新啟動後生效",
+ startupAnimation: "啟動動畫",
+ startupAnimationDesc: "啟動時播放你自己的影片,取代品牌啟動畫面。把一個影片放進 startup 資料夾即可;畫面會鋪滿視窗,請讓主體置中。按 Escape 可略過。下次啟動生效。",
+ startupAnimationNone: "找不到影片",
+ startupAnimationFolder: "開啟 startup 資料夾",
+ startupAnimationSkipWhenReady: "就緒後提前結束",
+ startupAnimationSkipWhenReadyDesc: "應用程式啟動完成後立即結束動畫,而不是等它播到最後一格。",
linkOpenTarget: "連結開啟位置",
linkOpenTargetWorkpanel: "工作區瀏覽器",
linkOpenTargetExternal: "系統預設瀏覽器",
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 5c6f01cbb..77c26450b 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -18,6 +18,10 @@
"types": "./dist/theme.d.ts",
"import": "./dist/theme.js"
},
+ "./startup-animation": {
+ "types": "./dist/startup-animation.d.ts",
+ "import": "./dist/startup-animation.js"
+ },
"./changelog-loader": {
"types": "./dist/changelog-loader.d.ts",
"import": "./dist/changelog-loader.js"
diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.ts
index 8f30e0dc9..42f698ced 100644
--- a/packages/shared/src/changelog-de.ts
+++ b/packages/shared/src/changelog-de.ts
@@ -5,6 +5,7 @@ export const deEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Eigenes Video als Startanimation verwenden: einfach eines in den Ordner „startup“ legen; danach wird die Oberfläche eingeblendet.",
"Plugins können gespeicherte Projekte und ihre Ordner auflisten, ohne die aktive Sitzung zu wechseln.",
"Die Pi-1.3.0-Engine verbessert die Validierung von Tool-Aufrufen und die sichere Wiedergabe des Verlaufs.",
"Optionale Inline-Visualisierungen unter Einstellungen → KI zeigen interaktive, isolierte Karten direkt im Gespräch.",
diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.ts
index 55e42dd70..9683a04fa 100644
--- a/packages/shared/src/changelog-en.ts
+++ b/packages/shared/src/changelog-en.ts
@@ -5,6 +5,7 @@ export const enEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Use your own video as the startup animation by dropping one into the startup folder; the interface fades in after it plays.",
"Let plugins list saved projects and their folders without switching the active session.",
"Use the Pi 1.3.0 agent engine with safer tool-call validation and replay.",
"Enable optional inline visualizations in Settings → AI to view interactive, sandboxed cards inside conversations.",
diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.ts
index beed843ba..378413af4 100644
--- a/packages/shared/src/changelog-es.ts
+++ b/packages/shared/src/changelog-es.ts
@@ -5,6 +5,7 @@ export const esEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Usa tu propio vídeo como animación de inicio: coloca uno en la carpeta «startup» y la interfaz aparece con un fundido al terminar.",
"Los plugins pueden listar los proyectos guardados y sus carpetas sin cambiar la sesión activa.",
"El motor Pi 1.3.0 mejora la validación de llamadas a herramientas y la reproducción segura del historial.",
"Activa las visualizaciones en línea opcionales en Ajustes → IA para ver tarjetas interactivas aisladas dentro de las conversaciones.",
diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.ts
index 2028ef42e..0990a9ab2 100644
--- a/packages/shared/src/changelog-fr.ts
+++ b/packages/shared/src/changelog-fr.ts
@@ -5,6 +5,7 @@ export const frEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Utilisez votre propre vidéo comme animation de démarrage : déposez-en une dans le dossier « startup » ; l’interface apparaît ensuite en fondu.",
"Les plugins peuvent lister les projets enregistrés et leurs dossiers sans changer de session active.",
"Le moteur Pi 1.3.0 améliore la validation des appels d’outils et la relecture sécurisée de l’historique.",
"Activez les visualisations intégrées facultatives dans Paramètres → IA pour afficher des cartes interactives isolées dans les conversations.",
diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.ts
index bc8dc0aa6..f72021b19 100644
--- a/packages/shared/src/changelog-ko.ts
+++ b/packages/shared/src/changelog-ko.ts
@@ -5,6 +5,7 @@ export const koEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "startup 폴더에 영상을 넣어 시작 애니메이션으로 사용하세요. 재생이 끝나면 화면이 서서히 나타납니다.",
"플러그인이 활성 세션을 전환하지 않고 저장된 프로젝트와 폴더를 나열할 수 있습니다.",
"Pi 1.3.0 엔진으로 업그레이드하여 도구 호출 검증과 기록 재생의 안전성을 개선했습니다.",
"설정 → AI에서 선택적 인라인 시각화를 켜면 대화 안에서 격리된 대화형 카드를 볼 수 있습니다.",
diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.ts
index a970ebb3a..97e808945 100644
--- a/packages/shared/src/changelog-pt-BR.ts
+++ b/packages/shared/src/changelog-pt-BR.ts
@@ -5,6 +5,7 @@ export const ptBREntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Use seu próprio vídeo como animação de inicialização: coloque um na pasta \"startup\" e a interface aparece com um fade ao terminar.",
"Plugins podem listar projetos salvos e suas pastas sem trocar a sessão ativa.",
"O motor Pi 1.3.0 melhora a validação de chamadas de ferramentas e a reprodução segura do histórico.",
"Ative as visualizações inline opcionais em Configurações → IA para ver cartões interativos isolados nas conversas.",
diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.ts
index 2e63db05b..3a8ec4782 100644
--- a/packages/shared/src/changelog-tr.ts
+++ b/packages/shared/src/changelog-tr.ts
@@ -5,6 +5,7 @@ export const trEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "Kendi videonuzu başlangıç animasyonu olarak kullanın: \"startup\" klasörüne bir video bırakın, oynatma bitince arayüz yavaşça belirir.",
"Eklentiler, etkin oturumu değiştirmeden kayıtlı projeleri ve klasörlerini listeleyebilir.",
"Daha güvenli araç çağrısı doğrulaması ve geçmiş yeniden oynatımı için Pi 1.3.0 motoruna geçin.",
"Konuşmalarda etkileşimli, korumalı kartlar görmek için Ayarlar → AI bölümünde isteğe bağlı satır içi görselleştirmeleri açın.",
diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.ts
index 01722a511..573064e86 100644
--- a/packages/shared/src/changelog-zh-CN.ts
+++ b/packages/shared/src/changelog-zh-CN.ts
@@ -5,6 +5,7 @@ export const zhCNEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "把视频放进 startup 文件夹即可当作启动动画;播放结束后主界面渐显。",
"插件可列出已保存的项目及其文件夹,无需切换当前会话。",
"升级至 Pi 1.3.0 引擎,改进工具调用校验与历史回放安全性。",
"可在设置 → AI 中启用内联可视化,在对话中查看交互式沙箱卡片。",
diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.ts
index db56c20b6..269eaea7a 100644
--- a/packages/shared/src/changelog-zh-TW.ts
+++ b/packages/shared/src/changelog-zh-TW.ts
@@ -5,6 +5,7 @@ export const zhTWEntries: ChangelogEntry[] = [
version: "0.21.0",
date: "2026-10-24",
highlights: [
+ "把影片放進 startup 資料夾即可當成啟動動畫;播放結束後主介面漸顯。",
"外掛可列出已儲存的專案及其資料夾,無須切換目前工作階段。",
"升級至 Pi 1.3.0 引擎,改善工具呼叫驗證與歷史重播安全性。",
"可在設定 → AI 中啟用行內視覺化,在對話中查看互動式沙箱卡片。",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 755903f8c..f19c7f853 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -62,6 +62,7 @@ export * from "./gen-ui.js";
export * from "./image-generation.js";
export * from "./font-size.js";
export * from "./chat-content-width.js";
+export * from "./startup-animation.js";
export * from "./radial-menu.js";
export * from "./racp.js";
export * from "./trusted-extensions.js";
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index ede945d38..bbdea6855 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -413,6 +413,8 @@ export const IPC = {
commandPaletteSearch: "pi-desktop/commandPalette/search",
commandPaletteExecute: "pi-desktop/commandPalette/execute",
logOpenFolder: "pi-desktop/log/openFolder",
+ startupAnimationStatus: "pi-desktop/startupAnimation/status",
+ startupAnimationOpenFolder: "pi-desktop/startupAnimation/openFolder",
devtoolsToggle: "pi-desktop/devtools/toggle",
composerPickFiles: "pi-desktop/composer/pickFiles",
composerPickPhotos: "pi-desktop/composer/pickPhotos",
diff --git a/packages/shared/src/startup-animation.test.ts b/packages/shared/src/startup-animation.test.ts
new file mode 100644
index 000000000..69527cb9d
--- /dev/null
+++ b/packages/shared/src/startup-animation.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from "vitest";
+import {
+ chooseStartupAnimation,
+ decodeStartupAnimationArgument,
+ encodeStartupAnimationArgument,
+ STARTUP_ANIMATION_ARGUMENT_PREFIX,
+ STARTUP_ANIMATION_EXTENSIONS,
+ STARTUP_ANIMATION_MAX_BYTES,
+ STARTUP_ANIMATION_MIME_TYPES,
+ startupAnimationExtensionOf,
+ type StartupAnimationDescriptor,
+} from "./startup-animation.js";
+
+describe("chooseStartupAnimation", () => {
+ it("returns nothing for an empty or unplayable directory", () => {
+ expect(chooseStartupAnimation([])).toBeNull();
+ expect(
+ chooseStartupAnimation([
+ { fileName: "readme.txt", byteLength: 10 },
+ { fileName: "poster.png", byteLength: 10 },
+ { fileName: "noextension", byteLength: 10 },
+ ]),
+ ).toBeNull();
+ });
+
+ it("prefers the container Chromium decodes in every build", () => {
+ const chosen = chooseStartupAnimation([
+ { fileName: "b.mp4", byteLength: 100 },
+ { fileName: "a.webm", byteLength: 100 },
+ { fileName: "c.mov", byteLength: 100 },
+ ]);
+ expect(chosen?.fileName).toBe("a.webm");
+ expect(chosen?.extension).toBe("webm");
+ });
+
+ it("breaks a tie inside one container by file name, not by directory order", () => {
+ const forward = chooseStartupAnimation([
+ { fileName: "b.mp4", byteLength: 1 },
+ { fileName: "a.mp4", byteLength: 1 },
+ ]);
+ const reversed = chooseStartupAnimation([
+ { fileName: "a.mp4", byteLength: 1 },
+ { fileName: "b.mp4", byteLength: 1 },
+ ]);
+ expect(forward?.fileName).toBe("a.mp4");
+ expect(reversed?.fileName).toBe("a.mp4");
+ });
+
+ it("is case-insensitive about the extension", () => {
+ expect(chooseStartupAnimation([{ fileName: "Intro.MP4", byteLength: 5 }])?.extension).toBe(
+ "mp4",
+ );
+ });
+
+ it("treats an oversized or empty file as absent", () => {
+ expect(
+ chooseStartupAnimation([
+ { fileName: "huge.webm", byteLength: STARTUP_ANIMATION_MAX_BYTES + 1 },
+ ]),
+ ).toBeNull();
+ expect(chooseStartupAnimation([{ fileName: "empty.webm", byteLength: 0 }])).toBeNull();
+ // The cap is inclusive, so a file exactly at the limit still plays.
+ expect(
+ chooseStartupAnimation([
+ { fileName: "atlimit.webm", byteLength: STARTUP_ANIMATION_MAX_BYTES },
+ ])?.fileName,
+ ).toBe("atlimit.webm");
+ });
+
+ it("skips dot-prefixed entries so a resource fork cannot win", () => {
+ // macOS writes `._intro.mp4` beside a copied file, and it sorts before the
+ // real one; an editor's swap file behaves the same way.
+ expect(
+ chooseStartupAnimation([
+ { fileName: "._intro.mp4", byteLength: 4 },
+ { fileName: "intro.mp4", byteLength: 400 },
+ ])?.fileName,
+ ).toBe("intro.mp4");
+ });
+
+ it("falls back to the next candidate when the preferred one is rejected", () => {
+ expect(
+ chooseStartupAnimation([
+ { fileName: "a.webm", byteLength: STARTUP_ANIMATION_MAX_BYTES + 1 },
+ { fileName: "b.mp4", byteLength: 10 },
+ ])?.fileName,
+ ).toBe("b.mp4");
+ });
+});
+
+describe("startupAnimationExtensionOf", () => {
+ it("accepts only the declared containers", () => {
+ for (const extension of STARTUP_ANIMATION_EXTENSIONS) {
+ expect(startupAnimationExtensionOf(`clip.${extension}`)).toBe(extension);
+ // Every accepted container must have a content type to serve it with.
+ expect(STARTUP_ANIMATION_MIME_TYPES[extension]).toMatch(/^video\//);
+ }
+ expect(startupAnimationExtensionOf("clip.avi")).toBeNull();
+ expect(startupAnimationExtensionOf("clip.")).toBeNull();
+ expect(startupAnimationExtensionOf(".webm")).toBeNull();
+ });
+});
+
+describe("the renderer creation argument", () => {
+ const descriptor: StartupAnimationDescriptor = {
+ fileName: "intro clip.webm",
+ extension: "webm",
+ byteLength: 2048,
+ skipWhenReady: true,
+ };
+
+ it("round-trips a descriptor", () => {
+ const argument = encodeStartupAnimationArgument(descriptor);
+ expect(argument.startsWith(STARTUP_ANIMATION_ARGUMENT_PREFIX)).toBe(true);
+ expect(decodeStartupAnimationArgument(["--other", argument])).toEqual(descriptor);
+ });
+
+ it("survives a file name with spaces, quotes, and non-ASCII characters", () => {
+ const awkward: StartupAnimationDescriptor = {
+ ...descriptor,
+ fileName: 'o"pen ing — 启动.mp4',
+ extension: "mp4",
+ };
+ expect(
+ decodeStartupAnimationArgument([encodeStartupAnimationArgument(awkward)]),
+ ).toEqual(awkward);
+ });
+
+ it("reads nothing when the argument is absent", () => {
+ expect(decodeStartupAnimationArgument([])).toBeNull();
+ expect(decodeStartupAnimationArgument(["--pi-desktop-locale=en"])).toBeNull();
+ });
+
+ it("refuses a malformed or incomplete descriptor rather than half-building one", () => {
+ // The argument vector is process input: every rejection here is a launch
+ // that keeps the brand splash instead of a renderer holding a bad value.
+ const cases = [
+ "not-json",
+ encodeURIComponent("null"),
+ encodeURIComponent('"a string"'),
+ encodeURIComponent(JSON.stringify({ extension: "webm", byteLength: 1 })),
+ encodeURIComponent(JSON.stringify({ fileName: "a.webm", byteLength: 1 })),
+ encodeURIComponent(
+ JSON.stringify({ fileName: "a.avi", extension: "avi", byteLength: 1 }),
+ ),
+ encodeURIComponent(
+ JSON.stringify({ fileName: "a.webm", extension: "webm", byteLength: 0 }),
+ ),
+ encodeURIComponent(
+ JSON.stringify({ fileName: "a.webm", extension: "webm", byteLength: 1.5 }),
+ ),
+ ];
+ for (const payload of cases) {
+ expect(
+ decodeStartupAnimationArgument([
+ `${STARTUP_ANIMATION_ARGUMENT_PREFIX}${payload}`,
+ ]),
+ ).toBeNull();
+ }
+ });
+
+ it("defaults skipWhenReady to playing the animation out", () => {
+ const argument = `${STARTUP_ANIMATION_ARGUMENT_PREFIX}${encodeURIComponent(
+ JSON.stringify({ fileName: "a.webm", extension: "webm", byteLength: 1 }),
+ )}`;
+ expect(decodeStartupAnimationArgument([argument])?.skipWhenReady).toBe(false);
+ });
+});
diff --git a/packages/shared/src/startup-animation.ts b/packages/shared/src/startup-animation.ts
new file mode 100644
index 000000000..69bc0ef44
--- /dev/null
+++ b/packages/shared/src/startup-animation.ts
@@ -0,0 +1,275 @@
+/**
+ * User-supplied startup animation (D679 / ADR 0338).
+ *
+ * A user who drops a video into `<dataDir>/startup/` gets it played as the
+ * boot surface instead of the brand splash. Everything here is the contract
+ * the three sides share: the main process resolves a file against these rules
+ * before the window exists, passes the result to the renderer as a creation
+ * argument, and the renderer drives the phases from the same bounds.
+ *
+ * The rules are deliberately narrow. The animation owns the first paint of a
+ * released app, so a file that is missing, oversized, undecodable, or simply
+ * never ends must degrade to the existing splash rather than hold the window.
+ */
+
+/**
+ * Container extensions a startup animation may use, most preferred first.
+ *
+ * `webm` leads because it is the only container Chromium decodes in every
+ * build; the two MP4-family entries depend on the proprietary codecs Electron's
+ * bundled ffmpeg carries. The order is also the tie-break when the directory
+ * holds more than one candidate, so the choice stays deterministic.
+ */
+export const STARTUP_ANIMATION_EXTENSIONS = ["webm", "mp4", "m4v", "mov"] as const;
+
+export type StartupAnimationExtension =
+ (typeof STARTUP_ANIMATION_EXTENSIONS)[number];
+
+/** Response `content-type` per container; a missing entry is not served. */
+export const STARTUP_ANIMATION_MIME_TYPES: Record<
+ StartupAnimationExtension,
+ string
+> = {
+ webm: "video/webm",
+ mp4: "video/mp4",
+ m4v: "video/mp4",
+ mov: "video/quicktime",
+};
+
+/** Directory below the installation data directory that holds the animation. */
+export const STARTUP_ANIMATION_DIR_NAME = "startup";
+
+/**
+ * Largest file that is played.
+ *
+ * The cap exists because the animation is in front of the user before anything
+ * else, so decoding it competes with the boot it is covering. A file past this
+ * is treated as absent, which keeps a 2 GB export from turning into a stalled
+ * launch instead of a visible mistake.
+ */
+export const STARTUP_ANIMATION_MAX_BYTES = 64 * 1024 * 1024;
+
+/**
+ * Longest the animation may stay on screen, counted from the first paint.
+ *
+ * `ended` is not guaranteed: a truncated container, a decoder failure after the
+ * first frame, or an infinitely looping stream all leave the event unfired.
+ * This is the bound that makes the boot surface recoverable in those cases.
+ */
+export const STARTUP_ANIMATION_MAX_DURATION_MS = 15_000;
+
+/**
+ * How long the first frame may take before the animation is abandoned.
+ *
+ * Past this the file is readable but not playable in practice, and the user is
+ * looking at an empty black window. Dropping to the reveal is better than
+ * waiting for a decoder that is not coming.
+ */
+export const STARTUP_ANIMATION_FIRST_FRAME_TIMEOUT_MS = 2_000;
+
+/**
+ * Cross-fade from the black mask to the shell.
+ *
+ * An order of magnitude above `--motion-duration-slow` (300ms), which is sized
+ * for in-flow UI feedback. This is the one deliberate exception: the reveal is
+ * the end of a cinematic, not a control responding to a click.
+ */
+export const STARTUP_ANIMATION_REVEAL_MS = 1_000;
+
+/**
+ * How long the mask may stay fully black before it admits the app is still
+ * starting.
+ *
+ * The mask is opaque by design, so a boot that outlasts the video is
+ * indistinguishable from a hang. Past this bound the surface adds the splash's
+ * own progress affordance; the startup watchdog still owns the real failure
+ * bounds (`STARTUP_SLOW_HINT_MS` / `STARTUP_STALLED_MS`).
+ */
+export const STARTUP_ANIMATION_HOLD_HINT_MS = 3_000;
+
+/** The URL the renderer plays; the scheme serves exactly one resolved file. */
+export const STARTUP_ANIMATION_SCHEME = "pi-startup";
+export const STARTUP_ANIMATION_URL = `${STARTUP_ANIMATION_SCHEME}://animation`;
+
+/** Renderer creation argument carrying the descriptor past the sandbox. */
+export const STARTUP_ANIMATION_ARGUMENT_PREFIX = "--pi-desktop-startup-animation=";
+
+/**
+ * What the renderer is told about the animation before its first paint.
+ *
+ * No filesystem path: the renderer plays `STARTUP_ANIMATION_URL` and the main
+ * process keeps the only reference to the file. `byteLength` and `extension`
+ * are carried for diagnostics and for the settings row, not for playback.
+ */
+export type StartupAnimationDescriptor = {
+ /** Base name of the resolved file, for the settings row and logs. */
+ fileName: string;
+ extension: StartupAnimationExtension;
+ byteLength: number;
+ /** Cut the animation short once the shell has its initial state. */
+ skipWhenReady: boolean;
+};
+
+/**
+ * What the Appearance row shows about the animation directory.
+ *
+ * Re-scanned per request, so it describes what the *next* launch will play
+ * rather than what this one did. `directoryName` is the folder's own name, not
+ * its path: the row names the folder it opens without disclosing where the
+ * user's data directory is.
+ */
+export type StartupAnimationStatus = {
+ directoryName: string;
+ fileName: string | null;
+ byteLength: number | null;
+};
+
+function isStartupAnimationExtension(
+ value: unknown,
+): value is StartupAnimationExtension {
+ return (
+ typeof value === "string" &&
+ (STARTUP_ANIMATION_EXTENSIONS as readonly string[]).includes(value)
+ );
+}
+
+/** The extension of a file name, lowercased, or null when it has none. */
+export function startupAnimationExtensionOf(
+ fileName: string,
+): StartupAnimationExtension | null {
+ const dot = fileName.lastIndexOf(".");
+ if (dot <= 0 || dot === fileName.length - 1) return null;
+ const extension = fileName.slice(dot + 1).toLowerCase();
+ return isStartupAnimationExtension(extension) ? extension : null;
+}
+
+/** One directory entry the chooser considers. */
+export type StartupAnimationCandidate = {
+ fileName: string;
+ byteLength: number;
+};
+
+/**
+ * Pick the one animation a directory offers.
+ *
+ * Deterministic so two launches from the same directory never disagree:
+ * oversized and unknown-extension entries drop out, then the most preferred
+ * container wins, and a tie inside one container falls to the lowest file name
+ * under a locale-independent comparison. A dot-prefixed entry is skipped so a
+ * macOS `._foo.mp4` resource fork or an editor's `.foo.mp4.swp` cannot win.
+ */
+export function chooseStartupAnimation(
+ candidates: readonly StartupAnimationCandidate[],
+ maxBytes: number = STARTUP_ANIMATION_MAX_BYTES,
+): { fileName: string; extension: StartupAnimationExtension; byteLength: number } | null {
+ let best:
+ | { fileName: string; extension: StartupAnimationExtension; byteLength: number; rank: number }
+ | null = null;
+ for (const candidate of candidates) {
+ if (candidate.fileName.startsWith(".")) continue;
+ if (!Number.isInteger(candidate.byteLength)) continue;
+ if (candidate.byteLength <= 0 || candidate.byteLength > maxBytes) continue;
+ const extension = startupAnimationExtensionOf(candidate.fileName);
+ if (!extension) continue;
+ const rank = STARTUP_ANIMATION_EXTENSIONS.indexOf(extension);
+ if (
+ best &&
+ (best.rank < rank ||
+ (best.rank === rank && best.fileName < candidate.fileName))
+ ) {
+ continue;
+ }
+ best = {
+ fileName: candidate.fileName,
+ extension,
+ byteLength: candidate.byteLength,
+ rank,
+ };
+ }
+ if (!best) return null;
+ return {
+ fileName: best.fileName,
+ extension: best.extension,
+ byteLength: best.byteLength,
+ };
+}
+
+/**
+ * Byte range a media request asked for, clamped to the file.
+ *
+ * `<video>` playback is range-driven, so the handler has to answer `Range`
+ * rather than always sending the whole file. Null means "no usable range":
+ * the caller replies 200 with the full body, which is also the correct answer
+ * for a header this does not understand.
+ */
+export function parseByteRange(
+ header: string | null,
+ size: number,
+): { start: number; end: number } | null {
+ if (!header) return null;
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
+ if (!match) return null;
+ const [, rawStart, rawEnd] = match;
+ if (!rawStart && !rawEnd) return null;
+ // A suffix range (`bytes=-N`) asks for the last N bytes.
+ if (!rawStart) {
+ const length = Number(rawEnd);
+ if (!Number.isFinite(length) || length <= 0) return null;
+ return { start: Math.max(0, size - length), end: size - 1 };
+ }
+ const start = Number(rawStart);
+ if (!Number.isFinite(start) || start >= size) return null;
+ const end = rawEnd ? Math.min(Number(rawEnd), size - 1) : size - 1;
+ if (!Number.isFinite(end) || end < start) return null;
+ return { start, end };
+}
+
+/** Encode the descriptor as the renderer creation argument. */
+export function encodeStartupAnimationArgument(
+ descriptor: StartupAnimationDescriptor,
+): string {
+ return `${STARTUP_ANIMATION_ARGUMENT_PREFIX}${encodeURIComponent(
+ JSON.stringify(descriptor),
+ )}`;
+}
+
+/**
+ * Read the descriptor back in the preload sandbox.
+ *
+ * Every field is re-validated rather than trusted: the argument vector is
+ * process input, and a malformed one must leave the window on the brand splash
+ * instead of handing the renderer a half-built descriptor.
+ */
+export function decodeStartupAnimationArgument(
+ argv: readonly string[],
+): StartupAnimationDescriptor | null {
+ const raw = argv.find((argument) =>
+ argument.startsWith(STARTUP_ANIMATION_ARGUMENT_PREFIX),
+ );
+ if (!raw) return null;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(
+ decodeURIComponent(raw.slice(STARTUP_ANIMATION_ARGUMENT_PREFIX.length)),
+ );
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== "object") return null;
+ const value = parsed as Record<string, unknown>;
+ if (typeof value.fileName !== "string" || !value.fileName) return null;
+ if (!isStartupAnimationExtension(value.extension)) return null;
+ if (
+ typeof value.byteLength !== "number" ||
+ !Number.isInteger(value.byteLength) ||
+ value.byteLength <= 0
+ ) {
+ return null;
+ }
+ return {
+ fileName: value.fileName,
+ extension: value.extension,
+ byteLength: value.byteLength,
+ skipWhenReady: value.skipWhenReady === true,
+ };
+}
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index 3e17e2571..a52dbd6f1 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -39,6 +39,25 @@ export type CloseBehavior = "ask" | "tray" | "quit";
export type TranscriptDisplayMode = "flat" | "command-first" | "fully-folded";
+/**
+ * Preferences for the user-supplied boot animation (D679 / ADR 0338).
+ *
+ * The file itself is never named here — it is discovered in
+ * `<dataDir>/startup/` — so these are only the two choices discovery cannot
+ * make: whether to play what it found, and whether a fast boot may cut the
+ * playback short.
+ */
+export type StartupAnimationSettings = {
+ /** `false` ignores a present file. Absent means play it. */
+ enabled?: boolean;
+ /**
+ * End the animation as soon as the shell has its initial state, instead of
+ * letting the video reach its last frame. Absent and `false` play it out,
+ * which is the shipped behavior.
+ */
+ skipWhenReady?: boolean;
+};
+
export type AppSettings = {
imageGeneration?: import("../image-generation.js").ImageGenerationBinding | null;
/** All models marked for image generation; absent falls back to imageGeneration. */
@@ -89,6 +108,14 @@ export type AppSettings = {
* launch.
*/
macosWindowTranslucency?: boolean;
+ /**
+ * User-supplied boot animation played from `<dataDir>/startup/` (D679).
+ *
+ * Absent means the feature is on but dormant: with no file in that directory
+ * the boot surface stays the brand splash, which is why no field here has to
+ * be written for an existing installation to behave as it always did.
+ */
+ startupAnimation?: StartupAnimationSettings;
/** UI language; `auto` (and absent) follows the OS locale. */
language?: "auto" | "en" | "zh-CN" | "zh-TW" | "tr" | "de" | "es" | "fr" | "ko" | "pt-BR";
/**
diff --git a/scripts/e2e-startup-animation.mjs b/scripts/e2e-startup-animation.mjs
new file mode 100644
index 000000000..fe89feff8
--- /dev/null
+++ b/scripts/e2e-startup-animation.mjs
@@ -0,0 +1,261 @@
+#!/usr/bin/env node
+/**
+ * E2E-076 (D679 / ADR 0338): the user's own video as the boot surface.
+ *
+ * These are the two things that cannot be checked from source. Everything else
+ * about the feature is unit-testable — the chooser, the bounds, the phase
+ * machine, the markup — but these two are properties of Chromium's media
+ * stack, Electron's scheme privileges, and the protocol handler together:
+ *
+ * 1. A `<video>` in a sandboxed renderer, under the page CSP, can actually
+ * decode bytes handed to it over the host-owned `pi-startup:` scheme. A
+ * regression here turns the boot surface into a black rectangle that no
+ * source assertion would notice.
+ * 2. A file `<video>` cannot play does not hold the launch. The decoder
+ * reports that case inconsistently, which is exactly why the renderer has
+ * its own bounds, and only a real launch exercises them.
+ *
+ * Prereqs: `pnpm --filter @pi-desktop/desktop build`, a host-core binary
+ * (target/debug, target/release, or PI_DESKTOP_HOST_BIN), and `ffmpeg` on PATH
+ * to generate the playable fixture.
+ */
+import { spawn, spawnSync } from "node:child_process";
+import { once } from "node:events";
+import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import {
+ createTempDataDir,
+ repositoryRoot,
+ resolveElectronBinary,
+} from "./e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { appDir, electronBinary } = resolveElectronBinary(root);
+
+if (!existsSync(join(appDir, "out/main/index.js"))) {
+ console.error("desktop app not built. Run: pnpm --filter @pi-desktop/desktop build");
+ process.exit(1);
+}
+
+/** A short, genuinely decodable VP9 clip; the point is that Chromium plays it. */
+function writePlayableVideo(target) {
+ const result = spawnSync(
+ "ffmpeg",
+ [
+ "-v", "error",
+ "-f", "lavfi",
+ "-i", "testsrc=size=640x360:rate=24:duration=1.5",
+ "-c:v", "libvpx-vp9",
+ "-b:v", "300k",
+ "-an",
+ "-y", target,
+ ],
+ { encoding: "utf8" },
+ );
+ if (result.status !== 0 || !existsSync(target)) {
+ console.error("ffmpeg could not write the fixture video:", result.stderr || result.error);
+ process.exit(1);
+ }
+ return statSync(target).size;
+}
+
+/**
+ * A file that passes discovery and fails playback: the extension is accepted
+ * and the size is plausible, so only the decoder can reject it. This is the
+ * shape of a real bad export.
+ */
+function writeUnplayableVideo(target) {
+ writeFileSync(target, Buffer.alloc(4096, 0x41));
+ return statSync(target).size;
+}
+
+const PROBE = `(() => {
+ const surface = document.querySelector('[data-testid="startup-animation"]');
+ const video = surface?.querySelector("video") ?? null;
+ return {
+ surface: !!surface,
+ splash: !!document.querySelector('[data-testid="startup-splash"]'),
+ recovery: !!document.querySelector('[data-testid="startup-recovery"]'),
+ shell: !!document.querySelector(".app-shell"),
+ revealing: surface?.classList.contains("is-revealing") ?? false,
+ src: video?.getAttribute("src") ?? null,
+ readyState: video?.readyState ?? null,
+ currentTime: video?.currentTime ?? null,
+ error: video?.error ? video.error.code : null,
+ muted: video?.muted ?? null,
+ };
+})()`;
+
+function waitFor(check, timeoutMs, label) {
+ const deadline = Date.now() + timeoutMs;
+ return (async () => {
+ for (;;) {
+ if (await check()) return;
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${label}`);
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ }
+ })();
+}
+
+/**
+ * Boot the app against a throwaway data directory holding one animation, and
+ * hand `run` a renderer probe. Everything is torn down on either outcome.
+ */
+async function withLaunch(writeFixture, run) {
+ const dataDir = createTempDataDir("pi-desktop-startup-animation-");
+ const userDataDir = join(dataDir, "user-data");
+ mkdirSync(userDataDir, { recursive: true });
+ const startupDir = join(dataDir, "startup");
+ mkdirSync(startupDir, { recursive: true });
+ const byteLength = writeFixture(join(startupDir, "intro.webm"));
+
+ const env = {
+ ...process.env,
+ PI_DESKTOP_DATA_DIR: dataDir,
+ PI_DESKTOP_START_MAXIMIZED: "0",
+ ELECTRON_RENDERER_URL: "",
+ };
+ delete env.ELECTRON_RUN_AS_NODE;
+ // Derive the port from the pid so two runs on one machine cannot collide.
+ const port = 9400 + (process.pid % 200) + (writeFixture === writePlayableVideo ? 0 : 1);
+ const child = spawn(
+ electronBinary,
+ [`--remote-debugging-port=${port}`, `--user-data-dir=${userDataDir}`, "."],
+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ let output = "";
+ child.stdout.on("data", (chunk) => { output = (output + chunk).slice(-6000); });
+ child.stderr.on("data", (chunk) => { output = (output + chunk).slice(-6000); });
+
+ let ws = null;
+ try {
+ let target;
+ await waitFor(async () => {
+ if (child.exitCode !== null) throw new Error(`app exited early:\n${output}`);
+ try {
+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
+ target = list.find(
+ (entry) =>
+ entry.type === "page" &&
+ entry.url.includes("index.html") &&
+ !entry.url.includes("plugin-launcher"),
+ );
+ return !!target;
+ } catch {
+ return false;
+ }
+ }, 40_000, "the desktop CDP target");
+
+ ws = new WebSocket(target.webSocketDebuggerUrl);
+ await once(ws, "open");
+ let sequence = 0;
+ const pending = new Map();
+ ws.onmessage = ({ data }) => {
+ const message = JSON.parse(data);
+ const entry = pending.get(message.id);
+ if (!entry) return;
+ pending.delete(message.id);
+ clearTimeout(entry.timer);
+ if (message.error) entry.reject(new Error(JSON.stringify(message.error)));
+ else entry.resolve(message.result);
+ };
+ const send = (method, params = {}) =>
+ new Promise((resolve, reject) => {
+ const id = ++sequence;
+ const timer = setTimeout(() => {
+ pending.delete(id);
+ reject(new Error(`CDP ${method} timed out`));
+ }, 15_000);
+ timer.unref();
+ pending.set(id, { resolve, reject, timer });
+ ws.send(JSON.stringify({ id, method, params }));
+ });
+ const probe = async () => {
+ const result = await send("Runtime.evaluate", {
+ expression: PROBE,
+ awaitPromise: true,
+ returnByValue: true,
+ });
+ if (result.exceptionDetails) {
+ throw new Error(`probe failed: ${JSON.stringify(result.exceptionDetails)}`);
+ }
+ return result.result.value;
+ };
+ return await run({ probe, byteLength });
+ } finally {
+ try { ws?.close(); } catch {}
+ try { child.kill("SIGKILL"); } catch {}
+ if (process.env.PI_DESKTOP_KEEP_TEMP !== "1") {
+ try { rmSync(dataDir, { recursive: true, force: true }); } catch {}
+ }
+ }
+}
+
+async function playableScenario() {
+ await withLaunch(writePlayableVideo, async ({ probe, byteLength }) => {
+ console.log(`playable fixture: ${byteLength} bytes`);
+
+ // `readyState >= 2` means Chromium has frames for the current position,
+ // which is only true if `pi-startup:` served playable bytes under the CSP.
+ let decoded = null;
+ await waitFor(async () => {
+ const state = await probe();
+ if (state.error) throw new Error(`the <video> reported error code ${state.error}`);
+ if (state.readyState !== null && state.readyState >= 2) {
+ decoded = state;
+ return true;
+ }
+ return false;
+ }, 20_000, "the boot animation to decode its first frames");
+
+ if (!decoded.surface) throw new Error("the animation surface was not mounted");
+ if (decoded.splash) throw new Error("the brand splash was mounted alongside the animation");
+ if (decoded.src !== "pi-startup://animation") {
+ throw new Error(`the <video> src was ${decoded.src}, not the host-owned URL`);
+ }
+ if (decoded.muted !== true) throw new Error("the boot animation was not muted");
+ console.log(`PASS decode — readyState ${decoded.readyState}`);
+
+ // The clock advances, so the stream is really playing rather than stuck on
+ // one buffered frame.
+ const startedAt = decoded.currentTime ?? 0;
+ await waitFor(async () => {
+ const state = await probe();
+ if (!state.surface) return true; // already finished and revealed
+ return (state.currentTime ?? 0) > startedAt;
+ }, 10_000, "playback to advance");
+ console.log("PASS playback — the stream advances");
+
+ await waitFor(async () => {
+ const state = await probe();
+ if (state.recovery) throw new Error("the launch stalled into the recovery surface");
+ return !state.surface && state.shell;
+ }, 30_000, "the animation to reveal the shell");
+ console.log("PASS reveal — the shell owns the window");
+ });
+}
+
+async function unplayableScenario() {
+ await withLaunch(writeUnplayableVideo, async ({ probe }) => {
+ // The whole point: a bad export must cost at most the first-frame bound
+ // (2s) plus the reveal (1s), not the watchdog's 180s. The allowance here is
+ // boot time plus a wide margin, and it must stay far below that bound.
+ const startedAt = Date.now();
+ await waitFor(async () => {
+ const state = await probe();
+ if (state.recovery) throw new Error("an unplayable file stalled the launch");
+ return !state.surface && state.shell;
+ }, 45_000, "an unplayable animation to yield the shell");
+ console.log(`PASS unplayable — the shell took over in ${Date.now() - startedAt}ms`);
+ });
+}
+
+try {
+ await playableScenario();
+ await unplayableScenario();
+} catch (error) {
+ console.error("FAIL startup-animation —", error.message);
+ process.exit(1);
+}
+console.log("startup animation E2E passed");
+process.exit(0);