From 7207c32ccfccfcb27d01e812e2a953c10ac5baff Mon Sep 17 00:00:00 2001 From: Charles Lowell Date: Fri, 13 Nov 2026 12:28:48 -0600 Subject: [PATCH] Require an abort signal for UI lifetime --- .changeset/ui-abort-signal.md | 5 ++ packages/ui/src/ui.lifecycle.test.ts | 129 +++++++++++++++++++-------- packages/ui/src/ui.ts | 75 +++++----------- packages/ui/test/ui.ts | 10 ++- 4 files changed, 126 insertions(+), 93 deletions(-) create mode 100644 .changeset/ui-abort-signal.md diff --git a/.changeset/ui-abort-signal.md b/.changeset/ui-abort-signal.md new file mode 100644 index 0000000..3e8804b --- /dev/null +++ b/.changeset/ui-abort-signal.md @@ -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. diff --git a/packages/ui/src/ui.lifecycle.test.ts b/packages/ui/src/ui.lifecycle.test.ts index 4457a69..0ef1bed 100644 --- a/packages/ui/src/ui.lifecycle.test.ts +++ b/packages/ui/src/ui.lifecycle.test.ts @@ -1,6 +1,7 @@ +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()); @@ -8,34 +9,57 @@ 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(); + const restoration = Promise.withResolvers(); 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 { @@ -43,11 +67,20 @@ describe('UI lifecycle', () => { } }); const { writes } = io; - const ui = await createUI(io); - let disposing: Promise | 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(); @@ -57,34 +90,34 @@ 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', { @@ -92,21 +125,41 @@ describe('UI lifecycle', () => { throw failure; }, }); - let disposing: Promise | 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(() => {}); } }); }); diff --git a/packages/ui/src/ui.ts b/packages/ui/src/ui.ts index eb27a8d..8889407 100644 --- a/packages/ui/src/ui.ts +++ b/packages/ui/src/ui.ts @@ -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; } @@ -15,75 +14,45 @@ export interface UIOptions { width?: number; input: Readable; output: Writable; + signal: AbortSignal; } export async function createUI(options: UIOptions): Promise { - 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 | 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; - term: Term; - output: Writable; -} - -class RenderLoop { - #layout: Layout; - #frames: AsyncIterable; - #term: Term; - #output: Writable; - #running: Promise | 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 { const result = Promise.withResolvers(); stream.write(bytes, (err) => { diff --git a/packages/ui/test/ui.ts b/packages/ui/test/ui.ts index 69d8255..3246213 100644 --- a/packages/ui/test/ui.ts +++ b/packages/ui/test/ui.ts @@ -11,6 +11,7 @@ export interface TestUI extends AsyncDisposable { export async function createTestUI(options: SyncTestTerminalOptions = {}): Promise { const { cols = 80, rows = 24 } = options; const terminal = createTestTerminal({ ...options, cols, rows }); + const controller = new AbortController(); try { const ui = await createUI({ @@ -18,21 +19,26 @@ export async function createTestUI(options: SyncTestTerminalOptions = {}): Promi 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; }