Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/cli/src/tests/prompt-external-editor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ async function harness(t: TestContext, busy = false, tty = true) {

test("Ctrl+G edits busy input, suspends terminal output, restores modes and supports undo", async (t) => {
const h = await harness(t, true);
assert.doesNotMatch(h.writes.join(""), /\x1b\[\?1004h/);
await h.send("draft");
await h.send("\x07\x07");
assert.equal(h.edits.length, 1);
Expand All @@ -138,7 +139,7 @@ test("Ctrl+G edits busy input, suspends terminal output, restores modes and supp
assert.match(h.latest(), /编辑/);
assert.match(h.writes.slice(count).join(""), /\x1b\[\?2004h/);
assert.match(h.writes.slice(count).join(""), /\x1b\[>4;1m/);
assert.match(h.writes.slice(count).join(""), /\x1b\[\?1004h/);
assert.doesNotMatch(h.writes.slice(count).join(""), /\x1b\[\?1004h/);
await h.send("!");
assert.match(h.latest(), /next!/);
await h.send("\x1b[45;5u");
Expand Down
20 changes: 19 additions & 1 deletion packages/cli/src/tests/prompt-queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,29 @@ async function input(t: TestContext, editing = false) {
events.push("cancel edit");
},
}),
100
100,
{ rows: 40 }
);
return { ...h, submissions, events };
}

test("switching away and back preserves the draft and lets the active task continue", async (t) => {
const h = await input(t);
const draft = "Draw three green circles.";
await h.send(draft);
await h.setWindowFocused(false);
await h.setWindowFocused(true);
assert.deepEqual(h.events, []);
await h.send("\r");
assert.equal(h.submissions[0]?.text, draft);
});

test("pressing Escape interrupts the active task once", async (t) => {
const h = await input(t);
await h.send("\x1b");
assert.deepEqual(h.events, ["interrupt"]);
});

test("busy input submits ordinary prompts and clears the input for another message", async (t) => {
const h = await input(t);
await h.send("first");
Expand Down
15 changes: 12 additions & 3 deletions packages/cli/src/tests/session-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import React from "react";
import { SessionManager, type SessionMessage } from "@vegamo/deepcode-core";
import App from "../ui/views/App";
import { terminal } from "./terminal-helper";
import { GitFileHistory } from "../../../core/src/common/file-history";
import { McpClient } from "../../../core/src/mcp/mcp-client";
import { createMcpTestServer } from "../../../core/src/tests/mcp-test-server";

Expand All @@ -26,6 +27,8 @@ async function harness(
const originalEnv = process.env;
process.env = Object.fromEntries(Object.entries(originalEnv).filter(([key]) => !key.startsWith("DEEPCODE_")));
t.mock.method(os, "homedir", () => root);
// File checkpoints spawn synchronous Git commands and are covered by dedicated tests.
t.mock.method(GitFileHistory.prototype, "ensureSession", () => undefined);
syncBuiltinESMExports();
fs.mkdirSync(path.join(root, ".deepcode"));
fs.writeFileSync(path.join(root, ".deepcode", "settings.json"), JSON.stringify({ statusline: { enabled: false } }));
Expand Down Expand Up @@ -212,7 +215,7 @@ for (const action of ["/exit", "Ctrl+D twice"] as const) {
assert.equal(h.rawMode(), false, "exit must restore terminal input mode");
});

test(`${action} exits promptly during an unresponsive MCP call`, { timeout: 5000 }, async (t) => {
test(`${action} exits promptly during an unresponsive MCP call`, { timeout: 15000 }, async (t) => {
const entered = deferred();
const callTool = McpClient.prototype.callTool;
let requestSignal: AbortSignal | undefined;
Expand Down Expand Up @@ -247,20 +250,26 @@ for (const action of ["/exit", "Ctrl+D twice"] as const) {
await entered.promise;
const id = h.manager.getActiveSessionId()!;
h.manager.enqueuePrompt(id, { text: "queued input" });
const disposedWhileRunning: boolean[] = [];
const dispose = h.manager.dispose.bind(h.manager);
t.mock.method(h.manager, "dispose", () => {
disposedWhileRunning.push(h.manager.isSessionRunning(id));
dispose();
});
if (action === "/exit") await h.submit("/exit");
else {
await h.send("\x04");
await h.send("\x04");
}
await h.waitUntilExit();
assert.equal(requestSignal?.aborted, true);
assert.equal(h.manager.isSessionRunning(id), false);
assert.equal(disposedWhileRunning[0], false, "cancellation must finish before exit disposes the manager");
assert.equal(h.manager.getSession(id)?.status, "interrupted");
assert.equal(requests, 1);
assert.equal(h.rawMode(), false);
});

test(`${action} exits after five seconds even if execution ignores cancellation`, { timeout: 12000 }, async (t) => {
test(`${action} exits after five seconds even if execution ignores cancellation`, { timeout: 15000 }, async (t) => {
const entered = deferred();
const cleanup = deferred();
t.after(() => cleanup.resolve());
Expand Down
8 changes: 8 additions & 0 deletions packages/cli/src/tests/terminal-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ export async function terminal(
rawFrame: () => rawFrame,
rawMode: () => rawMode,
screen,
async setWindowFocused(focused: boolean) {
if (!screen) throw new Error("Window focus changes require a terminal screen");
if (!screen.modes.sendFocusMode) return;
stdin.write("\x1b");
await setTimeout(50);
stdin.write(focused ? "[I" : "[O");
await flush();
},
async resize(columns: number, rows: number) {
screen?.resize(columns, rows);
Object.assign(stdout, { columns, rows });
Expand Down
21 changes: 0 additions & 21 deletions packages/cli/src/ui/hooks/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,6 @@ function hideCursor(): string {
return "\u001B[?25l";
}

function enableTerminalFocusReporting(): string {
return "\u001B[?1004h";
}

function disableTerminalFocusReporting(): string {
return "\u001B[?1004l";
}

function enableBracketedPaste(): string {
return "\u001B[?2004h";
}
Expand Down Expand Up @@ -203,19 +195,6 @@ export function useHiddenTerminalCursor(stdout: NodeJS.WriteStream | undefined,
}, [isActive, stdout]);
}

export function useTerminalFocusReporting(stdout: NodeJS.WriteStream | undefined, isActive: boolean): void {
useLayoutEffect(() => {
if (!isActive || !stdout?.isTTY) {
return;
}

stdout.write(enableTerminalFocusReporting());
return () => {
stdout.write(disableTerminalFocusReporting());
};
}, [isActive, stdout]);
}

export function useTerminalExtendedKeys(stdout: NodeJS.WriteStream | undefined, isActive: boolean): void {
useLayoutEffect(() => {
if (!isActive || !stdout?.isTTY) {
Expand Down
1 change: 0 additions & 1 deletion packages/cli/src/ui/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export {
useTerminalExtendedKeys,
useBracketedPaste,
usePromptTerminalCursor,
useTerminalFocusReporting,
getPromptCursorPlacement,
isPromptCursorAtWrapBoundary,
resolvePromptTerminalCursorPosition,
Expand Down
31 changes: 6 additions & 25 deletions packages/cli/src/ui/views/PromptInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,7 @@ import {
usePromptTerminalCursor,
} from "../hooks";
import type { InputKey } from "../hooks";
import {
useHiddenTerminalCursor,
useTerminalExtendedKeys,
useBracketedPaste,
useTerminalFocusReporting,
} from "../hooks";
import { useHiddenTerminalCursor, useTerminalExtendedKeys, useBracketedPaste } from "../hooks";
import SlashCommandMenu, { isSkillSelected } from "./SlashCommandMenu";
import {
readPermissionSettingsEdit,
Expand Down Expand Up @@ -216,7 +211,6 @@ export const PromptInput = React.memo(function PromptInput({
const [permissionEdit, setPermissionEdit] = useState<PermissionSettingsEdit | null>(null);
const [fileMentionItems, setFileMentionItems] = useState<FileMentionItem[]>(() => scanFileMentionItems(projectRoot));
const [dismissedFileMentionKey, setDismissedFileMentionKey] = useState<string | null>(null);
const [hasTerminalFocus, setHasTerminalFocus] = useState(true);
const lastCtrlDAt = React.useRef<number>(0);
const undoRedoRef = React.useRef(createPromptUndoRedoState());
const wasBusyRef = React.useRef(busy);
Expand Down Expand Up @@ -332,7 +326,7 @@ export const PromptInput = React.memo(function PromptInput({
[buffer, inputContentWidth]
);
const useInlineCursor = isPromptCursorAtWrapBoundary(buffer, inputContentWidth);
const usePositionedCursor = terminalActive && hasTerminalFocus && !showFooterText && stdout.isTTY && !useInlineCursor;
const usePositionedCursor = terminalActive && !showFooterText && stdout.isTTY && !useInlineCursor;
const promptCursorLayoutKey = useMemo(
() =>
[
Expand All @@ -356,13 +350,12 @@ export const PromptInput = React.memo(function PromptInput({
selectedSkills,
]
);
useTerminalFocusReporting(stdout, terminalActive);
useTerminalExtendedKeys(stdout, terminalActive);
useBracketedPaste(stdout, terminalActive);
const terminalCursorActive = usePromptTerminalCursor(
search ? searchTextRef : inputTextRef,
search ? { row: 0, column: searchFooter.column } : cursorPlacement,
!busy && (search ? terminalActive && hasTerminalFocus && Boolean(stdout.isTTY) : usePositionedCursor),
!busy && (search ? terminalActive && Boolean(stdout.isTTY) : usePositionedCursor),
`${promptCursorLayoutKey}:${search ? "search" : "input"}`
);
useHiddenTerminalCursor(stdout, terminalActive && !terminalCursorActive);
Expand Down Expand Up @@ -438,18 +431,7 @@ export const PromptInput = React.memo(function PromptInput({

useTerminalInput(
(input, key) => {
if (externalEditorRunningRef.current) return;

if (key.focusIn) {
setHasTerminalFocus(true);
return;
}
if (key.focusOut) {
setHasTerminalFocus(false);
return;
}

if (disabled) {
if (externalEditorRunningRef.current || disabled || key.focusIn || key.focusOut) {
return;
}

Expand Down Expand Up @@ -830,7 +812,6 @@ export const PromptInput = React.memo(function PromptInput({
: "Could not edit in vim"
);
} finally {
setHasTerminalFocus(true);
setEditingExternally(false);
externalEditorChangeRef.current?.(false, {
nonce: Date.now(),
Expand Down Expand Up @@ -1135,7 +1116,7 @@ export const PromptInput = React.memo(function PromptInput({
) : (
renderBufferWithCursor(
buffer,
terminalActive && hasTerminalFocus && !search,
terminalActive && !search,
placeholder,
pastesRef.current,
!terminalCursorActive && !search
Expand Down Expand Up @@ -1205,7 +1186,7 @@ export const PromptInput = React.memo(function PromptInput({
<Text wrap="truncate-end">
<Text dimColor>{searchFooter.prefix}</Text>
<Text color="cyan">{searchFooter.query}</Text>
<Text inverse={terminalActive && hasTerminalFocus && !terminalCursorActive}> </Text>
<Text inverse={terminalActive && !terminalCursorActive}> </Text>
</Text>
</Box>
{screenWidth > searchFooter.column + 1 && (
Expand Down
Loading