Skip to content

Commit d37f9a1

Browse files
authored
fix(beam): omit mixed Claude tool content and preserve snapshot state (#133460)
* fix(beam): keep automatic shares private and complete * test(beam): preserve attribution coverage after fixture cleanup * fix(beam): bound mixed Claude pages with resumable block cursors * refactor(beam): remove stale export and simplify page projection * fix(anthropic): resume mixed Claude rows from macOS nodes
1 parent 672b2a1 commit d37f9a1

19 files changed

Lines changed: 851 additions & 808 deletions

‎apps/macos/Sources/OpenClaw/NodeMode/MacNodeClaudeSessionCatalog.swift‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ enum MacNodeClaudeSessionCatalog {
351351
var position = end
352352
var scanned = 0
353353
var fragments: [Data] = []
354-
var found: [(item: [String: Any], start: UInt64)] = []
354+
var found: [(item: [String: Any], start: UInt64, end: UInt64)] = []
355355
func appendLine(prefix: Data, start: UInt64) {
356356
var line = Data(capacity: prefix.count + fragments.reduce(0) { $0 + $1.count })
357357
line.append(prefix)
@@ -360,7 +360,7 @@ enum MacNodeClaudeSessionCatalog {
360360
}
361361
fragments.removeAll(keepingCapacity: true)
362362
if let item = parseTranscriptLine(line) {
363-
found.append((item, start))
363+
found.append((item, start, start + UInt64(line.count)))
364364
}
365365
}
366366
while position > 0,
@@ -408,7 +408,7 @@ enum MacNodeClaudeSessionCatalog {
408408
throw CatalogError.responseTooLarge
409409
}
410410
let requested = Array(found.prefix(params.limit))
411-
var selected: [(item: [String: Any], start: UInt64)] = []
411+
var selected: [(item: [String: Any], start: UInt64, end: UInt64)] = []
412412
var selectedBytes = 0
413413
for entry in requested {
414414
try Task.checkCancellation()
@@ -422,16 +422,22 @@ enum MacNodeClaudeSessionCatalog {
422422
selectedBytes += data.count
423423
}
424424
let hasEarlierItems = selected.count < found.count || position > 0
425-
var response: [String: Any] = [
425+
let leaseId = target.leaseId ?? self.transcriptReadLeases.store(
426+
rootPath: self.projectsURL(homeURL: homeURL).standardizedFileURL.path,
427+
threadId: params.threadId,
428+
fileURL: fileURL)
429+
var response: [String: Any] = try [
426430
"threadId": params.threadId,
427431
// Shared UI expects newest-first pages and restores chronological order.
428-
"items": selected.map(\.item),
432+
"items": selected.map { entry in
433+
var item = entry.item
434+
// Mixed-block pages can resume even the only row. Preserve its byte
435+
// end and discovery lease across appends and changed page sizes.
436+
item["resumeCursor"] = try encodeTranscriptCursor(offset: Int(entry.end), leaseId: leaseId)
437+
return item
438+
},
429439
]
430440
if hasEarlierItems, let earliest = selected.last?.start, earliest > 0 {
431-
let leaseId = target.leaseId ?? self.transcriptReadLeases.store(
432-
rootPath: self.projectsURL(homeURL: homeURL).standardizedFileURL.path,
433-
threadId: params.threadId,
434-
fileURL: fileURL)
435441
response["nextCursor"] = try encodeTranscriptCursor(
436442
offset: Int(earliest),
437443
leaseId: leaseId)

‎apps/macos/Tests/OpenClawIPCTests/MacNodeClaudeSessionCatalogTests.swift‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -362,7 +362,7 @@ struct MacNodeClaudeSessionCatalogTests {
362362
let fixture = try Fixture()
363363
let project = try fixture.project()
364364
let sessionId = "transcript-session"
365-
let oldUser = String(repeating: "old user ", count: 20000)
365+
let oldUser = String(repeating: "old user 🦞 ", count: 20000)
366366
let transcript = fixture.file(sessionId, in: project)
367367
try fixture.writeIndex([
368368
fixture.indexEntry(
@@ -397,6 +397,18 @@ struct MacNodeClaudeSessionCatalogTests {
397397
#expect(olderItems.map { $0["text"] as? String } == ["old assistant", oldUser])
398398
#expect(older["nextCursor"] == nil)
399399
#expect(enumerations.value() == 1)
400+
401+
for item in latestItems + olderItems {
402+
let resume = try #require(item["resumeCursor"] as? String)
403+
let resumeParams = try #require(try fixture.params([
404+
"threadId": sessionId, "limit": 1, "cursor": resume,
405+
]))
406+
let resumed = try #require(try fixture.read(resumeParams))
407+
let resumedItem = try #require((resumed["items"] as? [[String: Any]])?.first)
408+
#expect(resumedItem["uuid"] as? String == item["uuid"] as? String)
409+
#expect(resumedItem["text"] as? String == item["text"] as? String)
410+
}
411+
#expect(enumerations.value() == 1)
400412
}
401413

402414
@Test func `missing pagination lease falls back to current discovery`() throws {
@@ -517,6 +529,12 @@ struct MacNodeClaudeSessionCatalogTests {
517529
let decoded = try #require(fixture.decode(response))
518530
let items = try #require(decoded["items"] as? [[String: Any]])
519531
#expect(items.first?["truncated"] as? Bool == true)
532+
let resume = try #require(items.first?["resumeCursor"] as? String)
533+
let resumeParams = try #require(try fixture.params([
534+
"threadId": sessionId, "limit": 1, "cursor": resume,
535+
]))
536+
let resumed = try #require(try fixture.read(resumeParams))
537+
#expect((resumed["items"] as? [[String: Any]])?.first?["truncated"] as? Bool == true)
520538
let itemData = try JSONSerialization.data(withJSONObject: #require(items.first))
521539
#expect(itemData.count <= 4 * 1024 * 1024)
522540
}

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,9 @@ extensions/anthropic/session-catalog-listing.ts 1
3636
extensions/anthropic/session-catalog-parsing.ts 7
3737
extensions/anthropic/session-catalog-registration.ts 3
3838
extensions/anthropic/session-catalog-runtime.ts 1
39-
extensions/anthropic/session-catalog.ts 3
4039
extensions/anthropic/stream-wrappers.ts 6
4140
extensions/baseten/models.ts 3
42-
extensions/beam/index.ts 1
4341
extensions/beam/src/mirror.ts 3
44-
extensions/beam/src/session-catalog.ts 6
4542
extensions/beam/src/types.ts 2
4643
extensions/bonjour/src/advertiser.ts 2
4744
extensions/brave/src/brave-web-search-provider.shared.ts 1

‎docs/plugins/beam.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,11 @@ Beam can also act as the sender: an opt-in mirror that continuously publishes th
159159
- `pollSeconds` (default 30, minimum 10): how often the mirror scans local catalogs.
160160
- `activeWindowMinutes` (default 180): sessions with newer activity than this window count as live and stay mirrored; when a session goes idle past the window the running mirror service retries its final `completed` update until the receiver accepts it or the seven-day retention window ends. Retry state is process-local: a Gateway restart clears pending terminal retries, so the remote row remains live until its normal seven-day retention expires.
161161

162-
The mirror applies the same redaction contract as the beam skill before anything leaves the machine: only user and agent message text is uploaded, while reasoning, tool calls, tool results, and raw payloads are replaced with compact counts. It converts newest-first catalog pages into chronological uploads before applying the receiver limits (200 items, 56 KiB), dropping oldest entries first and marking the upload `truncated`. Sessions on paired nodes are not mirrored; the mirror shares only sessions from this Gateway's machine, newest 32 first.
162+
The mirror uploads user and agent message text, replacing structured reasoning, tool calls, tool results, and raw payloads with compact counts. Titles and messages pass through OpenClaw's built-in credential masking and configured `logging.redactPatterns` before clipping, even when log redaction is disabled. The manual beam skill additionally strips setup wrappers, local paths, contact identifiers, and opaque values; automatic mirroring does not apply those additional rules. Enable it only for catalogs whose visible message text you intend to share.
163+
164+
The mirror converts newest-first catalog pages into chronological uploads before applying the receiver limits (200 items, 56 KiB), dropping oldest entries first. It marks the upload `truncated` whenever older pages remain, the source reports truncation, or text or items were clipped. Claude catalog pages count individual text, reasoning, and tool blocks and bound their text size. Sessions on paired nodes are not mirrored; the mirror shares only sessions from this Gateway's machine, newest 32 first. A listed session that leaves the active window receives its final completed update even when its catalog has more pages; an absent session is finalized only after a complete, successful host listing.
165+
166+
When browsing Claude sessions on paired nodes, update those nodes alongside the Gateway. Older node builds without block-resume metadata report an update-required error when a mixed row spans pages.
163167

164168
## Troubleshooting
165169

‎extensions/anthropic/session-catalog-listing.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ export async function readLocalClaudeTranscriptPage(
146146
const item = parseTranscriptLine(line, readBoundedString);
147147
fragments = [];
148148
if (item) {
149+
item.resumeCursor = encodeOffset(position + index + 1 + line.length);
149150
found.push({ item, start: position + index + 1 });
150151
if (found.length > params.limit) {
151152
break;
@@ -163,6 +164,7 @@ export async function readLocalClaudeTranscriptPage(
163164
const line = Buffer.concat([prefix, ...fragments.toReversed()]);
164165
const item = parseTranscriptLine(line, readBoundedString);
165166
if (item) {
167+
item.resumeCursor = encodeOffset(line.length);
166168
found.push({ item, start: 0 });
167169
}
168170
}

‎extensions/anthropic/session-catalog-parsing.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import type {
1313

1414
const DEFAULT_PAGE_LIMIT = 50;
1515
export const MAX_PAGE_LIMIT = 100;
16-
export const DEFAULT_TRANSCRIPT_LIMIT = 20;
16+
const DEFAULT_TRANSCRIPT_LIMIT = 20;
1717
export const MAX_TRANSCRIPT_LIMIT = 50;
1818
export const MAX_HOSTS = 100;
1919
const MAX_SEARCH_LENGTH = 500;

‎extensions/anthropic/session-catalog-transcript.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export type ClaudeTranscriptItem = {
1111
timestamp?: string;
1212
model?: string;
1313
uuid?: string;
14+
resumeCursor?: string;
1415
truncated?: true;
1516
};
1617

‎extensions/anthropic/session-catalog.test.ts‎

Lines changed: 117 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ async function writeBrokenClaudeNpmShim(binDir: string): Promise<string> {
431431
function message(
432432
sessionId: string,
433433
type: "user" | "assistant",
434-
text: string,
434+
text: string | Record<string, unknown>[],
435435
index: number,
436436
): Record<string, unknown> {
437437
return {
@@ -442,7 +442,7 @@ function message(
442442
isSidechain: false,
443443
message: {
444444
role: type,
445-
content: [{ type: "text", text }],
445+
content: typeof text === "string" ? [{ type: "text", text }] : text,
446446
...(type === "assistant" ? { model: "claude-opus-4-8" } : {}),
447447
},
448448
};
@@ -2390,7 +2390,7 @@ describe("Claude session catalog", () => {
23902390
expect(openSpy).toHaveBeenCalledTimes(1);
23912391
});
23922392

2393-
it("reads newest transcript messages first by page while returning each page chronologically", async () => {
2393+
it("reads newest-first transcript pages without overlapping older history", async () => {
23942394
const home = await createHome();
23952395
const sessionId = "transcript-session";
23962396
const oldUser = await writeLongPagedTranscript({ home, sessionId });
@@ -2405,27 +2405,128 @@ describe("Claude session catalog", () => {
24052405
);
24062406
expect(older.items.map((item) => item.text)).toEqual(["old assistant", oldUser]);
24072407
expect(older.nextCursor).toBeUndefined();
2408-
await expect(
2409-
readLocalClaudeTranscriptPage(
2410-
{ threadId: sessionId, limit: 1, cursor: ` ${latest.nextCursor} ` },
2411-
home,
2412-
),
2413-
).rejects.toThrow("transcript cursor is invalid");
2414-
await expect(
2415-
readLocalClaudeTranscriptPage({ threadId: sessionId, cursor: " ", limit: 1 }, home),
2416-
).rejects.toThrow("transcript cursor is invalid");
2417-
await expect(
2418-
readLocalClaudeTranscriptPage({ threadId: sessionId, cursor: null, limit: 1 }, home),
2419-
).rejects.toThrow("transcript cursor is invalid");
2408+
for (const cursor of [` ${latest.nextCursor} `, " ", null]) {
2409+
await expect(
2410+
readLocalClaudeTranscriptPage({ threadId: sessionId, cursor, limit: 1 }, home),
2411+
).rejects.toThrow("transcript cursor is invalid");
2412+
}
24202413
});
24212414

2415+
it.each(["gateway:local", "node:paired"])(
2416+
"pages mixed blocks without overlap on %s",
2417+
async (hostId) => {
2418+
const home = await createHome();
2419+
process.env.CLAUDE_CONFIG_DIR = path.join(home, ".claude");
2420+
const sessionId = "mixed-block-session";
2421+
await writeProject({
2422+
home,
2423+
entries: [{ sessionId, summary: "Mixed blocks", isSidechain: false }],
2424+
transcripts: {
2425+
[sessionId]: (
2426+
[
2427+
[
2428+
"user",
2429+
[
2430+
{ type: "text", text: "Original request" },
2431+
{ type: "text", text: "Oldest continuation 🦞" },
2432+
],
2433+
],
2434+
[
2435+
"user",
2436+
[
2437+
{ type: "tool_result", tool_use_id: "call-1", content: "Private tool output" },
2438+
{ type: "text", text: "Continue the task" },
2439+
],
2440+
],
2441+
[
2442+
"assistant",
2443+
[
2444+
{ type: "text", text: "I will check" },
2445+
{ type: "thinking", thinking: "Private reasoning" },
2446+
{
2447+
type: "tool_use",
2448+
id: "call-2",
2449+
name: "read",
2450+
input: { file: "private.txt", padding: "x".repeat(3 * 1024 * 1024) },
2451+
},
2452+
],
2453+
],
2454+
[
2455+
"assistant",
2456+
[
2457+
{ type: "text", text: "Public continuation" },
2458+
{ type: "thinking", thinking: "x".repeat(2 * 1024 * 1024) },
2459+
],
2460+
],
2461+
] satisfies Array<["user" | "assistant", Record<string, unknown>[]]>
2462+
).map(([role, content], index) => message(sessionId, role, content, index + 1)),
2463+
},
2464+
});
2465+
const runtime = createPluginRuntimeMock();
2466+
runtime.nodes.list = vi.fn(async () => ({
2467+
nodes: [{ nodeId: "paired", connected: true, commands: [CLAUDE_SESSION_READ_COMMAND] }],
2468+
}));
2469+
runtime.nodes.invoke = vi.fn(async ({ params }) => ({
2470+
payloadJSON: JSON.stringify(await readLocalClaudeTranscriptPage(params, home)),
2471+
}));
2472+
const provider = captureCatalogProvider(runtime);
2473+
const request = { hostId, threadId: sessionId, limit: 1 };
2474+
const oversized = await provider.read(request);
2475+
expect(oversized.items.map(({ type, truncated }) => ({ type, truncated }))).toEqual([
2476+
{ type: "other", truncated: true },
2477+
]);
2478+
expect(oversized.items[0]?.raw).toBeUndefined();
2479+
let cursor = oversized.nextCursor;
2480+
const items = [];
2481+
for (const limit of [1, 2, 3, 1]) {
2482+
expect(cursor).toEqual(expect.any(String));
2483+
const page = await provider.read({ ...request, cursor, limit });
2484+
expect(page.items.length).toBeLessThanOrEqual(limit);
2485+
items.push(...page.items);
2486+
cursor = page.nextCursor;
2487+
if (items.length === 1) {
2488+
expect(page.items[0]?.text?.length).toBeLessThanOrEqual(1_000_000);
2489+
expect(page.items[0]?.truncated).toBe(true);
2490+
await expect(
2491+
provider.read({ ...request, cursor: cursor?.replace(/^block:\d+:/u, "block:999:") }),
2492+
).rejects.toThrow("transcript cursor is invalid");
2493+
await fs.appendFile(
2494+
path.join(home, ".claude", "projects", "-workspace", `${sessionId}.jsonl`),
2495+
`${JSON.stringify(message(sessionId, "assistant", "Appended reply", 5))}\n`,
2496+
);
2497+
expect((await provider.read(request)).items[0]?.text).toBe("Appended reply");
2498+
}
2499+
}
2500+
expect(items.map(({ type, text }) => [type, text])).toEqual([
2501+
["toolCall", expect.stringContaining("private.txt")],
2502+
["reasoning", "Private reasoning"],
2503+
["agentMessage", "I will check"],
2504+
["userMessage", "Continue the task"],
2505+
["toolResult", "Private tool output"],
2506+
["userMessage", "Oldest continuation 🦞"],
2507+
["userMessage", "Original request"],
2508+
]);
2509+
expect(new Set(items.map((item) => item.id)).size).toBe(items.length);
2510+
expect(cursor).toBeUndefined();
2511+
},
2512+
);
2513+
24222514
it("rejects malformed provider read cursors before paired-node I/O", async () => {
24232515
const listNodes = vi.fn(async () => ({ nodes: [] }));
24242516
const provider = captureCatalogProvider({
24252517
nodes: { list: listNodes },
24262518
} as unknown as PluginRuntime);
24272519

2428-
for (const cursor of ["", " wrapped ", "x".repeat(257)]) {
2520+
for (const cursor of [
2521+
"",
2522+
" wrapped ",
2523+
"x".repeat(257),
2524+
"block:0",
2525+
"block:-1:x",
2526+
"block:1.5:x",
2527+
"block:9007199254740992:x",
2528+
"block:1: ",
2529+
]) {
24292530
await expect(
24302531
provider.read({
24312532
hostId: "node:node-a",

0 commit comments

Comments
 (0)