Skip to content

Commit 7b4981b

Browse files
authored
fix(tui): clear stale overlays after session restore (#125086)
Centralize TUI session identity in state so remembered-session restores use the same invalidation path as interactive switches. Fixes #125013.
1 parent 0af3b86 commit 7b4981b

4 files changed

Lines changed: 143 additions & 67 deletions

File tree

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

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,27 @@ export async function writeTuiPtyFixtureScript(dir: string) {
107107
const pickerSessionTitle = process.env.OPENCLAW_TUI_PTY_PICKER_SESSION_TITLE;
108108
const pickerSessionPreview = process.env.OPENCLAW_TUI_PTY_PICKER_SESSION_PREVIEW;
109109
const pickerSessionDisplayName = process.env.OPENCLAW_TUI_PTY_PICKER_SESSION_DISPLAY_NAME ?? "Picker target";
110+
const initialPluginApprovalSessionKey = process.env.OPENCLAW_TUI_PTY_INITIAL_APPROVAL_SESSION_KEY;
110111
const xaiLimitError = '403 {"code":"The caller does not have permission to execute the specified operation","error":"Your team team-redacted has either used all available credits or reached its monthly spending limit. To continue making API requests, please purchase more credits or raise your spending limit."}';
111112
let currentModel = footerModel ?? "fixture-provider/fixture-model";
112113
let currentThinkingLevel = footerThinkingLevel;
113114
let fastMode = process.env.OPENCLAW_TUI_PTY_FAST_MODE === "true";
115+
function pluginApproval(sessionKey: string) {
116+
return {
117+
id: "plugin:skill-pty",
118+
request: {
119+
title: "Apply workspace skill proposal",
120+
description: "Apply a pending workspace skill proposal into live workspace skills.",
121+
pluginId: "workspace-skills",
122+
severity: "warning" as const,
123+
toolName: "skill_workshop",
124+
allowedDecisions: ["allow-once", "deny"],
125+
sessionKey,
126+
},
127+
createdAtMs: Date.now(),
128+
expiresAtMs: Date.now() + 120_000,
129+
};
130+
}
114131
let pendingPluginApproval: {
115132
id: string;
116133
request: {
@@ -122,7 +139,9 @@ export async function writeTuiPtyFixtureScript(dir: string) {
122139
};
123140
createdAtMs: number;
124141
expiresAtMs: number;
125-
} | null = null;
142+
} | null = initialPluginApprovalSessionKey
143+
? pluginApproval(initialPluginApprovalSessionKey)
144+
: null;
126145
let pendingPluginApprovalRun: { runId: string; sessionKey: string } | null = null;
127146
let pendingTaskSuggestion: {
128147
id: string;
@@ -185,6 +204,9 @@ export async function writeTuiPtyFixtureScript(dir: string) {
185204
}
186205
187206
start() {
207+
if (pendingPluginApproval) {
208+
this.onEvent?.({ event: "plugin.approval.requested", payload: pendingPluginApproval });
209+
}
188210
queueMicrotask(() => this.onConnected?.());
189211
}
190212
@@ -320,20 +342,7 @@ export async function writeTuiPtyFixtureScript(dir: string) {
320342
}
321343
if (opts.message === "history gap proof") { return beginGapHistoryRecovery(this, runId, opts.sessionKey); }
322344
if (opts.message === "skill approval proof" || opts.message === "skill approval gap proof") {
323-
pendingPluginApproval = {
324-
id: "plugin:skill-pty",
325-
request: {
326-
title: "Apply workspace skill proposal",
327-
description: "Apply a pending workspace skill proposal into live workspace skills.",
328-
pluginId: "workspace-skills",
329-
severity: "warning",
330-
toolName: "skill_workshop",
331-
allowedDecisions: ["allow-once", "deny"],
332-
sessionKey: opts.sessionKey,
333-
},
334-
createdAtMs: Date.now(),
335-
expiresAtMs: Date.now() + 120_000,
336-
};
345+
pendingPluginApproval = pluginApproval(opts.sessionKey);
337346
pendingPluginApprovalRun = { runId, sessionKey: opts.sessionKey };
338347
queueMicrotask(() => {
339348
if (opts.message === "skill approval gap proof") {
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { afterEach, expect, it } from "vitest";
2+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
3+
import { buildTuiLastSessionScopeKey, writeTuiLastSessionKey } from "./tui-last-session.js";
4+
import {
5+
disposeActiveTuiFixtures,
6+
objectFieldEquals,
7+
startTuiFixture,
8+
waitForSynchronizedFrameRows,
9+
} from "./tui-pty-harness-fixture-test-support.js";
10+
11+
const STARTUP_TIMEOUT_MS = 60_000;
12+
const REMEMBERED_SESSION_KEY = "agent:main:picker-target";
13+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
14+
15+
afterEach(async () => {
16+
await disposeActiveTuiFixtures();
17+
});
18+
19+
it("hides a stale approval when startup restores the remembered session", async () => {
20+
const stateDir = tempDirs.make("openclaw-tui-identity-");
21+
await writeTuiLastSessionKey({
22+
scopeKey: buildTuiLastSessionScopeKey({
23+
connectionUrl: "pty-fixture://local",
24+
agentId: "main",
25+
sessionScope: "per-sender",
26+
}),
27+
sessionKey: REMEMBERED_SESSION_KEY,
28+
stateDir,
29+
});
30+
const fixture = await startTuiFixture({
31+
env: {
32+
OPENCLAW_STATE_DIR: stateDir,
33+
OPENCLAW_TUI_PTY_INITIAL_APPROVAL_SESSION_KEY: "agent:main:main",
34+
OPENCLAW_TUI_PTY_PICKER_FIXTURE: "1",
35+
},
36+
});
37+
38+
try {
39+
await fixture.waitForLogEntry(
40+
(entry) =>
41+
entry.method === "loadHistory" &&
42+
objectFieldEquals(entry, "sessionKey", REMEMBERED_SESSION_KEY),
43+
STARTUP_TIMEOUT_MS,
44+
);
45+
await fixture.waitForLogEntry(
46+
(entry) =>
47+
entry.method === "listPluginApprovals" && objectFieldEquals(entry, "pending", true),
48+
STARTUP_TIMEOUT_MS,
49+
);
50+
const rows = await waitForSynchronizedFrameRows(
51+
fixture.run,
52+
(frame) => frame.some((row) => row.includes("session picker-target")),
53+
STARTUP_TIMEOUT_MS,
54+
);
55+
56+
expect(rows.join("\n")).not.toContain("workspace skill approval");
57+
} finally {
58+
await fixture.cleanup();
59+
}
60+
}, 65_000);

‎src/tui/tui.ts‎

Lines changed: 56 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,17 @@ export async function runTui(opts: RunTuiOptions): Promise<TuiResult> {
745745
return await runTuiUnlocked(opts);
746746
}
747747

748+
class TuiSessionIdentityState {
749+
sessionKey = "";
750+
sessionId: string | null = null;
751+
readonly generations = new Map<string, number>();
752+
readonly sessionIds = new Map<string, string>();
753+
constructor(public agentId: string) {}
754+
generationKey() {
755+
return JSON.stringify([this.agentId, this.sessionKey]);
756+
}
757+
}
758+
748759
async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
749760
const isLocalMode = opts.local === true || opts.backend !== undefined;
750761
const config = opts.config ?? getRuntimeConfig({ skipPluginValidation: !isLocalMode });
@@ -755,19 +766,15 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
755766
const sessionScope = (config.session?.scope ?? "per-sender") as SessionScope;
756767
const sessionMainKey = normalizeMainKey(config.session?.mainKey);
757768
const configuredDefaultAgentId = tryResolveDefaultAgentId(config);
758-
let currentAgentId = resolveInitialTuiAgentId({
769+
const initialAgentId = resolveInitialTuiAgentId({
759770
cfg: config,
760771
fallbackAgentId: configuredDefaultAgentId,
761772
initialSessionInput,
762773
agentId: opts.agentId,
763774
});
764-
const agentDefaultId = configuredDefaultAgentId ?? currentAgentId;
775+
const agentDefaultId = configuredDefaultAgentId ?? initialAgentId;
765776
const agentNames = new Map<string, string>();
766-
let currentSessionKey = "";
767777
let rememberedSessionApplied = false;
768-
let currentSessionId: string | null = null;
769-
const sessionGenerations = new Map<string, number>();
770-
const sessionIds = new Map<string, string>();
771778
let connectionGeneration = 0;
772779
const connectionLineage = createTuiConnectionLineage();
773780
let remediationShown = false;
@@ -789,61 +796,58 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
789796
let statusStartedAt: number | null = null;
790797
let lastActivityStatus = "idle";
791798
let invalidateSessionRunOwnership: () => void = () => undefined;
799+
let notifySessionChanged: () => void = () => undefined;
792800
let retireHistoryAbsentRun: (_runId: string) => void = () => undefined;
793801

794-
const currentSessionGenerationKey = (): string =>
795-
JSON.stringify([currentAgentId, currentSessionKey]);
796-
const readCurrentSessionGeneration = () =>
797-
sessionGenerations.get(currentSessionGenerationKey()) ?? 0;
798-
const writeCurrentSessionGeneration = (value: number) => {
799-
sessionGenerations.set(currentSessionGenerationKey(), value);
800-
};
801-
802-
const state: TuiStateAccess = {
802+
const state: TuiStateAccess & {
803+
sessionGeneration: number;
804+
sessionIdentity: TuiSessionIdentityState;
805+
} = {
806+
sessionIdentity: new TuiSessionIdentityState(initialAgentId),
803807
agentDefaultId,
804808
sessionMainKey,
805809
sessionScope,
806810
agents: [],
807811
get currentAgentId() {
808-
return currentAgentId;
812+
return this.sessionIdentity.agentId;
809813
},
810-
set currentAgentId(value) {
811-
if (currentAgentId === value) {
814+
set currentAgentId(value: string) {
815+
if (this.sessionIdentity.agentId === value) {
812816
return;
813817
}
814-
currentAgentId = value;
818+
this.sessionIdentity.agentId = value;
815819
invalidateSessionRunOwnership();
816-
pluginApprovals?.sessionChanged();
817-
taskSuggestions?.sessionChanged();
820+
notifySessionChanged();
818821
},
819822
get currentSessionKey() {
820-
return currentSessionKey;
823+
return this.sessionIdentity.sessionKey;
821824
},
822-
set currentSessionKey(value) {
823-
currentSessionKey = value;
824-
pluginApprovals?.sessionChanged();
825-
taskSuggestions?.sessionChanged();
825+
set currentSessionKey(value: string) {
826+
this.sessionIdentity.sessionKey = value;
827+
notifySessionChanged();
826828
},
827829
get currentSessionId() {
828-
return currentSessionId;
830+
return this.sessionIdentity.sessionId;
829831
},
830-
set currentSessionId(value) {
832+
set currentSessionId(value: string | null) {
831833
if (value) {
832-
const generationKey = currentSessionGenerationKey();
833-
const previousSessionId = sessionIds.get(generationKey);
834+
const generationKey = this.sessionIdentity.generationKey();
835+
const previousSessionId = this.sessionIdentity.sessionIds.get(generationKey);
834836
// The first ID binds an unresolved selection; reset/replacement owners bump explicitly.
835837
if (previousSessionId && previousSessionId !== value) {
836-
writeCurrentSessionGeneration(readCurrentSessionGeneration() + 1);
838+
this.sessionGeneration += 1;
837839
}
838-
sessionIds.set(generationKey, value);
840+
this.sessionIdentity.sessionIds.set(generationKey, value);
839841
}
840-
currentSessionId = value;
842+
this.sessionIdentity.sessionId = value;
841843
},
842844
get sessionGeneration() {
843-
return readCurrentSessionGeneration();
845+
const generationKey = this.sessionIdentity.generationKey();
846+
return this.sessionIdentity.generations.get(generationKey) ?? 0;
844847
},
845-
set sessionGeneration(value) {
846-
writeCurrentSessionGeneration(Math.max(readCurrentSessionGeneration(), value));
848+
set sessionGeneration(value: number) {
849+
const generationKey = this.sessionIdentity.generationKey();
850+
this.sessionIdentity.generations.set(generationKey, Math.max(this.sessionGeneration, value));
847851
},
848852
activeChatRunId: null,
849853
pendingSubmit: null,
@@ -1033,9 +1037,10 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
10331037
});
10341038
};
10351039

1036-
currentSessionKey = resolveSessionSelection(initialSessionInput).key;
1040+
// Initial selection predates controller construction, so it intentionally does not notify.
1041+
state.sessionIdentity.sessionKey = resolveSessionSelection(initialSessionInput).key;
10371042

1038-
const buildLastSessionScopeKeyFor = (sessionKey = currentSessionKey) => {
1043+
const buildLastSessionScopeKeyFor = (sessionKey = state.currentSessionKey) => {
10391044
const parsed = parseAgentSessionKey(sessionKey);
10401045
return buildTuiLastSessionScopeKey({
10411046
connectionUrl: client.connection.url,
@@ -1069,7 +1074,7 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
10691074
}
10701075
const rememberedSelection = remembered ? resolveSessionSelection(remembered) : null;
10711076
const rememberedKey = rememberedSelection?.key ?? null;
1072-
if (!rememberedKey || rememberedKey === currentSessionKey) {
1077+
if (!rememberedKey || rememberedKey === state.currentSessionKey) {
10731078
rememberedSessionApplied = true;
10741079
return;
10751080
}
@@ -1102,16 +1107,16 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
11021107
currentAgentId: state.currentAgentId,
11031108
sessions: sessions.sessions,
11041109
});
1105-
if (!restored || restored === currentSessionKey) {
1110+
if (!restored || restored === state.currentSessionKey) {
11061111
return;
11071112
}
1108-
currentSessionKey = restored;
1113+
state.currentSessionKey = restored;
11091114
updateHeader();
11101115
updateFooter();
11111116
};
11121117

11131118
const updateHeader = () => {
1114-
const sessionLabel = formatSessionKey(currentSessionKey);
1119+
const sessionLabel = formatSessionKey(state.currentSessionKey);
11151120
const agentLabel = formatAgentLabel(state.currentAgentId);
11161121
const title = opts.title ?? "openclaw tui";
11171122
const text = `${title} - ${client.connection.url} - agent ${agentLabel} - session ${sessionLabel}`;
@@ -1369,7 +1374,7 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
13691374
: undefined;
13701375

13711376
const updateFooter = () => {
1372-
const sessionKeyLabel = formatSessionKey(currentSessionKey);
1377+
const sessionKeyLabel = formatSessionKey(state.currentSessionKey);
13731378
const sessionLabel = state.sessionInfo.displayName
13741379
? `${sessionKeyLabel} (${state.sessionInfo.displayName})`
13751380
: sessionKeyLabel;
@@ -1393,7 +1398,7 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
13931398
client,
13941399
chatLog,
13951400
getAgentId: () => state.currentAgentId,
1396-
getSessionKey: () => currentSessionKey,
1401+
getSessionKey: () => state.currentSessionKey,
13971402
openOverlay,
13981403
closeOverlay,
13991404
requestRender: () => tui.requestRender(),
@@ -1407,12 +1412,7 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
14071412
},
14081413
};
14091414

1410-
const initialSessionAgentId = (() => {
1411-
if (!initialSessionInput) {
1412-
return null;
1413-
}
1414-
return currentAgentId;
1415-
})();
1415+
const initialSessionAgentId = initialSessionInput ? state.currentAgentId : null;
14161416
const sessionActions = createSessionActions({
14171417
client,
14181418
chatLog,
@@ -1461,13 +1461,17 @@ async function runTuiUnlocked(opts: RunTuiOptions): Promise<TuiResult> {
14611461
const taskSuggestions = createTuiTaskSuggestionController({
14621462
client,
14631463
chatLog,
1464-
getAgentId: () => currentAgentId,
1465-
getSessionKey: () => currentSessionKey,
1464+
getAgentId: () => state.currentAgentId,
1465+
getSessionKey: () => state.currentSessionKey,
14661466
openOverlay,
14671467
closeOverlay,
14681468
requestRender: () => tui.requestRender(),
14691469
onAccepted: setSession,
14701470
});
1471+
notifySessionChanged = () => {
1472+
pluginApprovals.sessionChanged();
1473+
taskSuggestions.sessionChanged();
1474+
};
14711475

14721476
const {
14731477
handleChatEvent,

‎test/vitest/vitest.tui-pty.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@ import { resolveRepoRootPath, sharedVitestConfig } from "./vitest.shared.config.
66
const targetableIncludes = [
77
"src/tui/tui-pty-harness-assertion-test-support.test.ts",
88
"src/tui/tui-pty-harness.e2e.test.ts",
9+
"src/tui/tui-session-identity-pty.e2e.test.ts",
910
"src/tui/tui-pty-local.e2e.test.ts",
1011
"src/tui/tui-reset-transition-pty.e2e.test.ts",
1112
"tui/tui-pty-harness-assertion-test-support.test.ts",
1213
"tui/tui-pty-harness.e2e.test.ts",
14+
"tui/tui-session-identity-pty.e2e.test.ts",
1315
"tui/tui-pty-local.e2e.test.ts",
1416
"tui/tui-reset-transition-pty.e2e.test.ts",
1517
];
@@ -25,6 +27,7 @@ function createTuiPtyVitestConfig(env?: Record<string, string | undefined>) {
2527
const includeLocal = configEnv.OPENCLAW_TUI_PTY_INCLUDE_LOCAL === "1";
2628
const include = [
2729
"tui/tui-pty-harness.e2e.test.ts",
30+
"tui/tui-session-identity-pty.e2e.test.ts",
2831
"tui/tui-reset-transition-pty.e2e.test.ts",
2932
...(includeLocal ? ["tui/tui-pty-local.e2e.test.ts"] : []),
3033
];

0 commit comments

Comments
 (0)