Files
paseo/packages/desktop/e2e/daemon-lifecycle.e2e.mjs
T
Mohamed Boudra 6215e08efe Smooth streaming replies with a continuous left-to-right fade (#4859)
* feat(app): reveal streaming text as one continuous fade front

Streaming assistant text is released by word and every character fades in
over the same 150 ms envelope from a start time owned by the message. Start
times never decrease in reading order, so a line paints as a single front
moving left to right, however the text is chunked. Per-word envelopes with an
internal stagger let the next word's first letter overtake the previous word's
last letter, which read as holes and flashing words at the real frame rate;
100 ms frame strips hid it.

Native renderers receive the fade ranges as a prop on a host view wrapping the
root Text, so ranges and text land in the same Fabric mount transaction. The
earlier binding sent ranges through a separate async module call keyed by view
tag and had to reconcile them against the view's text; on a fast phone the UI
thread lags JS by several commits, mounts and calls interleave, and every
reconciliation heuristic guessed wrong. Native code no longer infers newness
or creates start times.

The mock load-test provider now separates cycles with a blank line so a cycle
heading is not appended to the previous paragraph.

* fix(ci): refresh streaming dependencies and isolate E2E setup

* test(app): distinguish fade cleanup from Markdown replacement

* test(app): detect restarted fades during Markdown updates

* docs(app): keep streaming guidance focused on constraints and QA

* test(app): control animation time in Android fade assertions

Fixed wall-clock sleeps let emulator scheduling select the sampled animation frame. Inject the animator time source and drive paint at exact timestamps within one UI-thread operation; production keeps the system clock. Verify the mid-fade sample and the exact cleanup boundary without sleeps, polling, or retries.

* fix(test): compile the desktop renderer before lifecycle checks

The lifecycle fixture treated Metro /status as app readiness. Its first
Settings click therefore spent its 90-second UI budget compiling the cold
bundle. An isolated cold-cache run restricted to one CPU reproduced the
click timeout before the app runtime had loaded.

Reuse the browser suite's existing bundle warmup before launching Electron,
and preserve Metro output in the lifecycle artifacts. The UI timeout,
build-request timeout, lifecycle assertions and product behavior are unchanged.

CI did not preserve Metro output, so its precise startup timing is not
recoverable from the failed run. The retained log makes subsequent startup
failures diagnosable without relying only on an empty renderer text dump.

Validation: three complete lifecycle E2E runs under private Xvfb displays;
existing Metro readiness tests; app typecheck; targeted lint; root format.

* test(file-observer): await burst delivery through native recovery

The deletion phase required every event within 10 seconds, but native
coalescing recovery uses a 30-second safety audit followed by the existing
reconciliation debounce. An idle diagnostic excludes that delayed audit
and therefore cannot act as a completion barrier.

Await the required delivered events instead, preserving every deletion
assertion and the existing overall test watchdog. A real-filesystem test
with controlled native notifications reproduces 95 outstanding paths at
the old deadline and verifies completion when the safety audit delivers
them. No production observer behavior changes.

* test(file-observer): verify burst recovery through public events

The controlled-clock regression constructed a private native backend,
bypassing the interface used by consumers. Consolidate recovery coverage
into the public observer integration test instead: drive real writes,
deletes and directory renames, then await every required public event,
including the 450 surviving files at their renamed paths.

No public capability was added: subscribe callbacks already express
completion. No production behavior or test timeout changes.

* test(app): drive Android fade tests through the native host

The instrumentation suite constructed TailFadeInAnimator directly, advanced
its private clock, and counted FadeInSpan instances. It now mounts the
WordFadeHost that React mounts, feeds it the ranges prop the bridge sends,
and asserts rendered pixels: hidden before a start time, a monotone front
inside and across words, settled frames equal to the baseline, and no frame
callbacks left after settling. Span counts and internal timing state are no
longer asserted.

Choreographer cannot be advanced deterministically from a test and the fade
epoch is the message's wall-clock start time, so the host takes a
WordFadeFrameClock (time plus frame callbacks) as its smallest public seam;
production keeps the Choreographer-backed default.

Fixture text is sized in pixels so every sample stays on one line at any
density; at 420 dpi the 32sp fixture wrapped and the column helper summed
glyphs from the first line.
2026-09-15 03:15:24 +02:00

214 lines
8.0 KiB
JavaScript

import { verifyAttachedDaemonControls } from "./daemon-lifecycle-renderer.electron.mjs";
import { once } from "node:events";
import assert from "node:assert/strict";
import { mkdtemp, mkdir, writeFile, readFile, rm, readdir, copyFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import net from "node:net";
import { fileURLToPath, pathToFileURL } from "node:url";
import { _electron as electron, expect } from "playwright/test";
import {
savePersistedConfig,
startDaemonInstance,
stopDaemonInstance,
readDaemonInstance,
} from "@getpaseo/server";
const repo = fileURLToPath(new URL("../../..", import.meta.url));
const root = await mkdtemp(path.join(tmpdir(), "paseo desktop lifecycle "));
const home = path.join(root, "daemon");
const env = Object.fromEntries(
Object.entries(process.env).filter(
([key]) => !key.startsWith("PASEO_") && key !== "ELECTRON_RUN_AS_NODE",
),
);
env.HOME = root;
env.USERPROFILE = root;
env.PASEO_HOME = home;
const server = net.createServer();
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const port = server.address().port;
await new Promise((resolve) => server.close(resolve));
assert.ok(port !== 6767 && port !== 6768);
await mkdir(path.join(root, "web"));
await writeFile(path.join(root, "web/index.html"), "<html><body>Lifecycle web UI</body></html>");
savePersistedConfig(home, {
daemon: { listen: `127.0.0.1:${port}`, relay: { enabled: false } },
features: {
dictation: { enabled: false },
voiceMode: { enabled: false },
webUi: { enabled: true, distDir: path.join(root, "web") },
},
});
const main = path.join(root, "main.cjs");
const managerPath = path.join(repo, "packages/desktop/dist/daemon/daemon-manager.js");
await writeFile(
main,
`const { app } = require("electron"); app.setPath("userData", ${JSON.stringify(path.join(root, "user-data"))}); app.whenReady().then(() => { global.lifecycle = require(${JSON.stringify(managerPath)}); });`,
);
let desktop;
let captured;
async function openDesktop() {
desktop = await electron.launch({
args: ["--no-sandbox", "--ozone-platform=headless", main],
env: {
...env,
PASEO_LISTEN: "127.0.0.1:1",
PASEO_WEB_UI_ENABLED: "false",
PASEO_HOST: "unused:1",
},
});
await expect
.poll(() => desktop.evaluate(() => Boolean(global.lifecycle)), { timeout: 10_000 })
.toBe(true);
}
async function closeDesktop() {
if (!desktop) return;
const child = desktop.process();
const exited = once(child, "exit");
await desktop.evaluate(({ app }) => app.exit(0)).catch(() => {});
await exited;
desktop = null;
}
async function command(name, args) {
console.log(`Desktop command: ${name}${args?.reason ? ` (${args.reason})` : ""}`);
return desktop.evaluate(
async (_, input) => global.lifecycle.createDaemonCommandHandlers()[input.name](input.args),
{ name, args },
);
}
try {
// Simulate a legacy independent launch that carries the old Desktop flag.
const launch = await startDaemonInstance({
home,
command: process.execPath,
args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")],
env,
mode: "deployment",
desktopManaged: true,
timeoutMs: 30_000,
});
captured = launch.instance;
await openDesktop();
const attached = await command("start_desktop_daemon");
assert.equal(attached.pid, captured.pid);
assert.equal(attached.desktopManaged, true);
assert.equal(attached.ownedByDesktop, false);
for (const reason of ["quit", "settings", "app_update", "host_remove", "version_mismatch"]) {
const status = await command("stop_desktop_daemon", { reason });
assert.equal(status.pid, captured.pid, `${reason} stopped an attached daemon`);
process.kill(captured.pid, 0);
}
const restarted = await command("restart_desktop_daemon");
assert.equal(restarted.pid, captured.pid);
await assert.rejects(
command("stop_desktop_daemon", {
reason: "manual_ipc",
pid: captured.pid,
startedAt: "outdated-confirmation",
}),
/changed since confirmation/,
);
const stopped = await command("stop_desktop_daemon", {
reason: "manual_ipc",
pid: captured.pid,
startedAt: captured.startedAt,
});
assert.equal(stopped.status, "stopped");
captured = null;
const owned = await command("start_desktop_daemon");
captured = await readDaemonInstance(home);
assert.equal(owned.pid, captured.pid);
assert.equal(owned.ownedByDesktop, true);
assert.equal(owned.listen, `127.0.0.1:${port}`);
assert.equal(
JSON.parse(await readFile(path.join(home, "config.json"), "utf8")).features.webUi.enabled,
true,
);
const liveWebUi = await fetch(`http://127.0.0.1:${port}/`);
assert.equal(liveWebUi.status, 200);
assert.match(await liveWebUi.text(), /Lifecycle web UI/);
await command("patch_desktop_settings", { daemon: { keepRunningAfterQuit: true } });
await closeDesktop();
desktop = null;
process.kill(captured.pid, 0);
await openDesktop();
assert.equal((await command("start_desktop_daemon")).ownedByDesktop, false);
await command("stop_desktop_daemon", { reason: "quit" });
process.kill(captured.pid, 0);
await command("stop_desktop_daemon", {
reason: "manual_ipc",
pid: captured.pid,
startedAt: captured.startedAt,
});
captured = null;
const next = await command("start_desktop_daemon");
captured = await readDaemonInstance(home);
assert.equal(next.ownedByDesktop, true);
await command("stop_desktop_daemon", { reason: "quit" });
assert.equal(await readDaemonInstance(home), null);
captured = null;
await closeDesktop();
if (process.platform === "linux") {
const rendererLaunch = await startDaemonInstance({
home,
command: process.execPath,
args: [path.join(repo, "packages/server/dist/scripts/supervisor-entrypoint.js")],
env,
mode: "deployment",
desktopManaged: true,
timeoutMs: 30_000,
});
captured = rendererLaunch.instance;
await verifyAttachedDaemonControls({ repo, root, env, home, port, instance: captured });
captured = null;
}
if (process.platform !== "win32") {
const preload = path.join(root, "slow-worker.mjs");
await writeFile(
preload,
'if (process.argv[1]?.endsWith("daemon-worker.js")) await new Promise(resolve => setTimeout(resolve, 45000));',
);
await openDesktop();
// Playwright removes NODE_OPTIONS from electron.launch's environment.
// Restore this runtime input inside the isolated fixture before it launches the daemon.
await desktop.evaluate(
(_, value) => {
process.env.NODE_OPTIONS = value;
},
`--import=${pathToFileURL(preload).href}`,
);
const began = Date.now();
const starting = await command("start_desktop_daemon");
captured = await readDaemonInstance(home);
assert.equal(starting.status, "starting");
assert.equal(starting.ownedByDesktop, true);
assert.equal(starting.pid, captured.pid);
assert.ok(Date.now() - began < 40_000, "Desktop did not return its bounded starting state");
process.kill(captured.pid, 0);
await command("stop_desktop_daemon", { reason: "quit" });
captured = null;
await closeDesktop();
console.log(
"PASS: Desktop readiness deadline returns starting and preserves its owned slow launch.",
);
}
console.log(
"PASS: attached legacy daemon survives automatic actions; explicit captured stop, owned launch, managed settings, worker restart, and next-session attachment.",
);
} finally {
await closeDesktop();
if (captured)
await stopDaemonInstance(home, { instance: captured, force: true, timeoutMs: 2_000 });
const artifacts =
process.env.PASEO_DESKTOP_LIFECYCLE_ARTIFACT_DIR ??
(await mkdtemp(path.join(tmpdir(), "paseo-desktop-lifecycle-artifacts-")));
await mkdir(artifacts, { recursive: true });
for (const name of await readdir(root))
if (name.endsWith(".png") || name === "metro.log")
await copyFile(path.join(root, name), path.join(artifacts, name));
await rm(root, { recursive: true, force: true });
console.log(`Lifecycle artifacts: ${artifacts}`);
}