Skip to content

Commit d8257bf

Browse files
committed
chore: upgrade to React 19 and Ink 6
Prerequisite for the upcoming `codify prompt` chat UI, which is built on @assistant-ui/react-ink (requires react ^19 and ink >=6). - react 18 -> 19.2, ink 5 -> 6.8, ink-gradient 3 -> 4, @types/react 19, react-devtools-core 6. Ink 6.8 is the newest line that still supports Node 20 (ink 7+ requires Node 22). React is pinned to ~19.2 to match the react-reconciler (0.33) that ink 6 ships with. - typescript 5.3 -> 5.9 and skipLibCheck: ink 6's type-fest 5 typings need TS >= 5.4, and TS 5.9 flags .d.ts files inside @codifycli/schemas. - Rewrite the App.js/ink.js parts of scripts/patch-ink.ts. Ink 6's App is a function component, so the stdin suspend/resume closures are registered on a `codifyStdinControl` prop instead of found by walking the fiber tree. pauseRendering now also cancels pending throttled writes, and resumeRendering forces the next frame to be written. - Wait for render state commits in DefaultReporter. React 19 no longer commits updates from outside React synchronously, so display calls that were followed by process.exit() (e.g. `codify plan`) exited before the final frame rendered. DefaultComponent now emits RENDER_STATE_COMMITTED from a layout effect and the reporter awaits it (250ms fallback). - Give <Static> width 100%: the newer yoga no longer stretches absolutely positioned boxes, which shrank the plan header box to its content. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk1T9WChsm317yyQKmh
1 parent 336afe0 commit d8257bf

11 files changed

Lines changed: 411 additions & 225 deletions

File tree

‎package-lock.json‎

Lines changed: 245 additions & 140 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
"detect-indent": "^7.0.1",
2323
"diff": "^8.0.3",
2424
"express": "^5.1.0",
25-
"ink": "^5.2.1",
25+
"ink": "^6.8.0",
2626
"ink-big-text": "^2.0.0",
27-
"ink-gradient": "^3.0.0",
27+
"ink-gradient": "^4.0.1",
2828
"ink-select-input": "^6.0.0",
2929
"jju": "^1.4.0",
3030
"jose": "^6.1.0",
@@ -39,7 +39,7 @@
3939
"node-pty": "1.2.0-beta.15",
4040
"open": "^10.1.2",
4141
"parse-json": "^8.1.0",
42-
"react": "^18.3.1",
42+
"react": "~19.2.0",
4343
"uuid": "^10.0.0",
4444
"ws": "^8.18.3"
4545
},
@@ -57,7 +57,7 @@
5757
"@types/json5": "^2.2.0",
5858
"@types/mocha": "^10.0.10",
5959
"@types/node": "^20",
60-
"@types/react": "^18.3.1",
60+
"@types/react": "~19.2.0",
6161
"@types/strip-ansi": "^5.2.1",
6262
"@types/uuid": "^10.0.0",
6363
"@types/ws": "^8.18.1",
@@ -70,16 +70,17 @@
7070
"ink-testing-library": "^4.0.0",
7171
"memfs": "^4.14.0",
7272
"oclif": "^6.0.10",
73-
"react-devtools-core": "4.28.5",
73+
"react-devtools-core": "^6.1.5",
7474
"shx": "^0.3.3",
7575
"strip-ansi": "^7.1.0",
7676
"tsx": "^4.7.3",
77-
"typescript": "5.3.3",
77+
"typescript": "~5.9.3",
7878
"vitest": "^4.0.18"
7979
},
8080
"overrides": {
81-
"ink-form": {
82-
"ink": "^5"
81+
"@codifycli/ink-form": {
82+
"ink": "$ink",
83+
"react": "$react"
8384
}
8485
},
8586
"engines": {

‎scripts/patch-ink.ts‎

Lines changed: 71 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,14 @@
77
// polling fd 0. The only clean fix is to let Ink tear down stdin via its own internal
88
// handleSetRawMode(false) path (which calls stdin.unref()), then re-add it afterward.
99
//
10+
// Targets ink 6.x. Every patch looks up exact source snippets and exits with an error if they are missing, so a
11+
// future ink upgrade fails loudly here instead of silently breaking the PTY handoff.
12+
//
1013
// What the patch adds:
11-
// App.js — suspendStdin() calls handleSetRawMode(false) to fully release stdin;
12-
// resumeStdin() calls handleSetRawMode(true) to restore it.
13-
// ink.js — suspendStdin()/resumeStdin() methods that delegate to the App instance.
14+
// App.js — registers suspend/resume closures on a `codifyStdinControl` prop. suspend fully releases stdin
15+
// (raw mode off, readable listener removed, unref); resume restores it.
16+
// ink.js — passes `codifyStdinControl` to App and exposes suspendStdin()/resumeStdin() plus
17+
// pauseRendering()/resumeRendering() for stopping the render loop during the handoff.
1418
// render.js — includes suspendStdin/resumeStdin in the return value of render().
1519
// reconciler.js — clears the cached <Static> node when it's unmounted (see the reconciler section below).
1620

@@ -57,60 +61,68 @@ if (!existsSync(APP_JS)) {
5761
}
5862

5963
// ── Patch App.js ─────────────────────────────────────────────────────────────
64+
// Since ink 6, App is a function component, so there is no class instance to call methods on. Instead, ink.js
65+
// (patched below) passes a mutable `codifyStdinControl` object as a prop, and App assigns suspend/resume closures
66+
// onto it on every render. The closures reuse App's own refs, so they always see the current listener state.
6067
let appContent = await fs.readFile(APP_JS, 'utf8');
6168

6269
if (!appContent.includes('CODIFY_INK_PATCH')) {
63-
// Remove any orphaned fragments from previous partial patch attempts
64-
appContent = appContent.replace(/\n stdin\.setRawMode\(false\);\n stdin\.removeListener\('readable', this\.handleReadable\);\n stdin\.unref\(\);\n \}\n \};\n resumeStdin[\s\S]*?\};\n(?= \/\/ CODIFY_INK_PATCH)/, '\n');
65-
66-
// Also patch handleSetRawMode to snapshot kState before addListener('readable')
67-
const SNAPSHOT_SEARCH = 'stdin.addListener(\'readable\', this.handleReadable);';
68-
const snapshotIdx = appContent.indexOf(SNAPSHOT_SEARCH);
69-
if (snapshotIdx !== -1) {
70-
const SNAPSHOT_PATCH = `const _ks = Object.getOwnPropertySymbols(stdin._readableState)[0];
71-
if (_ks !== undefined) { this._kStateBeforeReadable = stdin._readableState[_ks]; }
72-
`;
73-
appContent = appContent.slice(0, snapshotIdx) + SNAPSHOT_PATCH + appContent.slice(snapshotIdx);
74-
}
75-
76-
// Insert suspendStdin/resumeStdin just before the closing brace of the class
77-
const SEARCH = 'findPreviousFocusable = (state) => {';
78-
const idx = appContent.indexOf(SEARCH);
79-
if (idx === -1) {
80-
console.error('ERROR: Could not find insertion point in ink App.js.');
70+
const SIGNATURE_SEARCH = 'setCursorPosition, }) {';
71+
const SNAPSHOT_SEARCH = 'stdin.addListener(\'readable\', handleReadable);';
72+
const INSERT_SEARCH = '// Focus navigation helpers';
73+
if (
74+
!appContent.includes(SIGNATURE_SEARCH)
75+
|| !appContent.includes(SNAPSHOT_SEARCH)
76+
|| !appContent.includes(INSERT_SEARCH)
77+
) {
78+
console.error('ERROR: Could not find insertion points in ink App.js.');
8179
process.exit(1);
8280
}
8381

82+
// Accept the control object as a prop
83+
appContent = appContent.replace(SIGNATURE_SEARCH, 'setCursorPosition, codifyStdinControl, }) {');
84+
85+
// Snapshot stdin's internal kState bits right before ink adds its 'readable' listener (see suspend below)
86+
appContent = appContent.replace(SNAPSHOT_SEARCH, `if (codifyStdinControl) {
87+
const _ks = Object.getOwnPropertySymbols(stdin._readableState)[0];
88+
if (_ks !== undefined) { codifyStdinControl.kStateBeforeReadable = stdin._readableState[_ks]; }
89+
}
90+
${SNAPSHOT_SEARCH}`);
91+
8492
const PATCH = `// CODIFY_INK_PATCH — suspendStdin/resumeStdin
85-
_kStateBeforeReadable = undefined;
86-
suspendStdin = () => {
87-
if (this.isRawModeSupported() && this.rawModeEnabledCount > 0) {
88-
const { stdin } = this.props;
93+
if (codifyStdinControl) {
94+
codifyStdinControl.suspend = () => {
95+
if (!isRawModeSupported || rawModeEnabledCount.current === 0) {
96+
return;
97+
}
8998
stdin.setRawMode(false);
90-
stdin.removeListener('readable', this.handleReadable);
99+
detachReadableListener();
91100
stdin.unref();
101+
inputParserRef.current.reset();
102+
clearPendingInputFlush();
92103
// In Node 24, removeListener does not clear internal kState bits set by
93104
// addListener('readable'), so isPaused() stays true and resume() won't
94105
// switch to flowing mode. Restore the kState value from before Ink added
95106
// its readable listener to fully undo the listener registration.
96107
const kState = Object.getOwnPropertySymbols(stdin._readableState)[0];
97-
if (kState !== undefined && this._kStateBeforeReadable !== undefined) {
98-
stdin._readableState[kState] = this._kStateBeforeReadable;
108+
if (kState !== undefined && codifyStdinControl.kStateBeforeReadable !== undefined) {
109+
stdin._readableState[kState] = codifyStdinControl.kStateBeforeReadable;
110+
}
111+
};
112+
codifyStdinControl.resume = () => {
113+
if (!isRawModeSupported || rawModeEnabledCount.current === 0) {
114+
return;
99115
}
100-
}
101-
};
102-
resumeStdin = () => {
103-
if (this.isRawModeSupported() && this.rawModeEnabledCount > 0) {
104-
const { stdin } = this.props;
105116
stdin.ref();
106117
stdin.setRawMode(true);
107118
stdin.setEncoding('utf8');
108-
stdin.addListener('readable', this.handleReadable);
109-
}
110-
};
119+
readableListenerRef.current = handleReadable;
120+
stdin.addListener('readable', handleReadable);
121+
};
122+
}
111123
`;
112124

113-
appContent = appContent.slice(0, idx) + PATCH + appContent.slice(idx);
125+
appContent = appContent.replace(INSERT_SEARCH, PATCH + INSERT_SEARCH);
114126
await fs.writeFile(APP_JS, appContent, 'utf8');
115127
console.log('Patched ink App.js');
116128
} else {
@@ -120,51 +132,45 @@ if (!appContent.includes('CODIFY_INK_PATCH')) {
120132
// ── Patch ink.js ─────────────────────────────────────────────────────────────
121133
let inkContent = await fs.readFile(INK_JS, 'utf8');
122134

123-
if (!inkContent.includes('suspendStdin')) {
124-
// Add suspendStdin/resumeStdin methods that reach into the React tree via the
125-
// container's current fiber to call the App component's methods.
126-
// Simpler approach: store the App ref. But since we don't have a ref, we access
127-
// the fiber's stateNode. Add methods to the Ink class that call into the container.
128-
const SEARCH = 'async waitUntilExit() {';
129-
const idx = inkContent.indexOf(SEARCH);
130-
if (idx === -1) {
131-
console.error('ERROR: Could not find insertion point in ink ink.js.');
135+
if (!inkContent.includes('CODIFY_INK_PATCH')) {
136+
const METHODS_SEARCH = 'async waitUntilExit() {';
137+
const APP_PROPS_SEARCH = 'onExit: this.handleAppExit }';
138+
if (!inkContent.includes(METHODS_SEARCH) || !inkContent.includes(APP_PROPS_SEARCH)) {
139+
console.error('ERROR: Could not find insertion points in ink ink.js.');
132140
process.exit(1);
133141
}
134142

135-
const PATCH = `suspendStdin() {
136-
// Walk the fiber tree to find the App component instance and call suspendStdin
137-
let fiber = this.container.current;
138-
while (fiber) {
139-
if (fiber.stateNode && typeof fiber.stateNode.suspendStdin === 'function') {
140-
fiber.stateNode.suspendStdin();
141-
return;
142-
}
143-
fiber = fiber.child;
144-
}
143+
// Hand App the control object it registers suspend/resume on
144+
inkContent = inkContent.replace(
145+
APP_PROPS_SEARCH,
146+
'onExit: this.handleAppExit, codifyStdinControl: this.codifyStdinControl }'
147+
);
148+
149+
const PATCH = `// CODIFY_INK_PATCH — stdin + render loop handoff
150+
codifyStdinControl = {};
151+
suspendStdin() {
152+
this.codifyStdinControl.suspend?.();
145153
}
146154
resumeStdin() {
147-
let fiber = this.container.current;
148-
while (fiber) {
149-
if (fiber.stateNode && typeof fiber.stateNode.resumeStdin === 'function') {
150-
fiber.stateNode.resumeStdin();
151-
return;
152-
}
153-
fiber = fiber.child;
154-
}
155+
this.codifyStdinControl.resume?.();
155156
}
156157
pauseRendering() {
157158
// Temporarily stop all stdout writes without tearing down the React tree.
159+
// Cancel pending throttled writes so nothing lands on the terminal after the pause.
160+
this.throttledOnRender?.cancel?.();
161+
this.throttledLog?.cancel?.();
158162
this.isUnmounted = true;
159163
this.log.clear();
160164
}
161165
resumeRendering() {
162166
this.isUnmounted = false;
167+
// The log was cleared on pause, so force the next frame to be written even if it is unchanged.
168+
this.lastOutput = '';
163169
this.onRender();
164170
}
165171
`;
166172

167-
inkContent = inkContent.slice(0, idx) + PATCH + inkContent.slice(idx);
173+
inkContent = inkContent.replace(METHODS_SEARCH, PATCH + METHODS_SEARCH);
168174
await fs.writeFile(INK_JS, inkContent, 'utf8');
169175
console.log('Patched ink ink.js');
170176
} else {

‎src/ui/components/default-component.tsx‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,15 @@ export function DefaultComponent(props: {
3030
onWriteReady?: (write: (data: string) => void) => void
3131
}) {
3232
const { emitter, onWriteReady } = props
33-
const [{ status: renderStatus, data: renderData }] = useAtom(store.renderState);
33+
const [renderState] = useAtom(store.renderState);
34+
const { status: renderStatus, data: renderData } = renderState;
3435
const { write } = useStdout();
3536

37+
// Lets the reporter wait for a render state to be committed before it continues (see DefaultReporter)
38+
useLayoutEffect(() => {
39+
emitter.emit(RenderEvent.RENDER_STATE_COMMITTED);
40+
}, [renderState]);
41+
3642
useLayoutEffect(() => {
3743
onWriteReady?.(write);
3844
}, []);
@@ -45,7 +51,7 @@ export function DefaultComponent(props: {
4551
}
4652
{
4753
renderStatus === RenderStatus.APPLY_COMPLETE && (
48-
<Static items={[renderData as ApplyResult]}>{
54+
<Static items={[renderData as ApplyResult]} style={{ width: '100%' }}>{
4955
(result, idx) => <ApplyComplete key={idx} result={result} />
5056
}</Static>
5157
)
@@ -56,13 +62,13 @@ export function DefaultComponent(props: {
5662
)
5763
}
5864
{
59-
renderStatus === RenderStatus.DISPLAY_PLAN && <Static items={[renderData as Plan]}>{
65+
renderStatus === RenderStatus.DISPLAY_PLAN && <Static items={[renderData as Plan]} style={{ width: '100%' }}>{
6066
(plan, idx) => <PlanComponent key={idx} plan={plan}/>
6167
}</Static>
6268
}
6369
{
6470
renderStatus === RenderStatus.PLUGIN_ERROR && (
65-
<Static items={[renderData as string[]]}>{
71+
<Static items={[renderData as string[]]} style={{ width: '100%' }}>{
6672
(messages, idx) => (
6773
<Box key={idx} flexDirection="column" marginTop={1}>
6874
{messages.map((msg, i) => <Text key={i} color="red">{msg}</Text>)}
@@ -126,14 +132,14 @@ export function DefaultComponent(props: {
126132
}
127133
{
128134
renderStatus === RenderStatus.DISPLAY_IMPORT_RESULT && (
129-
<Static items={[renderData as { importResult: ImportResult; showConfigs: boolean }]}>{
135+
<Static items={[renderData as { importResult: ImportResult; showConfigs: boolean }]} style={{ width: '100%' }}>{
130136
(renderData, idx) => <ImportResultComponent importResult={renderData.importResult} key={idx} showConfigs={renderData.showConfigs} />
131137
}</Static>
132138
)
133139
}
134140
{
135141
renderStatus === RenderStatus.DISPLAY_FILE_MODIFICATION && (
136-
<Static items={[renderData as Array<{ file: string; modification: FileModificationResult }>]}>{
142+
<Static items={[renderData as Array<{ file: string; modification: FileModificationResult }>]} style={{ width: '100%' }}>{
137143
(data, idx) => <FileModificationDisplay data={data} key={idx}/>
138144
}</Static>
139145
)

‎src/ui/components/import/import-warning.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export function ImportWarning({
1313
emitter: EventEmitter
1414
}) {
1515
return <Box flexDirection="column">
16-
<Static items={[renderData]}>{
16+
<Static items={[renderData]} style={{ width: '100%' }}>{
1717
(data, idx) => <Box flexDirection='column' key={idx}>
1818
<Text> </Text>
1919
<Text bold>Additional information is required to continue import</Text>

‎src/ui/components/init/InitBanner.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export function InitBanner(props: { emitter: EventEmitter }) {
1414
});
1515

1616
return <Box flexDirection='column'>
17-
<Static items={[{}]}>{
17+
<Static items={[{}]} style={{ width: '100%' }}>{
1818
() => <Box flexDirection='column' key='0'>
1919
<Gradient name='morning'>
2020
<BigText font='tiny' text='Codify'/>

‎src/ui/components/widgets/PromptPressKeyToContinue.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ export function PromptPressKeyToContinue(props: {
99
props.onInput();
1010
});
1111

12-
return <Static items={[{}]}>{
12+
return <Static items={[{}]} style={{ width: '100%' }}>{
1313
(item, idx) => (<Box flexDirection='column' key={idx} marginTop={1}>
1414
{ props.message && (<Text wrap='middle'>{props.message}</Text>) }
1515
<Text> </Text>

‎src/ui/reporters/default-reporter.tsx‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ export class DefaultReporter implements Reporter {
136136
}
137137

138138
async hide(): Promise<void> {
139-
store.set(store.renderState, { status: RenderStatus.NOTHING, data: null });
139+
// Wait for the cleared frame to commit before the caller writes to stdout
140+
await this.setRenderStateAndWaitForCommit({ status: RenderStatus.NOTHING, data: null });
140141
}
141142

142143
async setRawMode(): Promise<void> {
@@ -493,10 +494,35 @@ export class DefaultReporter implements Reporter {
493494
private async updateRenderState(status: RenderStatus | null, data?: unknown): Promise<void> {
494495
const current = this.getRenderState();
495496
if (current?.status !== status) {
496-
store.set(store.renderState, { status: RenderStatus.NOTHING, data: null });
497+
await this.setRenderStateAndWaitForCommit({ status: RenderStatus.NOTHING, data: null });
497498
await sleep(50);
498499
}
499-
store.set(store.renderState, { status, data });
500+
501+
await this.setRenderStateAndWaitForCommit({ status, data });
502+
}
503+
504+
/**
505+
* Since React 19, updates coming from outside React (our jotai store) are no longer committed synchronously; React
506+
* schedules them for later. Callers often follow a display call with process.exit(), which unmounts Ink before a
507+
* pending update is ever rendered. So wait until DefaultComponent reports that the new state has been committed.
508+
* Once committed, Ink flushes the frame to stdout on exit. The timeout guards against waiting forever if Ink is not
509+
* rendering (e.g. it was never mounted).
510+
*/
511+
private async setRenderStateAndWaitForCommit(state: { status: RenderStatus | null; data: unknown }): Promise<void> {
512+
const committed = new Promise<void>((resolve) => {
513+
const done = () => {
514+
clearTimeout(timer);
515+
this.renderEmitter.off(RenderEvent.RENDER_STATE_COMMITTED, done);
516+
resolve();
517+
};
518+
519+
const timer = setTimeout(done, 250);
520+
// React applies updates in order, so any commit after this point includes (or supersedes) this state
521+
this.renderEmitter.on(RenderEvent.RENDER_STATE_COMMITTED, done);
522+
});
523+
524+
store.set(store.renderState, state);
525+
await committed;
500526
}
501527

502528
// This is needed if we await any prompts. It makes the UI feel a lot more fluid since the await is no longer blocking

‎src/ui/reporters/reporter.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export enum RenderEvent {
3030
TOGGLE_VERBOSITY = 'toggleVerbosity',
3131
SUDO_PASSWORD_TOGGLE = 'sudoPasswordToggle',
3232
SUDO_PASSWORD_CANCEL = 'sudoPasswordCancel',
33+
RENDER_STATE_COMMITTED = 'renderStateCommitted',
3334
}
3435

3536
/**

0 commit comments

Comments
 (0)