Skip to content

Commit 2dd6bdf

Browse files
committed
fix(cli): handle rewritten sessions tail trajectories
1 parent 51402ba commit 2dd6bdf

3 files changed

Lines changed: 220 additions & 35 deletions

File tree

‎docs/cli/sessions.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ Scope selection:
4747
- `--store <path>`: explicit store path (cannot be combined with `--agent` or `--all-agents`)
4848
- `--limit <n|all>`: max rows to output (default `100`; `all` restores full output)
4949

50+
Tail human-readable trajectory progress for stored sessions:
51+
52+
```bash
53+
openclaw sessions tail
54+
openclaw sessions tail --follow
55+
openclaw sessions tail --session-key "agent:main:telegram:direct:123" --tail 25
56+
openclaw sessions --agent work tail --follow
57+
openclaw sessions --all-agents tail --follow
58+
```
59+
60+
`openclaw sessions tail` renders recent trajectory JSONL events as compact progress lines. Without `--session-key`, it tails running sessions first, then the latest stored session. `--tail <count>` controls how many existing events print before follow mode; the default is `80`, and `0` starts at the current end. `--follow` keeps watching the selected trajectory files, including relocated files referenced by `<session>.trajectory-path.json`.
61+
62+
The progress view is intentionally conservative: prompt text, tool arguments, and tool result bodies are not printed. Tool calls show the tool name with `{...redacted...}`; tool results show status such as `ok`, `error`, or `done`; model completion lines show provider/model and terminal status.
63+
5064
Export a trajectory bundle for a stored session:
5165

5266
```bash

‎src/commands/sessions-tail.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,47 @@ describe("sessionsTailCommand", () => {
237237
expect(output).toContain("bash ok");
238238
});
239239

240+
it("continues following when a bounded trajectory window is rewritten", async () => {
241+
const runtime = makeRuntime();
242+
writeJsonl(trajectoryPath, [
243+
makeEvent({
244+
sourceSeq: 1,
245+
type: "session.started",
246+
ts: "2026-05-18T12:04:17.000Z",
247+
}),
248+
]);
249+
const rewrittenEvent = makeEvent({
250+
sourceSeq: 2,
251+
type: "tool.result",
252+
ts: "2026-05-18T12:04:21.000Z",
253+
data: { name: "python", success: true },
254+
});
255+
let rewritten = false;
256+
vi.mocked(runtime.log).mockImplementation((message) => {
257+
if (!rewritten && String(message).includes("session.started")) {
258+
rewritten = true;
259+
const nextPath = path.join(tmpDir, "session-one.next.trajectory.jsonl");
260+
writeJsonl(nextPath, [rewrittenEvent]);
261+
fs.renameSync(nextPath, trajectoryPath);
262+
}
263+
});
264+
265+
const run = sessionsTailCommand(
266+
{ store: storePath, sessionKey, tail: "1", follow: true },
267+
runtime,
268+
);
269+
try {
270+
await waitForRuntimeOutput(runtime, "python ok");
271+
} finally {
272+
process.emit("SIGTERM", "SIGTERM");
273+
await run;
274+
}
275+
276+
const output = runtimeOutput(runtime);
277+
expect(output).toContain("tool.result");
278+
expect(output).toContain("python ok");
279+
});
280+
240281
it("resolves the target store from a fully qualified non-default agent session key", async () => {
241282
const runtime = makeRuntime();
242283
const opsSessionKey = "agent:ops:telegram:direct:owner";

‎src/commands/sessions-tail.ts‎

Lines changed: 165 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,31 @@ type TailSelection = {
3131
};
3232

3333
type FollowState = {
34+
cursor: TrajectoryCursor | null;
35+
fileState: FollowFileState | null;
3436
offset: number;
3537
pending: string;
3638
selection: TailSelection;
3739
};
3840

3941
type TrajectorySnapshot = {
40-
lines: string[];
42+
events: TrajectoryEvent[];
43+
fileState: FollowFileState | null;
4144
offset: number;
4245
};
4346

47+
type FollowFileState = {
48+
dev: number;
49+
ino: number;
50+
mtimeMs: number;
51+
size: number;
52+
};
53+
54+
type TrajectoryCursor = {
55+
seq: number | null;
56+
tsMs: number;
57+
};
58+
4459
const DEFAULT_TAIL_COUNT = 80;
4560
const SESSION_KEY_PAD = 30;
4661
const EVENT_TYPE_PAD = 16;
@@ -92,6 +107,69 @@ function parseTrajectoryEventLine(line: string): TrajectoryEvent | null {
92107
}
93108
}
94109

110+
function parseTrajectoryEventLines(lines: string[]): TrajectoryEvent[] {
111+
return lines.flatMap((line) => {
112+
const event = parseTrajectoryEventLine(line);
113+
return event ? [event] : [];
114+
});
115+
}
116+
117+
function eventSequence(event: TrajectoryEvent): number | null {
118+
const seq = event.sourceSeq ?? event.seq;
119+
return Number.isFinite(seq) ? seq : null;
120+
}
121+
122+
function eventTimestampMs(event: TrajectoryEvent): number {
123+
const parsed = Date.parse(event.ts);
124+
return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;
125+
}
126+
127+
function eventCursor(event: TrajectoryEvent): TrajectoryCursor {
128+
return {
129+
seq: eventSequence(event),
130+
tsMs: eventTimestampMs(event),
131+
};
132+
}
133+
134+
function compareCursors(left: TrajectoryCursor, right: TrajectoryCursor): number {
135+
if (left.seq !== null && right.seq !== null && left.seq !== right.seq) {
136+
return left.seq - right.seq;
137+
}
138+
const byTimestamp = left.tsMs - right.tsMs;
139+
if (byTimestamp !== 0) {
140+
return byTimestamp;
141+
}
142+
if (left.seq !== null && right.seq !== null) {
143+
return left.seq - right.seq;
144+
}
145+
return 0;
146+
}
147+
148+
function maxCursorValue(
149+
current: TrajectoryCursor | null,
150+
candidate: TrajectoryCursor,
151+
): TrajectoryCursor {
152+
return !current || compareCursors(candidate, current) > 0 ? candidate : current;
153+
}
154+
155+
function maxCursor(current: TrajectoryCursor | null, event: TrajectoryEvent): TrajectoryCursor {
156+
return maxCursorValue(current, eventCursor(event));
157+
}
158+
159+
function maxCursorFromEvents(events: TrajectoryEvent[]): TrajectoryCursor | null {
160+
return events.reduce<TrajectoryCursor | null>((cursor, event) => maxCursor(cursor, event), null);
161+
}
162+
163+
function eventsAfterCursor(
164+
events: TrajectoryEvent[],
165+
cursor: TrajectoryCursor | null,
166+
): TrajectoryEvent[] {
167+
if (!cursor) {
168+
return events;
169+
}
170+
return events.filter((event) => compareCursors(eventCursor(event), cursor) > 0);
171+
}
172+
95173
function formatTimestamp(ts: string): string {
96174
const date = new Date(ts);
97175
if (Number.isNaN(date.getTime())) {
@@ -182,25 +260,51 @@ function formatProgressLine(event: TrajectoryEvent): string {
182260

183261
function readTrajectorySnapshot(filePath: string): TrajectorySnapshot {
184262
try {
263+
const stat = fs.statSync(filePath);
185264
const text = fs.readFileSync(filePath, "utf8");
186265
return {
187-
lines: text.split(/\r?\n/u).filter((line) => line.trim().length > 0),
266+
events: parseTrajectoryEventLines(text.split(/\r?\n/u)),
267+
fileState: fileStateFromStat(stat),
188268
offset: Buffer.byteLength(text, "utf8"),
189269
};
190270
} catch (error) {
191271
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
192-
return { lines: [], offset: 0 };
272+
return { events: [], fileState: null, offset: 0 };
193273
}
194274
throw error;
195275
}
196276
}
197277

198-
function renderLines(lines: string[], runtime: RuntimeEnv): void {
199-
for (const line of lines) {
200-
const event = parseTrajectoryEventLine(line);
201-
if (event) {
202-
runtime.log(formatProgressLine(event));
278+
function renderEvents(events: TrajectoryEvent[], runtime: RuntimeEnv): TrajectoryCursor | null {
279+
let cursor: TrajectoryCursor | null = null;
280+
for (const event of events) {
281+
runtime.log(formatProgressLine(event));
282+
cursor = maxCursor(cursor, event);
283+
}
284+
return cursor;
285+
}
286+
287+
function fileStateFromStat(stat: fs.Stats): FollowFileState {
288+
return {
289+
dev: stat.dev,
290+
ino: stat.ino,
291+
mtimeMs: stat.mtimeMs,
292+
size: stat.size,
293+
};
294+
}
295+
296+
function sameFileIdentity(left: FollowFileState | null, right: FollowFileState): boolean {
297+
return Boolean(left && left.dev === right.dev && left.ino === right.ino);
298+
}
299+
300+
function readFollowFileState(filePath: string): FollowFileState | null {
301+
try {
302+
return fileStateFromStat(fs.statSync(filePath));
303+
} catch (error) {
304+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
305+
return null;
203306
}
307+
throw error;
204308
}
205309
}
206310

@@ -267,53 +371,80 @@ function statFileSize(filePath: string): number {
267371
}
268372
}
269373

270-
function readNewFollowLines(state: FollowState): string[] {
271-
let size: number;
272-
try {
273-
size = fs.statSync(state.selection.trajectoryPath).size;
274-
} catch (error) {
275-
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
276-
return [];
277-
}
278-
throw error;
279-
}
280-
if (size < state.offset) {
374+
function readNewFollowEvents(state: FollowState): TrajectoryEvent[] {
375+
const fileState = readFollowFileState(state.selection.trajectoryPath);
376+
if (!fileState) {
377+
state.fileState = null;
281378
state.offset = 0;
282379
state.pending = "";
380+
return [];
381+
}
382+
383+
const replaced = !sameFileIdentity(state.fileState, fileState);
384+
const truncated = fileState.size < state.offset;
385+
const possiblyRewrittenSameSize =
386+
fileState.size === state.offset && state.fileState?.mtimeMs !== fileState.mtimeMs;
387+
388+
if (replaced || truncated || possiblyRewrittenSameSize) {
389+
const snapshot = readTrajectorySnapshot(state.selection.trajectoryPath);
390+
state.fileState = snapshot.fileState;
391+
state.offset = snapshot.offset;
392+
state.pending = "";
393+
return eventsAfterCursor(snapshot.events, state.cursor);
283394
}
284-
if (size === state.offset) {
395+
396+
if (fileState.size === state.offset) {
397+
state.fileState = fileState;
285398
return [];
286399
}
400+
287401
const fd = fs.openSync(state.selection.trajectoryPath, "r");
288402
try {
289-
const buffer = Buffer.alloc(size - state.offset);
403+
const buffer = Buffer.alloc(fileState.size - state.offset);
290404
fs.readSync(fd, buffer, 0, buffer.length, state.offset);
291-
state.offset = size;
405+
state.offset = fileState.size;
406+
state.fileState = fileState;
292407
const combined = `${state.pending}${buffer.toString("utf8")}`;
293408
const lines = combined.split(/\r?\n/u);
294409
state.pending = lines.pop() ?? "";
295-
return lines.filter((line) => line.trim().length > 0);
410+
return parseTrajectoryEventLines(lines);
296411
} finally {
297412
fs.closeSync(fd);
298413
}
299414
}
300415

416+
function renderFollowEvents(
417+
events: TrajectoryEvent[],
418+
state: FollowState,
419+
runtime: RuntimeEnv,
420+
): void {
421+
const cursor = renderEvents(events, runtime);
422+
if (cursor) {
423+
state.cursor = maxCursorValue(state.cursor, cursor);
424+
}
425+
}
426+
301427
async function followSelections(
302428
selections: TailSelection[],
303429
runtime: RuntimeEnv,
304-
initialOffsets: Map<string, number>,
430+
initialSnapshots: Map<string, TrajectorySnapshot>,
305431
): Promise<void> {
306-
const states = selections.map((selection) => ({
307-
offset: initialOffsets.get(selection.trajectoryPath) ?? statFileSize(selection.trajectoryPath),
308-
pending: "",
309-
selection,
310-
}));
432+
const states = selections.map((selection): FollowState => {
433+
const snapshot = initialSnapshots.get(selection.trajectoryPath);
434+
return {
435+
cursor: snapshot ? maxCursorFromEvents(snapshot.events) : null,
436+
fileState: snapshot?.fileState ?? readFollowFileState(selection.trajectoryPath),
437+
offset: snapshot?.offset ?? statFileSize(selection.trajectoryPath),
438+
pending: "",
439+
selection,
440+
};
441+
});
311442

312443
await new Promise<void>((resolve) => {
313444
const interval = setInterval(() => {
314445
for (const state of states) {
315446
try {
316-
renderLines(readNewFollowLines(state), runtime);
447+
renderFollowEvents(readNewFollowEvents(state), state, runtime);
317448
} catch (error) {
318449
runtime.error(
319450
`Failed to read trajectory progress for ${state.selection.key}: ${formatErrorMessage(
@@ -388,15 +519,14 @@ export async function sessionsTailCommand(
388519
return;
389520
}
390521

391-
const followOffsets = new Map<string, number>();
522+
const followSnapshots = new Map<string, TrajectorySnapshot>();
392523
for (const selection of selected) {
393524
const snapshot = readTrajectorySnapshot(selection.trajectoryPath);
394-
followOffsets.set(selection.trajectoryPath, snapshot.offset);
395-
const lines = snapshot.lines;
396-
renderLines(tailCount > 0 ? lines.slice(-tailCount) : [], runtime);
525+
followSnapshots.set(selection.trajectoryPath, snapshot);
526+
renderEvents(tailCount > 0 ? snapshot.events.slice(-tailCount) : [], runtime);
397527
}
398528

399529
if (opts.follow) {
400-
await followSelections(selected, runtime, followOffsets);
530+
await followSelections(selected, runtime, followSnapshots);
401531
}
402532
}

0 commit comments

Comments
 (0)