Skip to content

Commit 7207c32

Browse files
committed
Require an abort signal for UI lifetime
1 parent ea07228 commit 7207c32

4 files changed

Lines changed: 126 additions & 93 deletions

File tree

‎.changeset/ui-abort-signal.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
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.

‎packages/ui/src/ui.lifecycle.test.ts‎

Lines changed: 91 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,86 @@
1+
import { once } from 'node:events';
12
import { PassThrough, Writable } from 'node:stream';
23
import { alternateBuffer, cursor, settings } from '@bomb.sh/tty';
3-
import { describe, expect, test } from 'vitest';
4+
import { describe, expect, test, vi } from 'vitest';
45
import { createUI } from './ui.ts';
56

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

1011
describe('UI lifecycle', () => {
11-
test('restores terminal settings when main was never called', async () => {
12+
test('does not change terminal settings when main was never called', async () => {
1213
using io = setup();
13-
const { writes } = io;
14-
{
15-
await using _ui = await createUI(io);
16-
expect(writes).toEqual([apply]);
17-
}
14+
const controller = new AbortController();
15+
await createUI({ ...io, signal: controller.signal });
16+
expect(io.writes).toEqual([]);
1817

19-
expect(writes).toEqual([apply, restore]);
18+
controller.abort();
19+
await nextTurn();
20+
expect(io.writes).toEqual([]);
21+
});
22+
23+
test('does not start when the signal is already aborted', async () => {
24+
using io = setup();
25+
const controller = new AbortController();
26+
controller.abort();
27+
const ui = await createUI({ ...io, signal: controller.signal });
28+
ui.document.documentElement.appendChild(ui.document.createTextNode('unused'));
29+
30+
await ui.main();
31+
await ui.main();
32+
expect(io.writes).toEqual([]);
2033
});
2134

2235
test('repeated main calls return the same running task', async () => {
2336
using io = setup();
2437
const { writes } = io;
25-
{
26-
await using resource = await createUI(io);
27-
expect(resource.main()).toBe(resource.main());
38+
const controller = new AbortController();
39+
const ui = await createUI({ ...io, signal: controller.signal });
40+
const running = ui.main();
41+
try {
42+
expect(ui.main()).toBe(running);
43+
controller.abort();
44+
expect(ui.main()).toBe(running);
45+
} finally {
46+
controller.abort();
47+
await running;
2848
}
2949

50+
expect(ui.main()).toBe(running);
3051
expect(writes).toEqual([apply, restore]);
3152
});
3253

33-
test('disposal waits for a second output write before restoring the terminal', async () => {
54+
test('main waits for pending output and terminal restoration after abort', async () => {
3455
const output = Promise.withResolvers<void>();
56+
const restoration = Promise.withResolvers<void>();
3557
let frames = 0;
3658
using io = setup((chunk, complete) => {
37-
if (chunk === apply || chunk === restore) {
59+
if (chunk === apply) {
3860
complete();
61+
} else if (chunk === restore) {
62+
void restoration.promise.then(() => complete());
3963
} else if (++frames === 2) {
4064
void output.promise.then(() => complete());
4165
} else {
4266
complete();
4367
}
4468
});
4569
const { writes } = io;
46-
const ui = await createUI(io);
47-
let disposing: Promise<void> | undefined;
70+
const controller = new AbortController();
71+
const ui = await createUI({ ...io, signal: controller.signal });
72+
const running = ui.main();
73+
let settled = false;
74+
void running.then(
75+
() => {
76+
settled = true;
77+
},
78+
() => {
79+
settled = true;
80+
},
81+
);
4882

4983
try {
50-
void ui.main();
5184
const { document } = ui;
5285
document.documentElement.appendChild(document.createTextNode('first'));
5386
await nextTurn();
@@ -57,56 +90,76 @@ describe('UI lifecycle', () => {
5790
await nextTurn();
5891
expect(frames).toBe(2);
5992

60-
disposing = Promise.resolve(ui[Symbol.asyncDispose]());
61-
let settled = false;
62-
void disposing.then(
63-
() => {
64-
settled = true;
65-
},
66-
() => {
67-
settled = true;
68-
},
69-
);
93+
controller.abort();
94+
expect(ui.main()).toBe(running);
7095
await nextTurn();
7196
expect(settled).toBe(false);
7297
expect(writes).not.toContain(restore);
7398

7499
output.resolve();
75-
await disposing;
100+
await nextTurn();
76101
expect(writes.at(-1)).toBe(restore);
102+
expect(settled).toBe(false);
103+
104+
restoration.resolve();
105+
await running;
106+
expect(ui.main()).toBe(running);
77107
expect(frames).toBe(2);
78108
} finally {
109+
controller.abort();
79110
output.resolve();
80-
await (disposing ?? ui[Symbol.asyncDispose]());
111+
restoration.resolve();
112+
await running;
81113
}
82114
});
83115

84-
test('disposal propagates a render failure after restoring terminal settings', async () => {
116+
test('main propagates a render failure after restoring terminal settings', async () => {
85117
using io = setup();
86118
const { writes } = io;
87-
const ui = await createUI(io);
119+
const controller = new AbortController();
120+
const ui = await createUI({ ...io, signal: controller.signal });
88121
const failure = new TestRenderError();
89122
const text = ui.document.createTextNode('unreadable');
90123
Object.defineProperty(text, 'data', {
91124
get() {
92125
throw failure;
93126
},
94127
});
95-
let disposing: Promise<void> | undefined;
128+
const running = ui.main();
96129

97130
try {
98-
const failed = expect(ui.main()).rejects.toBe(failure);
131+
const failed = expect(running).rejects.toBe(failure);
99132
ui.document.documentElement.appendChild(text);
100133
await failed;
101134

102-
disposing = Promise.resolve(ui[Symbol.asyncDispose]());
103-
await expect(disposing).rejects.toBe(failure);
135+
controller.abort();
136+
expect(ui.main()).toBe(running);
137+
await expect(ui.main()).rejects.toBe(failure);
104138
expect(writes).toEqual([apply, restore]);
105139
} finally {
106-
// Manually own the expected failure; never dispose the resource twice.
107-
if (!disposing) {
108-
await Promise.resolve(ui[Symbol.asyncDispose]()).catch(() => {});
109-
}
140+
controller.abort();
141+
await running.catch(() => {});
142+
}
143+
});
144+
145+
test('rejects setup failure without attempting terminal restoration', async () => {
146+
const failure = new Error('setup failed');
147+
using io = setup((_chunk, complete) => complete(failure));
148+
const controller = new AbortController();
149+
const ui = await createUI({ ...io, signal: controller.signal });
150+
const write = vi.spyOn(io.output, 'write');
151+
const outputError = once(io.output, 'error');
152+
const running = ui.main();
153+
154+
try {
155+
await expect(running).rejects.toBe(failure);
156+
await expect(outputError).resolves.toEqual([failure]);
157+
expect(write).toHaveBeenCalledTimes(1);
158+
expect(io.writes).toEqual([apply]);
159+
} finally {
160+
controller.abort();
161+
write.mockRestore();
162+
await running.catch(() => {});
110163
}
111164
});
112165
});

‎packages/ui/src/ui.ts‎

Lines changed: 22 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import { alternateBuffer, createTerm, cursor, settings, type Term } from '@bomb.sh/tty';
1+
import { alternateBuffer, createTerm, cursor, settings } from '@bomb.sh/tty';
22
import type { Readable, Writable } from 'node:stream';
33
import { Document } from './dom.ts';
44
import { RenderApi } from './render.ts';
55
import { Layout } from './layout.ts';
66

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

@@ -15,75 +14,45 @@ export interface UIOptions {
1514
width?: number;
1615
input: Readable;
1716
output: Writable;
17+
signal: AbortSignal;
1818
}
1919

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

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

2725
const term = await createTerm({ width, height });
28-
const render = new RenderApi(controller.signal);
26+
const render = new RenderApi(signal);
2927

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

3230
const layout = new Layout(document.documentElement);
3331

34-
const loop = new RenderLoop({ layout, term, output, frames: render });
32+
let running: Promise<void> | undefined = undefined;
33+
34+
const run = async () => {
35+
await write(output, setup.apply);
36+
37+
try {
38+
for await (const _ of render) {
39+
const ops = [...layout.layout()];
40+
const result = term.render(ops);
41+
await write(output, result.output);
42+
}
43+
} finally {
44+
await write(output, setup.revert);
45+
}
46+
};
3547

3648
return {
3749
document,
38-
main: () => loop.run(),
39-
async [Symbol.asyncDispose]() {
40-
controller.abort();
41-
try {
42-
await loop.run();
43-
} finally {
44-
await write(output, setup.revert);
45-
}
50+
main() {
51+
return running ? running : signal.aborted ? Promise.resolve() : (running = run());
4652
},
4753
};
4854
}
4955

50-
interface RenderLoopOptions {
51-
layout: Layout;
52-
frames: AsyncIterable<void>;
53-
term: Term;
54-
output: Writable;
55-
}
56-
57-
class RenderLoop {
58-
#layout: Layout;
59-
#frames: AsyncIterable<void>;
60-
#term: Term;
61-
#output: Writable;
62-
#running: Promise<void> | undefined;
63-
64-
constructor(options: RenderLoopOptions) {
65-
this.#layout = options.layout;
66-
this.#frames = options.frames;
67-
this.#term = options.term;
68-
this.#output = options.output;
69-
}
70-
71-
async #loop() {
72-
for await (const _ of this.#frames) {
73-
const ops = [...this.#layout.layout()];
74-
const result = this.#term.render(ops);
75-
await write(this.#output, result.output);
76-
}
77-
}
78-
79-
run() {
80-
if (!this.#running) {
81-
this.#running = this.#loop();
82-
}
83-
return this.#running;
84-
}
85-
}
86-
8756
function write(stream: Writable, bytes: Uint8Array): Promise<void> {
8857
const result = Promise.withResolvers<void>();
8958
stream.write(bytes, (err) => {

‎packages/ui/test/ui.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,28 +11,34 @@ export interface TestUI extends AsyncDisposable {
1111
export async function createTestUI(options: SyncTestTerminalOptions = {}): Promise<TestUI> {
1212
const { cols = 80, rows = 24 } = options;
1313
const terminal = createTestTerminal({ ...options, cols, rows });
14+
const controller = new AbortController();
1415

1516
try {
1617
const ui = await createUI({
1718
input: terminal.input,
1819
output: terminal.output,
1920
width: cols,
2021
height: rows,
22+
signal: controller.signal,
2123
});
22-
void ui.main();
24+
const running = ui.main();
25+
// Disposal awaits the original task and propagates any rendering failure.
26+
void running.catch(() => {});
2327

2428
return {
2529
terminal,
2630
document: ui.document,
2731
async [Symbol.asyncDispose]() {
32+
controller.abort();
2833
try {
29-
await ui[Symbol.asyncDispose]();
34+
await running;
3035
} finally {
3136
await terminal[Symbol.asyncDispose]();
3237
}
3338
},
3439
};
3540
} catch (error) {
41+
controller.abort();
3642
await terminal[Symbol.asyncDispose]();
3743
throw error;
3844
}

0 commit comments

Comments
 (0)