Skip to content

Commit ab22e71

Browse files
committed
feat: enhance terminal handling with incremental rendering support
1 parent 02cefcc commit ab22e71

8 files changed

Lines changed: 451 additions & 47 deletions

File tree

‎package-lock.json‎

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

‎package.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,21 +31,24 @@
3131
"release:version": "node scripts/version.js",
3232
"prepare:package": "node scripts/prepare-package.js",
3333
"prepare:vscode": "node scripts/prepare-vscode.js",
34-
"prepare": "husky && npm run build && npm run bundle"
34+
"prepare": "husky && npm run build && npm run bundle",
35+
"postinstall": "patch-package --error-on-fail"
3536
},
3637
"devDependencies": {
3738
"@eslint/js": "^9.39.4",
3839
"@types/ejs": "^3.1.5",
3940
"@types/node": "^25.6.0",
4041
"@types/proper-lockfile": "^4.1.4",
4142
"@types/react": "^19.2.14",
43+
"@xterm/headless": "^6.0.0",
4244
"esbuild": "^0.28.0",
4345
"eslint": "^10.7.0",
4446
"eslint-config-prettier": "^10.1.8",
4547
"eslint-plugin-react-hooks": "^7.1.1",
4648
"glob": "^13.0.6",
4749
"husky": "^9.1.7",
4850
"lint-staged": "^17.0.4",
51+
"patch-package": "^8.0.1",
4952
"prettier": "^3.8.3",
5053
"react-devtools-core": "^7.0.1",
5154
"tsx": "^4.21.0",

‎packages/cli/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
"chalk": "^5.6.2",
3939
"gradient-string": "^3.0.0",
4040
"ignore": "^7.0.5",
41-
"ink": "^7.0.4",
41+
"ink": "7.1.0",
4242
"ink-gradient": "^4.0.1",
4343
"react": "^19.2.5",
4444
"read-package-up": "^12.0.0",

‎packages/cli/src/tests/prompt-input-wrap.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,36 @@ test("PromptInput uses the same Chinese wrapping in highlighted history previews
105105
await h.send("\r");
106106
assert.equal(submissions[0]?.text, text);
107107
});
108+
109+
for (const incrementalRendering of [false, true]) {
110+
for (const lines of [12, 21, 60]) {
111+
test(`PromptInput keeps the cursor on the input after expanding and clearing ${lines} lines (incremental=${incrementalRendering})`, async (t) => {
112+
const props = { ...inputProps([]), screenWidth: 160 };
113+
const h = await terminal(t, React.createElement(PromptInput, props), props.screenWidth, {
114+
rows: 24,
115+
incrementalRendering,
116+
});
117+
const screen = h.screen!;
118+
function assertCursorAtInput(column: number) {
119+
const buffer = screen.buffer.active;
120+
const row = Array.from({ length: screen.rows }, (_, y) =>
121+
buffer.getLine(buffer.viewportY + y)?.translateToString(true)
122+
).findIndex((line) => line === ">" || line?.startsWith("> "));
123+
assert.ok(row >= 0, "prompt must be visible");
124+
assert.equal(buffer.cursorY, row, "cursor must stay on the prompt row");
125+
assert.equal(buffer.cursorX, column);
126+
}
127+
128+
assertCursorAtInput(2);
129+
const text = Array.from({ length: lines }, (_, i) => `pasted line ${i + 1}`).join("\n");
130+
await h.send(`\x1b[200~${text}\x1b[201~`);
131+
await h.send("\x0f"); // Ctrl+O: expand past the terminal height.
132+
await h.send("\x15"); // Ctrl+U: return to an empty, single-line prompt.
133+
assertCursorAtInput(2);
134+
await h.send("hello");
135+
assertCursorAtInput(7);
136+
await h.send("\x1b[D");
137+
assertCursorAtInput(6);
138+
});
139+
}
140+
}

‎packages/cli/src/tests/session-lifecycle.test.ts‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ function deferred() {
1919

2020
async function harness(
2121
t: TestContext,
22-
respond: (messages: SessionMessage[], signal: AbortSignal) => unknown | Promise<unknown>
22+
respond: (messages: SessionMessage[], signal: AbortSignal) => unknown | Promise<unknown>,
23+
options?: { rows: number; incrementalRendering?: boolean }
2324
) {
2425
const root = fs.mkdtempSync(path.join(os.tmpdir(), "deepcode-session-lifecycle-"));
2526
const originalEnv = process.env;
@@ -44,7 +45,7 @@ async function harness(
4445
});
4546
});
4647
t.mock.method(SessionManager.prototype, "listSkills", async () => []);
47-
const h = await terminal(t, React.createElement(App, { projectRoot: root }), 100);
48+
const h = await terminal(t, React.createElement(App, { projectRoot: root }), 100, options);
4849
const manager = ref.current!;
4950
t.after(async () => {
5051
const id = manager.getActiveSessionId();
@@ -124,6 +125,50 @@ for (const next of ["Use the default settings.", "/continue"]) {
124125
}
125126

126127
for (const action of ["/exit", "Ctrl+D twice"] as const) {
128+
for (const { incrementalRendering, running } of [false, true].flatMap((incrementalRendering) =>
129+
[false, true].map((running) => ({ incrementalRendering, running }))
130+
)) {
131+
test(`${action} removes the exit notice (incremental=${incrementalRendering}, running=${running})`, async (t) => {
132+
const cleanup = deferred();
133+
t.after(() => cleanup.resolve());
134+
const h = await harness(
135+
t,
136+
async (_messages, signal) => {
137+
await cleanup.promise;
138+
signal.throwIfAborted();
139+
},
140+
{ rows: 40, incrementalRendering }
141+
);
142+
const screen = h.screen!;
143+
const contents = () =>
144+
Array.from({ length: screen.buffer.active.length }, (_, y) =>
145+
screen.buffer.active.getLine(y)?.translateToString(true)
146+
).join("\n");
147+
// Include direct process output in the same terminal, as in the real CLI.
148+
t.mock.method(process.stdout, "write", (chunk: string | Uint8Array) => {
149+
screen.write(chunk);
150+
return true;
151+
});
152+
if (running) await h.submit("keep working");
153+
if (action === "/exit") await h.submit("/exit");
154+
else {
155+
await h.send("\x04");
156+
await h.send("\x04");
157+
}
158+
if (running) assert.match(contents(), /Exiting…/);
159+
cleanup.resolve();
160+
await h.waitUntilExit();
161+
await new Promise<void>((resolve) => screen.write("", resolve));
162+
assert.doesNotMatch(contents(), /Exiting…/);
163+
if (action === "/exit") assert.match(contents(), /Goodbye!/);
164+
if (running) {
165+
assert.match(contents(), /keep working/);
166+
assert.match(contents(), /deepcode --resume/);
167+
}
168+
assert.equal(h.rawMode(), false);
169+
});
170+
}
171+
127172
test(`${action} aborts the running session and waits for cleanup before exiting`, { timeout: 10000 }, async (t) => {
128173
const entered = deferred();
129174
const cleanup = deferred();

‎packages/cli/src/tests/terminal-helper.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,17 @@ import { setTimeout } from "node:timers/promises";
44
import { stripTerminalControls } from "./terminal-output";
55
import type React from "react";
66
import { render } from "ink";
7+
import xterm from "@xterm/headless";
78

8-
export async function terminal(t: TestContext, element: React.ReactElement, columns = 80) {
9+
export async function terminal(
10+
t: TestContext,
11+
element: React.ReactElement,
12+
columns = 80,
13+
options?: { rows: number; incrementalRendering?: boolean }
14+
) {
15+
const screen = options
16+
? new xterm.Terminal({ cols: columns, rows: options.rows, allowProposedApi: true, convertEol: true })
17+
: null;
918
let frame = "";
1019
let rawFrame = "";
1120
let rawMode = false;
@@ -20,6 +29,7 @@ export async function terminal(t: TestContext, element: React.ReactElement, colu
2029
const stdout = Object.assign(
2130
new Writable({
2231
write(chunk, _encoding, done) {
32+
screen?.write(chunk.toString());
2333
// Title updates are terminal controls, not rendered frames.
2434
const text = stripTerminalControls(chunk.toString().replace(/\u001b\][^\u0007]*\u0007/g, ""));
2535
if (text.trim()) {
@@ -29,29 +39,34 @@ export async function terminal(t: TestContext, element: React.ReactElement, colu
2939
done();
3040
},
3141
}),
32-
{ isTTY: true, columns, rows: 40 }
42+
{ isTTY: true, columns, rows: options?.rows ?? 40 }
3343
);
3444
const app = render(element, {
3545
stdin: stdin as unknown as NodeJS.ReadStream,
3646
stdout: stdout as unknown as NodeJS.WriteStream,
3747
stderr: stdout as unknown as NodeJS.WriteStream,
38-
debug: true,
48+
debug: !screen,
49+
interactive: true,
50+
incrementalRendering: options?.incrementalRendering,
3951
patchConsole: false,
4052
exitOnCtrlC: false,
4153
});
4254
t.after(() => {
4355
app.unmount();
4456
app.cleanup();
57+
screen?.dispose();
4558
});
4659
async function flush() {
4760
await setTimeout(35);
4861
await app.waitUntilRenderFlush();
62+
if (screen) await new Promise<void>((resolve) => screen.write("", resolve));
4963
}
5064
await flush();
5165
return {
5266
frame: () => frame,
5367
rawFrame: () => rawFrame,
5468
rawMode: () => rawMode,
69+
screen,
5570
rerender: app.rerender,
5671
waitUntilExit: app.waitUntilExit,
5772
async send(input: string) {

‎packages/cli/src/ui/views/App.tsx‎

Lines changed: 47 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ function App({
8989
forkSessionId,
9090
onRestart,
9191
}: AppProps): React.ReactElement {
92-
const { exit } = useApp();
92+
const { exit, waitUntilRenderFlush } = useApp();
9393
const { stdout, write } = useStdout();
9494
const terminalTitle = useMemo(() => createTerminalTitle(stdout), [stdout]);
9595
const { columns, rows } = useWindowSize();
@@ -131,6 +131,7 @@ function App({
131131
} | null>(null);
132132
const [dismissedQuestionIds, setDismissedQuestionIds] = useState<Set<string>>(() => new Set());
133133
const [isExiting, setIsExiting] = useState(false);
134+
const [exitSummary, setExitSummary] = useState<{ showCommand: boolean; showSummary: boolean } | null>(null);
134135
const exitingRef = useRef(false);
135136
const [showWelcome, setShowWelcome] = useState(true);
136137
const [welcomeNonce, setWelcomeNonce] = useState(0);
@@ -438,44 +439,52 @@ function App({
438439
} finally {
439440
clearTimeout(timer);
440441
}
441-
setTimeout(() => {
442-
try {
443-
const activeSessionId = sessionManager.getActiveSessionId();
444-
const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null;
445-
const resumeHint = buildResumeHintText(activeSessionId ?? undefined);
446-
const rateLimitHint = buildPluginRateLimitHintText(session);
442+
setExitSummary({ showCommand, showSummary });
443+
},
444+
[sessionManager]
445+
);
446+
447+
useEffect(() => {
448+
if (!exitSummary) return;
449+
const { showCommand, showSummary } = exitSummary;
450+
void (async () => {
451+
try {
452+
// Remove the transient notice before writing permanent output outside Ink.
453+
await waitUntilRenderFlush();
454+
const activeSessionId = sessionManager.getActiveSessionId();
455+
const session = activeSessionId ? sessionManager.getSession(activeSessionId) : null;
456+
const resumeHint = buildResumeHintText(activeSessionId ?? undefined);
457+
const rateLimitHint = buildPluginRateLimitHintText(session);
447458

459+
writeStdoutLine("\n");
460+
if (showCommand) {
461+
writeStdoutLine(chalk.rgb(34, 154, 195)(" > /exit "));
448462
writeStdoutLine("\n");
449-
if (showCommand) {
450-
writeStdoutLine(chalk.rgb(34, 154, 195)(" > /exit "));
451-
writeStdoutLine("\n");
452-
}
453-
if (showSummary) {
454-
const summary = buildExitSummaryText({ session, sessionId: activeSessionId ?? undefined });
455-
writeStdoutLine(summary);
456-
writeStdoutLine("\n");
457-
}
458-
if (resumeHint) {
459-
writeStdoutLine(resumeHint);
460-
if (rateLimitHint) {
461-
writeStdoutLine(rateLimitHint);
462-
}
463-
writeStdoutLine("\n");
464-
}
465-
} catch {
466-
// Printing the summary is best effort during shutdown.
467463
}
468-
try {
469-
sessionManager.dispose();
470-
} catch {
471-
// Remaining handles are closed when the CLI process exits.
472-
} finally {
473-
exit();
464+
if (showSummary) {
465+
const summary = buildExitSummaryText({ session, sessionId: activeSessionId ?? undefined });
466+
writeStdoutLine(summary);
467+
writeStdoutLine("\n");
474468
}
475-
}, 0);
476-
},
477-
[exit, sessionManager]
478-
);
469+
if (resumeHint) {
470+
writeStdoutLine(resumeHint);
471+
if (rateLimitHint) {
472+
writeStdoutLine(rateLimitHint);
473+
}
474+
writeStdoutLine("\n");
475+
}
476+
} catch {
477+
// Printing the summary is best effort during shutdown.
478+
}
479+
try {
480+
sessionManager.dispose();
481+
} catch {
482+
// Remaining handles are closed when the CLI process exits.
483+
} finally {
484+
exit();
485+
}
486+
})();
487+
}, [exitSummary, exit, sessionManager, waitUntilRenderFlush]);
479488

480489
const handlePrompt = useCallback(
481490
async (submission: PromptSubmission) => {
@@ -1364,7 +1373,9 @@ function App({
13641373
</Box>
13651374
) : null}
13661375
{isExiting ? (
1367-
<Text dimColor>Exiting…</Text>
1376+
exitSummary ? null : (
1377+
<Text dimColor>Exiting…</Text>
1378+
)
13681379
) : showProcessStdout ? (
13691380
<ProcessStdoutView
13701381
key={activeSessionId}

‎patches/ink+7.1.0.patch‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
2+
--- a/node_modules/ink/build/ink.js
3+
+++ b/node_modules/ink/build/ink.js
4+
@@ -765,7 +765,9 @@
5+
if (sync) {
6+
this.options.stdout.write(bsu);
7+
}
8+
- this.options.stdout.write(ansiEscapes.clearTerminal + this.fullStaticOutput + output);
9+
+ // Match log.sync's trailing newline when shrinking below fullscreen,
10+
+ // so its cursor suffix starts from the actual bottom of the output.
11+
+ this.options.stdout.write(ansiEscapes.clearTerminal + this.fullStaticOutput + outputToRender);
12+
this.lastOutput = output;
13+
this.lastOutputToRender = outputToRender;
14+
this.lastOutputHeight = outputHeight;

0 commit comments

Comments
 (0)