Skip to content

Commit bf0d2d7

Browse files
authored
fix(session): clean up rollover resources
1 parent b0c55eb commit bf0d2d7

6 files changed

Lines changed: 317 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Docs: https://docs.openclaw.ai
1616

1717
- Browser/Playwright: ignore benign already-handled route races during guarded navigation so browser-page tasks no longer fail when Playwright tears down a route mid-flight. (#68708) Thanks @Steady-ai.
1818
- Browser/Linux: detect Chromium-based installs under `/opt/google`, `/opt/brave.com`, `/usr/lib/chromium`, and `/usr/lib/chromium-browser` before asking users to set `browser.executablePath`. (#48563) Thanks @lupuletic.
19+
- Sessions/browser: close tracked browser tabs when idle, daily, `/new`, or `/reset` session rollover archives the previous transcript, preventing tabs from leaking past the old session. Thanks @jakozloski.
20+
- Sessions/forking: fall back to transcript-estimated parent token counts when cached totals are stale or missing, so oversized thread forks start fresh instead of cloning the full parent transcript. Thanks @jalehman.
1921
- MCP/CLI: retire bundled MCP runtimes at the end of one-shot `openclaw agent` and `openclaw infer model run` gateway/local executions, so repeated scripted runs do not accumulate stdio MCP child processes. Fixes #71457.
2022
- OpenAI/Codex image generation: canonicalize legacy `openai-codex.baseUrl` values such as `https://chatgpt.com/backend-api` to the Codex Responses backend before calling `gpt-image-2`, matching the chat transport. Fixes #71460.
2123
- Control UI: make `/usage` use the fresh context snapshot for context percentage, and include cache-write tokens in the Usage overview cache-hit denominator. Fixes #47885. Thanks @imwyvern and @Ante042.
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import type { SessionEntry } from "../../config/sessions/types.js";
6+
import { resolveParentForkTokenCountRuntime } from "./session-fork.runtime.js";
7+
8+
const roots: string[] = [];
9+
10+
async function makeRoot(prefix: string): Promise<string> {
11+
const root = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
12+
roots.push(root);
13+
return root;
14+
}
15+
16+
afterEach(async () => {
17+
await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
18+
});
19+
20+
describe("resolveParentForkTokenCountRuntime", () => {
21+
it("falls back to transcript-estimated tokens when cached totals are stale", async () => {
22+
const root = await makeRoot("openclaw-parent-fork-token-estimate-");
23+
const sessionsDir = path.join(root, "sessions");
24+
await fs.mkdir(sessionsDir);
25+
26+
const sessionId = "parent-overflow-transcript";
27+
const sessionFile = path.join(sessionsDir, "parent.jsonl");
28+
const lines = [
29+
JSON.stringify({
30+
type: "session",
31+
version: 3,
32+
id: sessionId,
33+
timestamp: new Date().toISOString(),
34+
cwd: process.cwd(),
35+
}),
36+
];
37+
for (let index = 0; index < 40; index += 1) {
38+
const body = `turn-${index} ${"x".repeat(12_000)}`;
39+
lines.push(
40+
JSON.stringify({
41+
type: "message",
42+
id: `u${index}`,
43+
parentId: index === 0 ? null : `a${index - 1}`,
44+
timestamp: new Date().toISOString(),
45+
message: { role: "user", content: body },
46+
}),
47+
JSON.stringify({
48+
type: "message",
49+
id: `a${index}`,
50+
parentId: `u${index}`,
51+
timestamp: new Date().toISOString(),
52+
message: { role: "assistant", content: body },
53+
}),
54+
);
55+
}
56+
await fs.writeFile(sessionFile, `${lines.join("\n")}\n`, "utf-8");
57+
58+
const entry: SessionEntry = {
59+
sessionId,
60+
sessionFile,
61+
updatedAt: Date.now(),
62+
totalTokens: 1,
63+
totalTokensFresh: false,
64+
};
65+
66+
const tokens = resolveParentForkTokenCountRuntime({
67+
parentEntry: entry,
68+
storePath: path.join(root, "sessions.json"),
69+
});
70+
71+
expect(tokens).toBeGreaterThan(100_000);
72+
});
73+
});

‎src/auto-reply/reply/session-fork.runtime.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,49 @@
11
import crypto from "node:crypto";
22
import fs from "node:fs";
33
import path from "node:path";
4+
import type { AgentMessage } from "@mariozechner/pi-agent-core";
45
import { CURRENT_SESSION_VERSION, SessionManager } from "@mariozechner/pi-coding-agent";
6+
import { estimateMessagesTokens } from "../../agents/compaction.js";
57
import { resolveSessionFilePath } from "../../config/sessions/paths.js";
6-
import type { SessionEntry } from "../../config/sessions/types.js";
8+
import { resolveFreshSessionTotalTokens, type SessionEntry } from "../../config/sessions/types.js";
9+
import { readSessionMessages } from "../../gateway/session-utils.fs.js";
10+
11+
function resolvePositiveTokenCount(value: number | undefined): number | undefined {
12+
return typeof value === "number" && Number.isFinite(value) && value > 0
13+
? Math.floor(value)
14+
: undefined;
15+
}
16+
17+
export function resolveParentForkTokenCountRuntime(params: {
18+
parentEntry: SessionEntry;
19+
storePath: string;
20+
}): number | undefined {
21+
const freshPersistedTokens = resolveFreshSessionTotalTokens(params.parentEntry);
22+
if (typeof freshPersistedTokens === "number") {
23+
return freshPersistedTokens;
24+
}
25+
26+
try {
27+
const transcriptMessages = readSessionMessages(
28+
params.parentEntry.sessionId,
29+
params.storePath,
30+
params.parentEntry.sessionFile,
31+
) as AgentMessage[];
32+
if (transcriptMessages.length > 0) {
33+
const estimatedTokens = estimateMessagesTokens(transcriptMessages);
34+
const transcriptTokens = resolvePositiveTokenCount(
35+
Number.isFinite(estimatedTokens) ? Math.ceil(estimatedTokens) : undefined,
36+
);
37+
if (typeof transcriptTokens === "number") {
38+
return transcriptTokens;
39+
}
40+
}
41+
} catch {
42+
// Fall back to cached totals when the parent transcript cannot be read.
43+
}
44+
45+
return resolvePositiveTokenCount(params.parentEntry.totalTokens);
46+
}
747

848
export function forkSessionFromParentRuntime(params: {
949
parentEntry: SessionEntry;

‎src/auto-reply/reply/session-fork.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,11 @@ export async function forkSessionFromParent(params: {
3030
const runtime = await loadSessionForkRuntime();
3131
return runtime.forkSessionFromParentRuntime(params);
3232
}
33+
34+
export async function resolveParentForkTokenCount(params: {
35+
parentEntry: SessionEntry;
36+
storePath: string;
37+
}): Promise<number | undefined> {
38+
const runtime = await loadSessionForkRuntime();
39+
return runtime.resolveParentForkTokenCountRuntime(params);
40+
}

‎src/auto-reply/reply/session.test.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,15 @@ import { initSessionState } from "./session.js";
2828

2929
const sessionForkMocks = vi.hoisted(() => ({
3030
forkSessionFromParent: vi.fn(),
31+
resolveParentForkTokenCount: vi.fn(),
3132
nextSessionId: 0,
3233
}));
3334
const channelSummaryMocks = vi.hoisted(() => ({
3435
buildChannelSummary: vi.fn(async () => [] as string[]),
3536
}));
37+
const browserMaintenanceMocks = vi.hoisted(() => ({
38+
closeTrackedBrowserTabsForSessions: vi.fn(async () => 0),
39+
}));
3640

3741
type ForkSessionParamsForTest = {
3842
parentEntry: SessionEntry;
@@ -42,6 +46,8 @@ type ForkSessionParamsForTest = {
4246
vi.mock("./session-fork.js", () => ({
4347
forkSessionFromParent: (...args: [ForkSessionParamsForTest]) =>
4448
sessionForkMocks.forkSessionFromParent(...args),
49+
resolveParentForkTokenCount: (...args: [{ parentEntry: SessionEntry; storePath: string }]) =>
50+
sessionForkMocks.resolveParentForkTokenCount(...args),
4551
resolveParentForkMaxTokens: (cfg: { session?: { parentForkMaxTokens?: unknown } }) => {
4652
const configured = cfg.session?.parentForkMaxTokens;
4753
return typeof configured === "number" && Number.isFinite(configured) && configured >= 0
@@ -50,6 +56,10 @@ vi.mock("./session-fork.js", () => ({
5056
},
5157
}));
5258

59+
vi.mock("../../plugin-sdk/browser-maintenance.js", () => ({
60+
closeTrackedBrowserTabsForSessions: browserMaintenanceMocks.closeTrackedBrowserTabsForSessions,
61+
}));
62+
5363
vi.mock("../../plugins/hook-runner-global.js", () => ({
5464
getGlobalHookRunner: () => null,
5565
}));
@@ -248,8 +258,15 @@ function registerCurrentConversationBindingAdapterForTest(params: {
248258

249259
beforeEach(() => {
250260
channelSummaryMocks.buildChannelSummary.mockReset().mockResolvedValue([]);
261+
browserMaintenanceMocks.closeTrackedBrowserTabsForSessions.mockReset().mockResolvedValue(0);
251262
sessionBindingTesting.resetSessionBindingAdaptersForTests();
252263
sessionForkMocks.nextSessionId = 0;
264+
sessionForkMocks.resolveParentForkTokenCount.mockReset().mockImplementation(({ parentEntry }) => {
265+
const tokens = parentEntry.totalTokens;
266+
return typeof tokens === "number" && Number.isFinite(tokens) && tokens > 0
267+
? Math.floor(tokens)
268+
: undefined;
269+
});
253270
sessionForkMocks.forkSessionFromParent
254271
.mockReset()
255272
.mockImplementation(async ({ parentEntry, sessionsDir }: ForkSessionParamsForTest) => {
@@ -517,6 +534,66 @@ describe("initSessionState thread forking", () => {
517534
expect(result.sessionEntry.sessionFile).not.toBe(parentSessionFile);
518535
});
519536

537+
it("skips fork when resolved parent token estimate exceeds threshold", async () => {
538+
const root = await makeCaseDir("openclaw-thread-session-overflow-estimated-");
539+
const sessionsDir = path.join(root, "sessions");
540+
await fs.mkdir(sessionsDir);
541+
542+
const parentSessionId = "parent-overflow-estimated";
543+
const parentSessionFile = path.join(sessionsDir, "parent.jsonl");
544+
await fs.writeFile(
545+
parentSessionFile,
546+
`${JSON.stringify({
547+
type: "session",
548+
version: 3,
549+
id: parentSessionId,
550+
timestamp: new Date().toISOString(),
551+
cwd: process.cwd(),
552+
})}\n`,
553+
"utf-8",
554+
);
555+
556+
const storePath = path.join(root, "sessions.json");
557+
const parentSessionKey = "agent:main:slack:channel:c1";
558+
await writeSessionStoreFast(storePath, {
559+
[parentSessionKey]: {
560+
sessionId: parentSessionId,
561+
sessionFile: parentSessionFile,
562+
updatedAt: Date.now(),
563+
totalTokens: 1,
564+
totalTokensFresh: false,
565+
},
566+
});
567+
sessionForkMocks.resolveParentForkTokenCount.mockReturnValueOnce(170_000);
568+
569+
const cfg = {
570+
session: { store: storePath },
571+
} as OpenClawConfig;
572+
573+
const threadSessionKey = "agent:main:slack:channel:c1:thread:estimated";
574+
const result = await initSessionState({
575+
ctx: {
576+
Body: "Thread reply",
577+
SessionKey: threadSessionKey,
578+
ParentSessionKey: parentSessionKey,
579+
},
580+
cfg,
581+
commandAuthorized: true,
582+
});
583+
584+
expect(sessionForkMocks.resolveParentForkTokenCount).toHaveBeenCalledWith({
585+
parentEntry: expect.objectContaining({
586+
sessionId: parentSessionId,
587+
totalTokensFresh: false,
588+
}),
589+
storePath,
590+
});
591+
expect(result.sessionEntry.forkedFromParent).toBe(true);
592+
expect(result.sessionEntry.sessionId).not.toBe(parentSessionId);
593+
expect(result.sessionEntry.sessionFile).not.toBe(parentSessionFile);
594+
expect(sessionForkMocks.forkSessionFromParent).not.toHaveBeenCalled();
595+
});
596+
520597
it("respects session.parentForkMaxTokens override", async () => {
521598
const root = await makeCaseDir("openclaw-thread-session-overflow-override-");
522599
const sessionsDir = path.join(root, "sessions");
@@ -1616,6 +1693,95 @@ describe("initSessionState reset policy", () => {
16161693
});
16171694
});
16181695

1696+
describe("initSessionState browser tab cleanup", () => {
1697+
it("closes tracked browser tabs when idle session expires", async () => {
1698+
vi.setSystemTime(new Date(2026, 0, 18, 5, 30, 0));
1699+
const storePath = await createStorePath("openclaw-tab-cleanup-idle-");
1700+
const sessionKey = "agent:main:whatsapp:dm:tab-idle";
1701+
const existingSessionId = "tab-idle-session-id";
1702+
1703+
await writeSessionStoreFast(storePath, {
1704+
[sessionKey]: {
1705+
sessionId: existingSessionId,
1706+
updatedAt: new Date(2026, 0, 18, 4, 45, 0).getTime(),
1707+
},
1708+
});
1709+
1710+
const cfg = {
1711+
session: {
1712+
store: storePath,
1713+
reset: { mode: "daily", atHour: 4, idleMinutes: 30 },
1714+
},
1715+
} as OpenClawConfig;
1716+
const result = await initSessionState({
1717+
ctx: { Body: "hello", SessionKey: sessionKey },
1718+
cfg,
1719+
commandAuthorized: true,
1720+
});
1721+
1722+
expect(result.isNewSession).toBe(true);
1723+
expect(browserMaintenanceMocks.closeTrackedBrowserTabsForSessions).toHaveBeenCalledWith(
1724+
expect.objectContaining({
1725+
sessionKeys: expect.arrayContaining([existingSessionId, sessionKey]),
1726+
}),
1727+
);
1728+
});
1729+
1730+
it("closes tracked browser tabs on explicit /new reset", async () => {
1731+
const storePath = await createStorePath("openclaw-tab-cleanup-reset-");
1732+
const sessionKey = "agent:main:telegram:dm:tab-reset";
1733+
const existingSessionId = "tab-reset-session-id";
1734+
1735+
await writeSessionStoreFast(storePath, {
1736+
[sessionKey]: {
1737+
sessionId: existingSessionId,
1738+
updatedAt: Date.now(),
1739+
},
1740+
});
1741+
1742+
const cfg = {
1743+
session: { store: storePath, idleMinutes: 999 },
1744+
} as OpenClawConfig;
1745+
const result = await initSessionState({
1746+
ctx: {
1747+
Body: "/new",
1748+
RawBody: "/new",
1749+
CommandBody: "/new",
1750+
SessionKey: sessionKey,
1751+
},
1752+
cfg,
1753+
commandAuthorized: true,
1754+
});
1755+
1756+
expect(result.isNewSession).toBe(true);
1757+
expect(browserMaintenanceMocks.closeTrackedBrowserTabsForSessions).toHaveBeenCalledWith(
1758+
expect.objectContaining({
1759+
sessionKeys: expect.arrayContaining([existingSessionId, sessionKey]),
1760+
}),
1761+
);
1762+
});
1763+
1764+
it("does not close browser tabs for a fresh session without previous state", async () => {
1765+
const storePath = await createStorePath("openclaw-tab-cleanup-fresh-");
1766+
const sessionKey = "agent:main:telegram:dm:tab-fresh";
1767+
1768+
const cfg = {
1769+
session: { store: storePath, idleMinutes: 999 },
1770+
} as OpenClawConfig;
1771+
const result = await initSessionState({
1772+
ctx: {
1773+
Body: "hello",
1774+
SessionKey: sessionKey,
1775+
},
1776+
cfg,
1777+
commandAuthorized: true,
1778+
});
1779+
1780+
expect(result.isNewSession).toBe(true);
1781+
expect(browserMaintenanceMocks.closeTrackedBrowserTabsForSessions).not.toHaveBeenCalled();
1782+
});
1783+
});
1784+
16191785
describe("initSessionState channel reset overrides", () => {
16201786
it("uses channel-specific reset policy when configured", async () => {
16211787
const root = await makeCaseDir("openclaw-channel-idle-");

0 commit comments

Comments
 (0)