-
-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathsessionScanner.ts
More file actions
244 lines (220 loc) · 9.05 KB
/
sessionScanner.ts
File metadata and controls
244 lines (220 loc) · 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { RawJSONLines, RawJSONLinesSchema } from "../types";
import { basename, join } from "node:path";
import { readFile } from "node:fs/promises";
import { logger } from "@/ui/logger";
import { getProjectPath } from "./path";
import { BaseSessionScanner, SessionFileScanEntry, SessionFileScanResult, SessionFileScanStats } from "@/modules/common/session/BaseSessionScanner";
/**
* Known internal Claude Code event types that should be silently skipped.
* These are written to session JSONL files by Claude Code but are not
* actual conversation messages - they're internal state/tracking events.
*/
const INTERNAL_CLAUDE_EVENT_TYPES = new Set([
'file-history-snapshot',
'change',
'queue-operation',
]);
export async function createSessionScanner(opts: {
sessionId: string | null;
workingDirectory: string;
onMessage: (message: RawJSONLines) => void;
onTitleChange?: (title: string) => void;
}) {
const scanner = new ClaudeSessionScanner({
sessionId: opts.sessionId,
workingDirectory: opts.workingDirectory,
onMessage: opts.onMessage,
onTitleChange: opts.onTitleChange
});
await scanner.start();
return {
cleanup: async () => {
await scanner.cleanup();
},
onNewSession: (sessionId: string) => {
scanner.onNewSession(sessionId);
}
};
}
export type SessionScanner = ReturnType<typeof createSessionScanner>;
class ClaudeSessionScanner extends BaseSessionScanner<RawJSONLines> {
private readonly projectDir: string;
private readonly onMessage: (message: RawJSONLines) => void;
private readonly onTitleChange?: (title: string) => void;
private readonly finishedSessions = new Set<string>();
private readonly pendingSessions = new Set<string>();
private currentSessionId: string | null;
private readonly scannedSessions = new Set<string>();
constructor(opts: { sessionId: string | null; workingDirectory: string; onMessage: (message: RawJSONLines) => void; onTitleChange?: (title: string) => void }) {
super({ intervalMs: 3000 });
this.projectDir = getProjectPath(opts.workingDirectory);
this.onMessage = opts.onMessage;
this.onTitleChange = opts.onTitleChange;
this.currentSessionId = opts.sessionId;
}
public onNewSession(sessionId: string): void {
if (this.currentSessionId === sessionId) {
logger.debug(`[SESSION_SCANNER] New session: ${sessionId} is the same as the current session, skipping`);
return;
}
if (this.finishedSessions.has(sessionId)) {
logger.debug(`[SESSION_SCANNER] New session: ${sessionId} is already finished, skipping`);
return;
}
if (this.pendingSessions.has(sessionId)) {
logger.debug(`[SESSION_SCANNER] New session: ${sessionId} is already pending, skipping`);
return;
}
if (this.currentSessionId) {
this.pendingSessions.add(this.currentSessionId);
}
logger.debug(`[SESSION_SCANNER] New session: ${sessionId}`);
this.currentSessionId = sessionId;
this.invalidate();
}
protected async initialize(): Promise<void> {
if (!this.currentSessionId) {
return;
}
const sessionFile = this.sessionFilePath(this.currentSessionId);
const { events, titleChanges, totalLines } = await readSessionLog(sessionFile, 0);
if (titleChanges.length > 0) {
this.onTitleChange?.(titleChanges[titleChanges.length - 1]);
}
logger.debug(`[SESSION_SCANNER] Marking ${events.length} existing messages as processed from session ${this.currentSessionId}`);
const keys = events.map((entry) => messageKey(entry.event));
this.seedProcessedKeys(keys);
this.setCursor(sessionFile, totalLines);
}
protected async beforeScan(): Promise<void> {
this.scannedSessions.clear();
}
protected async findSessionFiles(): Promise<string[]> {
const files = new Set<string>();
for (const sessionId of this.pendingSessions) {
files.add(this.sessionFilePath(sessionId));
}
if (this.currentSessionId && !this.pendingSessions.has(this.currentSessionId)) {
files.add(this.sessionFilePath(this.currentSessionId));
}
for (const watched of this.getWatchedFiles()) {
files.add(watched);
}
return [...files];
}
protected async parseSessionFile(filePath: string, cursor: number): Promise<SessionFileScanResult<RawJSONLines>> {
const sessionId = sessionIdFromPath(filePath);
if (sessionId) {
this.scannedSessions.add(sessionId);
}
const { events, titleChanges, totalLines } = await readSessionLog(filePath, cursor);
for (const title of titleChanges) {
logger.debug(`[SESSION_SCANNER] Title change: ${title}`);
this.onTitleChange?.(title);
}
return {
events,
nextCursor: totalLines
};
}
protected generateEventKey(event: RawJSONLines): string {
return messageKey(event);
}
protected async handleFileScan(stats: SessionFileScanStats<RawJSONLines>): Promise<void> {
for (const message of stats.events) {
const id = message.type === 'summary' ? message.leafUuid : message.uuid;
logger.debug(`[SESSION_SCANNER] Sending new message: type=${message.type}, uuid=${id}`);
this.onMessage(message);
}
if (stats.parsedCount > 0) {
const sessionId = sessionIdFromPath(stats.filePath) ?? 'unknown';
logger.debug(`[SESSION_SCANNER] Session ${sessionId}: found=${stats.parsedCount}, skipped=${stats.skippedCount}, sent=${stats.newCount}`);
}
}
protected async afterScan(): Promise<void> {
for (const sessionId of this.scannedSessions) {
if (this.pendingSessions.has(sessionId)) {
this.pendingSessions.delete(sessionId);
this.finishedSessions.add(sessionId);
}
}
}
private sessionFilePath(sessionId: string): string {
return join(this.projectDir, `${sessionId}.jsonl`);
}
}
//
// Helpers
//
function messageKey(message: RawJSONLines): string {
if (message.type === 'user') {
return message.uuid;
} else if (message.type === 'assistant') {
return message.uuid;
} else if (message.type === 'summary') {
return 'summary: ' + message.leafUuid + ': ' + message.summary;
} else if (message.type === 'system') {
return message.uuid;
} else {
throw Error() // Impossible
}
}
/**
* Read and parse session log file.
* Returns only valid conversation messages, silently skipping internal events.
*/
async function readSessionLog(filePath: string, startLine: number): Promise<{ events: SessionFileScanEntry<RawJSONLines>[]; titleChanges: string[]; totalLines: number }> {
logger.debug(`[SESSION_SCANNER] Reading session file: ${filePath}`);
let file: string;
try {
file = await readFile(filePath, 'utf-8');
} catch (error) {
logger.debug(`[SESSION_SCANNER] Session file not found: ${filePath}`);
return { events: [], titleChanges: [], totalLines: startLine };
}
const lines = file.split('\n');
const hasTrailingEmpty = lines.length > 0 && lines[lines.length - 1] === '';
const totalLines = hasTrailingEmpty ? lines.length - 1 : lines.length;
let effectiveStartLine = startLine;
if (effectiveStartLine > totalLines) {
effectiveStartLine = 0;
}
const messages: SessionFileScanEntry<RawJSONLines>[] = [];
const titleChanges: string[] = [];
for (let index = effectiveStartLine; index < lines.length; index += 1) {
const l = lines[index];
try {
if (l.trim() === '') {
continue;
}
let message = JSON.parse(l);
// Capture custom-title events from Claude Code's /rename command
if (message.type === 'custom-title' && typeof message.customTitle === 'string') {
titleChanges.push(message.customTitle);
continue;
}
// Silently skip known internal Claude Code events
// These are state/tracking events, not conversation messages
if (message.type && INTERNAL_CLAUDE_EVENT_TYPES.has(message.type)) {
continue;
}
let parsed = RawJSONLinesSchema.safeParse(message);
if (!parsed.success) {
// Unknown message types are silently skipped.
continue;
}
messages.push({ event: parsed.data, lineIndex: index });
} catch (e) {
logger.debug(`[SESSION_SCANNER] Error processing message: ${e}`);
continue;
}
}
return { events: messages, titleChanges, totalLines };
}
function sessionIdFromPath(filePath: string): string | null {
const base = basename(filePath);
if (!base.endsWith('.jsonl')) {
return null;
}
return base.slice(0, -'.jsonl'.length);
}