Skip to content

Commit cd4bd7c

Browse files
authored
fix(tui): cancel buffered submissions on shutdown [AI-assisted] (#117331)
* fix(tui): cancel buffered submissions on shutdown * refactor(tui): preserve callable submit coalescer * test(tui): run local PTY smoke against built CLI
1 parent 951f130 commit cd4bd7c

12 files changed

Lines changed: 302 additions & 130 deletions

‎.github/workflows/ci.yml‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,6 +1063,7 @@ jobs:
10631063
channels-result: ${{ steps.built_artifact_checks.outputs['channels-result'] }}
10641064
core-support-boundary-result: ${{ steps.built_artifact_checks.outputs['core-support-boundary-result'] }}
10651065
gateway-watch-result: ${{ steps.built_artifact_checks.outputs['gateway-watch-result'] }}
1066+
tui-pty-result: ${{ steps.built_artifact_checks.outputs['tui-pty-result'] }}
10661067
steps:
10671068
- *linux_node_checkout_step
10681069
- name: Ensure secrets base commit (PR fast path)
@@ -1193,6 +1194,7 @@ jobs:
11931194
RUN_CHANNELS: ${{ needs.preflight.outputs.run_checks }}
11941195
RUN_CORE_SUPPORT_BOUNDARY: ${{ needs.preflight.outputs.run_checks_node_core_dist }}
11951196
RUN_GATEWAY_WATCH: ${{ needs.preflight.outputs.run_check_additional }}
1197+
RUN_TUI_PTY: ${{ needs.preflight.outputs.run_checks_node_core_dist }}
11961198
shell: bash
11971199
run: |
11981200
set -uo pipefail
@@ -1204,6 +1206,7 @@ jobs:
12041206
["channels"]="skipped"
12051207
["core-support-boundary"]="skipped"
12061208
["gateway-watch"]="skipped"
1209+
["tui-pty"]="skipped"
12071210
)
12081211
12091212
start_check() {
@@ -1254,6 +1257,15 @@ jobs:
12541257
node scripts/run-vitest.mjs run --config test/vitest/vitest.full-core-support-boundary.config.ts
12551258
fi
12561259
1260+
if [ "$RUN_TUI_PTY" = "true" ]; then
1261+
start_check "tui-pty" env \
1262+
NODE_OPTIONS=--max-old-space-size=8192 \
1263+
OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1 \
1264+
OPENCLAW_TUI_PTY_USE_BUILT_CLI=1 \
1265+
OPENCLAW_VITEST_MAX_WORKERS=2 \
1266+
node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts
1267+
fi
1268+
12571269
if [ "$RUN_GATEWAY_WATCH" = "true" ] && [ "$PARALLEL_GATEWAY_WATCH" = "true" ]; then
12581270
start_check "gateway-watch" \
12591271
node scripts/check-gateway-watch-regression.mjs --skip-build
@@ -1269,12 +1281,12 @@ jobs:
12691281
wait_checks
12701282
fi
12711283
1272-
for name in channels core-support-boundary gateway-watch; do
1284+
for name in channels core-support-boundary gateway-watch tui-pty; do
12731285
echo "${name}-result=${results[$name]}" >> "$GITHUB_OUTPUT"
12741286
done
12751287
12761288
failures=0
1277-
for name in channels core-support-boundary gateway-watch; do
1289+
for name in channels core-support-boundary gateway-watch tui-pty; do
12781290
if [ "${results[$name]}" = "failure" ]; then
12791291
echo "::error title=${name} failed::${name} failed"
12801292
failures=1

‎docs/ci.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ Separate iOS and macOS Periphery workflows enforce a zero-findings dead-code pol
101101
- **CI workflow edits** validate the Node CI graph, workflow linting, and the Windows lane (`ci.yml` executes it), but do not force iOS, Android, or macOS native builds by themselves; those platform lanes stay scoped to platform source changes.
102102
- **Workflow Sanity** runs `actionlint`, `zizmor` over all workflow YAML files, the composite-action interpolation guard, and the conflict-marker guard. The PR-scoped `security-fast` job also runs `zizmor` over changed workflow files so workflow security findings fail early in the main CI graph.
103103
- **Docs on `main` pushes** are checked by the standalone `Docs` workflow with the same ClawHub docs mirror used by CI, so mixed code+docs pushes do not also queue the CI `check-docs` shard. Pull requests and manual CI still run `check-docs` from CI when docs changed.
104-
- **TUI PTY** runs in the `checks-node-core-runtime-tui-pty` Linux Node shard for TUI changes. The shard runs `test/vitest/vitest.tui-pty.config.ts` with `OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1`, so it covers both the deterministic `TuiBackend` fixture lane and the slower `tui --local` smoke that mocks only the external model endpoint.
104+
- **TUI PTY** splits by runtime ownership. The Linux Node shard runs the deterministic source-level `TuiBackend` fixture lane. The `build-artifacts` job reruns `test/vitest/vitest.tui-pty.config.ts` with `OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1` and `OPENCLAW_TUI_PTY_USE_BUILT_CLI=1`, so the slower `tui --local` smoke exercises the exact-head built CLI while mocking only the external model endpoint.
105105
- **CI routing-only edits, the small set of core-test fixtures the fast task runs directly, and narrow plugin contract helper edits** use a fast Node-only manifest path: `preflight`, `security-fast`, and only the fast lanes the change touches — a single `checks-fast-core` CI-routing task, the two plugin contract shards, or both. That path skips build artifacts, Node 22 compatibility, channel contracts, full core shards, bundled-plugin shards, and additional guard matrices.
106106
- **Windows Node checks** are scoped to Windows-specific process/path wrappers, npm/pnpm/UI runner helpers, package manager config, and the CI workflow surfaces that execute that lane; unrelated source, plugin, install-smoke, and test-only changes stay on the Linux Node lanes.
107107

‎docs/reference/test.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ Test wrapper runs end with a short `[test] passed|failed|skipped ... in ...` sum
100100
## Control UI, TUI, and extension lanes
101101

102102
- **Control UI mocked E2E:** `pnpm test:ui:e2e` runs the Vitest + Playwright lane that starts the Vite Control UI and drives a real Chromium page against a mocked Gateway WebSocket. Tests live in `ui/src/**/*.e2e.test.ts`; shared mocks/controls live in `ui/src/test-helpers/control-ui-e2e.ts`. `pnpm test:e2e` includes this lane. Agent runs default to Testbox/Crabbox, including targeted proof; use `node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/ui/e2e/chat-flow.e2e.test.ts` only for an explicit local fallback.
103-
- **TUI PTY tests:** `node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts` runs the fast fake-backend PTY lane. `OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1` or `pnpm tui:pty:test:watch --mode local` runs the slower `tui --local` smoke, which mocks only the external model endpoint. Assert stable visible text or fixture calls, not raw ANSI snapshots.
103+
- **TUI PTY tests:** `node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts` runs the fast fake-backend PTY lane. `OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1` or `pnpm tui:pty:test:watch --mode local` runs the slower `tui --local` smoke, which mocks only the external model endpoint. CI also sets `OPENCLAW_TUI_PTY_USE_BUILT_CLI=1` after building `dist/`; use that flag only when exact-head built artifacts already exist. Assert stable visible text or fixture calls, not raw ANSI snapshots.
104104
- `pnpm test:extensions` and `pnpm test extensions` run all extension/plugin shards. Heavy channel plugins, the browser plugin, and OpenAI run as dedicated shards; other plugin groups stay batched. `pnpm test extensions/<id>` runs one bundled plugin lane.
105105
- Source files with sibling tests map to that sibling before falling back to wider directory globs. Helper edits under `src/channels/plugins/contracts/test-helpers`, `src/plugin-sdk/test-helpers`, and `src/plugins/contracts` use a local import graph to run importing tests instead of broad-running every shard when the dependency path is precise.
106106
- Contract directory targets fan out to their contract lanes: `pnpm test src/channels/plugins/contracts` runs the four channel contract configs and `pnpm test src/plugins/contracts` runs the plugin contracts config, since the generic `channels`/`plugins` projects exclude `contracts/**`.

‎scripts/lib/ci-node-test-plan.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1158,8 +1158,9 @@ const SPLIT_NODE_SHARDS = new Map([
11581158
configs: ["test/vitest/vitest.tui-pty.config.ts"],
11591159
env: {
11601160
OPENCLAW_TUI_PTY_INCLUDE_LOCAL: "1",
1161+
OPENCLAW_TUI_PTY_USE_BUILT_CLI: "1",
11611162
},
1162-
requiresDist: false,
1163+
requiresDist: true,
11631164
runner: "blacksmith-4vcpu-ubuntu-2404",
11641165
},
11651166
{

‎src/tui/tui-pty-harness.e2e.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,40 @@ describe.sequential("TUI PTY harness", () => {
309309
STARTUP_TEST_TIMEOUT_MS,
310310
);
311311

312+
it(
313+
"cancels a buffered submit before Ctrl+D shutdown",
314+
async () => {
315+
const bufferedFixture = await startTuiFixture({
316+
env: { OPENCLAW_TUI_PTY_SUBMIT_BURST_WINDOW_MS: "500" },
317+
});
318+
try {
319+
const message = "buffered shutdown proof";
320+
await bufferedFixture.run.waitForOutput("local ready", STARTUP_TIMEOUT_MS);
321+
await bufferedFixture.run.write(`${message}\r`, { delay: false });
322+
await bufferedFixture.waitForLogEntry(
323+
(entry) =>
324+
entry.method === "submitBurstCaptured" && objectFieldEquals(entry, "value", message),
325+
);
326+
327+
await bufferedFixture.run.write("\u0004", { delay: false });
328+
expect((await bufferedFixture.run.waitForExit()).exitCode).toBe(0);
329+
330+
const entries = await readFixtureLog(bufferedFixture.logPath);
331+
expect(entries).toEqual(
332+
expect.arrayContaining([expect.objectContaining({ method: "stop" })]),
333+
);
334+
expect(
335+
entries.some(
336+
(entry) => entry.method === "sendChat" && objectFieldEquals(entry, "message", message),
337+
),
338+
).toBe(false);
339+
} finally {
340+
await bufferedFixture.cleanup();
341+
}
342+
},
343+
STARTUP_TEST_TIMEOUT_MS,
344+
);
345+
312346
it.each([
313347
{ name: "Ctrl+D", input: "\u0004" },
314348
{ name: "/exit", input: "/exit\r" },

‎src/tui/tui-pty-local.e2e.test.ts‎

Lines changed: 101 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -432,45 +432,11 @@ function buildTuiCliScript(args: string[]) {
432432
].join("\n");
433433
}
434434

435-
function buildLocalValidationTuiScript() {
436-
const agentEventsModuleUrl = pathToFileURL(
437-
path.join(process.cwd(), "src/infra/agent-events.ts"),
438-
).href;
439-
const embeddedBackendModuleUrl = pathToFileURL(
440-
path.join(process.cwd(), "src/tui/embedded-backend.ts"),
441-
).href;
442-
const tuiModuleUrl = pathToFileURL(path.join(process.cwd(), "src/tui/tui.ts")).href;
443-
// A PTY-side abort can race the validation retry into another provider turn.
444-
// Abort through the real local backend after its listener records the second
445-
// tool error; the Gateway case below still covers keyboard-driven aborts.
446-
return [
447-
`import { onAgentEvent } from ${JSON.stringify(agentEventsModuleUrl)};`,
448-
`import { EmbeddedTuiBackend } from ${JSON.stringify(embeddedBackendModuleUrl)};`,
449-
`import { runTui } from ${JSON.stringify(tuiModuleUrl)};`,
450-
`const backend = new EmbeddedTuiBackend();`,
451-
`const sessionKey = "agent:main:main";`,
452-
`let validationErrorCount = 0;`,
453-
`onAgentEvent((event) => {`,
454-
` if (event.stream !== "tool" || event.data?.phase !== "result" || typeof event.data?.toolErrorSummary !== "string") return;`,
455-
` validationErrorCount += 1;`,
456-
` if (validationErrorCount !== 2) return;`,
457-
` queueMicrotask(() => {`,
458-
` void backend.abortChat({ sessionKey }).then((result) => {`,
459-
` if (!result.aborted) {`,
460-
` console.error("local validation test failed to abort its active run");`,
461-
` process.exit(1);`,
462-
` }`,
463-
` }).catch((error) => {`,
464-
` console.error(error);`,
465-
` process.exit(1);`,
466-
` });`,
467-
` });`,
468-
`});`,
469-
`runTui({ local: true, backend, session: sessionKey, deliver: false, historyLimit: 200, forceProcessExitOnReturn: true }).catch((error) => {`,
470-
` console.error(error);`,
471-
` process.exit(1);`,
472-
`});`,
473-
].join("\n");
435+
function buildTuiProcessArgs(args: string[]) {
436+
if (process.env.OPENCLAW_TUI_PTY_USE_BUILT_CLI === "1") {
437+
return [path.join(process.cwd(), "openclaw.mjs"), ...args];
438+
}
439+
return ["--import", "tsx", "--eval", buildTuiCliScript(args)];
474440
}
475441

476442
function buildMockModelProvider(baseUrl: string, modelIds: string[]): ModelProviderConfig {
@@ -539,6 +505,28 @@ function buildLocalModeConfig(params: {
539505
} satisfies OpenClawConfig;
540506
}
541507

508+
async function cleanupLocalModeResources(params: {
509+
run?: PtyRun;
510+
mockModel: MockModelServer;
511+
tempDir: string;
512+
}) {
513+
const settled = await Promise.allSettled([
514+
...(params.run ? [params.run.dispose()] : []),
515+
params.mockModel.stop(),
516+
]);
517+
const failures = settled.flatMap((result) =>
518+
result.status === "rejected" ? [result.reason] : [],
519+
);
520+
try {
521+
await rm(params.tempDir, { recursive: true, force: true });
522+
} catch (error) {
523+
failures.push(error);
524+
}
525+
if (failures.length > 0) {
526+
throw new AggregateError(failures, "local TUI PTY fixture cleanup failed");
527+
}
528+
}
529+
542530
async function startLocalModeTui(
543531
registerCleanup: CleanupRegistrar,
544532
opts: {
@@ -566,41 +554,60 @@ async function startLocalModeTui(
566554
providerBaseUrl: mockModel.baseUrl,
567555
toolsProfile: opts.invalidEditLoop ? "coding" : "minimal",
568556
});
569-
const script = opts.invalidEditLoop
570-
? buildLocalValidationTuiScript()
571-
: buildTuiCliScript(["tui", "--local"]);
572-
await Promise.all([
573-
mkdir(workspaceDir, { recursive: true }),
574-
mkdir(homeDir, { recursive: true }),
575-
mkdir(stateDir, { recursive: true }),
576-
mkdir(xdgConfigHome, { recursive: true }),
577-
mkdir(xdgDataHome, { recursive: true }),
578-
mkdir(xdgCacheHome, { recursive: true }),
579-
writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"),
580-
]);
581-
582-
const run = startPty(process.execPath, ["--import", "tsx", "--eval", script], {
583-
cwd: process.cwd(),
584-
env: {
585-
HOME: homeDir,
586-
OPENCLAW_HOME: homeDir,
587-
OPENCLAW_CONFIG_PATH: configPath,
588-
OPENCLAW_STATE_DIR: stateDir,
589-
XDG_CONFIG_HOME: xdgConfigHome,
590-
XDG_DATA_HOME: xdgDataHome,
591-
XDG_CACHE_HOME: xdgCacheHome,
592-
OPENCLAW_THEME: "dark",
593-
OPENCLAW_CODEX_DISCOVERY_LIVE: "0",
594-
NO_COLOR: undefined,
595-
},
596-
exitTimeoutMs: LOCAL_EXIT_TIMEOUT_MS,
597-
outputTimeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
598-
});
557+
let run: PtyRun;
558+
try {
559+
await Promise.all([
560+
mkdir(workspaceDir, { recursive: true }),
561+
mkdir(homeDir, { recursive: true }),
562+
mkdir(stateDir, { recursive: true }),
563+
mkdir(xdgConfigHome, { recursive: true }),
564+
mkdir(xdgDataHome, { recursive: true }),
565+
mkdir(xdgCacheHome, { recursive: true }),
566+
writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"),
567+
]);
568+
569+
run = startPty(process.execPath, buildTuiProcessArgs(["tui", "--local"]), {
570+
cwd: process.cwd(),
571+
env: {
572+
HOME: homeDir,
573+
OPENCLAW_HOME: homeDir,
574+
OPENCLAW_CONFIG_PATH: configPath,
575+
OPENCLAW_STATE_DIR: stateDir,
576+
OPENCLAW_AGENT_DIR: undefined,
577+
OPENCLAW_SKIP_PROVIDERS: undefined,
578+
XDG_CONFIG_HOME: xdgConfigHome,
579+
XDG_DATA_HOME: xdgDataHome,
580+
XDG_CACHE_HOME: xdgCacheHome,
581+
OPENCLAW_THEME: "dark",
582+
OPENCLAW_CODEX_DISCOVERY_LIVE: "0",
583+
NO_COLOR: undefined,
584+
},
585+
exitTimeoutMs: LOCAL_EXIT_TIMEOUT_MS,
586+
outputTimeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
587+
});
588+
} catch (error) {
589+
let cleanupFailure: unknown;
590+
try {
591+
await cleanupLocalModeResources({ mockModel, tempDir });
592+
} catch (cleanupError) {
593+
cleanupFailure = cleanupError;
594+
}
595+
if (cleanupFailure !== undefined) {
596+
const cleanupDetail =
597+
cleanupFailure instanceof Error
598+
? cleanupFailure.message
599+
: typeof cleanupFailure === "string"
600+
? cleanupFailure
601+
: "unknown cleanup error";
602+
throw new Error(`local TUI PTY fixture cleanup failed: ${cleanupDetail}`, {
603+
cause: error,
604+
});
605+
}
606+
throw error;
607+
}
599608

600609
const cleanup = createIdempotentCleanup(async () => {
601-
await run.dispose();
602-
await mockModel.stop();
603-
await rm(tempDir, { recursive: true, force: true });
610+
await cleanupLocalModeResources({ run, mockModel, tempDir });
604611
});
605612
registerCleanup(cleanup);
606613
return {
@@ -790,25 +797,28 @@ async function startGatewayModeTui(
790797
const requestOffset = shared.mockModel.requests(scenario.modelId).length;
791798
const sessionKey = `agent:${scenario.agentId}:tui-pty-${++gatewaySessionSequence}`;
792799
const sessionKeys = new Set([sessionKey]);
793-
const script = buildTuiCliScript([
794-
"tui",
795-
"--url",
796-
shared.gateway.url,
797-
"--token",
798-
shared.gateway.gatewayToken,
799-
"--session",
800-
sessionKey,
801-
]);
802-
const run = startPty(process.execPath, ["--import", "tsx", "--eval", script], {
803-
cwd: process.cwd(),
804-
env: {
805-
...shared.gateway.env,
806-
OPENCLAW_THEME: "dark",
807-
NO_COLOR: undefined,
800+
const run = startPty(
801+
process.execPath,
802+
buildTuiProcessArgs([
803+
"tui",
804+
"--url",
805+
shared.gateway.url,
806+
"--token",
807+
shared.gateway.gatewayToken,
808+
"--session",
809+
sessionKey,
810+
]),
811+
{
812+
cwd: process.cwd(),
813+
env: {
814+
...shared.gateway.env,
815+
OPENCLAW_THEME: "dark",
816+
NO_COLOR: undefined,
817+
},
818+
exitTimeoutMs: LOCAL_EXIT_TIMEOUT_MS,
819+
outputTimeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
808820
},
809-
exitTimeoutMs: LOCAL_EXIT_TIMEOUT_MS,
810-
outputTimeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
811-
});
821+
);
812822
const cleanup = createIdempotentCleanup(async () => {
813823
shared.mockModel.releaseFirstResponse(scenario.modelId);
814824
await run.dispose();
@@ -1077,9 +1087,7 @@ describe("TUI PTY real backends", () => {
10771087
),
10781088
});
10791089
}
1080-
if (mode === "gateway") {
1081-
await fixture.run.write("\u001b", { delay: false });
1082-
}
1090+
await fixture.run.write("\u001b", { delay: false });
10831091
await fixture.run.waitForOutput(
10841092
"run aborted: edit tool validation failed:",
10851093
LOCAL_OUTPUT_TIMEOUT_MS,

0 commit comments

Comments
 (0)