Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): stop theme build --watch at once when interrupted (#7508)

Cindy Zhangb359d5c452df
diff --git a/.changeset/theme-watch-stops-at-once.md b/.changeset/theme-watch-stops-at-once.md
new file mode 100644
index 0000000000..c9ab99b4a5
--- /dev/null
+++ b/.changeset/theme-watch-stops-at-once.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build --watch` stops as soon as it is interrupted (Ctrl-C or SIGTERM). A change saved while a rebuild was running no longer starts another rebuild after "Stopped watching.", and a rebuild in progress stops with the watcher instead of keeping the process alive.
+
+@cixzhang
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index 9274b7509c..3eec657afb 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -112,9 +112,11 @@ function resolveCliBin() {
* @param {{out?: string, iconsSpecifier?: string, detail?: string}} options -
* Parsed command options that affect generated output, plus the detail
* level the user chose.
+ * @param {(child: import('node:child_process').ChildProcess) => void} [onSpawn] -
+ * Receives the child, so a watcher that stops can stop it too.
* @returns {Promise<number>}
*/
-function runThemeBuildOnceChild(file, options) {
+function runThemeBuildOnceChild(file, options, onSpawn) {
const cliBin = resolveCliBin();
// A detail level the user chose applies to every rebuild.
const args = options.detail
@@ -128,6 +130,7 @@ function runThemeBuildOnceChild(file, options) {
stdio: 'inherit',
env: process.env,
});
+ onSpawn?.(child);
child.on('close', code => resolve(code ?? 0));
child.on('error', () => resolve(1));
});
@@ -139,7 +142,9 @@ function runThemeBuildOnceChild(file, options) {
* Rebuilds are serialized: one at a time, in the order the changes arrived, so
* the log stays readable. Each rebuild runs in a child process so a build error
* (which the single-build path reports via a hard exit) is contained and the
- * watcher keeps running.
+ * watcher keeps running. Stopping ends the watch at once: queued changes are
+ * dropped, the signal reaches a rebuild in progress, as Ctrl-C in a terminal
+ * reaches the whole process group, and "Stopped watching." is the last line.
*
* @param {Array<{file: string, filePath: string}>} entries - The theme file
* arguments as the user passed them, with their resolved absolute paths.
@@ -159,6 +164,11 @@ async function runThemeBuildWatch(entries, options) {
}
let building = false;
+ let stopped = false;
+ /** @type {import('node:child_process').ChildProcess | null} */
+ let rebuildChild = null;
+ /** @type {Promise<void> | null} */
+ let rebuildDone = null;
/** @type {Set<{file: string, filePath: string}>} */
const queued = new Set();
/** @type {Map<string, ReturnType<typeof setTimeout>>} */
@@ -166,6 +176,7 @@ async function runThemeBuildWatch(entries, options) {
/** @param {{file: string, filePath: string}} entry */
const rebuild = async entry => {
+ if (stopped) return;
if (building) {
// Coalesce changes that land mid-build into a single follow-up run.
queued.add(entry);
@@ -173,8 +184,16 @@ async function runThemeBuildWatch(entries, options) {
}
building = true;
emit(text(`\nChange detected — rebuilding ${rel(entry.filePath)}...`));
- await runThemeBuildOnceChild(entry.file, options);
+ const done = runThemeBuildOnceChild(entry.file, options, child => {
+ rebuildChild = child;
+ });
+ rebuildDone = done.then(() => {});
+ await done;
+ rebuildChild = null;
+ rebuildDone = null;
building = false;
+ // A stop during this build has already ended the watch.
+ if (stopped) return;
emit(text(watchingLine));
const next = queued.values().next();
if (!next.done) {
@@ -205,9 +224,18 @@ async function runThemeBuildWatch(entries, options) {
emit(text(watchingLine));
await new Promise((/** @type {(value?: void) => void} */ resolve) => {
- const stop = () => {
+ /** @param {NodeJS.Signals} signal */
+ const stop = async signal => {
+ process.removeListener('SIGINT', stop);
+ process.removeListener('SIGTERM', stop);
+ stopped = true;
+ queued.clear();
for (const d of debounces.values()) clearTimeout(d);
for (const w of watchers) w.close();
+ // A rebuild in progress would otherwise keep the process alive after
+ // "Stopped watching.". In a terminal, Ctrl-C already reached it.
+ rebuildChild?.kill(signal);
+ await rebuildDone;
emit(text('\nStopped watching.'));
resolve();
};
diff --git a/packages/cli/clients/cli/commands/build-theme.watch.test.mjs b/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
index 14d494b5e6..3b0d8e5ad6 100644
--- a/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.watch.test.mjs
@@ -124,7 +124,8 @@ describe('theme build --watch', () => {
const rebuilt = await waitFor(
() => {
try {
- if (fs.readFileSync(cssFile, 'utf-8').includes('#010203')) return true;
+ if (fs.readFileSync(cssFile, 'utf-8').includes('#010203'))
+ return true;
} catch {
// CSS mid-write; fall through to re-touch.
}
@@ -157,6 +158,63 @@ describe('theme build --watch', () => {
expect(stdout).toMatch(/Stopped watching/);
}, 30_000);
+ it('stops at once when interrupted mid-rebuild, and drops a queued change', async () => {
+ const themeFile = path.join(tmpDir, 'ws.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default { name: 'ws', tokens: { '--color-bg': '#ffffff' } };\n`,
+ );
+ // Top-level await holds every rebuild of this version in progress for 20 s,
+ // far longer than a stop may take.
+ const slow =
+ `await new Promise(resolve => setTimeout(resolve, 20000));\n` +
+ `export default { name: 'ws', tokens: { '--color-bg': '#010203' } };\n`;
+
+ const child = spawn(
+ process.execPath,
+ [CLI_BIN, 'theme', 'build', 'ws.mjs', '--watch'],
+ {cwd: tmpDir, env: {...process.env, FORCE_COLOR: '0'}},
+ );
+ let stdout = '';
+ child.stdout.on('data', d => (stdout += d.toString()));
+ child.stderr.on('data', d => (stdout += d.toString()));
+ const exited = new Promise(resolve =>
+ child.once('exit', () => resolve(Date.now())),
+ );
+
+ let stoppedAt;
+ try {
+ expect(await waitFor(() => /Watching/i.test(stdout))).toBe(true);
+ // Start the slow rebuild, re-touching in case a watch event is dropped.
+ const started = await waitFor(
+ () => {
+ if (/rebuilding ws\.mjs/.test(stdout)) return true;
+ fs.writeFileSync(themeFile, slow);
+ return false;
+ },
+ {timeout: 20000, interval: 200},
+ );
+ expect(started).toBe(true);
+ // Queue a change behind the rebuild in progress (debounce is 100 ms).
+ fs.writeFileSync(themeFile, `${slow}// queued\n`);
+ await new Promise(resolve => setTimeout(resolve, 500));
+ } finally {
+ stoppedAt = Date.now();
+ child.kill('SIGINT');
+ }
+
+ const exitedAt = await Promise.race([
+ exited,
+ new Promise(resolve => setTimeout(() => resolve(null), 15000)),
+ ]);
+ if (exitedAt === null) child.kill('SIGKILL');
+ // Finishing the interrupted rebuild, or starting the queued one, takes 20 s.
+ expect(exitedAt).not.toBeNull();
+ expect(exitedAt - stoppedAt).toBeLessThan(10000);
+ expect(stdout.match(/rebuilding/g)).toHaveLength(1);
+ expect(stdout.trimEnd().endsWith('Stopped watching.')).toBe(true);
+ }, 60_000);
+
it.each([
[[], false],
[['--detail', 'full'], true],
@@ -219,7 +277,10 @@ describe('theme build --watch', () => {
);
expect(built).toBe(true);
await waitFor(() => /Watching w1\.mjs, w2\.mjs/.test(stdout));
- const firstCssBefore = fs.readFileSync(path.join(tmpDir, 'w1.css'), 'utf-8');
+ const firstCssBefore = fs.readFileSync(
+ path.join(tmpDir, 'w1.css'),
+ 'utf-8',
+ );
const changed = `export default { name: 'w2', tokens: { '--color-bg': '#010203' } };\n`;
fs.writeFileSync(second, changed);