Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: finish chats left open after a turn

ogsamratdddbfcaa7312
diff --git a/apps/server/src/session-uploader.test.ts b/apps/server/src/session-uploader.test.ts
index 388a4346..5a9cd7b8 100644
--- a/apps/server/src/session-uploader.test.ts
+++ b/apps/server/src/session-uploader.test.ts
@@ -389,19 +389,22 @@ describe("session uploader privacy", () => {
const recoveredTurns: Array<{ sessionId: string; workspaceId: string; root: string }> = [];
const next = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, onRecoveredTurn: (turn) => recoveredTurns.push(turn) });
- for (let waited = 0; waited < 5_000 && envelopes.length < 2; waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
+ for (let waited = 0; waited < 5_000 && recoveredTurns.length === 0; waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
const recovered = envelopes[1]!;
expect(recovered).toMatchObject({ snapshot_type: "trace", session_segment: 1, sequence: 2 });
const types = (recovered.trace as Array<{ type: string }>).map((event) => event.type);
expect(types[0]).toBe("collector.recovered");
expect(types).toContain("engine.request");
expect(types).toContain("tool.call");
+ // The killed run's segment gets its end (marked recovered, turn open); the turn is settled in the next one.
+ expect(types.at(-1)).toBe("session.end_recovered");
+ expect(envelopes[2]).toMatchObject({ snapshot_type: "end", session_segment: 1, sequence: 3, trigger: "session_end" });
expect(recoveredTurns).toEqual([{ sessionId, workspaceId: "workspace-journal", root }]);
expect(await readdir(join(stateDir, "omnirush-upload-journal"))).toEqual([]);
- // The chat's next segment starts after the recovered upload.
+ // The chat's next segment starts after the recovered uploads.
next.startSession(sessionId, "workspace-journal", root);
await next.stop();
- expect(envelopes.slice(2).map((item) => [item.snapshot_type, item.session_segment, item.sequence])).toEqual([["start", 2, 3], ["trace", 2, 4], ["end", 2, 5]]);
+ expect(envelopes.slice(3).map((item) => [item.snapshot_type, item.session_segment, item.sequence])).toEqual([["start", 2, 4], ["trace", 2, 5], ["end", 2, 6]]);
}, 20_000);
test("an app that went away after a finished turn: the next launch sends the chat's end (marked recovered), once", async () => {
@@ -443,6 +446,177 @@ describe("session uploader privacy", () => {
expect(envelopes.length).toBe(count);
}, 20_000);
+ test("a chat left open after a finished turn sends its end once quiet; its next prompt reopens it and its close sends the next end", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-idleend-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-idleend-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const envelopes: Array<Record<string, unknown>> = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ envelopes.push(withTraceEvents(JSON.parse(zstdDecompressSync(compressed).toString("utf8"))) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ const ledger = async () => (JSON.parse(await readFile(join(stateDir, "omnirush-upload-sessions.json"), "utf8")) as { sessions: Record<string, { endedAt?: string; segment: number }> }).sessions;
+ const waitFor = async (check: () => boolean | Promise<boolean>) => {
+ for (let waited = 0; waited < 5_000 && !(await check()); waited += 25) await new Promise((resolve) => setTimeout(resolve, 25));
+ };
+ const uploader = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, idleEndMs: 300 });
+ const sessionId = "session-idleend-1234";
+ uploader.startSession(sessionId, "workspace-idleend", root);
+ uploader.captureSnapshot(sessionId, "prompt");
+ await writeFile(join(root, "app.txt"), "hello, turn one\n");
+ uploader.captureSnapshot(sessionId, "turn_completed");
+ uploader.flushTrace(sessionId, { messages: [] });
+ await waitFor(() => envelopes.some((item) => item.snapshot_type === "end"));
+ // The app stays open: the chat's end is out, with the turn's state.
+ const first = envelopes.findIndex((item) => item.snapshot_type === "end");
+ expect(envelopes[first]).toMatchObject({ session_id: sessionId, session_segment: 1, trigger: "session_end" });
+ const before = envelopes.slice(0, first).filter((item) => item.snapshot_type === "trace").flatMap((item) => (item.trace as Array<{ type: string }>) ?? []).map((event) => event.type);
+ expect(before).toContain("turn.completed");
+ expect(before.at(-1)).toBe("session.idle_end");
+ await waitFor(async () => Boolean((await ledger())[sessionId]?.endedAt));
+ expect((await ledger())[sessionId]?.endedAt).toBeString();
+ // A next prompt reopens the chat: the ledger no longer says it ended.
+ uploader.captureSnapshot(sessionId, "prompt");
+ await waitFor(async () => !(await ledger())[sessionId]?.endedAt);
+ expect((await ledger())[sessionId]?.endedAt).toBeUndefined();
+ await writeFile(join(root, "app.txt"), "hello, turn two\n");
+ uploader.captureSnapshot(sessionId, "turn_completed");
+ uploader.flushTrace(sessionId, { messages: [] });
+ // Closed before it went quiet: the close sends the chat's end, after the first one.
+ await uploader.stop();
+ const ends = envelopes.filter((item) => item.snapshot_type === "end");
+ expect(ends.map((item) => [item.session_segment, item.trigger])).toEqual([[1, "session_end"], [1, "session_end"]]);
+ expect((ends[1]!.sequence as number) > (ends[0]!.sequence as number)).toBe(true);
+ const sequences = envelopes.map((item) => item.sequence as number);
+ expect(new Set(sequences).size).toBe(sequences.length);
+ }, 20_000);
+
+ test("a chat whose quiet end is its last state sends no second end at close; one with edits since does", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-idleend2-"));
+ roots.push(root);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const envelopes: Array<Record<string, unknown>> = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ envelopes.push(withTraceEvents(JSON.parse(zstdDecompressSync(compressed).toString("utf8"))) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ const uploader = new SessionUploader({ upload, fallbackScanMs: 60_000, idleEndMs: 200, changeDebounceMs: 10_000 });
+ const quiet = "session-idleend-quiet";
+ const edited = "session-idleend-edited";
+ const other = await mkdtemp(join(tmpdir(), "omnirush-upload-idleend3-"));
+ roots.push(other);
+ await writeFile(join(other, "b.txt"), "b\n");
+ uploader.startSession(quiet, "ws", root);
+ uploader.startSession(edited, "ws2", other);
+ for (const id of [quiet, edited]) {
+ uploader.captureSnapshot(id, "prompt");
+ uploader.captureSnapshot(id, "turn_completed");
+ uploader.flushTrace(id, { messages: [] });
+ }
+ for (let waited = 0; waited < 5_000 && envelopes.filter((item) => item.snapshot_type === "end").length < 2; waited += 25) await new Promise((resolve) => setTimeout(resolve, 25));
+ await Promise.all([uploader.idle(quiet), uploader.idle(edited)]);
+ // An edit after the quiet end, still waiting for its change snapshot as the app quits.
+ await writeFile(join(other, "b.txt"), "b, edited after\n");
+ for (let waited = 0; waited < 2_000; waited += 25) await new Promise((resolve) => setTimeout(resolve, 25));
+ await uploader.stop();
+ const endsOf = (id: string) => envelopes.filter((item) => item.session_id === id && item.snapshot_type === "end").length;
+ expect(endsOf(quiet)).toBe(1);
+ expect(endsOf(edited)).toBe(2);
+ }, 20_000);
+
+ test("a journal whose chat the ledger lost: the next launch sends its end, numbered after the server's copy", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-lostledger-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-lostledger-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const envelopes: Array<Record<string, unknown>> = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ envelopes.push(withTraceEvents(JSON.parse(zstdDecompressSync(compressed).toString("utf8"))) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ const crashed = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, idleEndMs: 0 });
+ const sessionId = "session-lostledger-1234";
+ crashed.startSession(sessionId, "workspace-lostledger", root);
+ crashed.captureSnapshot(sessionId, "prompt");
+ crashed.captureSnapshot(sessionId, "turn_completed");
+ crashed.flushTrace(sessionId, { messages: [] });
+ await crashed.idle(sessionId);
+ crashed.recordTrace(sessionId, "tool.call", { n: 2 });
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ // Killed; and the ledger lost the chat.
+ await rm(join(stateDir, "omnirush-upload-sessions.json"), { force: true });
+ const top = Math.max(...envelopes.map((item) => item.sequence as number));
+ const next = new SessionUploader({
+ stateDir,
+ upload,
+ fallbackScanMs: 60_000,
+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),
+ sessionIntegrity: async (id) => Response.json({ session_id: id, max_segment: 1, max_sequence: top, segments: [{ segment: 1, sequences: [], gaps: [], max_sequence: top }] }),
+ confirm: false,
+ });
+ for (let waited = 0; waited < 5_000 && !envelopes.some((item) => item.snapshot_type === "end"); waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
+ await next.stop();
+ const recovered = envelopes.filter((item) => (item.sequence as number) > top);
+ expect(recovered.map((item) => [item.snapshot_type, item.session_segment, item.sequence])).toEqual([["trace", 1, top + 1], ["end", 1, top + 2]]);
+ const marker = (recovered[0]!.trace as Array<{ type: string; data?: Record<string, unknown> }>).find((event) => event.type === "session.end_recovered");
+ expect(marker?.data).toMatchObject({ reason: "run_ended_without_end", ledger: "missing" });
+ }, 20_000);
+
+ test("a ledger record with no end and no journal (an older launch read it): the next launch sends the end the server lacks, once", async () => {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-upload-ledgerend-"));
+ const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-ledgerend-state-"));
+ roots.push(root, stateDir);
+ await writeFile(join(root, "app.txt"), "hello\n");
+ const envelopes: Array<Record<string, unknown>> = [];
+ const upload = async (_sessionId: string, compressed: Uint8Array) => {
+ envelopes.push(withTraceEvents(JSON.parse(zstdDecompressSync(compressed).toString("utf8"))) as Record<string, unknown>);
+ return Response.json({ ok: true }, { status: 201 });
+ };
+ const crashed = new SessionUploader({ stateDir, upload, fallbackScanMs: 60_000, idleEndMs: 0 });
+ const missing = "session-ledgerend-missing";
+ const held = "session-ledgerend-held";
+ for (const id of [missing, held]) {
+ crashed.startSession(id, "workspace-ledgerend", root);
+ crashed.captureSnapshot(id, "prompt");
+ crashed.captureSnapshot(id, "turn_completed");
+ crashed.flushTrace(id, { messages: [] });
+ await crashed.idle(id);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ // Killed, then a launch of an older version read (and deleted) the journals.
+ await rm(join(stateDir, "omnirush-upload-journal"), { recursive: true, force: true });
+ const asked: string[] = [];
+ const make = () => new SessionUploader({
+ stateDir,
+ upload,
+ fallbackScanMs: 60_000,
+ capabilities: async () => ({ schema_versions: [1, 2], canonical_trace: false, idempotency_key: true, integrity: true, integrity_summary: true }),
+ sessionIntegrity: async (id, options) => {
+ asked.push(`${id}:${options?.summary === true}`);
+ // The server holds `held`'s end already (sent, the ledger never heard).
+ const uploads = [{ snapshot_type: "start", sequence: 1 }, { snapshot_type: "trace", sequence: 2 }, ...(id === held ? [{ snapshot_type: "end", sequence: 3 }] : [])];
+ return Response.json({ session_id: id, segments: [{ segment: 1, sequences: uploads.map((item) => item.sequence), gaps: [], max_sequence: uploads.length, uploads }] });
+ },
+ confirm: false,
+ });
+ const next = make();
+ for (let waited = 0; waited < 5_000 && !envelopes.some((item) => item.snapshot_type === "end"); waited += 50) await new Promise((resolve) => setTimeout(resolve, 50));
+ await next.stop();
+ const ends = envelopes.filter((item) => item.snapshot_type === "end");
+ expect(ends.map((item) => [item.session_id, item.session_segment, item.trigger])).toEqual([[missing, 1, "session_end"]]);
+ const marker = envelopes.filter((item) => item.session_id === missing && item.snapshot_type === "trace").flatMap((item) => (item.trace as Array<{ type: string; data?: Record<string, unknown> }>) ?? []).find((event) => event.type === "session.end_recovered");
+ expect(marker?.data).toMatchObject({ reason: "ledger_without_end" });
+ expect(asked.sort()).toEqual([`${held}:false`, `${missing}:false`]);
+ // A third launch finds nothing left to send or ask: `missing` ended, and the ledger now knows `held` did.
+ const count = envelopes.length;
+ const third = make();
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ await third.stop();
+ expect(envelopes.length).toBe(count);
+ expect(asked).toHaveLength(2);
+ }, 20_000);
+
test("the base's outcome rides along (collector.project_archive, workspace.project_archive); two chats on one folder mark turn.overlap", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-upload-gaps-"));
const stateDir = await mkdtemp(join(tmpdir(), "omnirush-upload-gaps-state-"));
diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.ts
index 7db98a6d..bf198cd9 100644
--- a/apps/server/src/session-uploader.ts
+++ b/apps/server/src/session-uploader.ts
@@ -216,6 +216,15 @@ const CONFIRM_PENDING_MS = 24 * 60 * 60_000;
/** Launch checks go out one at a time, this far apart, and at most this many per launch. */
const CONFIRM_LAUNCH_SPACING_MS = 5_000;
const CONFIRM_LAUNCH_MAX = 20;
+/**
+ * A chat quiet this long after a finished turn (no prompt, nothing running)
+ * sends its end: the workspace as the turn left it. A later turn supersedes
+ * it with the next end, so a chat the user never closes (the app left open,
+ * then killed, a machine that never comes back) is still finished.
+ */
+const IDLE_END_MS = 60_000;
+/** Chats the ledger says never sent their end (and no journal stands for), sent at one launch at most. */
+const LEDGER_END_RECOVERY_MAX = 25;
/** How long a chat's first prompt waits to learn where the server's copy of it stands. */
const SERVER_POSITION_TIMEOUT_MS = 5_000;
const ACCOUNT_REQUIRED_MARKER = "omnirush_account_required";
@@ -645,8 +654,14 @@ type SessionState = {
repositioned?: boolean;
/** "segment:sequence" of uploads the server refused for good. */
refused: string[];
- /** Set once the chat's end snapshot went out. */
+ /** Set once the chat's end snapshot went out (at its close, or once it went quiet after a turn: idleEnd). */
endedAt?: string;
+ /** The quiet-after-a-turn end, while it waits (IDLE_END_MS). */
+ idleEndTimer: ReturnType<typeof setTimeout> | null;
+ /** Prompts this process dispatched in the chat: an end taken while one came in is not the chat's last state. */
+ turns: number;
+ /** The last workspace snapshot that went out is an end, with no turn since: the chat's close sends none again. */
+ endCurrent: boolean;
/** Trace events not yet handed to an upload, as written to the chat's journal on disk. */
journal: JournalState;
};
@@ -746,6 +761,8 @@ type SessionUploaderOptions = {
repairTranscript?: (chat: RecoveredTurn) => Promise<unknown[][] | null>;
/** Integrity checks of ended chats (after each end, and at launch for recent unconfirmed ones); on unless false. */
confirm?: boolean;
+ /** How long a chat stays quiet after a finished turn before its end goes out (IDLE_END_MS); 0 turns it off. */
+ idleEndMs?: number;
/** GET /omnirush/me/sessions/{id}/integrity for this account (where the server's copy of a chat stands). */
sessionIntegrity?: (sessionId: string, options?: { summary?: boolean; turns?: number }) => Promise<Response>;
/**
@@ -4468,6 +4485,23 @@ export function serverSessionPosition(payload: unknown): { segment: number; sequ
return found ? { segment, sequence } : null;
}
+/**
+ * What the integrity answer (with its uploads) says of `segment`'s end:
+ * "present" (a live end upload), "missing" (the segment without one, and no
+ * later segment), "unknown" (no such segment, a later one, no uploads listed).
+ */
+export function segmentEnd(payload: unknown, segment: number): "missing" | "present" | "unknown" {
+ if (!isRecord(payload) || !Array.isArray(payload.segments)) return "unknown";
+ let answer: "missing" | "present" | "unknown" = "unknown";
+ for (const item of payload.segments) {
+ if (!isRecord(item) || !Number.isSafeInteger(item.segment)) continue;
+ if (Number(item.segment) > segment) return "unknown";
+ if (Number(item.segment) !== segment || !Array.isArray(item.uploads)) continue;
+ answer = item.uploads.some((upload) => isRecord(upload) && upload.snapshot_type === "end" && upload.deleted !== true) ? "present" : "missing";
+ }
+ return answer;
+}
+
/** The /collect features this client uses; without a capability answer, none. */
type UploadFeatures = { idempotencyKey: boolean; integrity: boolean };
const NO_UPLOAD_FEATURES: UploadFeatures = { idempotencyKey: false, integrity: false };
@@ -4511,6 +4545,7 @@ export class SessionUploader {
private readonly onRecoveredTurn?: SessionUploaderOptions["onRecoveredTurn"];
private readonly repairTranscript?: SessionUploaderOptions["repairTranscript"];
private readonly confirmEnabled: boolean;
+ private readonly idleEndMs: number;
/** Integrity checks waiting, by chat. */
private readonly confirmTimers = new Map<string, ReturnType<typeof setTimeout>>();
private readonly confirming = new Set<string>();
@@ -4637,6 +4672,7 @@ export class SessionUploader {
this.onRecoveredTurn = options.onRecoveredTurn;
this.repairTranscript = options.repairTranscript;
this.confirmEnabled = options.confirm !== false && Boolean(options.sessionIntegrity);
+ this.idleEndMs = options.idleEndMs ?? IDLE_END_MS;
this.snapshotMaxBytes = options.snapshotMaxBytes ?? MAX_SNAPSHOT_BYTES;
this.minChangeIntervalMs = options.minChangeIntervalMs ?? MIN_UPLOAD_CHANGE_INTERVAL_MS;
this.maxWatchedFiles = options.maxWatchedFiles ?? MAX_UPLOAD_WATCHED_FILES;
@@ -5138,6 +5174,9 @@ export class SessionUploader {
tail: Promise.resolve(),
journal: { pending: [], timer: null, tail: Promise.resolve(), bytes: 0, full: false, off: false, ready: false },
refused: [],
+ idleEndTimer: null,
+ turns: 0,
+ endCurrent: false,
};
}
@@ -5847,6 +5886,8 @@ export class SessionUploader {
if (trigger === "prompt") state.turnStartedAt = Date.now() + 1;
const startedAt = state.turnStartedAt;
state.turnInProgress = trigger === "prompt";
+ if (trigger === "prompt") this.reopenAfterEnd(state);
+ else this.scheduleIdleEnd(state);
// A crash from here on leaves the turn open in the journal (or no longer).
this.journalMeta(state, true);
// The milestone carries whatever edits were held back for another session's turn.
@@ -5979,9 +6020,67 @@ export class SessionUploader {
return read.content;
}
+ /**
+ * A turn finished: once the chat stays quiet for idleEndMs (no prompt, no
+ * turn running) its end goes out, the workspace as the turn left it. The
+ * chat stays open; its next prompt reopens it (reopenAfterEnd) and a later
+ * end supersedes this one, like any later snapshot of the segment.
+ */
+ private scheduleIdleEnd(state: SessionState): void {
+ if (state.idleEndTimer) clearTimeout(state.idleEndTimer);
+ state.idleEndTimer = null;
+ if (this.idleEndMs <= 0 || state.finished || this.stopped) return;
+ const turns = state.turns;
+ state.idleEndTimer = setTimeout(() => {
+ state.idleEndTimer = null;
+ this.sendIdleEnd(state, turns);
+ }, this.idleEndMs);
+ state.idleEndTimer.unref?.();
+ }
+
+ private sendIdleEnd(state: SessionState, turns: number): void {
+ if (state.finished || this.stopped || state.turnInProgress || state.turns !== turns) return;
+ this.enqueue(state, async () => {
+ await state.ready;
+ await state.changeCaptureTail;
+ if (state.finished || this.stopped || state.turnInProgress || state.turns !== turns || state.endCurrent) return;
+ this.appendTrace(state, "session.idle_end", { idle_ms: this.idleEndMs });
+ try {
+ await this.uploadTrace(state, state.trace.splice(0));
+ } finally {
+ await this.journalRewrite(state);
+ }
+ const sent = await this.uploadWorkspace(state, "end", "session_end");
+ // A prompt that came in meanwhile reopened the chat: this end is not its last state.
+ if (!sent || state.finished || state.turnInProgress || state.turns !== turns) {
+ if (state.turns !== turns || state.turnInProgress) state.endCurrent = false;
+ return;
+ }
+ state.endedAt = new Date().toISOString();
+ await this.persistSession(state).catch(() => undefined);
+ this.log("info", "OmniRush session end sent after a quiet finished turn", { sessionId: state.id });
+ });
+ }
+
+ /** A prompt: the quiet-turn end waits for this turn, and an end already sent no longer stands for the chat. */
+ private reopenAfterEnd(state: SessionState): void {
+ state.turns += 1;
+ if (state.idleEndTimer) clearTimeout(state.idleEndTimer);
+ state.idleEndTimer = null;
+ state.endCurrent = false;
+ if (!state.endedAt) return;
+ // The ledger says so at once: a run killed in this turn still gets its end at the next launch.
+ state.endedAt = undefined;
+ void this.persistSession(state).catch(() => undefined);
+ }
+
finishSession(sessionId: string, finalTrace?: unknown): void {
const state = this.sessions.get(sessionId);
if (!state || state.finished) return;
+ if (state.idleEndTimer) clearTimeout(state.idleEndTimer);
+ state.idleEndTimer = null;
+ // Edits still on their way to a snapshot: the close sends its end even after a quiet-turn end.
+ const changesPending = Boolean(state.changeTimer || state.deferTimer || state.changesHeld || state.dirty.size > 0 || state.dirtyOverflow);
const pendingTrace = state.trace.splice(0);
if (finalTrace !== undefined) {
for (const evidence of knownToolPathEvidence("session.completed", finalTrace)) {
@@ -6009,8 +6108,11 @@ export class SessionUploader {
if (finalTrace !== undefined) pendingTrace.push({ at: new Date().toISOString(), type: "session.completed", data: finalTrace });
try {
await this.uploadTrace(state, pendingTrace);
- await this.uploadWorkspace(state, "end", "session_end");
- state.endedAt = new Date().toISOString();
+ // The quiet-turn end is the chat's last state when nothing moved since: no second end.
+ if (!state.endCurrent || changesPending || this.journalHasChanges(state) || !state.endedAt) {
+ await this.uploadWorkspace(state, "end", "session_end");
+ state.endedAt = new Date().toISOString();
+ }
await this.persistSession(state).catch(() => undefined);
// Once after a chat ends (not at quit: the next launch asks).
if (!this.stopped) this.scheduleConfirm(sessionId, CONFIRM_AFTER_END_MS);
@@ -6591,6 +6693,7 @@ export class SessionUploader {
// The baseline is the last *accepted* manifest (uploaded or spooled): the
// next change snapshot reports exactly what moved since this one.
accepted = true;
+ state.endCurrent = type === "end";
state.manifest = manifest;
state.extras = extraEntries;
state.turnManifest ??= turnBaseline(manifest, state.turnStartedAt, [previous]);
@@ -7274,9 +7377,10 @@ export class SessionUploader {
try {
names = (await readdir(this.journalDir)).filter((name) => name.endsWith(".jsonl"));
} catch {
- return;
+ // No journal folder: the ledger may still name chats whose end never went out.
+ names = [];
}
- const found: Array<{ path: string; meta: JournalMeta; events: TraceEvent[] }> = [];
+ const found: Array<{ path: string | null; meta: JournalMeta; events: TraceEvent[]; reason?: string }> = [];
for (const name of names) {
const path = join(this.journalDir, name);
try {
@@ -7292,6 +7396,9 @@ export class SessionUploader {
await rm(path, { force: true }).catch(() => undefined);
}
}
+ // Chats the ledger says never sent their end, with no journal left to say so (a launch of an
+ // older version read it, or it was lost): their end goes out too, once the server confirms it lacks it.
+ found.push(...(await this.ledgerEndsMissing(new Set(found.map((journal) => journal.meta.session_id)))));
// Registered before this resolves, so a chat's start finds its recovery.
const recovered: Promise<void>[] = [];
let chain = Promise.resolve();
@@ -7308,22 +7415,89 @@ export class SessionUploader {
void Promise.allSettled(recovered);
}
- /** A chat's journal outlived the app, its turn is not open, and the ledger has no end for it: the end never went out. */
+ /**
+ * A chat's journal outlived the app and the ledger has no end for it: the
+ * end never went out. A turn left open too (its messages are settled in the
+ * chat's next segment), and a chat the ledger has no record of at all (it
+ * lost it), like the CLI's recovery: the journal goes only once the end went.
+ */
private endMissing(meta: JournalMeta): boolean {
const record = this.ledger.sessions[meta.session_id];
- return !meta.turn_open && Boolean(record) && !record?.endedAt && !this.sessions.has(meta.session_id);
+ return !record?.endedAt && !this.sessions.has(meta.session_id);
+ }
+
+ /**
+ * Ledger records with no end and no journal, seen within the spool's age
+ * limit, whose folder is still there: the newest LEDGER_END_RECOVERY_MAX,
+ * each asked of the server first (its segment has no end there, and no later
+ * segment exists). Without the integrity route none is sent.
+ */
+ private async ledgerEndsMissing(journaled: Set<string>): Promise<Array<{ path: null; meta: JournalMeta; events: TraceEvent[]; reason: string }>> {
+ if (!this.sessionIntegrity || !(await this.uploadFeatures().catch(() => NO_UPLOAD_FEATURES)).integrity) return [];
+ const now = Date.now();
+ const candidates = Object.entries(this.ledger.sessions)
+ .filter(([sessionId, record]) => !record.endedAt && !journaled.has(sessionId) && !this.sessions.has(sessionId)
+ && record.root && record.workspaceId && now - Date.parse(record.lastSeenAt) <= this.spoolMaxAgeMs)
+ .sort(([, left], [, right]) => right.lastSeenAt.localeCompare(left.lastSeenAt))
+ .slice(0, LEDGER_END_RECOVERY_MAX);
+ const out: Array<{ path: null; meta: JournalMeta; events: TraceEvent[]; reason: string }> = [];
+ let confirmed = false;
+ for (const [sessionId, record] of candidates) {
+ if (!(await stat(record.root!).then((entry) => entry.isDirectory(), () => false))) continue;
+ const end = await this.serverEnd(sessionId, record.segment);
+ if (end === "present") {
+ // The end went out and the ledger never heard (a write lost): it says so now, and is not asked again.
+ record.endedAt = new Date().toISOString();
+ confirmed = true;
+ }
+ if (end !== "missing") continue;
+ out.push({
+ path: null,
+ meta: { v: 1, session_id: sessionId, workspace_id: record.workspaceId!, root: record.root!, segment: record.segment, turn_open: false, at: record.lastSeenAt },
+ events: [],
+ reason: "ledger_without_end",
+ });
+ }
+ if (confirmed) await this.saveLedger().catch(() => undefined);
+ return out;
+ }
+
+ /** Whether the server holds an end for `segment` of the chat ("missing": the segment without one, and nothing after it). */
+ private async serverEnd(sessionId: string, segment: number): Promise<"missing" | "present" | "unknown"> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const response = await Promise.race([
+ this.sessionIntegrity!(sessionId),
+ new Promise<null>((resolvePromise) => {
+ timer = setTimeout(() => resolvePromise(null), SERVER_POSITION_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ if (!response) return "unknown";
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return "unknown";
+ }
+ return segmentEnd(JSON.parse(await boundedResponseText(response, 4 * 1024 * 1024)), segment);
+ } catch {
+ return "unknown";
+ } finally {
+ clearTimeout(timer);
+ }
}
- private async recoverJournal(journal: { path: string; meta: JournalMeta; events: TraceEvent[] }): Promise<void> {
+ private async recoverJournal(journal: { path: string | null; meta: JournalMeta; events: TraceEvent[]; reason?: string }): Promise<void> {
const { meta, events } = journal;
const record = this.ledger.sessions[meta.session_id];
const endMissing = this.endMissing(meta);
if (events.length > 0 || endMissing) {
- // The segment the events were recorded in, numbered after what it already sent.
+ // The segment the events were recorded in, numbered after what it already sent
+ // (the server says where, when this ledger lost the chat).
+ const server = record ? null : await this.serverPosition(meta.session_id);
const state = this.newSessionState(meta.session_id, meta.workspace_id, meta.root, new FileHashCache());
state.journal.off = true;
state.segment = record?.segment ?? meta.segment;
- state.sequence = record?.nextSequence ?? 0;
+ state.sequence = record?.nextSequence ?? server?.sequence ?? 0;
state.sentBytes = record?.sentBytes ?? 0;
state.lastMessageId = record?.lastMessageId;
state.failureCount = record?.failureCount ?? 0;
@@ -7348,7 +7522,7 @@ export class SessionUploader {
};
// The end that follows was taken at this launch, not when the app went away.
const endMarker: TraceEvent[] = endMissing
- ? [{ at: marker.at, type: "session.end_recovered", data: { reason: "run_ended_without_end", last_message_id: state.lastMessageId ?? null } }]
+ ? [{ at: marker.at, type: "session.end_recovered", data: { reason: journal.reason ?? "run_ended_without_end", last_message_id: state.lastMessageId ?? null, ...(meta.turn_open ? { turn_open: true } : {}), ...(record ? {} : { ledger: "missing" }) } }]
: [];
try {
await this.uploadTrace(state, [marker, ...events, ...endMarker]);
@@ -7365,7 +7539,7 @@ export class SessionUploader {
}
this.log("info", "OmniRush session journal recovered", { sessionId: meta.session_id, events: events.length, turnOpen: meta.turn_open });
}
- await rm(journal.path, { force: true });
+ if (journal.path) await rm(journal.path, { force: true });
// The open turn's messages are still in the engine: the host settles it once this chat's recovery is done.
if (meta.turn_open && this.onRecoveredTurn) {
const turn: RecoveredTurn = { sessionId: meta.session_id, workspaceId: meta.workspace_id, root: meta.root };