Skip to content

Commit 17ef777

Browse files
authored
fix(ci): stabilize TUI PTY proof ownership (#119420)
* fix(ci): stabilize TUI PTY proof ownership Punchcard-Session: cobalt-brook-meadow-m9 * fix(test): align TUI PTY event typings Punchcard-Session: cobalt-brook-meadow-m9
1 parent 23c7981 commit 17ef777

7 files changed

Lines changed: 276 additions & 35 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,15 +1291,18 @@ jobs:
12911291
wait_checks
12921292
fi
12931293
1294-
# The built local TUI lane owns a real Gateway fixture. Keep it
1295-
# exclusive so sibling artifact shards cannot starve its requests.
1294+
# The dedicated Node shard owns the full built-CLI PTY suite. Keep
1295+
# only the local roundtrip and Gateway-connect artifact canaries here.
12961296
if [ "$RUN_TUI_PTY" = "true" ]; then
12971297
start_check "tui-pty" env \
12981298
NODE_OPTIONS=--max-old-space-size=8192 \
12991299
OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1 \
13001300
OPENCLAW_TUI_PTY_USE_BUILT_CLI=1 \
13011301
OPENCLAW_VITEST_MAX_WORKERS=2 \
1302-
node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts
1302+
node scripts/run-vitest.mjs run \
1303+
--config test/vitest/vitest.tui-pty.config.ts \
1304+
src/tui/tui-pty-local.e2e.test.ts \
1305+
--testNamePattern "launches openclaw (chat as local mode|tui against a real Gateway) through a real PTY"
13031306
wait_checks
13041307
fi
13051308

‎docs/ci.md‎

Lines changed: 2 additions & 2 deletions
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** 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. That built local lane runs after the other artifact checks because it owns a real Gateway fixture whose request deadlines must not compete with sibling shards.
104+
- **TUI PTY** splits by proof ownership. The dedicated `core-runtime-tui-pty` Node shard owns the full real-backend suite against the exact-head built CLI. The `build-artifacts` job keeps only a local model roundtrip and a real Gateway connection canary, so every artifact boundary proves the built launcher without duplicating the full serial suite inside the build job.
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

@@ -121,7 +121,7 @@ The slowest Node test families are split or balanced so each job stays small wit
121121
- The build-artifact job also persists content-fingerprinted `build-all` step outputs. CI's self-built plugin SDK declarations hash the complete repository-owned TypeScript/JSON source graph, exclude installed and generated directories, and restore both flat declarations and package bridges after `tsdown` clears `dist`. Documentation, workflow, plugin, and other changes outside that graph can reuse the declaration snapshot; source changes rebuild it before the export gate runs.
122122
- Full declaration builds split `tsdown` into AI, workspace-package, and unified groups. Each group caches declarations only, then still rebuilds runtime JavaScript before restoring those declarations. Core or plugin changes therefore invalidate only the large unified graph, while workspace-package changes conservatively invalidate every dependent declaration group. Public full builds generally use an immutable Actions cache; coarse restore keys seed partial changes, per-group content fingerprints reject stale data, and GitHub's cache quota evicts old generations. The weekly Node 22 lane instead publishes a 14-day artifact after successful `main` runs and restores only artifacts whose immutable producer identity resolves to that workflow on `main`, avoiding quota churn without allowing PR code to write a shared cache. Private-QA declarations are never persisted in Actions caches because cache namespaces are not confidentiality boundaries.
123123
- `check-additional-*` stripes the supplemental boundary guard list (`scripts/run-additional-boundary-checks.mjs`) into one prompt-heavy shard (`check-additional-boundaries-a`, which includes the Codex prompt snapshot drift check) and one combined shard for the remaining stripes (`check-additional-boundaries-bcd`), each running independent guards concurrently and printing per-check timings. Package-boundary compile/canary work stays together, and runtime topology architecture runs separately from the gateway watch coverage embedded in `build-artifacts`.
124-
- On the 32-vCPU self-hosted build runner, Gateway watch, channel tests, and the core support-boundary shard start together inside `build-artifacts` after `dist/` and `dist-runtime/` are already built. GitHub-hosted fallback runs keep Gateway watch serial so low-core contention cannot consume its readiness deadline. Both paths then run built local TUI PTY alone so its real Gateway fixture has exclusive process and event-loop capacity.
124+
- On the 32-vCPU self-hosted build runner, Gateway watch, channel tests, and the core support-boundary shard start together inside `build-artifacts` after `dist/` and `dist-runtime/` are already built. GitHub-hosted fallback runs keep Gateway watch serial so low-core contention cannot consume its readiness deadline. Both paths then run the two built TUI PTY artifact canaries alone; the dedicated Node shard owns the full serial suite.
125125

126126
Once admitted, canonical Linux CI permits up to 28 concurrent Node test jobs and
127127
12 for the smaller fast/check lanes; Windows and Android stay at two because

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

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,106 @@
11
import { describe, expect, it } from "vitest";
22
import { createDeferred } from "../test-utils/deferred.js";
3-
import { cleanupStartedFixture, createFreshSession } from "./tui-pty-local-test-support.js";
3+
import {
4+
cleanupStartedFixture,
5+
createChatTerminalObserver,
6+
createFreshSession,
7+
registerIdempotentCleanup,
8+
} from "./tui-pty-local-test-support.js";
49
import type { PtyRun } from "./tui-pty-test-support.js";
510

611
const SUBMISSION_SETTLE_MS = 150;
712
const SESSION_ROLLOVER_BUSY_MESSAGE = "abort the current run before /new";
813

914
describe("local TUI PTY fixture support", () => {
15+
it("registers idempotent cleanup before fallible fixture setup", async () => {
16+
const order: string[] = [];
17+
let registeredCleanup: (() => Promise<void>) | undefined;
18+
const setupError = new Error("setup failed");
19+
let cleanupCalls = 0;
20+
21+
await expect(
22+
(async () => {
23+
const cleanup = registerIdempotentCleanup(
24+
(registered) => {
25+
order.push("registered");
26+
registeredCleanup = registered;
27+
},
28+
async () => {
29+
cleanupCalls += 1;
30+
order.push("cleanup");
31+
},
32+
);
33+
try {
34+
order.push("setup");
35+
throw setupError;
36+
} finally {
37+
await cleanup();
38+
}
39+
})(),
40+
).rejects.toBe(setupError);
41+
await registeredCleanup!();
42+
43+
expect(order).toEqual(["registered", "setup", "cleanup"]);
44+
expect(cleanupCalls).toBe(1);
45+
});
46+
47+
it("waits for the matching successful terminal event before history observation", async () => {
48+
const observer = createChatTerminalObserver();
49+
const terminal = observer.waitForFinal({
50+
runId: "run-history",
51+
sessionKey: "agent:main:history",
52+
timeoutMs: 1_000,
53+
});
54+
55+
observer.onEvent({
56+
event: "chat",
57+
payload: {
58+
runId: "run-history",
59+
sessionKey: "agent:main:history",
60+
state: "delta",
61+
},
62+
});
63+
observer.onEvent({
64+
event: "chat",
65+
payload: {
66+
runId: "run-other",
67+
sessionKey: "agent:main:history",
68+
state: "final",
69+
},
70+
});
71+
observer.onEvent({
72+
event: "chat",
73+
payload: {
74+
runId: "run-history",
75+
sessionKey: "agent:main:history",
76+
state: "final",
77+
},
78+
});
79+
80+
await expect(terminal).resolves.toMatchObject({ state: "final" });
81+
});
82+
83+
it("fails promptly when the observed chat run terminates with an error", async () => {
84+
const observer = createChatTerminalObserver();
85+
observer.onEvent({
86+
event: "chat",
87+
payload: {
88+
errorMessage: "provider failed",
89+
runId: "run-history",
90+
sessionKey: "agent:main:history",
91+
state: "error",
92+
},
93+
});
94+
95+
await expect(
96+
observer.waitForFinal({
97+
runId: "run-history",
98+
sessionKey: "agent:main:history",
99+
timeoutMs: 1_000,
100+
}),
101+
).rejects.toThrow("chat run run-history ended as error: provider failed");
102+
});
103+
10104
it("owns late fixture startup without swallowing cleanup failures", async () => {
11105
await expect(cleanupStartedFixture(Promise.reject(new Error("setup failed")))).resolves.toBe(
12106
undefined,

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

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,85 @@ import { waitFor, type PtyRun } from "./tui-pty-test-support.js";
33
const STARTUP_TIMEOUT_MS = 60_000;
44
const OUTPUT_TIMEOUT_MS = 120_000;
55

6+
type CleanupRegistrar = (cleanup: () => Promise<void>) => void;
7+
8+
export function createIdempotentCleanup(cleanup: () => Promise<void>) {
9+
let cleanupPromise: Promise<void> | undefined;
10+
return () => (cleanupPromise ??= cleanup());
11+
}
12+
13+
// Register before setup starts so a timed-out test still owns partial resources.
14+
export function registerIdempotentCleanup(
15+
registerCleanup: CleanupRegistrar,
16+
cleanup: () => Promise<void>,
17+
) {
18+
const registeredCleanup = createIdempotentCleanup(cleanup);
19+
registerCleanup(registeredCleanup);
20+
return registeredCleanup;
21+
}
22+
23+
type ObservedChatTerminal = {
24+
errorMessage?: string;
25+
runId: string;
26+
sessionKey: string;
27+
state: "aborted" | "error" | "final";
28+
};
29+
30+
// A completed-history assertion must wait for the run's terminal event first.
31+
// Polling history during the run can consume the RPC deadline and leak that run.
32+
export function createChatTerminalObserver() {
33+
const terminals = new Map<string, ObservedChatTerminal>();
34+
const keyFor = (sessionKey: string, runId: string) => `${sessionKey}\u0000${runId}`;
35+
36+
return {
37+
onEvent: ({ event, payload }: { event: string; payload?: unknown }) => {
38+
if (event !== "chat" || !payload || typeof payload !== "object") {
39+
return;
40+
}
41+
const chatEvent = payload as {
42+
errorMessage?: unknown;
43+
runId?: unknown;
44+
sessionKey?: unknown;
45+
state?: unknown;
46+
};
47+
if (
48+
typeof chatEvent.runId !== "string" ||
49+
typeof chatEvent.sessionKey !== "string" ||
50+
(chatEvent.state !== "aborted" &&
51+
chatEvent.state !== "error" &&
52+
chatEvent.state !== "final")
53+
) {
54+
return;
55+
}
56+
terminals.set(keyFor(chatEvent.sessionKey, chatEvent.runId), {
57+
...(typeof chatEvent.errorMessage === "string"
58+
? { errorMessage: chatEvent.errorMessage }
59+
: {}),
60+
runId: chatEvent.runId,
61+
sessionKey: chatEvent.sessionKey,
62+
state: chatEvent.state,
63+
});
64+
},
65+
waitForFinal: async (params: { runId: string; sessionKey: string; timeoutMs: number }) => {
66+
const terminal = await waitFor({
67+
timeoutMs: params.timeoutMs,
68+
read: () => terminals.get(keyFor(params.sessionKey, params.runId)) ?? null,
69+
onTimeout: () =>
70+
new Error(`chat run ${params.runId} did not reach a terminal event before history load`),
71+
});
72+
terminals.delete(keyFor(params.sessionKey, params.runId));
73+
if (terminal.state !== "final") {
74+
throw new Error(
75+
`chat run ${params.runId} ended as ${terminal.state}${
76+
terminal.errorMessage ? `: ${terminal.errorMessage}` : ""
77+
}`,
78+
);
79+
}
80+
return terminal;
81+
},
82+
};
83+
}
84+
685
export async function waitForOutputAfter(
786
run: PtyRun,
887
needle: string,

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

Lines changed: 86 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,11 @@ import { GatewayChatClient } from "./gateway-chat.js";
2121
import { synchronizedFrameRows } from "./tui-pty-harness-assertion-test-support.js";
2222
import {
2323
cleanupStartedFixture,
24+
createChatTerminalObserver,
25+
createIdempotentCleanup,
2426
createFreshSession,
2527
lastOutputIndexAfter,
28+
registerIdempotentCleanup,
2629
waitForOutputAfter,
2730
} from "./tui-pty-local-test-support.js";
2831
import { sleep, startPty, waitFor, type PtyRun } from "./tui-pty-test-support.js";
@@ -159,11 +162,6 @@ async function requestWithUnavailableRetry<T>(request: () => Promise<T>): Promis
159162
}
160163
}
161164

162-
function createIdempotentCleanup(cleanup: () => Promise<void>) {
163-
let cleanupPromise: Promise<void> | undefined;
164-
return () => (cleanupPromise ??= cleanup());
165-
}
166-
167165
type CleanupRegistrar = (cleanup: () => Promise<void>) => void;
168166

169167
async function readRequestBody(req: IncomingMessage): Promise<string> {
@@ -845,8 +843,37 @@ async function startGatewayModeTui(
845843
const rejectedRequestOffset = shared.mockModel.rejectedRequests().length;
846844
const sessionKey = `agent:${scenario.agentId}:tui-pty-${++gatewaySessionSequence}`;
847845
const sessionKeys = new Set([sessionKey]);
848-
await shared.controlClient.createSession({ key: sessionKey, agentId: scenario.agentId });
849-
await shared.controlClient.patchSession({
846+
const controlClient = new GatewayChatClient({
847+
url: shared.gateway.url,
848+
token: shared.gateway.gatewayToken,
849+
allowInsecureLocalOperatorUi: false,
850+
});
851+
let controlClientConnected = false;
852+
controlClient.onConnected = () => {
853+
controlClientConnected = true;
854+
};
855+
// A timed-out RPC drops its pending response while leaving the socket open.
856+
// Case-local ownership prevents that late work from crossing into the next test.
857+
const cleanup = registerIdempotentCleanup(registerCleanup, async () => {
858+
shared.mockModel.releaseFirstResponse(scenario.modelId);
859+
try {
860+
if (controlClientConnected) {
861+
for (const key of sessionKeys) {
862+
await controlClient.abortChat({ sessionKey: key });
863+
}
864+
}
865+
} finally {
866+
await controlClient.stop();
867+
}
868+
});
869+
controlClient.start();
870+
await waitFor({
871+
timeoutMs: LOCAL_STARTUP_TIMEOUT_MS,
872+
read: () => (controlClientConnected ? true : null),
873+
onTimeout: () => new Error("Gateway case control client did not connect"),
874+
});
875+
await controlClient.createSession({ key: sessionKey, agentId: scenario.agentId });
876+
await controlClient.patchSession({
850877
key: sessionKey,
851878
agentId: scenario.agentId,
852879
model: `tui-pty-mock/${scenario.modelId}`,
@@ -865,13 +892,6 @@ async function startGatewayModeTui(
865892
onTimeout: () => new Error("adopted Gateway session did not reach an idle final screen"),
866893
});
867894
const outputOffset = run.visibleOutput().length;
868-
const cleanup = createIdempotentCleanup(async () => {
869-
shared.mockModel.releaseFirstResponse(scenario.modelId);
870-
for (const key of sessionKeys) {
871-
await shared.controlClient.abortChat({ sessionKey: key });
872-
}
873-
});
874-
registerCleanup(cleanup);
875895
return {
876896
kind: "gateway" as const,
877897
run,
@@ -1593,27 +1613,62 @@ export default {
15931613
const shared = await requireSharedGatewayFixture();
15941614
const agentId = SHARED_GATEWAY_AGENT_ID;
15951615
const sessionKey = `agent:${agentId}:tui-pty-history`;
1616+
const runId = randomUUID();
15961617
const userMarker = "T02_HISTORY_USER";
15971618
const assistantMarker = GATEWAY_SCENARIOS.history.replyText;
15981619
const model = `tui-pty-mock/${GATEWAY_SCENARIOS.history.modelId}`;
1599-
await shared.controlClient.createSession({ key: sessionKey, agentId });
1600-
await shared.controlClient.patchSession({ key: sessionKey, agentId, model });
1601-
await shared.controlClient.sendChat({ sessionKey, message: userMarker });
1602-
await waitForHistoryMessages(shared.controlClient, sessionKey, ({ messages }) =>
1603-
hasOrderedTurn(messages, userMarker, assistantMarker),
1604-
);
1605-
const attached = await startIsolatedGatewayPty({
1606-
gateway: shared.gateway,
1607-
registerCleanup: onTestFinished,
1608-
sessionKey,
1620+
const terminalObserver = createChatTerminalObserver();
1621+
const historyClient = new GatewayChatClient({
1622+
url: shared.gateway.url,
1623+
token: shared.gateway.gatewayToken,
1624+
allowInsecureLocalOperatorUi: false,
1625+
});
1626+
let historyClientConnected = false;
1627+
historyClient.onConnected = () => {
1628+
historyClientConnected = true;
1629+
};
1630+
historyClient.onEvent = terminalObserver.onEvent;
1631+
const cleanup = registerIdempotentCleanup(onTestFinished, async () => {
1632+
try {
1633+
if (historyClientConnected) {
1634+
await historyClient.abortChat({ sessionKey, runId });
1635+
}
1636+
} finally {
1637+
await historyClient.stop();
1638+
}
16091639
});
1640+
let attached: Awaited<ReturnType<typeof startIsolatedGatewayPty>> | undefined;
16101641
try {
1611-
await attached.run.waitForOutput(assistantMarker, LOCAL_STARTUP_TIMEOUT_MS);
1642+
historyClient.start();
1643+
await waitFor({
1644+
timeoutMs: LOCAL_STARTUP_TIMEOUT_MS,
1645+
read: () => (historyClientConnected ? true : null),
1646+
onTimeout: () => new Error("history Gateway client did not connect"),
1647+
});
1648+
await historyClient.subscribeSessionEvents();
1649+
await historyClient.createSession({ key: sessionKey, agentId });
1650+
await historyClient.patchSession({ key: sessionKey, agentId, model });
1651+
await historyClient.sendChat({ sessionKey, message: userMarker, runId });
1652+
await terminalObserver.waitForFinal({
1653+
runId,
1654+
sessionKey,
1655+
timeoutMs: LOCAL_OUTPUT_TIMEOUT_MS,
1656+
});
1657+
await waitForHistoryMessages(historyClient, sessionKey, ({ messages }) =>
1658+
hasOrderedTurn(messages, userMarker, assistantMarker),
1659+
);
1660+
attached = await startIsolatedGatewayPty({
1661+
gateway: shared.gateway,
1662+
registerCleanup: onTestFinished,
1663+
sessionKey,
1664+
});
1665+
const attachedRun = attached.run;
1666+
await attachedRun.waitForOutput(assistantMarker, LOCAL_STARTUP_TIMEOUT_MS);
16121667
const output = await waitFor({
16131668
timeoutMs: LOCAL_STARTUP_TIMEOUT_MS,
16141669
read: () => {
16151670
const screen =
1616-
synchronizedFrameRows(attached.run.output(), attached.run)[0]?.join("\n") ?? "";
1671+
synchronizedFrameRows(attachedRun.output(), attachedRun)[0]?.join("\n") ?? "";
16171672
return screen.includes(userMarker) && screen.includes(assistantMarker) ? screen : null;
16181673
},
16191674
onTimeout: () => new Error("history did not reach a final synchronized TUI screen"),
@@ -1622,7 +1677,11 @@ export default {
16221677
expect(output.split(assistantMarker)).toHaveLength(2);
16231678
expect(output.indexOf(userMarker)).toBeLessThan(output.indexOf(assistantMarker));
16241679
} finally {
1625-
await attached.cleanup();
1680+
try {
1681+
await attached?.cleanup();
1682+
} finally {
1683+
await cleanup();
1684+
}
16261685
}
16271686
},
16281687
LOCAL_TEST_TIMEOUT_MS,

0 commit comments

Comments
 (0)