Repository navigation
Expand file tree
/
Copy pathsuspend.ts
More file actions
696 lines (666 loc) · 28.9 KB
/
Copy pathsuspend.ts
File metadata and controls
696 lines (666 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import { CliError } from '../process/errors.js';
import { EgressWorkScope } from '../engine/egress-work.js';
import {
DISABLE_MOUSE,
ENABLE_MOUSE,
ENTER_ALT_SCREEN,
EXIT_ALT_SCREEN,
HIDE_CURSOR,
SHOW_CURSOR,
} from './alt-screen.js';
/**
* **Suspend the full-screen renderer** and hand the raw terminal to something else — the substrate for the ADR-0068 §e
* copy-and-search escape hatches (`/scrollback` dumps the transcript into native scrollback; `/edit` opens it in
* `$EDITOR`). 2.6.F Step 5d.
*
* It wraps ink 7's `useApp().suspendTerminal(cb)`, whose contract (read from `ink@7.1.0/build/ink.js`
* `beginSuspend`/`endSuspend`, since none of this is documented) decides everything below:
*
* 1. `beginSuspend()` flushes + **erases ink's current frame** (`log.clear()` + `log.done()`), then `pauseInput()` —
* which turns OFF raw mode and bracketed paste (DECSET 2004) and detaches ink's stdin listeners. So we must NOT
* touch raw mode or bracketed paste ourselves: ink owns both, symmetrically.
* 2. It toggles the alternate screen (DECSET 1049) **only `if (this.alternateScreen)`** — ink's *render option*, not
* whether the terminal happens to be in the alt buffer. That option is `true` for the bare Home but HARD `false`
* for `relavium chat`, whose hoisted `AltScreenController` owns 1049 (Step 4b-3). Hence {@link
* SuspendFullScreenOptions.inkOwnsAltScreen}: on the chat surface we exit/re-enter 1049 ourselves, or `$EDITOR`
* would paint into the alt buffer and vanish on resume. Both halves ALSO early-return under
* `!interactive || isUnmounted || isUnmounting` for buffer writes. Crucially, `endSuspend()` calls
* `resumeInput()` BEFORE that guard in installed Ink 7.1.0: a late continuation can restore raw input even
* after unmount. An owned mount must seal and join entered suspension before its final unmount.
* 3. ink writes **no mouse escapes at all** (verified: its whole build contains no `?1000`/`?1006`). Mouse reporting
* is entirely ours, so we suspend and restore it on both surfaces — leaving DECSET 1002 on while a child owns the
* TTY floods that child with `\x1b[<…M` reports.
* 4. `endSuspend()` calls `resumeInput()` **before** re-entering the alt buffer, then forces a full redraw. So every
* write we make must land inside the callback, while input is still paused — never after it returns.
*
* ORDERING, therefore: exit the alt buffer INSIDE the callback (after ink erased its frame). Doing it earlier would
* make ink's `log.clear()` erase the *primary* buffer — scrolling the user's shell history away.
*
* EXIT SAFETY, in the spirit of `withHoistedAltScreen`. Three rules, and NOT a `finally` — see below:
* - **Restore only what was changed.** A release write that throws part-way must not be "undone" (re-entering an
* alt buffer we never exited would corrupt a terminal ink left intact).
* - **The restores are isolated.** Each reclaim write has its own `try`, so a failing alt-buffer re-enter can
* never skip the mouse restore after it — a stranded DECSET-1000 is the worst state we can leave.
* - **The first error wins.** A `finally` cannot express this: a throw from a `finally` REPLACES the throw already
* unwinding out of its `try`, so a failing restore write would mask the real cause and tell the user "stdout
* closed" instead of "could not start $EDITOR" (`error-handling.md`). The body's error is captured into
* `pending` and rethrown after the reclaim; a secondary write failure is dropped.
*/
/** ink 7's `useApp().suspendTerminal` in its callback form. Rejects if the terminal is ALREADY suspended
* (`beginSuspend` throws), so a surface must gate re-entrancy before calling {@link suspendFullScreen}. */
export type SuspendTerminal = (callback: () => Promise<void>) => Promise<void>;
export interface SuspendFullScreenOptions {
/** ink's `useApp().suspendTerminal` — the only way to make ink release raw mode, bracketed paste, and its frame. */
readonly suspendTerminal: SuspendTerminal;
/** Write a raw control sequence to the TTY (production: `process.stdout.write`; tests: a capture). */
readonly writeControl: (sequence: string) => void | Promise<void>;
/**
* `true` when ink's `alternateScreen` RENDER OPTION is on — the bare Home, where ink's own `beginSuspend`/
* `endSuspend` exit and re-enter DECSET-1049 for us. `false` for `relavium chat` (the option is hard-`false`; the
* hoisted controller owns 1049), where WE must toggle it. Getting this backwards either strands `$EDITOR` inside
* the invisible alt buffer, or double-toggles 1049 and loses the frame.
*/
readonly inkOwnsAltScreen: boolean;
/** `true` when the alt buffer is currently entered. `false` on the inline renderer — there is no buffer to leave,
* and `suspendFullScreen` degrades to "ink hands over raw mode" (which `/edit` still needs). */
readonly altActive: boolean;
/** `true` when mouse reporting (DECSET 1002+1006) is currently on. Independent of {@link altActive} on purpose:
* once `--no-mouse` lands, the alt screen can be active with the mouse off. */
readonly mouseActive: boolean;
}
/**
* Run `body` with the terminal handed back to the user (or to a TTY-inheriting child), then restore the full-screen
* renderer exactly as it was. Rejects with whatever `body` (or ink) threw, AFTER restoring.
*/
export async function suspendFullScreen(
opts: SuspendFullScreenOptions,
body: () => Promise<void>,
): Promise<void> {
const { suspendTerminal, writeControl, inkOwnsAltScreen, altActive, mouseActive } = opts;
const weOwnAltScreen = altActive && !inkOwnsAltScreen;
await suspendTerminal(async () => {
// Track what we ACTUALLY changed, so a write that throws part-way cannot leave a half-restored terminal (a
// blind symmetric restore would, say, re-enter an alt buffer we never exited).
let mouseSuspended = false;
let altExited = false;
// The FIRST error seen — the root cause. A later restore-write failure must never replace it: the user needs to
// read "could not start $EDITOR", not "stdout closed" (error-handling.md — never swallow a root cause to
// re-throw a vaguer one). A `finally` cannot express this: a throw from a `finally` REPLACES the pending throw.
let pending: { readonly error: unknown } | undefined;
// RELEASE — hand the terminal over.
try {
if (mouseActive) {
await writeControl(DISABLE_MOUSE); // Delivery precedes native handoff to a child/job stop.
mouseSuspended = true;
}
if (weOwnAltScreen) {
await writeControl(EXIT_ALT_SCREEN + SHOW_CURSOR); // Ink does not own this surface's buffer.
altExited = true;
}
await body();
} catch (error) {
pending = { error };
}
// RECLAIM — mirror the release, innermost-first. Each write is isolated, so one failing sequence can never skip
// the next: a stranded DECSET-1000 (mouse reporting left on) is the worst terminal state we can leave, and it is
// restored even when re-entering the alt buffer throws.
const reclaim = async (sequence: string): Promise<void> => {
try {
await writeControl(sequence);
} catch (error) {
pending ??= { error }; // only the root cause survives; a secondary write failure on a dead stdout is noise
}
};
if (altExited) await reclaim(ENTER_ALT_SCREEN + HIDE_CURSOR);
if (mouseSuspended) await reclaim(ENABLE_MOUSE);
if (pending !== undefined) throw pending.error;
});
}
/**
* The **suspend port** — the repo's first React→core capability bridge, and the reason the hatches need no
* surface-specific interception at all.
*
* `suspendTerminal` exists ONLY inside a mounted ink tree (`useApp()`), but the slash-command dispatch that must call
* it lives outside React: `relavium chat`'s `ReplCommandContext` is built before `driveInk` mounts, and the Home's
* `createHomeController` is built before `RootApp` mounts. Every existing port (`runShellCommand`, `modelPicker`,
* `mentionReader`) flows the other way — built outside React, consumed inside. This one inverts that: the non-React
* layer creates an empty port, hands it to both the command context and the component; the component `attach`es its
* `suspendTerminal` on mount and detaches on unmount.
*
* `current()` is therefore the honest answer to "is there a live full-screen renderer right now?" — `undefined` on a
* plain / `--json` driver (no ink at all), and between a session's unmount and the next mount. A hatch that reads
* `undefined` surfaces an actionable notice instead of failing.
*/
export interface SuspendPort {
/** Called by the ink tree: the live `suspendTerminal` on mount, `undefined` on unmount. */
readonly attach: (suspend: SuspendTerminal | undefined) => void;
/** The live `suspendTerminal`, or `undefined` when no ink tree is mounted. Read at CALL time, never captured. */
readonly current: () => SuspendTerminal | undefined;
/**
* `true` for exactly as long as a suspension obtained from {@link current} is in flight.
*
* LOAD-BEARING, not diagnostic. During a suspension ink has turned raw mode OFF, so a keyboard **Ctrl-C is no
* longer swallowed by `useInput`** — the tty line discipline delivers it as a REAL process SIGINT. The chat's
* `process.on('SIGINT')` handler would then run its cooperative `/cancel`, unmount ink, and exit the hoisted alt
* buffer *behind the suspension's back* — while the suspension is still awaiting `$EDITOR` or the "press Enter"
* prompt. Its reclaim would later re-enter the alt buffer and re-enable the mouse on the user's SHELL. A signal
* handler must therefore ask this before acting (Step-5d-3 Sonnet review).
*/
readonly isSuspended: () => boolean;
/** Publish and acknowledge a notice while Ink owns the terminal, excluding suspension until completion. */
readonly withActiveTerminal: (publish: () => Promise<void>) => Promise<void>;
/** Reserve a mount-specific attachment before rendering; an old effect cannot detach its successor. */
readonly reserveAttachment: () => SuspendAttachment;
}
export interface SuspendAttachment {
readonly port: SuspendPort;
/** Synchronously stop future entry, then join full entered suspension/publication continuations. */
readonly sealAndJoin: () => Promise<void>;
}
/**
* The flag is maintained by the PORT, wrapped around the ink call it hands out — not by the caller. A caller cannot
* forget to set it, and it is impossible for `isSuspended()` to disagree with what the terminal is actually doing.
*/
export function createSuspendPort(): SuspendPort {
interface Reservation {
readonly work: EgressWorkScope;
readonly generation: number;
sealed: boolean;
}
interface Attached {
readonly reservation: Reservation;
readonly suspend: SuspendTerminal;
}
let attached: Attached | undefined;
let legacy: SuspendAttachment | undefined;
let legacySealed = false;
let suspended = false;
let occupied = false;
let generation = 0;
let latestActivated = 0;
const waiters = new Set<() => void>();
const changed = (): void => {
const pending = [...waiters];
waiters.clear();
for (const wake of pending) wake();
};
const live = (expected: Attached): boolean =>
attached === expected && !expected.reservation.sealed;
const unavailable = (): CliError =>
new CliError('internal', 'The terminal renderer is no longer active.');
const exclusive = async (expected: Attached, body: () => Promise<void>): Promise<void> => {
while (occupied) {
if (!live(expected)) throw unavailable();
await new Promise<void>((resolve) => waiters.add(resolve));
}
if (!live(expected)) throw unavailable();
occupied = true;
try {
await body();
} finally {
occupied = false;
changed();
}
};
const enter = (expected: Attached, body: () => Promise<void>): Promise<void> => {
if (!live(expected)) return Promise.reject(unavailable());
return expected.reservation.work.retainWork(() => exclusive(expected, body));
};
const current = (): SuspendTerminal | undefined => {
const expected = attached;
if (expected === undefined || !live(expected)) return undefined;
return (callback) => {
if (suspended)
return Promise.reject(new CliError('internal', 'The terminal is already suspended.'));
return enter(expected, async () => {
suspended = true;
try {
await expected.suspend(callback);
} finally {
suspended = false;
}
});
};
};
const withActiveTerminal = (publish: () => Promise<void>): Promise<void> => {
const expected = attached;
return expected === undefined ? Promise.reject(unavailable()) : enter(expected, publish);
};
const reserveAttachment = (): SuspendAttachment => {
const reservation: Reservation = {
work: new EgressWorkScope(),
generation: ++generation,
sealed: false,
};
const port: SuspendPort = Object.freeze({
attach: (next: SuspendTerminal | undefined) => {
if (next === undefined) {
if (attached?.reservation === reservation) attached = undefined;
} else if (!reservation.sealed && reservation.generation >= latestActivated) {
const predecessor = attached?.reservation;
if (predecessor !== undefined && predecessor !== reservation) {
predecessor.sealed = true;
predecessor.work.seal();
}
latestActivated = reservation.generation;
attached = { reservation, suspend: next };
}
changed();
},
current: () => (attached?.reservation === reservation ? current() : undefined),
isSuspended: () => suspended,
withActiveTerminal: (publish: () => Promise<void>) =>
attached?.reservation === reservation
? withActiveTerminal(publish)
: Promise.reject(unavailable()),
reserveAttachment,
});
return Object.freeze({
port,
sealAndJoin: () => {
reservation.sealed = true;
reservation.work.seal();
changed(); // Queued, not-entered work rejects; actual entered continuations remain owed.
return reservation.work.done;
},
});
};
return Object.freeze({
attach: (next: SuspendTerminal | undefined) => {
// The legacy embedding API keeps working; owned surfaces reserve their exact mount explicitly.
if (legacy === undefined || (next !== undefined && legacySealed)) {
if (legacy !== undefined) void legacy.sealAndJoin();
legacy = reserveAttachment();
legacySealed = false;
}
legacy.port.attach(next);
if (next === undefined) {
legacySealed = true;
void legacy.sealAndJoin();
}
},
current,
isSuspended: () => suspended,
withActiveTerminal,
reserveAttachment,
});
}
/**
* The named, POSIX-only job-control signal seam. `SIGTSTP`/`SIGCONT` are deliberately NOT folded into the normal
* termination callbacks: stopping a foreground job is reversible, whereas SIGINT/TERM/HUP/QUIT tear the command
* down, close its database, and exit. Keeping the names here also avoids treating platform-specific signal numbers
* as a public contract.
*/
export interface JobControlLifecycle {
/** `false` on platforms without POSIX job control (notably Windows): no listeners are installed and Ctrl-Z is inert. */
readonly supported: boolean;
/** Register the catchable stop request; returns its exact remover. */
readonly onSuspend: (listener: () => void) => () => void;
/** Register the continuation notification; it remains installed while the process is stopped. */
readonly onContinue: (listener: () => void) => () => void;
/** Re-deliver SIGTSTP to this process after our listener has released terminal state and removed itself. */
readonly suspendSelf: () => void;
}
const noop = (): void => undefined;
/** Production process binding for {@link JobControlLifecycle}. No unsupported Windows signal is ever registered. */
export const defaultJobControlLifecycle: JobControlLifecycle = {
supported: process.platform !== 'win32',
onSuspend: (listener) => {
if (process.platform === 'win32') return noop;
process.on('SIGTSTP', listener);
return () => process.removeListener('SIGTSTP', listener);
},
onContinue: (listener) => {
if (process.platform === 'win32') return noop;
process.on('SIGCONT', listener);
return () => process.removeListener('SIGCONT', listener);
},
suspendSelf: () => {
if (process.platform !== 'win32') process.kill(process.pid, 'SIGTSTP');
},
};
/**
* Perform an Ink-aware terminal release and wait for a matching SIGCONT. `run` must use {@link suspendFullScreen}
* (rather than calling Ink directly), preserving each surface's proven alt-screen and mouse ownership rules.
*/
export type JobControlRun = (
suspendTerminal: SuspendTerminal,
waitForContinue: () => Promise<void>,
) => Promise<void>;
/** The reversible job-control binding returned by {@link wireJobControl}. */
export interface JobControlBinding {
/** Request a stop from either a process SIGTSTP or the raw-mode Ctrl-Z input byte. */
readonly requestSuspend: () => void;
/** Remove the process listeners; safe to call more than once. */
readonly dispose: () => void;
/** Drain an already-entered handoff while Ink is still mounted, before final unmount/restore. */
readonly finish: () => Promise<void>;
/** Positive listener removal and entered-work acknowledgement, never supplied by dispose alone. */
readonly released: Promise<void>;
}
/**
* Bind POSIX job control to one mounted Ink surface.
*
* The critical ordering is enforced in one place:
*
* 1. `run` enters Ink's suspension window and releases mouse/alt state.
* 2. only inside that released window do we remove our SIGTSTP listener and re-deliver SIGTSTP to the process;
* 3. SIGCONT re-arms SIGTSTP before resolving the wait, after which Ink restores raw input and redraws. A second
* stop received while that reclaim is in flight is remembered and replayed only after Ink has finished its redraw;
* it is never silently swallowed.
*
* A hatch may already own `SuspendPort` (`/scrollback`/`/edit`), and a chat rebuild has a brief interval with no Ink
* tree at all. Those paths deliberately do not nest Ink suspension: they release/reclaim only the optional hoisted
* terminal state around the real stop, then let the existing owner resume normally.
*/
export function wireJobControl(opts: {
readonly suspendPort: SuspendPort;
readonly lifecycle: JobControlLifecycle;
readonly run: JobControlRun;
/** Optional reversible release for an interval with no Ink tree (the chat hoist's rebuild window). */
readonly releaseWithoutInk?: () => boolean;
/** Mirrors {@link releaseWithoutInk} after the stopped process is foregrounded again. */
readonly reclaimWithoutInk?: () => void;
/** Owned delivery-before-stop path; the synchronous embedding ports above retain compatibility. */
readonly releaseWithoutInkAcknowledged?: () => Promise<boolean>;
readonly reclaimWithoutInkAcknowledged?: () => Promise<void>;
/** Transfer cleanup before any potentially allocating signal registration. */
readonly adopt?: (binding: JobControlBinding) => void;
readonly onFailure?: (cause: unknown) => void;
}): JobControlBinding {
if (!opts.lifecycle.supported) {
const released = Promise.resolve();
const binding = Object.freeze({
requestSuspend: noop,
dispose: noop,
finish: () => released,
released,
});
opts.adopt?.(binding);
return binding;
}
let disposed = false;
let suspending = false;
let pendingSuspend = false;
let resolveContinue: (() => void) | undefined;
let removeSuspend: (() => void) | undefined;
let removeContinue: (() => void) | undefined;
let constructing = true;
let unknownRegistration = false;
let registrations = 0;
let finishing: Promise<void> | undefined;
const work = new EgressWorkScope();
let acknowledge: () => void = () => undefined;
let rejectRelease: (cause: unknown) => void = () => undefined;
const released = new Promise<void>((resolve, reject) => {
acknowledge = resolve;
rejectRelease = reject;
});
void released.catch(noop); // Embeddings may observe later; rejection supplies no positive native ACK.
const report = (cause: unknown): void => {
try {
opts.onFailure?.(cause);
} catch (observer) {
rejectRelease(new CliError('cli_internal', '', { cause: { primary: cause, observer } }));
}
};
const removeSuspendListener = (): void => {
const remove = removeSuspend;
if (remove === undefined) return;
removeSuspend = undefined;
registrations += 1;
try {
remove();
} catch (cause) {
removeSuspend = remove;
throw cause;
} finally {
registrations -= 1;
}
};
const installSuspendListener = (): void => {
if (disposed || removeSuspend !== undefined) return;
registrations += 1;
let acquired = false;
try {
removeSuspend = opts.lifecycle.onSuspend(requestSuspend);
acquired = true;
if (disposed) removeSuspendListener();
} catch (cause) {
if (!acquired) unknownRegistration = true;
throw cause;
} finally {
registrations -= 1;
}
};
const continueSuspension = (): void => {
if (disposed) return;
const resolve = resolveContinue;
if (resolve === undefined) return; // a stray SIGCONT must not perturb an active surface
// Re-arm BEFORE Ink resumes input/redraws. A fast second Ctrl-Z is then captured by our handler rather than
// falling through to a default stop while the terminal is still being reclaimed.
installSuspendListener();
if (disposed) return;
resolveContinue = undefined;
resolve();
};
/** Remove our handler just long enough for the OS default SIGTSTP action to stop the process. */
const forwardSuspend = (): void => {
if (disposed) return;
removeSuspendListener();
if (disposed) return;
try {
opts.lifecycle.suspendSelf();
} catch (cause) {
report(cause);
// A failed self-signal means there was no stop/continuation. Resolve a pending release so Ink can reclaim;
// the finally below restores our SIGTSTP listener too.
continueSuspension();
} finally {
// `suspendSelf()` returns only after SIGCONT. This is the re-arm for the no-Ink and hatch-owned paths; the
// Ink-owned path already re-arms in `continueSuspension` before it resolves the deferred, so this is a no-op.
installSuspendListener();
}
};
const settle = (): void => {
resolveContinue = undefined;
suspending = false;
installSuspendListener();
// `SIGCONT` deliberately re-arms before Ink starts reclaiming terminal state: an external SIGTSTP can otherwise
// default-stop the process in the tiny interval after 1049/raw input has been restored but before the mouse/
// redraw have completed. The coordinator is still busy, so retain ONE request and replay it after the terminal is
// coherent again. `queueMicrotask` also keeps the signal callback itself synchronous and side-effect bounded.
queueMicrotask(() => {
if (disposed || suspending || !pendingSuspend) return;
pendingSuspend = false;
requestSuspend();
});
};
function performSuspend(): void {
if (disposed) return;
if (suspending) {
// Coalesce a burst into one real follow-up stop. Dropping it would make a fast Ctrl-Z / SIGTSTP after `fg`
// appear to succeed (the listener consumed it) while leaving the process running.
pendingSuspend = true;
return;
}
// A hatch has already released Ink's input and its terminal modes. Nesting `suspendTerminal` would throw
// "already suspended" and could reclaim the hatch's terminal behind its back, so just perform genuine POSIX job
// control and let the still-pending hatch resume after foregrounding.
if (opts.suspendPort.isSuspended()) {
forwardSuspend();
return;
}
const suspendTerminal = opts.suspendPort.current();
if (disposed) return;
if (suspendTerminal === undefined) {
if (opts.releaseWithoutInkAcknowledged !== undefined) {
suspending = true;
try {
const raw = work.retainWork(async () => {
if (!(await opts.releaseWithoutInkAcknowledged?.()) || disposed) return;
forwardSuspend();
if (!disposed) await opts.reclaimWithoutInkAcknowledged?.();
});
void raw
.then(settle, (cause: unknown) => {
report(cause);
settle();
})
.catch(report);
} catch (cause) {
report(cause);
settle();
}
return;
}
// Before Home mounts (onboarding) there is no Ink state to release. In the chat's rebuild window there can be
// a live hoisted alt buffer, supplied by the reversible hooks below.
if (opts.releaseWithoutInk !== undefined && !opts.releaseWithoutInk()) return;
if (disposed) return;
forwardSuspend();
if (disposed) return;
opts.reclaimWithoutInk?.();
return;
}
suspending = true;
const waitForContinue = (): Promise<void> =>
new Promise((resolve) => {
if (disposed) {
resolve();
return;
}
resolveContinue = resolve;
forwardSuspend();
});
// Signals cannot await a promise. Absorb a terminal-write/Ink failure here: `suspendFullScreen` has already
// performed its own partial-state reclaim, and an unhandled rejection from a signal handler is strictly worse.
// We intentionally do not re-raise after a failed release because terminal release never reached the safe point.
try {
const raw = work.retainWork(() => opts.run(suspendTerminal, waitForContinue));
void raw
.then(settle, (cause: unknown) => {
try {
report(cause);
} finally {
settle();
}
})
.catch(report);
} catch (cause) {
try {
report(cause);
} finally {
settle();
}
}
}
function requestSuspend(): void {
if (constructing) {
pendingSuspend = true;
return;
}
try {
performSuspend();
} catch (cause) {
report(cause);
}
}
const dispose = (): void => {
disposed = true;
pendingSuspend = false;
// BOTH listeners, not just SIGCONT: `wireJobControl` installs the SIGTSTP one at construction, so
// removing only the continue handler leaked a suspend handler per binding. Every session rebuild — a
// `/clear`, a `/model` reseat, the onboarding→Home handoff — added another, so one Ctrl-Z eventually ran
// several handlers and Node warned about a listener leak.
let failed: { readonly cause: unknown } | undefined;
try {
removeSuspendListener();
} catch (cause) {
failed = { cause };
}
const remove = removeContinue;
if (remove !== undefined) {
removeContinue = undefined;
registrations += 1;
try {
remove();
} catch (cause) {
removeContinue = remove;
failed ??= { cause };
} finally {
registrations -= 1;
}
}
if (failed !== undefined) throw failed.cause;
};
const finish = (): Promise<void> => {
if (finishing !== undefined) return finishing;
finishing = released;
let failed: { readonly cause: unknown } | undefined;
try {
dispose();
} catch (cause) {
failed = { cause };
}
// Synchronous exit fallback deliberately leaves this waiter held. An owned asynchronous
// finish instead drains the full reclaim BEFORE its caller unmounts/restores the terminal.
const resume = resolveContinue;
resolveContinue = undefined;
resume?.();
work.seal();
if (failed !== undefined) report(failed.cause);
void work.done.then(() => {
if (
!constructing &&
registrations === 0 &&
!unknownRegistration &&
removeSuspend === undefined &&
removeContinue === undefined
)
acknowledge();
});
return released;
};
const binding = Object.freeze({ requestSuspend, dispose, finish, released });
opts.adopt?.(binding);
let primary: { readonly cause: unknown } | undefined;
try {
if (!disposed) {
registrations += 1;
let acquired = false;
try {
removeContinue = opts.lifecycle.onContinue(() => {
try {
continueSuspension();
} catch (cause) {
report(cause);
}
});
acquired = true;
} catch (cause) {
if (!acquired) unknownRegistration = true;
throw cause;
} finally {
registrations -= 1;
}
if (disposed) dispose();
else installSuspendListener();
}
} catch (cause) {
primary = { cause };
try {
dispose();
} catch (cleanup) {
report(cleanup);
}
} finally {
constructing = false;
}
if (primary !== undefined) throw primary.cause;
if (pendingSuspend && !disposed) {
pendingSuspend = false;
queueMicrotask(requestSuspend);
}
return binding;
}