mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-01 08:59:32 +01:00
feat(story-mode): draw a Claude session's turns as comic pages, live
Story Mode is an opt-in header button (showStoryButton, per device, default off, kept off phones) that opens the active Claude Code session as comic pages: one page per prompt, panels for reading code, planning, helpers, edits, tests (POW/KRAK), questions and saving, each with a plain story caption and a Director's cut caption naming the tools. Files open in the existing file preview, the code page opens the exact diff, a test board opens the output, and a running turn redraws as Claude works. Server: GET /api/sessions/:id/story (experimental) reads a bounded tail of the session's own transcript. A pure core (src/story-mode.ts) reduces lines, joins tool calls with their results, splits turns at prompts and turn_duration, and groups events into at most 12 panels; Bash calls are sorted by what the command does. The reader (src/story-reader.ts) caches reduced entries and reads only appended bytes while the file grows. Frontend: story-mode.js (canvas frame engine, live refresh from transcript and hook SSE events plus a poll while a turn runs, details drawer, the wire) and story-mode.css, with two self-hosted OFL comic fonts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
0ab71d61d1
commit
2653db10b5
27 files changed
+5746
-6
No files matched your search
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* @fileoverview Story Mode transcript reader: the IO half of Story Mode (the pure half is story-mode.ts).
|
||||
*
|
||||
* Reads the TAIL of a Claude Code transcript, never the whole file: transcripts reach tens of MB
|
||||
* (Write/Edit results carry whole files). The first read takes the last `STORY_TAIL_BYTES` and drops
|
||||
* the partial first line; later reads, while the file only grows, read just the appended bytes. A line
|
||||
* that is still being written (no newline yet) is left for the next read.
|
||||
*
|
||||
* Each transcript's reduced entries are cached (`createStoryReducer()` already dropped file contents,
|
||||
* images and long outputs), bounded per transcript by entry count and character budget, and across
|
||||
* transcripts by an LRU, so a live view refetching every second costs one small append read.
|
||||
* Concurrent reads of one path share a single in-flight promise.
|
||||
*
|
||||
* All IO is async (`fs/promises`); nothing here runs on a path the browser supplied. The route decides
|
||||
* which file is read (story-routes.ts).
|
||||
*/
|
||||
|
||||
import { open, stat } from 'node:fs/promises';
|
||||
import { LRUMap } from './utils/lru-map.js';
|
||||
import { createStoryReducer, type StoryEntry, type StoryReducer } from './story-mode.js';
|
||||
|
||||
/** How much of the file's end a first read takes. */
|
||||
export const STORY_TAIL_BYTES = 8 * 1024 * 1024;
|
||||
/** Entries kept per transcript (the oldest go first). */
|
||||
const MAX_ENTRIES = 20_000;
|
||||
/** Approximate characters kept per transcript across all entries. */
|
||||
const MAX_CHARS = 6_000_000;
|
||||
/** Transcripts cached at once. */
|
||||
const MAX_TRANSCRIPTS = 6;
|
||||
|
||||
interface CacheEntry {
|
||||
size: number;
|
||||
mtimeMs: number;
|
||||
/** Byte offset up to which complete lines were consumed. */
|
||||
offset: number;
|
||||
entries: StoryEntry[];
|
||||
chars: number;
|
||||
reducer: StoryReducer;
|
||||
/** The read began mid-file, so the oldest turn may be cut. */
|
||||
partial: boolean;
|
||||
}
|
||||
|
||||
export interface StoryEntriesResult {
|
||||
entries: StoryEntry[];
|
||||
partial: boolean;
|
||||
}
|
||||
|
||||
const cache = new LRUMap<string, CacheEntry>({ maxSize: MAX_TRANSCRIPTS });
|
||||
const inFlight = new Map<string, Promise<StoryEntriesResult>>();
|
||||
|
||||
/** For tests: forget every cached transcript. */
|
||||
export function clearStoryReaderCache(): void {
|
||||
cache.clear();
|
||||
inFlight.clear();
|
||||
}
|
||||
|
||||
async function readRange(path: string, start: number, end: number): Promise<Buffer> {
|
||||
const length = Math.max(0, end - start);
|
||||
const buf = Buffer.alloc(length);
|
||||
const handle = await open(path, 'r');
|
||||
try {
|
||||
let read = 0;
|
||||
while (read < length) {
|
||||
const { bytesRead } = await handle.read(buf, read, length - read, start + read);
|
||||
if (bytesRead === 0) break;
|
||||
read += bytesRead;
|
||||
}
|
||||
return read === length ? buf : buf.subarray(0, read);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
const entryChars = (e: StoryEntry): number => JSON.stringify(e).length;
|
||||
|
||||
function ingest(entry: CacheEntry, buf: Buffer, startsMidLine: boolean): void {
|
||||
let begin = 0;
|
||||
if (startsMidLine) {
|
||||
const firstNewline = buf.indexOf(0x0a);
|
||||
if (firstNewline < 0) return; // one huge partial line: nothing complete yet
|
||||
begin = firstNewline + 1;
|
||||
}
|
||||
const lastNewline = buf.lastIndexOf(0x0a);
|
||||
if (lastNewline < begin) {
|
||||
// No complete line in what was read; consume nothing beyond a dropped partial head.
|
||||
entry.offset += begin;
|
||||
return;
|
||||
}
|
||||
const text = buf.subarray(begin, lastNewline).toString('utf8');
|
||||
entry.offset += lastNewline + 1;
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line.trim()) continue;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // a malformed line is skipped, never fatal
|
||||
}
|
||||
for (const reduced of entry.reducer.reduce(parsed)) {
|
||||
entry.entries.push(reduced);
|
||||
entry.chars += entryChars(reduced);
|
||||
}
|
||||
}
|
||||
while (entry.entries.length > MAX_ENTRIES || (entry.chars > MAX_CHARS && entry.entries.length > 1)) {
|
||||
const dropped = entry.entries.shift();
|
||||
if (dropped) entry.chars -= entryChars(dropped);
|
||||
entry.partial = true;
|
||||
}
|
||||
}
|
||||
|
||||
async function load(path: string): Promise<StoryEntriesResult> {
|
||||
const info = await stat(path);
|
||||
if (!info.isFile()) throw new Error('Transcript is not a regular file');
|
||||
const cached = cache.get(path);
|
||||
if (cached && cached.size === info.size && cached.mtimeMs === info.mtimeMs) {
|
||||
return { entries: cached.entries, partial: cached.partial };
|
||||
}
|
||||
if (
|
||||
cached &&
|
||||
info.size > cached.offset &&
|
||||
info.size - cached.offset <= STORY_TAIL_BYTES &&
|
||||
info.size >= cached.size
|
||||
) {
|
||||
// The file only grew: read what was appended since the last complete line.
|
||||
const buf = await readRange(path, cached.offset, info.size);
|
||||
ingest(cached, buf, false);
|
||||
cached.size = info.size;
|
||||
cached.mtimeMs = info.mtimeMs;
|
||||
cache.set(path, cached);
|
||||
return { entries: cached.entries, partial: cached.partial };
|
||||
}
|
||||
// First read, a rewrite, or more appended than a tail holds: start over from the tail.
|
||||
const start = Math.max(0, info.size - STORY_TAIL_BYTES);
|
||||
const fresh: CacheEntry = {
|
||||
size: info.size,
|
||||
mtimeMs: info.mtimeMs,
|
||||
offset: start,
|
||||
entries: [],
|
||||
chars: 0,
|
||||
reducer: createStoryReducer(),
|
||||
partial: start > 0,
|
||||
};
|
||||
const buf = await readRange(path, start, info.size);
|
||||
ingest(fresh, buf, start > 0);
|
||||
cache.set(path, fresh);
|
||||
return { entries: fresh.entries, partial: fresh.partial };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduced entries for the transcript at `path`, newest last. Throws when the file cannot be read;
|
||||
* the caller turns that into an error response.
|
||||
*/
|
||||
export function readStoryEntries(path: string): Promise<StoryEntriesResult> {
|
||||
const running = inFlight.get(path);
|
||||
if (running) return running;
|
||||
const promise = load(path).finally(() => inFlight.delete(path));
|
||||
inFlight.set(path, promise);
|
||||
return promise;
|
||||
}
|
||||
Reference in new issue
Block a user