diff --git a/app/api/sessions/route.ts b/app/api/sessions/route.ts index 628cf9121..e747f79d7 100644 --- a/app/api/sessions/route.ts +++ b/app/api/sessions/route.ts @@ -14,16 +14,31 @@ const SESSION_LIST_HEADERS = { export async function GET(req: Request) { try { + const filterId = new URL(req.url).searchParams.get("id"); + const sessions = await listSessionsAllHosts(); 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 Response(bodyJson, { + headers: { "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) { 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/AppShell.tsx b/components/AppShell.tsx index cc14c0ddb..f82a8c9dc 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -1257,7 +1257,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 607ad49b1..664d62756 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -5,7 +5,7 @@ import React from "react"; const { act, cleanup, fireEvent, render, waitFor } = await import("@testing-library/react/pure.js"); import { renderToStaticMarkup } from "react-dom/server"; -const { HeldMessageView, MessageView, SafeMarkdownBody, TaskResultPanel, isInterruptedMessage } = await import("./MessageView.tsx"); +const { HeldMessageView, MessageView, SafeMarkdownBody, TaskResultPanel, isInterruptedMessage, areMessageViewPropsEqual, haveSameRelevantToolResults } = await import("./MessageView.tsx"); const { CodeBlock } = await import("./MermaidBlock.tsx"); const { buildSessionContext } = await import("../lib/session-reader.ts"); const { collectToolResults, planTranscriptRows } = await import("../lib/chat-transcript-plan.ts"); @@ -1030,6 +1030,101 @@ test("user messages fork at their own entry and edit the prompt", async (t) => { view.unmount(); }); +test("SafeMarkdownBody is wrapped in React.memo", () => { + assert.equal(SafeMarkdownBody.$$typeof, React.memo(() => null).$$typeof); +}); + +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 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("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; window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }); diff --git a/components/MessageView.tsx b/components/MessageView.tsx index a8e2f1a1c..835cea25f 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -96,7 +96,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); @@ -123,7 +123,7 @@ export function SafeMarkdownBody({ children, className, ...props }: ComponentPro ); -} +}); function loadThinkingContent(sessionId: string, entryId: string, blockIndex: number): Promise { const key = `${sessionId}:${entryId}:${blockIndex}`; @@ -199,20 +199,52 @@ 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; + if (block.type === "toolCall") { + if (previous?.get(block.toolCallId) !== next?.get(block.toolCallId)) { + 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 ; @@ -241,31 +273,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-routes.test.mjs b/lib/session-routes.test.mjs index 87b8b5eb3..c6f4b985e 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -15,13 +15,14 @@ const sessionArchiveRoute = await import("../app/api/sessions/[id]/archive/route const exportRoute = await import("../app/api/sessions/[id]/export/route.ts"); const stateRoute = await import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await import("../app/api/sessions/[id]/auto-name/route.ts"); +const sessionsListRoute = await import("../app/api/sessions/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await import("./rpc-manager.ts"); const { closeHostLink, getHost, linkTimings } = await import("./hosts/hub.ts"); const { HostOpError } = await import("./hosts/link-protocol.ts"); const { revokeHost } = await import("./hosts/registry.ts"); -const { listSessionsAllHosts } = await import("./hosts/session-index.ts"); +const { invalidateHostSessionList, listSessionsAllHosts } = await import("./hosts/session-index.ts"); const { closeOutboxStore, outboxScope } = await import("./message-outbox.ts"); const getContext = (id, query = "") => contextRoute.GET( @@ -1595,3 +1596,137 @@ test("automatic title fallback cannot write after Edit takes over", 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" } }, + ]); + + 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, host: { id: "local" } }]]); + try { + const res4 = await sessionsListRoute.GET(new Request("http://localhost/api/sessions")); + assert.equal(res4.status, 200); + 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; + } + }); +}); + +test("GET /api/sessions invalidates ETag and returns 200 when worktreeBranch or projectRoot changes", async () => { + await withAgentDir(async (dir) => { + const id1 = "0a000000-0000-4000-8000-000000000072"; + 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" } }, + ]); + + 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(), + }; + invalidateHostSessionList("local"); + + 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(), + }; + + invalidateHostSessionList("local"); + 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"); + + invalidateSessionListCache(); + }); +}); + +test("GET /api/sessions?id= returns only the requested session for navigation", async () => { + await withAgentDir(async (dir) => { + const id1 = "0a000000-0000-4000-8000-000000000073"; + const id2 = "0a000000-0000-4000-8000-000000000074"; + 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" } }, + ]); + + // 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, []); + }); +});