-
Notifications
You must be signed in to change notification settings - Fork 2
Make session operations independent of transcript history #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { open, readdir, stat } from "node:fs/promises"; | ||
| import { join } from "node:path"; | ||
| import type { SessionInfoDto } from "./dto.js"; | ||
|
|
||
| const HEAD_BYTES = 32 * 1024; | ||
| const TAIL_BYTES = 8 * 1024; | ||
|
|
||
| function parseLines(text: string) { | ||
| const entries: any[] = []; | ||
| for (const line of text.split("\n")) { | ||
| if (!line.trim()) continue; | ||
| try { entries.push(JSON.parse(line)); } catch { /* a bounded read may end mid-entry */ } | ||
| } | ||
| return entries; | ||
| } | ||
|
|
||
| function textContent(content: unknown): string { | ||
| if (typeof content === "string") return content; | ||
| if (!Array.isArray(content)) return ""; | ||
| return content.flatMap((part: any) => part?.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n"); | ||
| } | ||
|
|
||
| function filenameMetadata(name: string) { | ||
| const match = name.match(/^(.+)_([^_]+)\.jsonl$/); | ||
| if (!match) return undefined; | ||
| const encoded = match[1]; | ||
| const iso = encoded.replace( | ||
| /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/, | ||
| "$1T$2:$3:$4.$5Z", | ||
| ); | ||
| const created = new Date(iso); | ||
| if (Number.isNaN(created.getTime())) return undefined; | ||
| return { id: match[2], created }; | ||
| } | ||
|
|
||
| export interface ShallowListMetrics { files: number; bytesRead: number } | ||
|
|
||
| async function boundedContents(path: string, size: number, metrics?: ShallowListMetrics) { | ||
| const handle = await open(path, "r"); | ||
| try { | ||
| const headSize = Math.min(size, HEAD_BYTES); | ||
| const head = Buffer.allocUnsafe(headSize); | ||
| const { bytesRead: headRead } = await handle.read(head, 0, headSize, 0); | ||
| if (metrics) metrics.bytesRead += headRead; | ||
| let text = head.subarray(0, headRead).toString("utf8"); | ||
| if (size > HEAD_BYTES) { | ||
| const tailSize = Math.min(size - HEAD_BYTES, TAIL_BYTES); | ||
| const tail = Buffer.allocUnsafe(tailSize); | ||
| const position = size - tailSize; | ||
| const { bytesRead: tailRead } = await handle.read(tail, 0, tailSize, position); | ||
| if (metrics) metrics.bytesRead += tailRead; | ||
| // Deliberately drop any entry straddling the head/tail boundary, including | ||
| // contiguous 32–40 KiB reads; bounded metadata projection tolerates that loss. | ||
| const tailText = tail.subarray(0, tailRead).toString("utf8"); | ||
| text += `\n${tailText.slice(Math.max(0, tailText.indexOf("\n") + 1))}`; | ||
| } | ||
| return text; | ||
| } finally { await handle.close(); } | ||
| } | ||
|
|
||
| export async function shallowSessionCwd(path: string): Promise<string | undefined> { | ||
| try { | ||
| const fileStat = await stat(path); | ||
| const header = parseLines(await boundedContents(path, fileStat.size)).find((entry) => entry?.type === "session"); | ||
| return typeof header?.cwd === "string" && header.cwd ? header.cwd : undefined; | ||
| } catch { return undefined; } | ||
| } | ||
|
|
||
| /** A bounded projection of pi's append-only JSONL. It never reads transcript bodies. */ | ||
| export async function shallowListSessions(cwd: string, directory: string, metrics?: ShallowListMetrics): Promise<SessionInfoDto[]> { | ||
| let names: string[]; | ||
| try { names = await readdir(directory); } catch { return []; } | ||
| return (await Promise.all(names.filter((name) => name.endsWith(".jsonl")).map(async (name) => { | ||
| const metadata = filenameMetadata(name); | ||
| if (!metadata) return undefined; | ||
| const path = join(directory, name); | ||
| try { | ||
| const fileStat = await stat(path); | ||
| if (!fileStat.isFile()) return undefined; | ||
| if (metrics) metrics.files += 1; | ||
| const entries = parseLines(await boundedContents(path, fileStat.size, metrics)); | ||
| const header = entries.find((entry) => entry?.type === "session"); | ||
| if (header?.id && header.id !== metadata.id) return undefined; | ||
| let sessionName: string | undefined; | ||
| let firstMessage: string | undefined; | ||
| for (const entry of entries) { | ||
| if (entry?.type === "session_info") sessionName = typeof entry.name === "string" && entry.name ? entry.name : undefined; | ||
| if (!firstMessage && entry?.type === "message" && entry.message?.role === "user") { | ||
| firstMessage = textContent(entry.message.content).replace(/\s+/g, " ").trim() || undefined; | ||
| } | ||
| } | ||
| const result: SessionInfoDto = { | ||
| id: metadata.id, | ||
| path, | ||
| name: sessionName, | ||
| firstMessage, | ||
| created: metadata.created.toISOString(), | ||
| modified: fileStat.mtime.toISOString(), | ||
| cwd: typeof header?.cwd === "string" && header.cwd ? header.cwd : cwd, | ||
| isCurrent: false as const, | ||
| }; | ||
| return result; | ||
| } catch { return undefined; } | ||
| }))).filter((value): value is SessionInfoDto => value !== undefined); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For a cold session renamed after its first 32 KiB and followed by more than 8 KiB of transcript, the authoritative
session_infoentry is in the unread middle of the file. This loop consequently reports an older head-window name or no name at all, so a renamed session reverts in the drawer after restart; the latest name needs storage or indexing that remains accessible without parsing the transcript body.Useful? React with 👍 / 👎.