Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/ui-abort-signal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/ui': minor
---

Require an AbortSignal when creating a UI. Stop the UI by aborting the signal and await main() for in-flight output and terminal restoration; UI instances no longer implement AsyncDisposable. Terminal settings are applied only when main() starts.
129 changes: 91 additions & 38 deletions packages/ui/src/ui.lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,86 @@
import { once } from 'node:events';
import { PassThrough, Writable } from 'node:stream';
import { alternateBuffer, cursor, settings } from '@bomb.sh/tty';
import { describe, expect, test } from 'vitest';
import { describe, expect, test, vi } from 'vitest';
import { createUI } from './ui.ts';

const terminalSettings = settings(cursor(false), alternateBuffer());
const apply = Buffer.from(terminalSettings.apply).toString('utf8');
const restore = Buffer.from(terminalSettings.revert).toString('utf8');

describe('UI lifecycle', () => {
test('restores terminal settings when main was never called', async () => {
test('does not change terminal settings when main was never called', async () => {
using io = setup();
const { writes } = io;
{
await using _ui = await createUI(io);
expect(writes).toEqual([apply]);
}
const controller = new AbortController();
await createUI({ ...io, signal: controller.signal });
expect(io.writes).toEqual([]);

expect(writes).toEqual([apply, restore]);
controller.abort();
await nextTurn();
expect(io.writes).toEqual([]);
});

test('does not start when the signal is already aborted', async () => {
using io = setup();
const controller = new AbortController();
controller.abort();
const ui = await createUI({ ...io, signal: controller.signal });
ui.document.documentElement.appendChild(ui.document.createTextNode('unused'));

await ui.main();
await ui.main();
expect(io.writes).toEqual([]);
});

test('repeated main calls return the same running task', async () => {
using io = setup();
const { writes } = io;
{
await using resource = await createUI(io);
expect(resource.main()).toBe(resource.main());
const controller = new AbortController();
const ui = await createUI({ ...io, signal: controller.signal });
const running = ui.main();
try {
expect(ui.main()).toBe(running);
controller.abort();
expect(ui.main()).toBe(running);
} finally {
controller.abort();
await running;
}

expect(ui.main()).toBe(running);
expect(writes).toEqual([apply, restore]);
});

test('disposal waits for a second output write before restoring the terminal', async () => {
test('main waits for pending output and terminal restoration after abort', async () => {
const output = Promise.withResolvers<void>();
const restoration = Promise.withResolvers<void>();
let frames = 0;
using io = setup((chunk, complete) => {
if (chunk === apply || chunk === restore) {
if (chunk === apply) {
complete();
} else if (chunk === restore) {
void restoration.promise.then(() => complete());
} else if (++frames === 2) {
void output.promise.then(() => complete());
} else {
complete();
}
});
const { writes } = io;
const ui = await createUI(io);
let disposing: Promise<void> | undefined;
const controller = new AbortController();
const ui = await createUI({ ...io, signal: controller.signal });
const running = ui.main();
let settled = false;
void running.then(
() => {
settled = true;
},
() => {
settled = true;
},
);

try {
void ui.main();
const { document } = ui;
document.documentElement.appendChild(document.createTextNode('first'));
await nextTurn();
Expand All @@ -57,56 +90,76 @@ describe('UI lifecycle', () => {
await nextTurn();
expect(frames).toBe(2);

disposing = Promise.resolve(ui[Symbol.asyncDispose]());
let settled = false;
void disposing.then(
() => {
settled = true;
},
() => {
settled = true;
},
);
controller.abort();
expect(ui.main()).toBe(running);
await nextTurn();
expect(settled).toBe(false);
expect(writes).not.toContain(restore);

output.resolve();
await disposing;
await nextTurn();
expect(writes.at(-1)).toBe(restore);
expect(settled).toBe(false);

restoration.resolve();
await running;
expect(ui.main()).toBe(running);
expect(frames).toBe(2);
} finally {
controller.abort();
output.resolve();
await (disposing ?? ui[Symbol.asyncDispose]());
restoration.resolve();
await running;
}
});

test('disposal propagates a render failure after restoring terminal settings', async () => {
test('main propagates a render failure after restoring terminal settings', async () => {
using io = setup();
const { writes } = io;
const ui = await createUI(io);
const controller = new AbortController();
const ui = await createUI({ ...io, signal: controller.signal });
const failure = new TestRenderError();
const text = ui.document.createTextNode('unreadable');
Object.defineProperty(text, 'data', {
get() {
throw failure;
},
});
let disposing: Promise<void> | undefined;
const running = ui.main();

try {
const failed = expect(ui.main()).rejects.toBe(failure);
const failed = expect(running).rejects.toBe(failure);
ui.document.documentElement.appendChild(text);
await failed;

disposing = Promise.resolve(ui[Symbol.asyncDispose]());
await expect(disposing).rejects.toBe(failure);
controller.abort();
expect(ui.main()).toBe(running);
await expect(ui.main()).rejects.toBe(failure);
expect(writes).toEqual([apply, restore]);
} finally {
// Manually own the expected failure; never dispose the resource twice.
if (!disposing) {
await Promise.resolve(ui[Symbol.asyncDispose]()).catch(() => {});
}
controller.abort();
await running.catch(() => {});
}
});

test('rejects setup failure without attempting terminal restoration', async () => {
const failure = new Error('setup failed');
using io = setup((_chunk, complete) => complete(failure));
const controller = new AbortController();
const ui = await createUI({ ...io, signal: controller.signal });
const write = vi.spyOn(io.output, 'write');
const outputError = once(io.output, 'error');
const running = ui.main();

try {
await expect(running).rejects.toBe(failure);
await expect(outputError).resolves.toEqual([failure]);
expect(write).toHaveBeenCalledTimes(1);
expect(io.writes).toEqual([apply]);
} finally {
controller.abort();
write.mockRestore();
await running.catch(() => {});
}
});
});
Expand Down
75 changes: 22 additions & 53 deletions packages/ui/src/ui.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { alternateBuffer, createTerm, cursor, settings, type Term } from '@bomb.sh/tty';
import { alternateBuffer, createTerm, cursor, settings } from '@bomb.sh/tty';
import type { Readable, Writable } from 'node:stream';
import { Document } from './dom.ts';
import { RenderApi } from './render.ts';
import { Layout } from './layout.ts';

export interface UI extends AsyncDisposable {
export interface UI {
document: Document;
/** Start rendering once. Disposal waits for this task and propagates its failure. */
main(): Promise<void>;
}

Expand All @@ -15,75 +14,45 @@ export interface UIOptions {
width?: number;
input: Readable;
output: Writable;
signal: AbortSignal;
}

export async function createUI(options: UIOptions): Promise<UI> {
const { output, width = 80, height = 24 } = options;
const controller = new AbortController();
const { output, width = 80, height = 24, signal } = options;

const setup = settings(cursor(false), alternateBuffer());
await write(output, setup.apply);

const term = await createTerm({ width, height });
const render = new RenderApi(controller.signal);
const render = new RenderApi(signal);

const document = new Document(() => render.request());

const layout = new Layout(document.documentElement);

const loop = new RenderLoop({ layout, term, output, frames: render });
let running: Promise<void> | undefined = undefined;

const run = async () => {
await write(output, setup.apply);

try {
for await (const _ of render) {
const ops = [...layout.layout()];
const result = term.render(ops);
await write(output, result.output);
}
} finally {
await write(output, setup.revert);
}
};

return {
document,
main: () => loop.run(),
async [Symbol.asyncDispose]() {
controller.abort();
try {
await loop.run();
} finally {
await write(output, setup.revert);
}
main() {
return running ? running : signal.aborted ? Promise.resolve() : (running = run());
},
};
}

interface RenderLoopOptions {
layout: Layout;
frames: AsyncIterable<void>;
term: Term;
output: Writable;
}

class RenderLoop {
#layout: Layout;
#frames: AsyncIterable<void>;
#term: Term;
#output: Writable;
#running: Promise<void> | undefined;

constructor(options: RenderLoopOptions) {
this.#layout = options.layout;
this.#frames = options.frames;
this.#term = options.term;
this.#output = options.output;
}

async #loop() {
for await (const _ of this.#frames) {
const ops = [...this.#layout.layout()];
const result = this.#term.render(ops);
await write(this.#output, result.output);
}
}

run() {
if (!this.#running) {
this.#running = this.#loop();
}
return this.#running;
}
}

function write(stream: Writable, bytes: Uint8Array): Promise<void> {
const result = Promise.withResolvers<void>();
stream.write(bytes, (err) => {
Expand Down
10 changes: 8 additions & 2 deletions packages/ui/test/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,34 @@ export interface TestUI extends AsyncDisposable {
export async function createTestUI(options: SyncTestTerminalOptions = {}): Promise<TestUI> {
const { cols = 80, rows = 24 } = options;
const terminal = createTestTerminal({ ...options, cols, rows });
const controller = new AbortController();

try {
const ui = await createUI({
input: terminal.input,
output: terminal.output,
width: cols,
height: rows,
signal: controller.signal,
});
void ui.main();
const running = ui.main();
// Disposal awaits the original task and propagates any rendering failure.
void running.catch(() => {});

return {
terminal,
document: ui.document,
async [Symbol.asyncDispose]() {
controller.abort();
try {
await ui[Symbol.asyncDispose]();
await running;
} finally {
await terminal[Symbol.asyncDispose]();
}
},
};
} catch (error) {
controller.abort();
await terminal[Symbol.asyncDispose]();
throw error;
}
Expand Down
Loading