Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f
- Align the + button and primary action with matching composer insets.
- Clearly dim Attach files while the agent is running; queued messages remain text-only.
- Recover saved responses before reporting an empty agent reply after returning to a backgrounded page or PWA. Preserve provider errors and distinguish new runs from older answers.
- Catch up missed conversation entries incrementally after reconnecting or returning to the page, including during active runs. Restore quiet partial responses and live tool output without duplicating history or overwriting newer updates.

---

Expand Down
67 changes: 67 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,73 @@ Models and allow-listed OMP settings use surgical YAML updates that preserve
unrelated content. Plugin operations run the installed `omp plugin` CLI. MCP
configuration is project-local, validated before writing, and saved atomically.

### Reconnect and foreground catch-up

Completed conversation history is identified by persisted session entry IDs.
Live `message_end` frames have no durable ID and can arrive before OMP writes
the entry, so they trigger catch-up rather than append an unidentified copy.
Streaming text, active tool output, and an optimistic user prompt remain
separate from confirmed history.

`GET /api/sessions/:id/context?sync=1` returns a `SessionSyncResponse`:

- `cursor` contains `firstEntryId` and `lastEntryId` (both null for empty
history). Send its JSON value in the next request's `cursor` query parameter.
- `mode: "append"` returns only messages after that position; `baseEntryId`
identifies the expected client prefix. An orphaned cursor or changed
compaction prefix returns `mode: "replace"`.
- `context.messages` and `context.entryIds` remain aligned. `limit` is an
integer from 1 to 200 (default 200); follow `hasMore` with the returned cursor.
Only the selected page's image blobs are resolved.
- Existing `leafId`, `includePreCompaction`, `deferThinking`, and `deferMedia`
view parameters remain available. A historical view excludes live output.
- `live` contains the web-owned process's current partial message, active tool
snapshots, and lifecycle flags, or null for a file-only session. Reading
history never starts an OMP process. A live process can supply its first
partial before its session file exists, but a missing file cannot erase a
nonempty confirmed cursor.
- `live.responseObserved` retains positive visible-answer evidence for the
current run after completion, even before its entry is readable on disk.
New runs and process/session changes reset it; tool calls alone do not count.

`GET /api/sessions/:id/context?boundary=1` returns only `{ entryIds }` for
the current active context. Prompt and interrupt dispatch use this fresh
ID-only boundary instead of downloading the transcript. It shares the history
index without hydrating message bodies or blobs and cannot be combined with
sync, pagination, or historical-view parameters.

SSE events carry `web: { streamId, sequence }`. The stream epoch changes when
the native process or session identity changes. These values order live
snapshots; they are not a persisted replay journal or `Last-Event-ID` support.
Subscription precedes the `connected` cursor announcement. The client keeps
processing live events while history loads and applies snapshot fields only
when they cannot overwrite newer message, tool, or lifecycle state.

Open/reopen, foreground/online, message completion, and persisted-file
notifications share one coalesced catch-up loop. Pages are accumulated privately
and published only when the selected history is complete. Failed reads retain
the last complete cursor and displayed history. Overlapping full loads preserve
newer complete history rather than treating an intermediate page as authoritative.
Full initial loads and terminal metadata refreshes still update the branch tree.
A completion or persistence notification during an in-flight read schedules
one follow-up read from the newly returned cursor. Raw SSE completions never
append a second copy of an entry that the history response already includes.

Unchanged history pages reuse a file-versioned offset index and seek only the
requested message bodies. The in-memory index cache is bounded to 32 views and
32 MiB of charged metadata; it does not retain transcript bodies or increase
the existing 256 MiB raw-file cache budget or 1 GiB load ceiling. Cold indexes
and changed files require a full metadata scan. Growth alone is not proof of
an append: the same inode can be rewritten and then extended, so any file
version change invalidates offsets rather than trusting an unchecked prefix.
Failed reads never advance the confirmed cursor.

File-only catch-up also refreshes model and thinking metadata without replacing
newer or pending RPC choices. Replacement observer connections restore browser
registrations and the subagent roster only after successfully connecting.

Deploy the frontend and API support together; no native OMP upgrade is required.

## Security contract

- Bind loopback-only by default. A non-loopback hostname is an explicit opt-in.
Expand Down
12 changes: 9 additions & 3 deletions app/api/agent/[id]/events/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,15 @@ export async function GET(
return;
}

encode({ type: "connected", sessionId: id });
if (closed) return;
unsubscribe = session.onEvent((event) => encode(event));
// onEvent can synchronously replay pending UI requests. Subscribe before
// sampling the cursor/announcing readiness so catch-up has no event gap.
const detach = session.onEvent((event) => encode(event));
if (closed) {
detach();
return;
}
unsubscribe = detach;
encode({ type: "connected", sessionId: id, web: session.getStreamSnapshot().cursor });
},
// When a slow consumer resumes reading, the stream calls pull() as soon
// as queue space is available. Flush any coalesced message_update here so
Expand Down
69 changes: 67 additions & 2 deletions app/api/sessions/[id]/context/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { NextResponse } from "next/server";
import { existsSync } from "fs";
import { loadSessionFile } from "@/lib/omp/session-files";
import { buildSessionContext, getSessionEntriesForDisplayAsync, readSessionHeader, SessionFileTooLargeError } from "@/lib/session-reader";
import { buildSessionContext, getSessionContextBoundary, getSessionEntriesForDisplayAsync, getSessionHistoryPage, readSessionHeader, SessionFileTooLargeError } from "@/lib/session-reader";
import { apiErrorResponse, resolveSessionPathOr404 } from "@/lib/api-utils";
import { getRpcSession } from "@/lib/rpc-manager";
import { MAX_SYNC_MESSAGES, parseHistoryCursor, selectSessionHistory, type SessionHistoryCursor, type SessionSyncResponse } from "@/lib/session-sync";

/** Uniform error mapping for this route: the display read throws
* SessionFileTooLargeError on files past the load ceiling, which must surface
Expand All @@ -28,10 +31,54 @@ export async function GET(
const deferToolResultImages = url.searchParams.has("deferMedia");
// Read-only transcript mode: include entries omitted from the active agent context.
const includePreCompaction = url.searchParams.has("includePreCompaction");
const sync = url.searchParams.get("sync");
const boundary = url.searchParams.get("boundary");
if (boundary !== null) {
if (boundary !== "1" || url.searchParams.getAll("boundary").length !== 1) {
return NextResponse.json({ error: "Invalid boundary mode", code: "invalid_boundary" }, { status: 400 });
}
if (["sync", "leafId", "includePreCompaction", "cursor", "limit"].some((option) => url.searchParams.has(option))) {
return NextResponse.json({ error: "Boundary mode requires the current active context", code: "invalid_boundary_options" }, { status: 400 });
}
}
let cursor: SessionHistoryCursor | null = null;
let limit = MAX_SYNC_MESSAGES;
if (sync !== null && sync !== "1") {
return NextResponse.json({ error: "Invalid sync mode", code: "invalid_sync" }, { status: 400 });
}
if (sync === "1") {
try {
cursor = parseHistoryCursor(url.searchParams.get("cursor"));
} catch {
return NextResponse.json({ error: "Invalid history cursor", code: "invalid_sync_cursor" }, { status: 400 });
}
const rawLimit = url.searchParams.get("limit");
if (rawLimit !== null) {
limit = Number(rawLimit);
if (!/^[1-9]\d*$/.test(rawLimit) || !Number.isInteger(limit) || limit > MAX_SYNC_MESSAGES) {
return NextResponse.json({ error: "Invalid history page limit", code: "invalid_sync_limit" }, { status: 400 });
}
}
}

try {
const resolved = await resolveSessionPathOr404(id);
if ("response" in resolved) return resolved.response;
if ("response" in resolved) {
// OMP may not create the file until the first assistant message is
// committed. A live wrapper can still recover that first partial reply.
// Never replace previously confirmed history when its file is missing.
const session = sync === "1" && !cursor?.lastEntryId && leafId === undefined ? getRpcSession(id) : undefined;
if (session?.isAlive() && !existsSync(session.sessionFile)) {
const response: SessionSyncResponse = {
...selectSessionHistory(buildSessionContext([]), cursor, limit),
sessionId: id,
leafId: null,
live: session.getStreamSnapshot(),
};
return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } });
}
return resolved.response;
}
const filePath = resolved.filePath;

const header = readSessionHeader(filePath);
Expand All @@ -45,6 +92,24 @@ export async function GET(
}
return NextResponse.json({ error: "Session file is missing or malformed", code: "session_file_malformed" }, { status: 404 });
}
if (boundary === "1") {
return NextResponse.json(getSessionContextBoundary(filePath), { headers: { "Cache-Control": "no-store" } });
}
if (sync === "1") {
const page = await getSessionHistoryPage(filePath, cursor, limit, leafId, {
deferThinking,
deferToolResultImages,
includePreCompaction,
});
// Sample AFTER the disk read: a quiet active run still supplies its most
// recent partial output, and events arriving during the read win.
const session = getRpcSession(id);
const live = session?.isAlive() && (leafId === undefined || leafId === page.tipId)
? session.getStreamSnapshot()
: null;
const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live };
return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } });
}
// Deduplicated cached read; blob resolution on per-entry deep copies.
const entries = await getSessionEntriesForDisplayAsync(filePath, { skipToolResultImages: deferToolResultImages });
const context = buildSessionContext(entries, leafId, {
Expand Down
34 changes: 3 additions & 31 deletions hooks/useAgentSession-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
SubagentProgress,
} from "@/lib/subagent-types";
import { translate } from "@/lib/i18n";
import type { SessionStreamCursor } from "@/lib/session-sync";

export interface SessionData {
sessionId: string;
Expand Down Expand Up @@ -59,6 +60,7 @@ export function streamReducer(state: StreamingState, action: StreamAction): Stre

export interface AgentEvent {
type: string;
web?: SessionStreamCursor;
[key: string]: unknown;
}

Expand Down Expand Up @@ -164,6 +166,7 @@ export type AgentStateResponse = {
isPromptRunning?: boolean;
isBashRunning?: boolean;
isCompacting?: boolean;
responseObserved?: boolean;
tokensPerSecond?: number | null;
extensionStatuses?: ExtensionStatusItem[];
extensionWidgets?: ExtensionWidgetItem[];
Expand Down Expand Up @@ -306,37 +309,6 @@ export function describeMcpMountNotice(message: CustomMessage): string {
return extractMessageText(message).trim() || "The MCP tool inventory changed.";
}

export function imageSignature(block: unknown): string {
if (!block || typeof block !== "object" || (block as { type?: unknown }).type !== "image") return "";
const source = (block as { source?: unknown }).source;
if (source && typeof source === "object") {
const src = source as { type?: unknown; media_type?: unknown; data?: unknown; url?: unknown };
return [
src.type === "url" ? "url" : "base64",
typeof src.media_type === "string" ? src.media_type : "",
typeof src.data === "string" ? src.data : "",
typeof src.url === "string" ? src.url : "",
].join(":");
}
const flat = block as { data?: unknown; mimeType?: unknown };
return [
"base64",
typeof flat.mimeType === "string" ? flat.mimeType : "",
typeof flat.data === "string" ? flat.data : "",
"",
].join(":");
}

export function userMessageKey(message: Partial<AgentMessage>): string {
const content = (message as { content?: unknown }).content;
if (typeof content === "string") return JSON.stringify({ text: content, images: [] });
if (!Array.isArray(content)) return JSON.stringify({ text: "", images: [] });
return JSON.stringify({
text: extractMessageText(message),
images: content.map(imageSignature).filter(Boolean),
});
}

export function readCompactResult(result: unknown, reason: string): CompactResultInfo | null {
if (!result || typeof result !== "object") return null;
const r = result as CompactCommandResult;
Expand Down
79 changes: 79 additions & 0 deletions hooks/useAgentSession-sync.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createJiti } from "jiti";
import { fileURLToPath } from "node:url";

const jiti = createJiti(import.meta.url, { alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) } });
const { createSessionCatchUp } = await jiti.import("./useAgentSession-sync.ts");

test("a newer user delivery cannot block recovery of an unrelated assistant partial", async (t) => {
const context = { messages: [], entryIds: [], thinkingLevel: "off", model: null, todoPhases: [] };
let displayed = "visible before the gap";
let release;
let started;
const requested = new Promise((resolve) => { started = resolve; });
t.mock.method(globalThis, "fetch", () => new Promise((resolve) => {
release = () => resolve({ ok: true, json: async () => ({
sessionId: "s1", mode: "append", baseEntryId: null, context,
cursor: { firstEntryId: null, lastEntryId: null }, hasMore: false, leafId: null,
live: {
cursor: { streamId: "stream", sequence: 2 }, isStreaming: true, isPromptRunning: true, isCompacting: false,
streamingMessage: { role: "assistant", content: [{ type: "text", text: "recovered partial" }] }, toolEvents: [],
},
}) });
started();
}));
const catchUp = createSessionCatchUp({
sessionId: () => "s1", scope: () => "same-run", history() {}, subscribe: () => false,
live(snapshot, fields) { if (fields.message) displayed = snapshot.streamingMessage.content[0].text; },
});
catchUp.seed(context);
catchUp.observe({ type: "connected", web: { streamId: "stream", sequence: 1 } });
const pending = catchUp.request();
await requested;
catchUp.observe({ type: "message_end", message: { role: "user", content: "steering" }, web: { streamId: "stream", sequence: 3 } });
release();
await pending;
assert.equal(displayed, "recovered partial");
});

test("a held full response cannot resurrect truncated entries and fresh catch-up recovers later appends", async (t) => {
let displayed;
let requests = 0;
let release;
let started;
const following = new Promise((resolve) => { started = resolve; });
const context = (ids) => ({
messages: ids.map((id) => ({ role: "user", content: id })),
entryIds: ids, thinkingLevel: "off", model: null, todoPhases: [],
});
t.mock.method(globalThis, "fetch", (url) => {
requests += 1;
const page = (ids, mode, baseEntryId) => ({ ok: true, json: async () => ({
sessionId: "s1", mode, baseEntryId, context: context(ids),
cursor: { firstEntryId: "a", lastEntryId: ids.at(-1) },
hasMore: false, leafId: ids.at(-1), live: null,
}) });
if (requests === 1) return Promise.resolve(page(["a", "b"], "replace", null));
assert.equal(JSON.parse(new URL(url, "http://localhost").searchParams.get("cursor")).lastEntryId, "b");
return new Promise((resolve) => {
release = () => resolve(page(["d"], "append", "b"));
started();
});
});
const catchUp = createSessionCatchUp({
sessionId: () => "s1", scope: () => "same-view",
history(next) { displayed = next; }, live() {}, subscribe: () => false,
});
catchUp.seed(context(["a", "b", "c"]));
const fullReadPosition = catchUp.position();
await catchUp.request();
assert.deepEqual(displayed.entryIds, ["a", "b"]);
catchUp.seed(context(["a", "b", "c"]), fullReadPosition);
assert.deepEqual(displayed.entryIds, ["a", "b"]);
await following;
release();
await new Promise(setImmediate);
assert.deepEqual(displayed.entryIds, ["a", "b", "d"]);
assert.equal(requests, 2);
});
Loading
Loading