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
52 changes: 47 additions & 5 deletions test/e2e/live/launch-agent-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,7 @@ const interceptPath = process.env.OPENSHELL_NEMOCLAW_LAUNCH_INTERCEPT_PATH;
const monitorStarterScript = process.env.OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT;
const runtimeEnvScript = process.env.OPENSHELL_NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT;
const keyPath = process.env.OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_KEY_PATH;
const firstInput = process.env.OPENSHELL_NEMOCLAW_LAUNCH_FIRST_INPUT;
const keyWriterScript = ${JSON.stringify(OPENCLAW_PTY_MONITOR_KEY_WRITER_SCRIPT)};

function fail(reason) {
Expand Down Expand Up @@ -607,6 +608,10 @@ const launchLike = sameSandbox && hasExpectedTail;

if (!launchLike) runRealOpenShell(argv);

if (!/^[\x20-\x7e]{1,512}$/.test(firstInput || "")) {
fail("openshell_shim_first_input_invalid");
}

let optionIndex = 4;
if (argv[optionIndex] === "-g") {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(argv[optionIndex + 1] || "")) {
Expand Down Expand Up @@ -659,6 +664,15 @@ const keyWriterArgv = [
if (invokeRealOpenShell(keyWriterArgv, privateKeyBase64) !== 0) {
fail("openshell_shim_private_key_write_failed");
}
// OpenClaw submits --message only after its Gateway subscription and history
// load complete. Use a positional parameter so the generated input never
// enters shell source.
const launchRemoteArgv = [
...remoteArgv.slice(0, -1),
'exec openclaw tui --message "$1"',
"nemoclaw-launch-first-turn",
firstInput,
];
const replacement = [
...argv.slice(0, separator + 1),
"node",
Expand All @@ -668,7 +682,7 @@ const replacement = [
monitorRoot,
publicKeyBase64,
privateKeyPath,
...remoteArgv,
...launchRemoteArgv,
];
runRealOpenShell(replacement);
`;
Expand Down Expand Up @@ -1018,6 +1032,12 @@ function qualifyTuiInputMode() {
client.on("error", () => finish(1, "pty_socket_unavailable"));
}

function qualifyPtyMonitorReady() {
readPtyMonitorRoot(true);
readPtyMonitorSocket(true);
finish(0);
}

function readCompleteSession(fileName) {
let raw;
try {
Expand Down Expand Up @@ -1278,6 +1298,7 @@ function qualifyTurns() {
try {
validateRunContext();
if (mode === "baseline") recordBaseline();
else if (mode === "monitor-ready") qualifyPtyMonitorReady();
else if (mode === "input-mode") qualifyTuiInputMode();
else if (mode === "qualify") qualifyTurns();
else if (mode === "cleanup-baseline") removeBaseline();
Expand Down Expand Up @@ -1472,6 +1493,25 @@ wait_for_pty_input_mode() {
fail_launch_session "launch did not observe noncanonical PTY input mode before the session deadline or before the PTY child process exited"
}

wait_for_pty_monitor_ready() {
local evidence_status
while (( SECONDS < session_deadline )); do
if session_evidence monitor-ready >/dev/null 2>"$evidence_error"; then
return 0
else
evidence_status=$?
fi
if [[ "$evidence_status" != 1 ]]; then
fail_launch_session "OpenClaw PTY monitor evidence was invalid or unavailable (status $evidence_status)"
fi
if ! kill -0 "$session_pid" 2>/dev/null; then
break
fi
sleep 0.1
done
fail_launch_session "launch did not observe the PTY monitor socket before the session deadline or before the PTY child process exited"
}

if ! session_evidence baseline >/dev/null 2>"$evidence_error"; then
fail_launch_session "launch could not record the structured session baseline"
fi
Expand All @@ -1494,6 +1534,7 @@ OPENSHELL_NEMOCLAW_LAUNCH_REAL_COMMAND="$NEMOCLAW_OPENSHELL_COMMAND" \
OPENSHELL_NEMOCLAW_LAUNCH_SANDBOX="$NEMOCLAW_LAUNCH_SANDBOX" \
OPENSHELL_NEMOCLAW_LAUNCH_RUN_ID="$NEMOCLAW_LAUNCH_RUN_ID" \
OPENSHELL_NEMOCLAW_LAUNCH_INTERCEPT_PATH="$intercept_path" \
OPENSHELL_NEMOCLAW_LAUNCH_FIRST_INPUT="$NEMOCLAW_LAUNCH_FIRST_INPUT" \
OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT="$NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT" \
OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_KEY_PATH="$pty_monitor_key_path" \
OPENSHELL_NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT="$NEMOCLAW_LAUNCH_RUNTIME_ENV_SCRIPT" \
Expand All @@ -1520,11 +1561,12 @@ if [[ "$capture_ready" != 1 ]]; then
fail_launch_session "launch did not create a PTY diagnostic capture"
fi

wait_for_pty_input_mode
if ! printf '%s\r' "$NEMOCLAW_LAUNCH_FIRST_INPUT" >&3; then
fail_launch_session "launch exited before the first PTY input was submitted"
fi
# Establish monitor availability without consuming its single noncanonical
# observation. A fresh input-mode proof is required after OpenClaw records its
# startup-aware first turn.
wait_for_pty_monitor_ready
wait_for_turn_count 1
wait_for_pty_input_mode
if ! printf '%s\r' "$NEMOCLAW_LAUNCH_SECOND_INPUT" >&3; then
fail_launch_session "launch exited before the second PTY input was submitted"
fi
Expand Down
80 changes: 54 additions & 26 deletions test/e2e/support/launch-agent-turn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type FixtureMode =
| "cleanup-failure"
| "delayed-input-attachment"
| "delayed-recording"
| "delayed-tui-ready"
| "input-mode-timeout"
| "invalid-order"
| "late-extra"
Expand Down Expand Up @@ -370,8 +371,8 @@ if (process.argv[2] !== "tui") {
if (!monitorPid) process.exit(71);
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_MONITOR_PID, monitorPid);
if (mode === "pty-response-forgery") {
process.stdin.on("data", () => {
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_EARLY_INPUT_MARKER, "");
process.stdin.on("data", (chunk) => {
if (chunk.includes(13)) fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_EARLY_INPUT_MARKER, "");
});
fs.unlinkSync(socketPath);
const ttyPath = fs.realpathSync("/proc/self/fd/0");
Expand Down Expand Up @@ -438,6 +439,9 @@ if (process.argv[2] !== "tui") {
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_TTY_MARKER, "");
const sessionFile = process.env.NEMOCLAW_FIXTURE_SESSION_FILE;
const terminalCopy = process.env.NEMOCLAW_FIXTURE_TERMINAL_COPY;
const messageIndex = process.argv.indexOf("--message");
const firstInput = messageIndex === -1 ? "" : process.argv[messageIndex + 1];
if (!firstInput) process.exit(75);
const append = (role, content) => fs.appendFileSync(
sessionFile,
JSON.stringify({ message: { content: [{ text: content, type: "text" }], role }, type: "message" }) + "\n",
Expand All @@ -446,61 +450,61 @@ if (process.argv[2] !== "tui") {
process.stdin.setRawMode(true);
await new Promise((resolve) => setTimeout(resolve, 750));
process.stdin.setRawMode(false);
append("user", firstInput);
append("assistant", "first response");
const recordUnexpectedInput = () =>
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_EARLY_INPUT_MARKER, "");
process.stdin.on("data", recordUnexpectedInput);
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_CANONICAL_RESTORED_MARKER, "");
await new Promise((resolve) => setTimeout(resolve, 10_000));
process.stdin.off("data", recordUnexpectedInput);
}
if (mode === "delayed-input-attachment" || mode === "input-mode-timeout") {
let inputBeforeAttachment = false;
const recordEarlyInput = () => { inputBeforeAttachment = true; };
if (mode === "input-mode-timeout") {
append("user", firstInput);
append("assistant", "first response");
await new Promise((resolve) => setTimeout(resolve, 10_000));
}
if (mode === "delayed-input-attachment" || mode === "delayed-tui-ready") {
const recordEarlyInput = () =>
fs.writeFileSync(process.env.NEMOCLAW_FIXTURE_EARLY_INPUT_MARKER, "");
if (mode === "delayed-tui-ready") process.stdin.setRawMode(true);
process.stdin.on("data", recordEarlyInput);
await new Promise((resolve) => setTimeout(resolve, mode === "input-mode-timeout" ? 10_000 : 1_500));
await new Promise((resolve) => setTimeout(resolve, 1_500));
process.stdin.off("data", recordEarlyInput);
if (inputBeforeAttachment) process.exit(67);
if (fs.existsSync(process.env.NEMOCLAW_FIXTURE_EARLY_INPUT_MARKER)) process.exit(67);
}
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
const ask = () => new Promise((resolve) => rl.question("", resolve));
if (terminalCopy === "ansi") process.stdout.write("\u001b[2Kgateway connected | idle\r");
if (terminalCopy === "reordered") process.stdout.write("idle | gateway connected\n");

const first = await ask();
process.kill(Number(monitorPid), "SIGTERM");
await new Promise((resolve) => setTimeout(resolve, 50));
const monitorStat = fs.readFileSync("/proc/" + monitorPid + "/stat", "utf8");
const monitorState = monitorStat ? monitorStat.slice(monitorStat.lastIndexOf(") ") + 2)[0] : null;
if (!monitorState || monitorState === "Z") process.exit(71);
const delayedInputs = [];
if (mode === "delayed-recording") {
const recordDelayedInput = (line) => delayedInputs.push(line);
rl.on("line", recordDelayedInput);
const publicationDeadline = Date.now() + 2_000;
while (!fs.existsSync(process.env.NEMOCLAW_FIXTURE_PENDING_QUALIFICATION_MARKER)) {
if (Date.now() >= publicationDeadline) process.exit(68);
await new Promise((resolve) => setTimeout(resolve, 10));
}
rl.off("line", recordDelayedInput);
}
if (mode === "recording-timeout") await new Promise((resolve) => setTimeout(resolve, 10_000));
if (mode === "invalid-order") {
append("assistant", "response before input");
append("user", first);
append("user", firstInput);
} else {
append("user", first);
append("user", firstInput);
append("assistant", "first response");
}
for (const duplicate of delayedInputs) {
append("user", duplicate);
append("assistant", "duplicate response");
}

process.kill(Number(monitorPid), "SIGTERM");
await new Promise((resolve) => setTimeout(resolve, 50));
const monitorStat = fs.readFileSync("/proc/" + monitorPid + "/stat", "utf8");
const monitorState = monitorStat ? monitorStat.slice(monitorStat.lastIndexOf(") ") + 2)[0] : null;
if (!monitorState || monitorState === "Z") process.exit(71);

const second = await ask();
append("user", second);
append("assistant", "second response");
const exitCommand = await ask();
if (mode === "late-extra") append("user", first);
if (mode === "late-extra") append("user", firstInput);
rl.close();
if (exitCommand !== "/exit") process.exit(65);
process.exit(mode.includes("nonzero") ? 23 : 0);
Expand Down Expand Up @@ -757,6 +761,7 @@ require("node:fs").appendFileSync(
NEMOCLAW_OPENSHELL_BIN: shim,
NEMOCLAW_OPENSHELL_COMMAND: realOpenShell,
OPENSHELL_NEMOCLAW_LAUNCH_INTERCEPT_PATH: interceptPath,
OPENSHELL_NEMOCLAW_LAUNCH_FIRST_INPUT: "fixture input",
OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_KEY_PATH: keyPath,
OPENSHELL_NEMOCLAW_LAUNCH_PTY_MONITOR_STARTER_SCRIPT: OPENCLAW_PTY_MONITOR_STARTER_SCRIPT,
OPENSHELL_NEMOCLAW_LAUNCH_REAL_COMMAND: realOpenShell,
Expand Down Expand Up @@ -799,6 +804,10 @@ require("node:fs").appendFileSync(
const passThrough = runShim(passThroughArgv, hostEnv);
const ttyPassThrough = runShim(ttyPassThroughArgv);
const malformed = runShim(malformedArgv);
const invalidFirstInput = runShim(exactArgv, {
...env,
OPENSHELL_NEMOCLAW_LAUNCH_FIRST_INPUT: "",
});
const intercepted = runShim(exactArgv);
const duplicate = runShim(exactArgv);
const records = readFileSync(callsPath, "utf8")
Expand All @@ -813,6 +822,7 @@ require("node:fs").appendFileSync(
exactArgv,
interceptMode: statSync(interceptPath).mode & 0o777,
intercepted,
invalidFirstInput,
malformed,
passThrough,
passThroughArgv,
Expand Down Expand Up @@ -926,6 +936,10 @@ it.each([[], ["-g", "fixture-gateway"]].map((gatewayArgs) => [gatewayArgs] as co
expect(fixture.ttyPassThrough.status, fixture.ttyPassThrough.stderr).toBe(0);
expect(fixture.malformed.status).toBe(73);
expect(fixture.malformed.stderr).toContain('"reason":"openshell_launch_invocation_invalid"');
expect(fixture.invalidFirstInput.status).toBe(73);
expect(fixture.invalidFirstInput.stderr).toContain(
'"reason":"openshell_shim_first_input_invalid"',
);
expect(fixture.intercepted.status, fixture.intercepted.stderr).toBe(0);
expect(fixture.duplicate.status).toBe(73);
expect(fixture.duplicate.stderr).toContain('"reason":"openshell_launch_intercept_duplicate"');
Expand Down Expand Up @@ -956,7 +970,10 @@ it.each([[], ["-g", "fixture-gateway"]].map((gatewayArgs) => [gatewayArgs] as co
fixture.monitorRoot,
fixture.publicKey,
`${fixture.monitorRoot}/pty-monitor-private-key`,
...expectedRemote,
...expectedRemote.slice(0, -1),
'exec openclaw tui --message "$1"',
"nemoclaw-launch-first-turn",
"fixture input",
]);
expect(fixture.calls.flat()).not.toContain(fixture.privateKey);
},
Expand Down Expand Up @@ -997,7 +1014,7 @@ it.runIf(process.platform === "linux")(
);

it.runIf(process.platform === "linux").each(["absent", "ansi", "reordered"] as const)(
"keeps the monitor alive through SIGTERM, sends two PTY inputs and /exit, strips launch authority, and ignores terminal copy evidence [%s] (#9160)",
"keeps the monitor alive through SIGTERM, records an auto-message and PTY turn, sends /exit, strips launch authority, and ignores terminal copy evidence [%s] (#9160, #9384)",
(terminalCopy) => {
const {
baselineRemoved,
Expand Down Expand Up @@ -1053,6 +1070,17 @@ it.runIf(process.platform === "linux")(
},
);

it.runIf(process.platform === "linux")(
"waits for OpenClaw startup to accept its auto-message before submitting one PTY input (#9384)",
() => {
const fixture = runLaunchSessionFixture("delayed-tui-ready", "absent");

expect(fixture.earlyInputObserved, fixture.result.stderr).toBe(false);
expect(fixture.baselineRemoved, fixture.result.stderr).toBe(true);
expect(fixture.result.status, fixture.result.stderr).toBe(0);
},
);

it.runIf(process.platform === "linux" && process.getuid?.() !== 0)(
"uses the inherited PTY descriptor when the sandbox user cannot reopen the device path (#9384)",
() => {
Expand Down
Loading