Skip to content

Commit 9b9afc3

Browse files
authored
fix(tui): recover replacement runs after reconnect (#128221)
1 parent 225a395 commit 9b9afc3

5 files changed

Lines changed: 99 additions & 8 deletions

‎src/tui/tui-event-handlers.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3754,6 +3754,38 @@ describe("tui-event-handlers: streaming watchdog", () => {
37543754
handlers.dispose?.();
37553755
});
37563756

3757+
it.each([
3758+
{ description: "replaces the previous run", previousRunId: "run-before-reconnect" },
3759+
{ description: "appears after an idle disconnect", previousRunId: null },
3760+
])("rearms reconnect recovery when authoritative history $description", ({ previousRunId }) => {
3761+
const { state, setActivityStatus, loadHistory, handlers } = createHarness({
3762+
streamingWatchdogMs: 5_000,
3763+
});
3764+
3765+
if (previousRunId) {
3766+
handlers.handleChatEvent({
3767+
runId: previousRunId,
3768+
message: { content: "previous reply" },
3769+
});
3770+
}
3771+
handlers.pauseStreamingWatchdog();
3772+
handlers.reconnectStreamingWatchdog();
3773+
3774+
state.activeChatRunId = "run-after-reconnect";
3775+
handlers.reconnectStreamingWatchdog({
3776+
state: "active",
3777+
runId: "run-after-reconnect",
3778+
});
3779+
3780+
vi.advanceTimersByTime(5_001);
3781+
3782+
expect(state.activeChatRunId).toBeNull();
3783+
expect(setActivityStatus).toHaveBeenLastCalledWith("idle");
3784+
expect(loadHistory).toHaveBeenCalledTimes(1);
3785+
3786+
handlers.dispose?.();
3787+
});
3788+
37573789
it("reloads history only once when reconnect recovery and deferred history refresh overlap", () => {
37583790
const { loadHistory, noteLocalRunId, handlers } = createHarness({
37593791
streamingWatchdogMs: 5_000,

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -248,9 +248,9 @@ describe.sequential("TUI PTY harness", () => {
248248
);
249249

250250
it(
251-
"reconciles active and terminal runs after reconnect history",
252-
() => exerciseTuiReconnectOutcomes(STARTUP_TIMEOUT_MS),
253-
STARTUP_TEST_TIMEOUT_MS,
251+
"reconciles active, replacement, and terminal runs after reconnect history",
252+
() => exerciseTuiReconnectOutcomes(35_000),
253+
45_000,
254254
);
255255

256256
it.each([{ failures: 1 }, { failures: 2 }, { failures: 3 }, { failures: 4 }])(

‎src/tui/tui-pty-reconnect-fixture-test-support.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ export const TUI_PTY_RECONNECT_FIXTURE = {
33
variables: `
44
const disconnectReason = process.env.OPENCLAW_TUI_PTY_DISCONNECT_REASON;
55
const reconnectOutcome = process.env.OPENCLAW_TUI_PTY_RECONNECT_OUTCOME;
6+
const replacementReconnect = reconnectOutcome === "replacement" || reconnectOutcome === "appeared";
67
let disconnectPending = disconnectReason === undefined
78
? 0
89
: Number(process.env.OPENCLAW_TUI_PTY_DISCONNECT_COUNT ?? 1);
910
let reconnectHistoryReady = false;
1011
let reconnectRunId = "run-reconnect-fixture";
12+
let replacementReconnectHistoryLoads = 0;
1113
`,
1214
disconnect: `
1315
emitDisconnect() {
@@ -47,6 +49,18 @@ export const TUI_PTY_RECONNECT_FIXTURE = {
4749
`,
4850
loadHistory: `
4951
if (reconnectHistoryReady && reconnectOutcome) {
52+
if (replacementReconnect) {
53+
replacementReconnectHistoryLoads += 1;
54+
record("replacementReconnectHistory", {
55+
attempt: replacementReconnectHistoryLoads,
56+
});
57+
if (replacementReconnectHistoryLoads > 1) {
58+
return {
59+
sessionInfo: { ...sessionEntry(sessionKey), status: "done" },
60+
messages: [{ role: "assistant", content: "PTY_RECONNECT_RECOVERED" }],
61+
};
62+
}
63+
}
5064
const sessionInfo = {
5165
...sessionEntry(sessionKey),
5266
...(reconnectOutcome === "interrupted"
@@ -60,8 +74,15 @@ export const TUI_PTY_RECONNECT_FIXTURE = {
6074
messages: reconnectOutcome === "completed"
6175
? [{ role: "assistant", content: "PTY_RECONNECT_COMPLETED" }]
6276
: [],
63-
...(reconnectOutcome === "active"
64-
? { inFlightRun: { runId: reconnectRunId, text: "PTY_RECONNECT_PARTIAL" } }
77+
...(reconnectOutcome === "active" || replacementReconnect
78+
? {
79+
inFlightRun: {
80+
runId: replacementReconnect ? "run-reconnect-replacement" : reconnectRunId,
81+
text: replacementReconnect
82+
? "PTY_RECONNECT_REPLACEMENT"
83+
: "PTY_RECONNECT_PARTIAL",
84+
},
85+
}
6586
: {}),
6687
};
6788
}

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

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ const RECONNECT_CASES = [
1313
] as const;
1414

1515
export async function exerciseTuiReconnectOutcomes(timeoutMs: number): Promise<void> {
16-
await Promise.all(
17-
RECONNECT_CASES.map(async ({ outcome, marker, activity }) => {
16+
await Promise.all([
17+
...RECONNECT_CASES.map(async ({ outcome, marker, activity }) => {
1818
const fixture = await startTuiFixture({
1919
env: {
2020
OPENCLAW_TUI_PTY_DISCONNECT_REASON: "fixture transport loss",
@@ -46,5 +46,39 @@ export async function exerciseTuiReconnectOutcomes(timeoutMs: number): Promise<v
4646
await fixture.cleanup();
4747
}
4848
}),
49+
exerciseTuiReplacementReconnectRecovery(timeoutMs),
50+
]);
51+
}
52+
53+
async function exerciseTuiReplacementReconnectRecovery(timeoutMs: number): Promise<void> {
54+
await Promise.all(
55+
["replacement", "appeared"].map(async (outcome) => {
56+
const fixture = await startTuiFixture({
57+
env: {
58+
OPENCLAW_TUI_PTY_DISCONNECT_REASON: "fixture transport loss",
59+
OPENCLAW_TUI_PTY_RECONNECT_OUTCOME: outcome,
60+
},
61+
});
62+
try {
63+
await fixture.run.waitForOutput("local ready", timeoutMs);
64+
if (outcome === "replacement") {
65+
await fixture.run.write("reconnect terminal proof\r", { delay: false });
66+
await fixture.run.waitForOutput("PTY_RECONNECT_PARTIAL", timeoutMs);
67+
}
68+
await fixture.run.write("/gateway-status\r", { delay: false });
69+
await fixture.run.waitForOutput("gateway reconnected after transport loss", timeoutMs);
70+
await fixture.run.waitForOutput("PTY_RECONNECT_REPLACEMENT", timeoutMs);
71+
await fixture.run.waitForOutput("PTY_RECONNECT_RECOVERED", timeoutMs);
72+
73+
const frame = await waitForSynchronizedFrameRows(
74+
fixture.run,
75+
(rows) => rows.some((row) => row.includes("PTY_RECONNECT_RECOVERED")),
76+
timeoutMs,
77+
);
78+
expect(frame.join("\n")).not.toContain("PTY_RECONNECT_REPLACEMENT");
79+
} finally {
80+
await fixture.cleanup();
81+
}
82+
}),
4983
);
5084
}

‎src/tui/tui.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1446,7 +1446,11 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
14461446
const activeRunAtStart = state.activeChatRunId;
14471447
const result = await loadHistorySnapshot();
14481448
if (result.loaded) {
1449-
if (reconcileReconnect && activeRunAtStart && activeRunAtStart === state.activeChatRunId) {
1449+
// History can adopt a newer run before returning; terminal outcomes
1450+
// still belong only to the unchanged run captured before the request.
1451+
const recoveredRunId =
1452+
result.runOutcome.state === "active" ? result.runOutcome.runId : activeRunAtStart;
1453+
if (reconcileReconnect && recoveredRunId && recoveredRunId === state.activeChatRunId) {
14501454
reconcileReconnectRun(result.runOutcome);
14511455
}
14521456
restoreConnectionNotices();

0 commit comments

Comments
 (0)