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 @@ -36,6 +36,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixes & Improvements

- **Reuse unchanged chat Markdown during streaming.** Markdown bodies skip rendering when their props are unchanged, while relevant tool-result changes still refresh their message. Back/forward session navigation requests the selected session instead of downloading the full session list.
- **Listing files in a folder that is not a Git repository no longer leaves a `git` process running in it.** The @-mention and file-search index asks Git first; when the folder is not a repository it now waits for both Git queries to exit before falling back to reading the folder. A leftover `git` process could briefly keep Windows from deleting or renaming that folder.
- **Dollar amounts no longer render as math.** In text such as “$5 and $10”, the span between the two dollar signs turned into glued italic formula text. Single-dollar math now follows Pandoc's rule: the opening `$` must be followed by a non-space, and the closing `$` must be preceded by a non-space and not followed by a digit. `$x^2$` still renders as math.
- **Dollar amounts no longer render as math.** In text such as “$5 and $10” or “R$5 or US$10”, the span between the two dollar signs turned into glued italic formula text. Single-dollar math now follows Pandoc's rule: the opening `$` must be followed by a non-space, and the closing `$` must be preceded by a non-space and not followed by a digit. A letter directly before `$` and a digit after it (R$5, US$10) marks a price. `$x^2$` still renders as math; single-dollar math that spans lines now renders as text.
Expand Down
17 changes: 16 additions & 1 deletion app/api/sessions/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔥 The Roast: The PR's whole selling point is "navigation requests the selected session instead of downloading the full session list." But you put the filterId guard after listSessionsAllHosts() and getRunningRpcSessions(), so every back/forward nav still scans every session file on every host and walks the entire RPC registry. The optimization is present in the diff and completely dead on arrival — like installing a spoiler on a car with the parking brake on.

🩹 The Fix: Move the filterId short-circuit above the expensive calls. Resolve the single session first (e.g. hostForSessionId(filterId) + sessionSpawnTarget), and only compute the full list + running set for unfiltered requests:

const filterId = new URL(req.url).searchParams.get("id");
if (filterId) {
  const matched = await listSessionById(filterId);
  const runningSessions = getRunningRpcSessions();
  const runningSessionIds = runningSessions.map((s) => s.id);
  return new Response(JSON.stringify({ sessions: matched, runningSessionIds, runningSessions }), {
    headers: { "Content-Type": "application/json", ...SESSION_LIST_HEADERS },
  });
}
const sessions = await listSessionsAllHosts();

📏 Severity: warning

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" },
Expand Down
2 changes: 1 addition & 1 deletion components/AppShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@
if (container && active instanceof HTMLElement && container.contains(active)) {
active.blur();
}
}, [sidebarOpen, mobileSidebarReady]);

Check warning on line 364 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useLayoutEffect has a missing dependency: 'sidebarContainerRef'. Either include it or remove the dependency array

Check warning on line 364 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useLayoutEffect has a missing dependency: 'sidebarContainerRef'. Either include it or remove the dependency array
const refreshAppUpdate = useCallback(async (force = false, autoOpen = false): Promise<AppUpdateInfo | null> => {
const data = await fetchAppUpdateJson<AppUpdateInfo>(
force ? "/api/app-update?force=1" : "/api/app-update",
Expand Down Expand Up @@ -828,7 +828,7 @@
sidebarResizeHandlersRef.current = { onMove, onUp };
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", onUp);
}, [isMobile, sidebarWidth]);

Check warning on line 831 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 'sidebarContainerRef'. Either include it or remove the dependency array

Check warning on line 831 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 'sidebarContainerRef'. Either include it or remove the dependency array

// If the app unmounts mid-drag, remove the window listeners and restore the
// body cursor; otherwise the handlers leak and body stays cursor:col-resize.
Expand All @@ -845,7 +845,7 @@
const resetRightPanelWidth = useCallback(() => {
rightPanelRef.current?.style.removeProperty("--right-panel-width");
setRightPanelWidth(null);
}, []);

Check warning on line 848 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

Check warning on line 848 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

const changeRightPanelWidth = useCallback((delta: number) => {
setRightPanelWidth((prev) => {
Expand All @@ -856,7 +856,7 @@
rightPanelRef.current?.style.setProperty("--right-panel-width", `${next}px`);
return next;
});
}, []);

Check warning on line 859 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

Check warning on line 859 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

const handleRightPanelResizeKey = useCallback((e: React.KeyboardEvent) => {
// The handle sits on the panel's left edge: left widens, right narrows.
Expand Down Expand Up @@ -917,7 +917,7 @@
rightResizeHandlersRef.current = { onMove, onUp };
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", onUp);
}, [isMobile]);

Check warning on line 920 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

Check warning on line 920 in components/AppShell.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 'rightPanelRef'. Either include it or remove the dependency array

// If the app unmounts mid-drag, remove the window listeners and restore the
// body cursor; otherwise the handlers leak and body stays cursor:col-resize.
Expand Down Expand Up @@ -1257,7 +1257,7 @@
// list itself could not be fetched (keep the entry, abort this navigation).
const fetchSessionForNavigation = useCallback(async (sessionId: string): Promise<SessionInfo | null | "unavailable"> => {
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;
Expand Down
97 changes: 96 additions & 1 deletion components/MessageView.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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() {} });
Expand Down
72 changes: 40 additions & 32 deletions components/MessageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof MarkdownBody>) {
export const SafeMarkdownBody = memo(function SafeMarkdownBody({ children, className, ...props }: ComponentProps<typeof MarkdownBody>) {
const { t } = useI18n();
const [showRaw, setShowRaw] = useState(false);

Expand All @@ -123,7 +123,7 @@ export function SafeMarkdownBody({ children, className, ...props }: ComponentPro
</pre>
</div>
);
}
});

function loadThinkingContent(sessionId: string, entryId: string, blockIndex: number): Promise<string> {
const key = `${sessionId}:${entryId}:${blockIndex}`;
Expand Down Expand Up @@ -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<string, ToolResultMessage> | undefined,
next: Map<string, ToolResultMessage> | 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 <UserMessageView message={message as UserMessage} cwd={cwd} onOpenFile={onOpenFile} entryId={entryId} onFork={onFork} forking={forking} forkDisabled={forkDisabled} onEdit={onEdit} editing={editing} editDisabled={editDisabled} />;
Expand Down Expand Up @@ -241,31 +273,7 @@ export const MessageView = memo(function MessageView({ message, isStreaming, too
return <BashExecutionView message={message as BashExecutionMessage} sessionId={sessionId} entryId={entryId} />;
}
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.
Expand Down
2 changes: 1 addition & 1 deletion graphify-out/graph.json

Large diffs are not rendered by default.

Loading
Loading