From fd3c9cd541eba651be47a15293c614d6640decf0 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:30:32 +0800 Subject: [PATCH 1/7] perf: memoize session list ETag, optimize streaming renders and single-session lookup --- app/api/sessions/[id]/context/route.ts | 31 ++++++---- app/api/sessions/route.ts | 80 +++++++++++++++++++++++++- components/AppShell.tsx | 2 +- components/MessageView.test.mjs | 48 +++++++++++++++- components/MessageView.tsx | 74 +++++++++++++----------- lib/session-reader.ts | 11 +++- lib/session-routes.test.mjs | 67 +++++++++++++++++++++ 7 files changed, 265 insertions(+), 48 deletions(-) diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index ba8c7648f..abd72186d 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { existsSync } from "fs"; import { loadSessionFile } from "@/lib/omp/session-files"; -import { buildSessionContext, getSessionContextBoundary, getSessionEntriesForDisplayAsync, getSessionHistoryPage, readSessionHeader, SessionFileTooLargeError } from "@/lib/session-reader"; +import { buildSessionContext, getSessionContextBoundary, getSessionEntriesForDisplayAsync, getSessionHistoryPage, readSessionHeader, SessionFileMalformedError, 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"; @@ -17,6 +17,12 @@ function contextErrorResponse(error: unknown): NextResponse { { status: 413 }, ); } + if (error instanceof SessionFileMalformedError) { + return NextResponse.json( + { error: "Session file is missing or malformed", code: "session_file_malformed" }, + { status: 404 }, + ); + } return apiErrorResponse(error); } @@ -85,17 +91,6 @@ export async function GET( } const filePath = resolved.filePath; - const header = readSessionHeader(filePath); - if (header === null) { - const loaded = loadSessionFile(filePath, { resolveBlobs: false }); - if (loaded.error === "too_large") { - return NextResponse.json( - { error: "Session file is too large to open in omp-web", code: "session_file_too_large" }, - { status: 413 }, - ); - } - 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" } }); } @@ -114,6 +109,18 @@ export async function GET( const response: SessionSyncResponse = { ...page.history, sessionId: id, leafId: page.leafId, live }; return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } }); } + + const header = readSessionHeader(filePath); + if (header === null) { + const loaded = loadSessionFile(filePath, { resolveBlobs: false }); + if (loaded.error === "too_large") { + return NextResponse.json( + { error: "Session file is too large to open in omp-web", code: "session_file_too_large" }, + { status: 413 }, + ); + } + return NextResponse.json({ error: "Session file is missing or malformed", code: "session_file_malformed" }, { status: 404 }); + } // Deduplicated cached read; blob resolution on per-entry deep copies. const entries = await getSessionEntriesForDisplayAsync(filePath, { skipToolResultImages: deferToolResultImages }); const context = buildSessionContext(entries, leafId, { diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 56af7d8e3..212be6793 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -2,6 +2,36 @@ import { NextResponse } from "next/server"; import { createHash } from "crypto"; import { listAllSessions } from "@/lib/session-reader"; import { getRunningRpcSessions } from "@/lib/rpc-manager"; +import type { SessionInfo } from "@/lib/types"; + +declare global { + var __ompSessionsRouteCache: { + sessionsRef: SessionInfo[] | null; + sessionsSig: string | null; + runningSig: string | null; + bodyJson: string | null; + etag: string | null; + } | undefined; +} + +function getRouteCache() { + return (globalThis.__ompSessionsRouteCache ??= { + sessionsRef: null, + sessionsSig: null, + runningSig: null, + bodyJson: null, + etag: null, + }); +} +function computeSessionsSig(sessions: SessionInfo[]): string { + let sig = `${sessions.length}:`; + for (let i = 0; i < sessions.length; i++) { + const s = sessions[i]; + sig += `${s.id},${s.modified},${s.messageCount},${s.name};`; + } + return sig; +} + // The session list mixes on-disk sessions with the live runningSessionIds set, // which changes on every agent turn, so it must never be cached by proxies or @@ -15,13 +45,61 @@ const SESSION_LIST_HEADERS = { export async function GET(req: Request) { try { + const url = new URL(req.url); + const filterId = "nextUrl" in req && req.nextUrl instanceof URL + ? req.nextUrl.searchParams.get("id") + : url.searchParams.get("id"); + const sessions = await listAllSessions(); const runningSessions = getRunningRpcSessions(); const runningSessionIds = runningSessions.map((s) => s.id); + + if (filterId) { + const matched = sessions.filter((s) => s.id === filterId); + const body = { sessions: matched, runningSessionIds, runningSessions }; + const bodyJson = JSON.stringify(body); + return new NextResponse(bodyJson, { + headers: { "Content-Type": "application/json", ...SESSION_LIST_HEADERS }, + }); + } + + const runningSig = runningSessions + .map((s) => { + const status = "status" in s ? s.status : ""; + const updatedAt = "updatedAt" in s ? s.updatedAt : ""; + const isCompacting = "isCompacting" in s ? s.isCompacting : ""; + return `${s.id}:${status}:${updatedAt}:${isCompacting}:${s.cwd}`; + }) + .join(";"); + const ifNoneMatch = req.headers.get("if-none-match"); + + const cache = getRouteCache(); + if ( + cache.bodyJson !== null && + cache.etag !== null && + cache.runningSig === runningSig && + (cache.sessionsRef === sessions || computeSessionsSig(sessions) === cache.sessionsSig) + ) { + cache.sessionsRef = sessions; + if (ifNoneMatch === cache.etag) { + return new NextResponse(null, { status: 304, headers: { ETag: cache.etag, ...SESSION_LIST_HEADERS } }); + } + return new NextResponse(cache.bodyJson, { + headers: { ETag: cache.etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS }, + }); + } + const body = { sessions, runningSessionIds, runningSessions }; const bodyJson = JSON.stringify(body); const etag = `"${createHash("sha1").update(bodyJson).digest("hex").slice(0, 16)}"`; - if (req.headers.get("if-none-match") === etag) { + + cache.sessionsRef = sessions; + cache.sessionsSig = computeSessionsSig(sessions); + cache.runningSig = runningSig; + cache.bodyJson = bodyJson; + cache.etag = etag; + + if (ifNoneMatch === etag) { return new NextResponse(null, { status: 304, headers: { ETag: etag, ...SESSION_LIST_HEADERS } }); } return new NextResponse(bodyJson, { headers: { ETag: etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS } }); diff --git a/components/AppShell.tsx b/components/AppShell.tsx index a0ea786a4..bd84b5b54 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1288,7 +1288,7 @@ export function AppShell({ appName }: { appName: string }) { // list itself could not be fetched (keep the entry, abort this navigation). const fetchSessionForNavigation = useCallback(async (sessionId: string): Promise => { try { - const res = await fetch("/api/sessions"); + const res = await fetch(`/api/sessions?id=${encodeURIComponent(sessionId)}`); if (!res.ok) return "unavailable"; const data = (await res.json()) as { sessions?: SessionInfo[] }; return data.sessions?.find((s) => s.id === sessionId) ?? null; diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 3789df1fd..283648ea2 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -10,7 +10,7 @@ const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true, }); -const { MessageView, SafeMarkdownBody, TaskResultPanel, isInterruptedMessage } = await jiti.import("./MessageView.tsx"); +const { MessageView, SafeMarkdownBody, TaskResultPanel, isInterruptedMessage, areMessageViewPropsEqual, haveSameRelevantToolResults } = await jiti.import("./MessageView.tsx"); const { CodeBlock } = await jiti.import("./MermaidBlock.tsx"); const { buildSessionContext } = await jiti.import("../lib/session-reader.ts"); const { collectToolResults, planTranscriptRows } = await jiti.import("../lib/chat-transcript-plan.ts"); @@ -950,3 +950,49 @@ test("user messages fork at their own entry and edit the prompt", async (t) => { assert.deepEqual(forked, [["user-7", true]]); view.unmount(); }); + +test("SafeMarkdownBody is wrapped in React.memo", () => { + assert.equal(typeof SafeMarkdownBody, "object"); + assert.ok(SafeMarkdownBody.$$typeof, "SafeMarkdownBody should have a React component symbol"); +}); + +test("areMessageViewPropsEqual skips re-render when unrelated toolResults change", () => { + const msg1 = { + role: "assistant", + content: [ + { type: "text", text: "Running tool..." }, + { type: "toolCall", toolCallId: "call-1", toolName: "read", input: { path: "a.ts" } }, + ], + }; + const res1 = { role: "toolResult", toolCallId: "call-1", content: "file content" }; + const res2 = { role: "toolResult", toolCallId: "call-2", content: "another content" }; + + const mapA = new Map([["call-1", res1]]); + const mapB = new Map([["call-1", res1], ["call-2", res2]]); + const mapC = new Map([["call-1", { ...res1, content: "modified" }]]); + + const baseProps = { message: msg1, toolResults: mapA }; + // New tool in mapB is unrelated to msg1: props should be considered equal + assert.equal(areMessageViewPropsEqual(baseProps, { ...baseProps, toolResults: mapB }), true); + // Change in msg1's own tool: props should NOT be equal + assert.equal(areMessageViewPropsEqual(baseProps, { ...baseProps, toolResults: mapC }), false); +}); + +test("haveSameRelevantToolResults supports tool_use and tool_call block formats", () => { + const msg = { + role: "assistant", + content: [ + { type: "tool_use", id: "tool-u1", name: "bash", input: {} }, + { type: "tool_call", id: "tool-c1", name: "glob", input: {} }, + ], + }; + const resU1 = { role: "toolResult", toolCallId: "tool-u1", content: "done" }; + const resC1 = { role: "toolResult", toolCallId: "tool-c1", content: "done" }; + + const map1 = new Map([["tool-u1", resU1], ["tool-c1", resC1]]); + const map2 = new Map([["tool-u1", resU1], ["tool-c1", resC1], ["tool-other", { role: "toolResult", toolCallId: "tool-other", content: "x" }]]); + const map3 = new Map([["tool-u1", { ...resU1, content: "changed" }], ["tool-c1", resC1]]); + + assert.equal(haveSameRelevantToolResults(msg, map1, map2), true); + assert.equal(haveSameRelevantToolResults(msg, map1, map3), false); +}); diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 82f65b5a1..9d347e6be 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -93,7 +93,7 @@ function formatMessageSize(chars: number): string { return chars >= 1_000_000 ? `${(chars / 1_000_000).toFixed(1)} MB` : `${Math.round(chars / 1_000)} KB`; } -export function SafeMarkdownBody({ children, className, ...props }: ComponentProps) { +export const SafeMarkdownBody = memo(function SafeMarkdownBody({ children, className, ...props }: ComponentProps) { const { t } = useI18n(); const [showRaw, setShowRaw] = useState(false); @@ -120,7 +120,7 @@ export function SafeMarkdownBody({ children, className, ...props }: ComponentPro ); -} +}); function loadThinkingContent(sessionId: string, entryId: string, blockIndex: number): Promise { const key = `${sessionId}:${entryId}:${blockIndex}`; @@ -196,20 +196,54 @@ function formatTime(ts: number | undefined, locale: Locale): string | null { return `${date} ${time}`; } -function haveSameRelevantToolResults( +export function haveSameRelevantToolResults( message: AgentMessage, previous: Map | undefined, next: Map | undefined, ): boolean { - if (previous === next || message.role !== "assistant") return true; - for (const block of (message as AssistantMessage).content ?? []) { - if (block.type === "toolCall" && previous?.get(block.toolCallId) !== next?.get(block.toolCallId)) { - return false; + if (previous === next) return true; + if (message.role !== "assistant") return true; + const content = (message as AssistantMessage).content; + if (!Array.isArray(content)) return true; + for (const block of content) { + if (!block || typeof block !== "object") continue; + const b = block as unknown as Record; + if (b.type === "toolCall" || b.type === "tool_use" || b.type === "tool_call") { + const id = typeof b.id === "string" ? b.id : typeof b.toolCallId === "string" ? b.toolCallId : undefined; + if (id && previous?.get(id) !== next?.get(id)) { + return false; + } } } return true; } +export function areMessageViewPropsEqual(prev: Props, next: Props): boolean { + return Object.is(prev.message, next.message) + && Object.is(prev.isStreaming, next.isStreaming) + && haveSameRelevantToolResults(prev.message, prev.toolResults, next.toolResults) + && Object.is(prev.modelNames, next.modelNames) + && Object.is(prev.cwd, next.cwd) + && Object.is(prev.onOpenFile, next.onOpenFile) + && Object.is(prev.entryId, next.entryId) + && Object.is(prev.forkEntryId, next.forkEntryId) + && Object.is(prev.forkEditsPrompt, next.forkEditsPrompt) + && Object.is(prev.onFork, next.onFork) + && Object.is(prev.forking, next.forking) + && Object.is(prev.forkDisabled, next.forkDisabled) + && Object.is(prev.onEdit, next.onEdit) + && Object.is(prev.editing, next.editing) + && Object.is(prev.editDisabled, next.editDisabled) + && Object.is(prev.showTimestamp, next.showTimestamp) + && Object.is(prev.prevTimestamp, next.prevTimestamp) + && Object.is(prev.sessionId, next.sessionId) + && Object.is(prev.toolCallsDefaultCollapsed, next.toolCallsDefaultCollapsed) + && Object.is(prev.expandThinkingByDefault, next.expandThinkingByDefault) + && Object.is(prev.hideThinking, next.hideThinking) + && prev.sourceBlockIndices?.join() === next.sourceBlockIndices?.join() + && (!prev.isStreaming || Object.is(prev.liveTokensPerSecond, next.liveTokensPerSecond)); +} + export const MessageView = memo(function MessageView({ message, isStreaming, toolResults, modelNames, cwd, onOpenFile, entryId, forkEntryId, forkEditsPrompt, onFork, forking, forkDisabled, onEdit, editing, editDisabled, showTimestamp, prevTimestamp, sessionId, toolCallsDefaultCollapsed = true, expandThinkingByDefault = false, hideThinking = false, sourceBlockIndices, liveTokensPerSecond }: Props) { if (message.role === "user") { return ; @@ -238,31 +272,7 @@ export const MessageView = memo(function MessageView({ message, isStreaming, too return ; } return null; -}, (prev, next) => { - return prev.message === next.message - && prev.isStreaming === next.isStreaming - && haveSameRelevantToolResults(prev.message, prev.toolResults, next.toolResults) - && prev.modelNames === next.modelNames - && prev.cwd === next.cwd - && prev.onOpenFile === next.onOpenFile - && prev.entryId === next.entryId - && prev.forkEntryId === next.forkEntryId - && prev.forkEditsPrompt === next.forkEditsPrompt - && prev.onFork === next.onFork - && prev.forking === next.forking - && prev.forkDisabled === next.forkDisabled - && prev.onEdit === next.onEdit - && prev.editing === next.editing - && prev.editDisabled === next.editDisabled - && prev.showTimestamp === next.showTimestamp - && prev.prevTimestamp === next.prevTimestamp - && prev.sessionId === next.sessionId - && prev.toolCallsDefaultCollapsed === next.toolCallsDefaultCollapsed - && prev.expandThinkingByDefault === next.expandThinkingByDefault - && prev.hideThinking === next.hideThinking - && prev.sourceBlockIndices?.join() === next.sourceBlockIndices?.join() - && (!prev.isStreaming || prev.liveTokensPerSecond === next.liveTokensPerSecond); -}); +}, areMessageViewPropsEqual); // lib/types.ts ImageContent uses the Anthropic-style {source:{type,data,media_type,url}} // shape; pi-ai on-disk format uses flat {data, mimeType} — handle both. diff --git a/lib/session-reader.ts b/lib/session-reader.ts index d62f3d39f..d1b573c2e 100644 --- a/lib/session-reader.ts +++ b/lib/session-reader.ts @@ -439,6 +439,14 @@ export class SessionFileTooLargeError extends Error { this.name = "SessionFileTooLargeError"; } } +export class SessionFileMalformedError extends Error { + readonly code = "session_file_malformed" as const; + constructor(filePath: string) { + super(`Session file is missing or malformed: ${filePath}`); + this.name = "SessionFileMalformedError"; + } +} + /** * Display-path entry read for the session/context routes: reuses the memoized @@ -634,6 +642,7 @@ function buildHistoryIndex( }, }); if (loaded.error === "too_large") throw new SessionFileTooLargeError(filePath); + if (!loaded.header) throw new SessionFileMalformedError(filePath); const { selected, compactionId, ...metadata } = selectSessionContext(loaded.entries, leafId, { includePreCompaction }); const rows = selected.map((entry): HistoryEntryRange => ({ id: entry.id, @@ -737,7 +746,7 @@ export function getSessionHistoryPage( } rawEntries.push(entry); } - if (historyFileVersion(fstatSync(fd)) !== version || historyFileVersion(statSync(filePath)) !== version) { + if (historyFileVersion(fstatSync(fd)) !== version) { throw new Error("Session changed while reading history"); } } catch (error) { diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5d966ed28..5e4ec1e7a 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -18,6 +18,7 @@ const contextRoute = await jiti.import("../app/api/sessions/[id]/context/route.t const importRoute = await jiti.import("../app/api/sessions/import/route.ts"); const stateRoute = await jiti.import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/route.ts"); +const sessionsListRoute = await jiti.import("../app/api/sessions/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await jiti.import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await jiti.import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await jiti.import("./rpc-manager.ts"); @@ -704,3 +705,69 @@ test("automatic title fallback cannot write after Edit takes over", async () => } }); }); + +test("GET /api/sessions memoizes payload and ETag across unchanged session list and running state", async () => { + await withAgentDir(async (dir) => { + const id1 = "session-etag-1"; + writeSessionFile(dir, "session-1.jsonl", { id: id1, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "hello 1" } }, + ]); + globalThis.__ompSessionsRouteCache = undefined; + + const res1 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(res1.status, 200); + const etag1 = res1.headers.get("etag"); + assert.ok(etag1, "initial request must produce an ETag"); + + // Conditional request with matching ETag returns 304 without recomputing + const res2 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions", { + headers: { "if-none-match": etag1 }, + })); + assert.equal(res2.status, 304); + assert.equal(res2.headers.get("etag"), etag1); + + // Subsequent unconditional request returns same cached ETag + const res3 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(res3.status, 200); + assert.equal(res3.headers.get("etag"), etag1); + + // Running sessions change invalidates ETag + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([["running-1", { isRunning: () => true, cwd: dir, isAlive: () => true }]]); + try { + const res4 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(res4.status, 200); + assert.notEqual(res4.headers.get("etag"), etag1, "running state change must invalidate ETag"); + } finally { + globalThis.__ompSessions = previousSessions; + globalThis.__ompSessionsRouteCache = undefined; + } + }); +}); + +test("GET /api/sessions?id= returns only the requested session for navigation", async () => { + await withAgentDir(async (dir) => { + const id1 = "session-target"; + const id2 = "session-other"; + writeSessionFile(dir, "target.jsonl", { id: id1, cwd: dir }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "target" } }, + ]); + writeSessionFile(dir, "other.jsonl", { id: id2, cwd: dir }, [ + { type: "message", id: "u2", parentId: null, message: { role: "user", content: "other" } }, + ]); + globalThis.__ompSessionsRouteCache = undefined; + + // Filtered request + const res = await sessionsListRoute.GET(new Request(`http://localhost/api/sessions?id=${id1}`)); + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.sessions.length, 1); + assert.equal(data.sessions[0].id, id1); + + // Non-existent id returns empty sessions array + const resNone = await sessionsListRoute.GET(new Request("http://localhost/api/sessions?id=nonexistent-id")); + assert.equal(resNone.status, 200); + const dataNone = await resNone.json(); + assert.deepEqual(dataNone.sessions, []); + }); +}); From a7b9c8da0c0e320003b1a13e33e01e0543de52c3 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 31 Oct 2026 23:42:15 +0800 Subject: [PATCH 2/7] fix(sessions): include all serialized fields in computeSessionsSig and test invalidation --- app/api/sessions/route.ts | 2 +- lib/session-routes.test.mjs | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 212be6793..7b3ecabde 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -27,7 +27,7 @@ function computeSessionsSig(sessions: SessionInfo[]): string { let sig = `${sessions.length}:`; for (let i = 0; i < sessions.length; i++) { const s = sessions[i]; - sig += `${s.id},${s.modified},${s.messageCount},${s.name};`; + sig += `${JSON.stringify([s.id, s.path, s.cwd, s.modified, s.messageCount, s.name, s.firstMessage, s.lastMessageAt ?? null, s.projectRoot, s.worktreeBranch ?? null, s.parentSessionId ?? null])};`; } return sig; } diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5e4ec1e7a..d077b7121 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -745,6 +745,58 @@ test("GET /api/sessions memoizes payload and ETag across unchanged session list }); }); +test("GET /api/sessions invalidates ETag and returns 200 when worktreeBranch or projectRoot changes", async () => { + await withAgentDir(async (dir) => { + const id1 = "session-branch-invalidation"; + writeSessionFile(dir, "session-branch.jsonl", { id: id1, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "branch test" } }, + ]); + globalThis.__ompSessionsRouteCache = undefined; + + const res1 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(res1.status, 200); + const etag1 = res1.headers.get("etag"); + assert.ok(etag1, "initial request must produce an ETag"); + + // Simulate updating worktreeBranch on the cached session list + invalidateSessionListCache(); + const sessionsList = await listAllSessions(); + const modifiedSessions = sessionsList.map((s) => (s.id === id1 ? { ...s, worktreeBranch: "feature/foo" } : s)); + globalThis.__piSessionListCache = { + data: modifiedSessions, + ts: Date.now(), + }; + + const resBranch = await sessionsListRoute.GET(new Request("http://localhost/api/sessions", { + headers: { "if-none-match": etag1 }, + })); + assert.equal(resBranch.status, 200, "worktreeBranch change must invalidate ETag and return 200"); + const etagBranch = resBranch.headers.get("etag"); + assert.notEqual(etagBranch, etag1); + const dataBranch = await resBranch.json(); + assert.equal(dataBranch.sessions.find((s) => s.id === id1)?.worktreeBranch, "feature/foo"); + + // Simulate updating projectRoot on the cached session list + const modifiedProjectRoot = modifiedSessions.map((s) => (s.id === id1 ? { ...s, projectRoot: "/new/project/root" } : s)); + globalThis.__piSessionListCache = { + data: modifiedProjectRoot, + ts: Date.now(), + }; + + const resProjectRoot = await sessionsListRoute.GET(new Request("http://localhost/api/sessions", { + headers: { "if-none-match": etagBranch }, + })); + assert.equal(resProjectRoot.status, 200, "projectRoot change must invalidate ETag and return 200"); + const etagProjectRoot = resProjectRoot.headers.get("etag"); + assert.notEqual(etagProjectRoot, etagBranch); + const dataProjectRoot = await resProjectRoot.json(); + assert.equal(dataProjectRoot.sessions.find((s) => s.id === id1)?.projectRoot, "/new/project/root"); + + globalThis.__ompSessionsRouteCache = undefined; + invalidateSessionListCache(); + }); +}); + test("GET /api/sessions?id= returns only the requested session for navigation", async () => { await withAgentDir(async (dir) => { const id1 = "session-target"; From b2f9fd5df5aca40519b30e4906151d17fb3d18a3 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:14:18 +0800 Subject: [PATCH 3/7] fix(sessions): include running session hostId in ETag signature --- app/api/sessions/route.ts | 2 +- lib/session-routes.test.mjs | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 45065fa4f..848e37847 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -80,7 +80,7 @@ export async function GET(req: Request) { const status = "status" in s ? s.status : ""; const updatedAt = "updatedAt" in s ? s.updatedAt : ""; const isCompacting = "isCompacting" in s ? s.isCompacting : ""; - return `${s.id}:${status}:${updatedAt}:${isCompacting}:${s.cwd}`; + return `${s.id}:${status}:${updatedAt}:${isCompacting}:${s.cwd}:${s.hostId ?? ""}`; }) .join(";"); const ifNoneMatch = req.headers.get("if-none-match"); diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 1eff43f8f..b235f143c 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -799,7 +799,26 @@ test("GET /api/sessions memoizes payload and ETag across unchanged session list try { const res4 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); assert.equal(res4.status, 200); - assert.notEqual(res4.headers.get("etag"), etag1, "running state change must invalidate ETag"); + const etag4 = res4.headers.get("etag"); + assert.notEqual(etag4, etag1, "running state change must invalidate ETag"); + + // Conditional request with matching etag4 returns 304 + const resCond = await sessionsListRoute.GET(new Request("http://localhost/api/sessions", { + headers: { "if-none-match": etag4 }, + })); + assert.equal(resCond.status, 304); + + // Running session hostId change (while id and cwd stay the same) invalidates ETag + globalThis.__ompSessions = new Map([ + ["running-1", { isRunning: () => true, cwd: dir, isAlive: () => true, host: { id: "remote-worker-1" } }], + ]); + const resHostChange = await sessionsListRoute.GET(new Request("http://localhost/api/sessions", { + headers: { "if-none-match": etag4 }, + })); + assert.equal(resHostChange.status, 200, "running session hostId change must invalidate ETag and return 200"); + assert.notEqual(resHostChange.headers.get("etag"), etag4); + const dataHostChange = await resHostChange.json(); + assert.equal(dataHostChange.runningSessions.find((s) => s.id === "running-1")?.hostId, "remote-worker-1"); } finally { globalThis.__ompSessions = previousSessions; globalThis.__ompSessionsRouteCache = undefined; From 1792da2f72505853e1124807098ef16a48e3480d Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:21:50 +0800 Subject: [PATCH 4/7] test(sessions): include local host mock on running session fixture --- lib/session-routes.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 772455382..c4863d153 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -825,7 +825,7 @@ test("GET /api/sessions memoizes payload and ETag across unchanged session list // Running sessions change invalidates ETag const previousSessions = globalThis.__ompSessions; - globalThis.__ompSessions = new Map([["running-1", { isRunning: () => true, cwd: dir, isAlive: () => true }]]); + globalThis.__ompSessions = new Map([["running-1", { isRunning: () => true, cwd: dir, isAlive: () => true, host: { id: "local" } }]]); try { const res4 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); assert.equal(res4.status, 200); From 637e935f7b9bc1e2063fbe19ffb9a1a0f92905d3 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:15:19 +0800 Subject: [PATCH 5/7] fix(sessions,chat): prefer toolCallId in comparator and simplify sessions route --- app/api/sessions/route.ts | 86 ++------------------------------- components/MessageView.test.mjs | 36 ++++++++++++++ components/MessageView.tsx | 2 +- lib/hosts/session-ops.ts | 3 +- lib/rpc-manager.ts | 3 +- lib/session-reader.ts | 11 +---- lib/session-routes.test.mjs | 7 +-- 7 files changed, 46 insertions(+), 102 deletions(-) diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 848e37847..e747f79d7 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -1,49 +1,6 @@ import { createHash } from "crypto"; import { listSessionsAllHosts } from "@/lib/hosts/session-index"; import { getRunningRpcSessions } from "@/lib/rpc-manager"; -import type { SessionInfo } from "@/lib/types"; - -declare global { - var __ompSessionsRouteCache: { - sessionsRef: SessionInfo[] | null; - sessionsSig: string | null; - runningSig: string | null; - bodyJson: string | null; - etag: string | null; - } | undefined; -} - -function getRouteCache() { - return (globalThis.__ompSessionsRouteCache ??= { - sessionsRef: null, - sessionsSig: null, - runningSig: null, - bodyJson: null, - etag: null, - }); -} - -function computeSessionsSig(sessions: SessionInfo[]): string { - let sig = `${sessions.length}:`; - for (let i = 0; i < sessions.length; i++) { - const s = sessions[i]; - sig += `${JSON.stringify([ - s.id, - s.path, - s.cwd, - s.modified, - s.messageCount, - s.name, - s.firstMessage, - s.lastMessageAt ?? null, - s.projectRoot, - s.worktreeBranch ?? null, - s.parentSessionId ?? null, - s.hostId ?? null, - ])};`; - } - return sig; -} // The session list mixes on-disk sessions with the live runningSessionIds set, // which changes on every agent turn, so it must never be cached by proxies or @@ -57,10 +14,7 @@ const SESSION_LIST_HEADERS = { export async function GET(req: Request) { try { - const url = new URL(req.url); - const filterId = "nextUrl" in req && req.nextUrl instanceof URL - ? req.nextUrl.searchParams.get("id") - : url.searchParams.get("id"); + const filterId = new URL(req.url).searchParams.get("id"); const sessions = await listSessionsAllHosts(); const runningSessions = getRunningRpcSessions(); @@ -75,46 +29,16 @@ export async function GET(req: Request) { }); } - const runningSig = runningSessions - .map((s) => { - const status = "status" in s ? s.status : ""; - const updatedAt = "updatedAt" in s ? s.updatedAt : ""; - const isCompacting = "isCompacting" in s ? s.isCompacting : ""; - return `${s.id}:${status}:${updatedAt}:${isCompacting}:${s.cwd}:${s.hostId ?? ""}`; - }) - .join(";"); - const ifNoneMatch = req.headers.get("if-none-match"); - - const cache = getRouteCache(); - if ( - cache.bodyJson !== null && - cache.etag !== null && - cache.runningSig === runningSig && - (cache.sessionsRef === sessions || computeSessionsSig(sessions) === cache.sessionsSig) - ) { - cache.sessionsRef = sessions; - if (ifNoneMatch === cache.etag) { - return new Response(null, { status: 304, headers: { ETag: cache.etag, ...SESSION_LIST_HEADERS } }); - } - return new Response(cache.bodyJson, { - headers: { ETag: cache.etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS }, - }); - } - const body = { sessions, runningSessionIds, runningSessions }; const bodyJson = JSON.stringify(body); const etag = `"${createHash("sha1").update(bodyJson).digest("hex").slice(0, 16)}"`; - cache.sessionsRef = sessions; - cache.sessionsSig = computeSessionsSig(sessions); - cache.runningSig = runningSig; - cache.bodyJson = bodyJson; - cache.etag = etag; - - if (ifNoneMatch === etag) { + if (req.headers.get("if-none-match") === etag) { return new Response(null, { status: 304, headers: { ETag: etag, ...SESSION_LIST_HEADERS } }); } - return new Response(bodyJson, { headers: { ETag: etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS } }); + return new Response(bodyJson, { + headers: { ETag: etag, "Content-Type": "application/json", ...SESSION_LIST_HEADERS }, + }); } catch (error) { return Response.json( { error: error instanceof Error ? error.message : String(error), code: "internal_error" }, diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 124322685..79dcad2e6 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -1075,6 +1075,42 @@ test("haveSameRelevantToolResults supports tool_use and tool_call block formats" assert.equal(haveSameRelevantToolResults(msg, map1, map2), true); assert.equal(haveSameRelevantToolResults(msg, map1, map3), false); }); +test("haveSameRelevantToolResults and MessageView re-render look up hybrid toolCall blocks by toolCallId over id", () => { + const hybridMsg = { + role: "assistant", + content: [ + { type: "toolCall", id: "fc_item_1", toolCallId: "call_A", toolName: "bash", input: {} }, + ], + }; + const resA1 = { role: "toolResult", toolCallId: "call_A", content: [{ type: "text", text: "initial output" }] }; + const resA2 = { role: "toolResult", toolCallId: "call_A", content: [{ type: "text", text: "updated output" }] }; + const resLegacyId = { role: "toolResult", toolCallId: "fc_item_1", content: [{ type: "text", text: "wrong lookup" }] }; + + const mapA1 = new Map([["call_A", resA1], ["fc_item_1", resLegacyId]]); + const mapA1Same = new Map([["call_A", resA1], ["fc_item_1", { ...resLegacyId, content: [{ type: "text", text: "changed legacy" }] }]]); + const mapA2 = new Map([["call_A", resA2], ["fc_item_1", resLegacyId]]); + + // Looking up by toolCallId ("call_A") means changing legacy "fc_item_1" does NOT trigger difference + assert.equal(haveSameRelevantToolResults(hybridMsg, mapA1, mapA1Same), true); + // Changing "call_A" returns false + assert.equal(haveSameRelevantToolResults(hybridMsg, mapA1, mapA2), false); + + // Verify MessageView re-renders with updated tool result when toolResults changes for "call_A" + const initialProps = { + isStreaming: true, + toolCallsDefaultCollapsed: false, + message: hybridMsg, + toolResults: mapA1, + }; + const { container, rerender } = render(React.createElement(MessageView, initialProps)); + assert.match(container.textContent, /initial output/); + assert.doesNotMatch(container.textContent, /wrong lookup/); + + rerender(React.createElement(MessageView, { ...initialProps, toolResults: mapA2 })); + assert.match(container.textContent, /updated output/); + assert.doesNotMatch(container.textContent, /initial output/); +}); + test("user-message Edit only runs after confirmation, and not once blocked", async (t) => { const originalMatchMedia = window.matchMedia; diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 94d95f760..74ece0511 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -212,7 +212,7 @@ export function haveSameRelevantToolResults( if (!block || typeof block !== "object") continue; const b = block as unknown as Record; if (b.type === "toolCall" || b.type === "tool_use" || b.type === "tool_call") { - const id = typeof b.id === "string" ? b.id : typeof b.toolCallId === "string" ? b.toolCallId : undefined; + const id = typeof b.toolCallId === "string" ? b.toolCallId : typeof b.id === "string" ? b.id : undefined; if (id && previous?.get(id) !== next?.get(id)) { return false; } diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index 2358a784f..4104e004c 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -50,7 +50,6 @@ import { resolveParentSessionId, resolveSessionIdByPath, resolveSessionPath, - SessionFileMalformedError, SessionFileTooLargeError, } from "../session-reader"; import type { SessionHistoryCursor } from "../session-sync"; @@ -356,8 +355,8 @@ export const sessionOps: SessionOps = { return ok({ context }); } catch (error) { // Past the load ceiling: the same 413 as the null-header path, not a + // 500, so the frontend does not treat history as gone. if (error instanceof SessionFileTooLargeError) return sessionTooLarge(); - if (error instanceof SessionFileMalformedError) return fail(404, "session_file_malformed", "Session file is missing or malformed"); throw error; } }, diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 7fcc496dc..9436d4df2 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -3139,8 +3139,7 @@ export function getRunningRpcSessions(): RunningRpcSession[] { for (const [sessionId, session] of getRegistry()) { if (session.isRunning()) { const id = session.sessionId || sessionId; - const hostId = session.host?.id; - map.set(id, { id, cwd: session.cwd, ...(!hostId || hostId === LOCAL_HOST_ID ? {} : { hostId }) }); + map.set(id, { id, cwd: session.cwd, ...(session.host.id === LOCAL_HOST_ID ? {} : { hostId: session.host.id }) }); } } return [...map.values()]; diff --git a/lib/session-reader.ts b/lib/session-reader.ts index d1b573c2e..d62f3d39f 100644 --- a/lib/session-reader.ts +++ b/lib/session-reader.ts @@ -439,14 +439,6 @@ export class SessionFileTooLargeError extends Error { this.name = "SessionFileTooLargeError"; } } -export class SessionFileMalformedError extends Error { - readonly code = "session_file_malformed" as const; - constructor(filePath: string) { - super(`Session file is missing or malformed: ${filePath}`); - this.name = "SessionFileMalformedError"; - } -} - /** * Display-path entry read for the session/context routes: reuses the memoized @@ -642,7 +634,6 @@ function buildHistoryIndex( }, }); if (loaded.error === "too_large") throw new SessionFileTooLargeError(filePath); - if (!loaded.header) throw new SessionFileMalformedError(filePath); const { selected, compactionId, ...metadata } = selectSessionContext(loaded.entries, leafId, { includePreCompaction }); const rows = selected.map((entry): HistoryEntryRange => ({ id: entry.id, @@ -746,7 +737,7 @@ export function getSessionHistoryPage( } rawEntries.push(entry); } - if (historyFileVersion(fstatSync(fd)) !== version) { + if (historyFileVersion(fstatSync(fd)) !== version || historyFileVersion(statSync(filePath)) !== version) { throw new Error("Session changed while reading history"); } } catch (error) { diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index c4863d153..56a8f316f 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -798,13 +798,12 @@ test("automatic title fallback cannot write after Edit takes over", async () => }); }); -test("GET /api/sessions memoizes payload and ETag across unchanged session list and running state", async () => { +test("GET /api/sessions returns ETag and 304 across unchanged session list and running state", async () => { await withAgentDir(async (dir) => { const id1 = "0a000000-0000-4000-8000-000000000071"; writeSessionFile(dir, "session-1.jsonl", { id: id1, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ { type: "message", id: "u1", parentId: null, message: { role: "user", content: "hello 1" } }, ]); - globalThis.__ompSessionsRouteCache = undefined; const res1 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); assert.equal(res1.status, 200); @@ -851,7 +850,6 @@ test("GET /api/sessions memoizes payload and ETag across unchanged session list assert.equal(dataHostChange.runningSessions.find((s) => s.id === "running-1")?.hostId, "remote-worker-1"); } finally { globalThis.__ompSessions = previousSessions; - globalThis.__ompSessionsRouteCache = undefined; } }); }); @@ -862,7 +860,6 @@ test("GET /api/sessions invalidates ETag and returns 200 when worktreeBranch or writeSessionFile(dir, "session-branch.jsonl", { id: id1, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ { type: "message", id: "u1", parentId: null, message: { role: "user", content: "branch test" } }, ]); - globalThis.__ompSessionsRouteCache = undefined; const res1 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); assert.equal(res1.status, 200); @@ -905,7 +902,6 @@ test("GET /api/sessions invalidates ETag and returns 200 when worktreeBranch or const dataProjectRoot = await resProjectRoot.json(); assert.equal(dataProjectRoot.sessions.find((s) => s.id === id1)?.projectRoot, "/new/project/root"); - globalThis.__ompSessionsRouteCache = undefined; invalidateSessionListCache(); }); }); @@ -920,7 +916,6 @@ test("GET /api/sessions?id= returns only the requested session for na writeSessionFile(dir, "other.jsonl", { id: id2, cwd: dir }, [ { type: "message", id: "u2", parentId: null, message: { role: "user", content: "other" } }, ]); - globalThis.__ompSessionsRouteCache = undefined; // Filtered request const res = await sessionsListRoute.GET(new Request(`http://localhost/api/sessions?id=${id1}`)); From ed5e05326a467c3c6cc50953af5d3afb4f06a3c2 Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:36:53 +0800 Subject: [PATCH 6/7] fix(chat): simplify toolCall comparator and verify React.memo symbol --- components/MessageView.test.mjs | 21 +-------------------- components/MessageView.tsx | 6 ++---- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 79dcad2e6..66c426d75 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -1031,8 +1031,7 @@ test("user messages fork at their own entry and edit the prompt", async (t) => { }); test("SafeMarkdownBody is wrapped in React.memo", () => { - assert.equal(typeof SafeMarkdownBody, "object"); - assert.ok(SafeMarkdownBody.$$typeof, "SafeMarkdownBody should have a React component symbol"); + assert.equal(SafeMarkdownBody.$$typeof, React.memo(() => null).$$typeof); }); test("areMessageViewPropsEqual skips re-render when unrelated toolResults change", () => { @@ -1057,24 +1056,6 @@ test("areMessageViewPropsEqual skips re-render when unrelated toolResults change assert.equal(areMessageViewPropsEqual(baseProps, { ...baseProps, toolResults: mapC }), false); }); -test("haveSameRelevantToolResults supports tool_use and tool_call block formats", () => { - const msg = { - role: "assistant", - content: [ - { type: "tool_use", id: "tool-u1", name: "bash", input: {} }, - { type: "tool_call", id: "tool-c1", name: "glob", input: {} }, - ], - }; - const resU1 = { role: "toolResult", toolCallId: "tool-u1", content: "done" }; - const resC1 = { role: "toolResult", toolCallId: "tool-c1", content: "done" }; - - const map1 = new Map([["tool-u1", resU1], ["tool-c1", resC1]]); - const map2 = new Map([["tool-u1", resU1], ["tool-c1", resC1], ["tool-other", { role: "toolResult", toolCallId: "tool-other", content: "x" }]]); - const map3 = new Map([["tool-u1", { ...resU1, content: "changed" }], ["tool-c1", resC1]]); - - assert.equal(haveSameRelevantToolResults(msg, map1, map2), true); - assert.equal(haveSameRelevantToolResults(msg, map1, map3), false); -}); test("haveSameRelevantToolResults and MessageView re-render look up hybrid toolCall blocks by toolCallId over id", () => { const hybridMsg = { role: "assistant", diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 74ece0511..46f88f85c 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -210,10 +210,8 @@ export function haveSameRelevantToolResults( if (!Array.isArray(content)) return true; for (const block of content) { if (!block || typeof block !== "object") continue; - const b = block as unknown as Record; - if (b.type === "toolCall" || b.type === "tool_use" || b.type === "tool_call") { - const id = typeof b.toolCallId === "string" ? b.toolCallId : typeof b.id === "string" ? b.id : undefined; - if (id && previous?.get(id) !== next?.get(id)) { + if (block.type === "toolCall" && block.toolCallId) { + if (previous?.get(block.toolCallId) !== next?.get(block.toolCallId)) { return false; } } From df85963ca895faad1c4f093a53df7db8aebd38ac Mon Sep 17 00:00:00 2001 From: Tanger <49036591+GTanger@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:06:28 +0800 Subject: [PATCH 7/7] fix(chat): compare toolResults for empty toolCallId and add regression test --- components/MessageView.test.mjs | 32 ++++++++++++++++++++++++++++++++ components/MessageView.tsx | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 66c426d75..664d62756 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -1092,6 +1092,38 @@ test("haveSameRelevantToolResults and MessageView re-render look up hybrid toolC assert.doesNotMatch(container.textContent, /initial output/); }); +test("haveSameRelevantToolResults and areMessageViewPropsEqual handle toolCall with empty string toolCallId", () => { + const emptyIdMsg = { + role: "assistant", + content: [ + { type: "toolCall", toolCallId: "", toolName: "bash", input: {} }, + ], + }; + const resEmpty1 = { role: "toolResult", toolCallId: "", content: [{ type: "text", text: "empty id output 1" }] }; + const resEmpty2 = { role: "toolResult", toolCallId: "", content: [{ type: "text", text: "empty id output 2" }] }; + const resUnrelated = { role: "toolResult", toolCallId: "other", content: [{ type: "text", text: "other" }] }; + + const mapEmpty1 = new Map([["", resEmpty1]]); + const mapEmpty2 = new Map([["", resEmpty2]]); + const mapEmpty1WithUnrelated = new Map([["", resEmpty1], ["other", resUnrelated]]); + const mapEmptyWithoutResult = new Map(); + + // Adding a result under "" causes unequal comparison + assert.equal(haveSameRelevantToolResults(emptyIdMsg, mapEmptyWithoutResult, mapEmpty1), false); + // Updating result under "" causes unequal comparison + assert.equal(haveSameRelevantToolResults(emptyIdMsg, mapEmpty1, mapEmpty2), false); + // Unrelated key changing while "" is unchanged causes equal comparison + assert.equal(haveSameRelevantToolResults(emptyIdMsg, mapEmpty1, mapEmpty1WithUnrelated), true); + + const baseProps = { + isStreaming: false, + message: emptyIdMsg, + toolResults: mapEmpty1, + }; + assert.equal(areMessageViewPropsEqual(baseProps, { ...baseProps, toolResults: mapEmpty2 }), false); + assert.equal(areMessageViewPropsEqual(baseProps, { ...baseProps, toolResults: mapEmpty1WithUnrelated }), true); +}); + test("user-message Edit only runs after confirmation, and not once blocked", async (t) => { const originalMatchMedia = window.matchMedia; diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 46f88f85c..835cea25f 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -210,7 +210,7 @@ export function haveSameRelevantToolResults( if (!Array.isArray(content)) return true; for (const block of content) { if (!block || typeof block !== "object") continue; - if (block.type === "toolCall" && block.toolCallId) { + if (block.type === "toolCall") { if (previous?.get(block.toolCallId) !== next?.get(block.toolCallId)) { return false; }