2026-10-23 14:00:48 +02:00
|
|
|
|
/**
|
|
|
|
|
|
* @fileoverview Reads a claude session's edit history on request: the new bytes of its
|
|
|
|
|
|
* transcripts (main + subagents) go into its `EditHistoryStore`, and the Bash image
|
|
|
|
|
|
* candidates that came with them are confirmed against the files on disk.
|
|
|
|
|
|
*
|
|
|
|
|
|
* WHEN. Only when the panel asks (`GET …/edits?sync=1` on open and while it follows the
|
|
|
|
|
|
* session, `POST …/edits/older`): no timer, no hook, no background read for sessions nobody
|
2026-10-23 14:30:05 +02:00
|
|
|
|
* looks at. One sync per session runs at a time; requests during a run are folded into one
|
|
|
|
|
|
* more forward read and/or one more older read afterwards.
|
|
|
|
|
|
*
|
|
|
|
|
|
* GONE. `remove()` (the session's record is deleted) marks the session gone before it deletes
|
|
|
|
|
|
* the file: a run in flight stops after its current read, its store no longer writes, and a
|
|
|
|
|
|
* later request reads nothing (`unavailable`, reason `removed`) instead of loading a new store.
|
|
|
|
|
|
*
|
|
|
|
|
|
* OLDER. "Load older" splits the budget evenly over the sources with older lines and reads
|
|
|
|
|
|
* only those blocks, so every source moves back with each click.
|
2026-10-23 14:00:48 +02:00
|
|
|
|
*
|
|
|
|
|
|
* WHICH SESSIONS. Local claude sessions. Remote, Docker and non-claude sessions answer
|
|
|
|
|
|
* `unsupported` and are never read.
|
|
|
|
|
|
*
|
|
|
|
|
|
* IMAGES. A Bash candidate counts only when the file's mtime lies in the call's window
|
|
|
|
|
|
* (start − 2 s … end + 2 s), so `ls *.png` lists nothing.
|
|
|
|
|
|
*
|
|
|
|
|
|
* Tests: `test/edit-history-sync.test.ts`.
|
|
|
|
|
|
*
|
|
|
|
|
|
* @module web/edit-history-sync
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
|
|
import type { SessionRemote } from '../types/session.js';
|
2026-10-23 14:30:05 +02:00
|
|
|
|
import type { EditSourceReadOptions, EditSourceRequest, EditSources, PathProbe } from '../edit-history-local-source.js';
|
2026-10-23 14:00:48 +02:00
|
|
|
|
import type { ImageCandidate } from '../edit-history-parse.js';
|
|
|
|
|
|
import { EditHistoryStore, READ_BUDGET_BYTES, type ConfirmedImage } from '../edit-history-store.js';
|
|
|
|
|
|
import { getCli } from '../config/cli-registry/registry.js';
|
|
|
|
|
|
|
|
|
|
|
|
/** Slack around a Bash call's window for the image mtime check. */
|
|
|
|
|
|
export const IMAGE_MTIME_SLACK_MS = 2000;
|
|
|
|
|
|
/** Forward passes per sync when a file grew by more than one budget. */
|
|
|
|
|
|
export const MAX_FORWARD_PASSES = 3;
|
|
|
|
|
|
/** `reason` when the session has no transcript yet (no prompt yet, or not found). */
|
|
|
|
|
|
export const NO_TRANSCRIPT = 'no-transcript';
|
2026-10-23 14:30:05 +02:00
|
|
|
|
/** `reason` once the session's history was deleted. */
|
|
|
|
|
|
export const REMOVED = 'removed';
|
2026-10-23 14:00:48 +02:00
|
|
|
|
|
|
|
|
|
|
export type EditHistoryState = 'ok' | 'unavailable' | 'unsupported';
|
|
|
|
|
|
|
|
|
|
|
|
export interface EditHistoryStatus {
|
|
|
|
|
|
state: EditHistoryState;
|
|
|
|
|
|
reason?: string;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** The slice of a session this needs. */
|
|
|
|
|
|
export interface EditHistorySession {
|
|
|
|
|
|
id: string;
|
|
|
|
|
|
mode: string;
|
|
|
|
|
|
remote: SessionRemote | undefined;
|
|
|
|
|
|
docker?: unknown;
|
|
|
|
|
|
claudeSessionId: string | null;
|
|
|
|
|
|
/** The session's own `CLAUDE_CONFIG_DIR` (Codeman env override), if it has one. */
|
|
|
|
|
|
claudeConfigDir?: string;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export interface EditHistorySyncDeps {
|
|
|
|
|
|
/** The session's main transcript path, or null when it has none yet. */
|
|
|
|
|
|
transcriptPath(session: EditHistorySession): Promise<string | null>;
|
2026-10-23 14:30:05 +02:00
|
|
|
|
readSources(
|
|
|
|
|
|
mainPath: string,
|
|
|
|
|
|
requests: readonly EditSourceRequest[],
|
|
|
|
|
|
budget: number,
|
|
|
|
|
|
opts?: EditSourceReadOptions
|
|
|
|
|
|
): Promise<EditSources | null>;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
probe(paths: readonly string[]): Promise<Array<PathProbe | null>>;
|
|
|
|
|
|
loadStore(sessionId: string): Promise<EditHistoryStore>;
|
|
|
|
|
|
budget?: number;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export interface SyncOptions {
|
|
|
|
|
|
older?: boolean;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Why a session has no edit history, or undefined when it can have one. */
|
|
|
|
|
|
export function unsupportedReason(session: EditHistorySession): string | undefined {
|
|
|
|
|
|
if (session.remote) return 'remote';
|
|
|
|
|
|
if (session.docker) return 'docker';
|
|
|
|
|
|
if (getCli(session.mode)?.capabilities.transcript !== 'claude-jsonl') return 'mode';
|
|
|
|
|
|
return undefined;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* Bash candidates whose probed file is a regular file with an mtime inside the call's window
|
|
|
|
|
|
* (files claude sent to the user skip the window: they exist and were shown on purpose).
|
|
|
|
|
|
* A candidate whose file version is already recorded is skipped: `known(path)` is the newest
|
|
|
|
|
|
* entry time for that path, and an entry at or after `mtime − slack` saw this version — the
|
|
|
|
|
|
* `ls *.png` right after the render, or a Write followed by a listing. Candidates are taken
|
|
|
|
|
|
* in call order so a batch dedupes itself the same way.
|
|
|
|
|
|
*/
|
|
|
|
|
|
export function confirmImages(
|
|
|
|
|
|
candidates: readonly ImageCandidate[],
|
|
|
|
|
|
probe: (path: string) => PathProbe | null | undefined,
|
|
|
|
|
|
known: (path: string) => number | undefined = () => undefined
|
|
|
|
|
|
): ConfirmedImage[] {
|
|
|
|
|
|
const out: ConfirmedImage[] = [];
|
|
|
|
|
|
const seen = new Map<string, number>();
|
|
|
|
|
|
for (const c of [...candidates].sort((a, b) => a.end - b.end)) {
|
|
|
|
|
|
for (const path of c.paths) {
|
|
|
|
|
|
const p = probe(path);
|
|
|
|
|
|
if (!p || p.kind !== 'file' || !p.mtimeMs) continue;
|
|
|
|
|
|
const inWindow = p.mtimeMs >= c.start - IMAGE_MTIME_SLACK_MS && p.mtimeMs <= c.end + IMAGE_MTIME_SLACK_MS;
|
|
|
|
|
|
if (!c.sent && !inWindow) continue;
|
|
|
|
|
|
const entryPath = path.startsWith('~/') ? p.realPath : path;
|
|
|
|
|
|
const last = Math.max(seen.get(entryPath) ?? -Infinity, known(entryPath) ?? -Infinity);
|
|
|
|
|
|
if (last >= p.mtimeMs - IMAGE_MTIME_SLACK_MS) continue;
|
|
|
|
|
|
seen.set(entryPath, c.end);
|
|
|
|
|
|
const img: ConfirmedImage = {
|
|
|
|
|
|
toolUseId: c.toolUseId,
|
|
|
|
|
|
path: entryPath,
|
|
|
|
|
|
ts: c.end,
|
|
|
|
|
|
tool: c.sent ? 'sent' : 'bash',
|
|
|
|
|
|
};
|
|
|
|
|
|
if (c.agentId) img.agentId = c.agentId;
|
|
|
|
|
|
out.push(img);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return out;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:30:05 +02:00
|
|
|
|
interface SyncWant {
|
|
|
|
|
|
forward: boolean;
|
|
|
|
|
|
older: boolean;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:00:48 +02:00
|
|
|
|
interface SessionSlot {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
store?: Promise<EditHistoryStore>;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
status: EditHistoryStatus;
|
|
|
|
|
|
running?: Promise<void>;
|
2026-10-23 14:30:05 +02:00
|
|
|
|
again?: SyncWant;
|
|
|
|
|
|
/** The history was deleted: nothing reads for this session any more. */
|
|
|
|
|
|
gone?: boolean;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export class EditHistorySync {
|
|
|
|
|
|
private readonly slots = new Map<string, SessionSlot>();
|
|
|
|
|
|
private readonly budget: number;
|
|
|
|
|
|
|
|
|
|
|
|
constructor(private readonly deps: EditHistorySyncDeps) {
|
|
|
|
|
|
this.budget = deps.budget ?? READ_BUDGET_BYTES;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:30:05 +02:00
|
|
|
|
/** The session's store, loaded from disk on first use (one load for concurrent callers). */
|
|
|
|
|
|
getStore(sessionId: string): Promise<EditHistoryStore> {
|
2026-10-23 14:00:48 +02:00
|
|
|
|
const slot = this.slot(sessionId);
|
2026-10-23 14:30:05 +02:00
|
|
|
|
if (!slot.store) {
|
|
|
|
|
|
const loading = this.deps.loadStore(sessionId);
|
|
|
|
|
|
slot.store = loading;
|
|
|
|
|
|
loading.catch(() => {
|
|
|
|
|
|
if (slot.store === loading) slot.store = undefined;
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
2026-10-23 14:00:48 +02:00
|
|
|
|
return slot.store;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
getStatus(sessionId: string): EditHistoryStatus {
|
|
|
|
|
|
return { ...this.slot(sessionId).status };
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* Read what is new (or, with `older`, the next older block). Resolves when this
|
|
|
|
|
|
* request's run is done; never rejects. A call during a run queues one more run.
|
|
|
|
|
|
*/
|
|
|
|
|
|
async sync(session: EditHistorySession, opts: SyncOptions = {}): Promise<EditHistoryStatus> {
|
|
|
|
|
|
const why = unsupportedReason(session);
|
|
|
|
|
|
const slot = this.slot(session.id);
|
2026-10-23 14:30:05 +02:00
|
|
|
|
if (slot.gone) return this.getStatus(session.id);
|
2026-10-23 14:00:48 +02:00
|
|
|
|
if (why) {
|
|
|
|
|
|
slot.status = { state: 'unsupported', reason: why };
|
|
|
|
|
|
return this.getStatus(session.id);
|
|
|
|
|
|
}
|
2026-10-23 14:30:05 +02:00
|
|
|
|
const want: SyncWant = { forward: !opts.older, older: !!opts.older };
|
2026-10-23 14:00:48 +02:00
|
|
|
|
if (slot.running) {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
slot.again = {
|
|
|
|
|
|
forward: (slot.again?.forward ?? false) || want.forward,
|
|
|
|
|
|
older: (slot.again?.older ?? false) || want.older,
|
|
|
|
|
|
};
|
2026-10-23 14:00:48 +02:00
|
|
|
|
await slot.running;
|
|
|
|
|
|
// The queued run starts when the current one ends; wait for it too.
|
|
|
|
|
|
if (slot.running) await slot.running;
|
|
|
|
|
|
return this.getStatus(session.id);
|
|
|
|
|
|
}
|
2026-10-23 14:30:05 +02:00
|
|
|
|
slot.running = this.runLoop(session, slot, want);
|
2026-10-23 14:00:48 +02:00
|
|
|
|
try {
|
|
|
|
|
|
await slot.running;
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
slot.running = undefined;
|
|
|
|
|
|
}
|
|
|
|
|
|
return this.getStatus(session.id);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Write every loaded store's pending changes (server shutdown). */
|
|
|
|
|
|
async flushAll(): Promise<void> {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
await Promise.all([...this.slots.values()].map(async (slot) => (await slot.store)?.flush()));
|
2026-10-23 14:00:48 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:30:05 +02:00
|
|
|
|
/**
|
|
|
|
|
|
* Delete a session's stored history (its record is gone). The session stays marked, so a
|
|
|
|
|
|
* run in flight or a late request cannot load and write a new store for it.
|
|
|
|
|
|
*/
|
2026-10-23 14:00:48 +02:00
|
|
|
|
async remove(sessionId: string): Promise<void> {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
const slot = this.slot(sessionId);
|
|
|
|
|
|
slot.gone = true;
|
|
|
|
|
|
slot.again = undefined;
|
|
|
|
|
|
slot.status = { state: 'unavailable', reason: REMOVED };
|
2026-10-23 14:00:48 +02:00
|
|
|
|
const store = await this.getStore(sessionId);
|
|
|
|
|
|
await store.remove();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private slot(sessionId: string): SessionSlot {
|
|
|
|
|
|
let slot = this.slots.get(sessionId);
|
|
|
|
|
|
if (!slot) {
|
|
|
|
|
|
slot = { status: { state: 'ok' } };
|
|
|
|
|
|
this.slots.set(sessionId, slot);
|
|
|
|
|
|
}
|
|
|
|
|
|
return slot;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:30:05 +02:00
|
|
|
|
private async runLoop(session: EditHistorySession, slot: SessionSlot, want: SyncWant): Promise<void> {
|
|
|
|
|
|
let next: SyncWant | undefined = want;
|
|
|
|
|
|
while (next && !slot.gone) {
|
|
|
|
|
|
if (next.forward) await this.runOnce(session, slot, false);
|
|
|
|
|
|
if (next.older && !slot.gone) await this.runOnce(session, slot, true);
|
|
|
|
|
|
next = slot.again;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
slot.again = undefined;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-10-23 14:30:05 +02:00
|
|
|
|
private async runOnce(session: EditHistorySession, slot: SessionSlot, older: boolean): Promise<void> {
|
2026-10-23 14:00:48 +02:00
|
|
|
|
const store = await this.getStore(session.id);
|
2026-10-23 14:30:05 +02:00
|
|
|
|
let status: EditHistoryStatus;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
try {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
const path = slot.gone ? null : await this.deps.transcriptPath(session);
|
2026-10-23 14:00:48 +02:00
|
|
|
|
let found: boolean;
|
|
|
|
|
|
if (!path) {
|
|
|
|
|
|
found = false;
|
|
|
|
|
|
} else if (older) {
|
|
|
|
|
|
found = await this.readOlder(path, store);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
found = true;
|
2026-10-23 14:30:05 +02:00
|
|
|
|
for (let pass = 0; pass < MAX_FORWARD_PASSES && found && !slot.gone; pass++) {
|
2026-10-23 14:00:48 +02:00
|
|
|
|
const r = await this.readForward(path, store);
|
|
|
|
|
|
found = r.found;
|
|
|
|
|
|
if (!r.more) break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-10-23 14:30:05 +02:00
|
|
|
|
status = found ? { state: 'ok' } : { state: 'unavailable', reason: NO_TRANSCRIPT };
|
2026-10-23 14:00:48 +02:00
|
|
|
|
} catch (err) {
|
2026-10-23 14:30:05 +02:00
|
|
|
|
status = { state: 'unavailable', reason: err instanceof Error ? err.message : String(err) };
|
2026-10-23 14:00:48 +02:00
|
|
|
|
}
|
2026-10-23 14:30:05 +02:00
|
|
|
|
if (!slot.gone) slot.status = status;
|
2026-10-23 14:00:48 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private forwardRequests(store: EditHistoryStore): EditSourceRequest[] {
|
|
|
|
|
|
const out: EditSourceRequest[] = [];
|
|
|
|
|
|
for (const relPath of store.knownSources()) {
|
|
|
|
|
|
const c = store.getCursor(relPath);
|
|
|
|
|
|
if (c) out.push({ relPath, offset: c.offset });
|
|
|
|
|
|
}
|
|
|
|
|
|
return out;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* One forward read of all sources. `more` = some file has unread bytes after it.
|
|
|
|
|
|
* A transcript other than the stored one (`/clear`, resume) is read like a first read.
|
|
|
|
|
|
*/
|
|
|
|
|
|
private async readForward(path: string, store: EditHistoryStore): Promise<{ found: boolean; more: boolean }> {
|
|
|
|
|
|
const known = store.getTranscriptId();
|
|
|
|
|
|
const requests = known !== null && path.endsWith(`/${known}.jsonl`) ? this.forwardRequests(store) : [];
|
|
|
|
|
|
const res = await this.deps.readSources(path, requests, this.budget);
|
|
|
|
|
|
if (!res) return { found: false, more: false };
|
|
|
|
|
|
for (const [agentId, text] of Object.entries(res.metas)) {
|
|
|
|
|
|
if (!store.hasAgentMeta(agentId)) store.setAgentMeta(agentId, text);
|
|
|
|
|
|
}
|
|
|
|
|
|
let more = false;
|
|
|
|
|
|
const candidates: ImageCandidate[] = [];
|
|
|
|
|
|
for (const f of res.files) {
|
|
|
|
|
|
const r = store.apply({
|
|
|
|
|
|
transcriptId: res.transcriptId,
|
|
|
|
|
|
source: f.relPath,
|
|
|
|
|
|
startOffset: f.startOffset,
|
|
|
|
|
|
chunk: f.chunk,
|
|
|
|
|
|
size: f.size,
|
|
|
|
|
|
});
|
|
|
|
|
|
candidates.push(...r.candidates);
|
|
|
|
|
|
if (f.startOffset + f.chunk.length < f.size) more = true;
|
|
|
|
|
|
}
|
|
|
|
|
|
await this.addImages(store, candidates);
|
|
|
|
|
|
return { found: true, more };
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private async readOlder(path: string, store: EditHistoryStore): Promise<boolean> {
|
|
|
|
|
|
if (!store.backfillTruncated) return true;
|
2026-10-23 14:30:05 +02:00
|
|
|
|
const sources = store.sourcesWithOlder();
|
|
|
|
|
|
if (sources.length === 0) return true;
|
|
|
|
|
|
const share = Math.max(1, Math.floor(this.budget / sources.length));
|
2026-10-23 14:00:48 +02:00
|
|
|
|
const requests: EditSourceRequest[] = [];
|
2026-10-23 14:30:05 +02:00
|
|
|
|
for (const relPath of sources) {
|
|
|
|
|
|
const range = store.olderRange(relPath, share);
|
2026-10-23 14:00:48 +02:00
|
|
|
|
if (range) requests.push({ relPath, offset: range.offset, len: range.len });
|
|
|
|
|
|
}
|
|
|
|
|
|
if (requests.length === 0) return true;
|
2026-10-23 14:30:05 +02:00
|
|
|
|
const res = await this.deps.readSources(path, requests, this.budget, { onlyRequested: true });
|
2026-10-23 14:00:48 +02:00
|
|
|
|
if (!res) return false;
|
|
|
|
|
|
if (res.transcriptId !== store.getTranscriptId()) return true;
|
|
|
|
|
|
const wanted = new Set(requests.map((r) => r.relPath));
|
|
|
|
|
|
const candidates: ImageCandidate[] = [];
|
|
|
|
|
|
for (const f of res.files) {
|
|
|
|
|
|
if (!wanted.has(f.relPath)) continue;
|
|
|
|
|
|
const r = store.applyOlder({
|
|
|
|
|
|
transcriptId: res.transcriptId,
|
|
|
|
|
|
source: f.relPath,
|
|
|
|
|
|
startOffset: f.startOffset,
|
|
|
|
|
|
chunk: f.chunk,
|
|
|
|
|
|
size: f.size,
|
|
|
|
|
|
});
|
|
|
|
|
|
candidates.push(...r.candidates);
|
|
|
|
|
|
}
|
|
|
|
|
|
await this.addImages(store, candidates);
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private async addImages(store: EditHistoryStore, candidates: readonly ImageCandidate[]): Promise<void> {
|
|
|
|
|
|
const paths = [...new Set(candidates.flatMap((c) => c.paths))];
|
|
|
|
|
|
if (paths.length === 0) return;
|
|
|
|
|
|
let probes: Array<PathProbe | null>;
|
|
|
|
|
|
try {
|
|
|
|
|
|
probes = await this.deps.probe(paths);
|
|
|
|
|
|
} catch {
|
|
|
|
|
|
// The edits of this read are in; only its images are lost. The read itself succeeded.
|
|
|
|
|
|
return;
|
|
|
|
|
|
}
|
|
|
|
|
|
const byPath = new Map(paths.map((p, i) => [p, probes[i]]));
|
|
|
|
|
|
const newest = new Map<string, number>();
|
|
|
|
|
|
for (const e of store.list()) newest.set(e.path, Math.max(newest.get(e.path) ?? -Infinity, e.ts));
|
|
|
|
|
|
store.addImageEntries(
|
|
|
|
|
|
confirmImages(
|
|
|
|
|
|
candidates,
|
|
|
|
|
|
(p) => byPath.get(p),
|
|
|
|
|
|
(p) => newest.get(p)
|
|
|
|
|
|
)
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|