Skip to content

The open-source app everyone uses to manage agents at work

[codex] Split PR #4692 UI/QoL updates (#4701)

Dotta6b7f6ce4b853
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 5b9bb6410f..ab6a423266 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -671,7 +671,6 @@ export function issueRoutes(
details: {
issueId: issue.id,
status: issue.status,
- securityPrinciples: ["Complete Mediation", "Fail Securely"],
},
});
return false;
@@ -694,7 +693,6 @@ export function issueRoutes(
holdId: activePauseHold.holdId,
rootIssueId: activePauseHold.rootIssueId,
mode: activePauseHold.mode,
- securityPrinciples: ["Complete Mediation", "Fail Securely", "Secure Defaults"],
},
});
return false;
@@ -928,7 +926,6 @@ export function issueRoutes(
const parsedOffset = rawOffset !== undefined && /^\d+$/.test(rawOffset)
? Number.parseInt(rawOffset, 10)
: null;
- const offset = parsedOffset ?? 0;
if (assigneeUserFilterRaw === "me" && (!assigneeUserId || req.actor.type !== "board")) {
res.status(403).json({ error: "assigneeUserId=me requires board authentication" });
@@ -954,6 +951,7 @@ export function issueRoutes(
res.status(400).json({ error: "offset must be a non-negative integer" });
return;
}
+ const offset = parsedOffset ?? 0;
const result = await svc.list(companyId, {
status: req.query.status as string | undefined,
diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts
index 741d8ce302..104d12da2d 100644
--- a/server/src/services/issues.ts
+++ b/server/src/services/issues.ts
@@ -942,7 +942,8 @@ async function listIssueProductivityReviewMap(
isNull(issues.hiddenAt),
notInArray(issues.status, PRODUCTIVITY_REVIEW_TERMINAL_STATUSES),
),
- );
+ )
+ .orderBy(desc(issues.createdAt), desc(issues.id));
reviewRows.push(...rows);
}
@@ -985,6 +986,7 @@ async function listIssueProductivityReviewMap(
for (const row of reviewRows) {
if (!row.sourceIssueId) continue;
+ if (map.has(row.sourceIssueId)) continue;
const detail = triggerByReviewIssueId.get(row.reviewIssueId);
map.set(row.sourceIssueId, {
reviewIssueId: row.reviewIssueId,
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index c34d8d966b..ec82de9dbd 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -14,6 +14,7 @@ import { ProjectWorkspaceDetail } from "./pages/ProjectWorkspaceDetail";
import { Workspaces } from "./pages/Workspaces";
import { Issues } from "./pages/Issues";
import { IssueDetail } from "./pages/IssueDetail";
+import { IssueChatLongThreadPerf } from "./pages/IssueChatLongThreadPerf";
import { Routines } from "./pages/Routines";
import { RoutineDetail } from "./pages/RoutineDetail";
import { UserProfile } from "./pages/UserProfile";
@@ -50,7 +51,7 @@ import { InviteLandingPage } from "./pages/InviteLanding";
import { JoinRequestQueue } from "./pages/JoinRequestQueue";
import { NotFoundPage } from "./pages/NotFound";
import { useCompany } from "./context/CompanyContext";
-import { useDialog } from "./context/DialogContext";
+import { useDialogActions } from "./context/DialogContext";
import { loadLastInboxTab } from "./lib/inbox";
import { shouldRedirectCompanylessRouteToOnboarding } from "./lib/onboarding-route";
@@ -98,6 +99,9 @@ function boardRoutes() {
<Route path="issues/done" element={<Navigate to="/issues" replace />} />
<Route path="issues/recent" element={<Navigate to="/issues" replace />} />
<Route path="issues/:issueId" element={<IssueDetail />} />
+ {import.meta.env.DEV ? (
+ <Route path="tests/perf/long-thread" element={<IssueChatLongThreadPerf />} />
+ ) : null}
<Route path="routines" element={<Routines />} />
<Route path="routines/:routineId" element={<RoutineDetail />} />
<Route path="execution-workspaces/:workspaceId" element={<ExecutionWorkspaceDetail />} />
@@ -139,7 +143,7 @@ function LegacySettingsRedirect() {
function OnboardingRoutePage() {
const { companies } = useCompany();
- const { openOnboarding } = useDialog();
+ const { openOnboarding } = useDialogActions();
const { companyPrefix } = useParams<{ companyPrefix?: string }>();
const matchedCompany = companyPrefix
? companies.find((company) => company.issuePrefix.toUpperCase() === companyPrefix.toUpperCase()) ?? null
@@ -231,7 +235,7 @@ function UnprefixedBoardRedirect() {
}
function NoCompaniesStartPage() {
- const { openOnboarding } = useDialog();
+ const { openOnboarding } = useDialogActions();
return (
<div className="mx-auto max-w-xl py-10">
diff --git a/ui/src/api/issues.test.ts b/ui/src/api/issues.test.ts
index 6dba7027ec..107f12b1a3 100644
--- a/ui/src/api/issues.test.ts
+++ b/ui/src/api/issues.test.ts
@@ -39,4 +39,12 @@ describe("issuesApi.list", () => {
"/companies/company-1/issues?workspaceId=workspace-1&limit=1000",
);
});
+
+ it("passes pagination offsets through to the company issues endpoint", async () => {
+ await issuesApi.list("company-1", { limit: 500, offset: 1500 });
+
+ expect(mockApi.get).toHaveBeenCalledWith(
+ "/companies/company-1/issues?limit=500&offset=1500",
+ );
+ });
});
diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts
index 53fb9b92f9..61abcba691 100644
--- a/ui/src/api/issues.ts
+++ b/ui/src/api/issues.ts
@@ -48,6 +48,7 @@ export const issuesApi = {
includeBlockedBy?: boolean;
q?: string;
limit?: number;
+ offset?: number;
},
) => {
const params = new URLSearchParams();
@@ -70,6 +71,7 @@ export const issuesApi = {
if (filters?.includeBlockedBy) params.set("includeBlockedBy", "true");
if (filters?.q) params.set("q", filters.q);
if (filters?.limit) params.set("limit", String(filters.limit));
+ if (filters?.offset !== undefined) params.set("offset", String(filters.offset));
const qs = params.toString();
return api.get<Issue[]>(`/companies/${companyId}/issues${qs ? `?${qs}` : ""}`);
},
diff --git a/ui/src/components/CommandPalette.test.tsx b/ui/src/components/CommandPalette.test.tsx
index b229cc9673..165f1390c2 100644
--- a/ui/src/components/CommandPalette.test.tsx
+++ b/ui/src/components/CommandPalette.test.tsx
@@ -39,6 +39,7 @@ vi.mock("../context/CompanyContext", () => ({
vi.mock("../context/DialogContext", () => ({
useDialog: () => dialogState,
+ useDialogActions: () => dialogState,
}));
vi.mock("../context/SidebarContext", () => ({
diff --git a/ui/src/components/CommandPalette.tsx b/ui/src/components/CommandPalette.tsx
index f5a0ef750b..2853004252 100644
--- a/ui/src/components/CommandPalette.tsx
+++ b/ui/src/components/CommandPalette.tsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useMemo } from "react";
import { useNavigate } from "@/lib/router";
import { useQuery } from "@tanstack/react-query";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useSidebar } from "../context/SidebarContext";
import { issuesApi } from "../api/issues";
import { agentsApi } from "../api/agents";
@@ -37,7 +37,7 @@ export function CommandPalette() {
const [query, setQuery] = useState("");
const navigate = useNavigate();
const { selectedCompanyId } = useCompany();
- const { openNewIssue, openNewAgent } = useDialog();
+ const { openNewIssue, openNewAgent } = useDialogActions();
const { isMobile, setSidebarOpen } = useSidebar();
const searchQuery = query.trim();
diff --git a/ui/src/components/CompanyRail.tsx b/ui/src/components/CompanyRail.tsx
index 496dd40a2b..2766a16bd0 100644
--- a/ui/src/components/CompanyRail.tsx
+++ b/ui/src/components/CompanyRail.tsx
@@ -17,7 +17,7 @@ import {
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { cn } from "../lib/utils";
import { queryKeys } from "../lib/queryKeys";
import { sidebarBadgesApi } from "../api/sidebarBadges";
@@ -125,7 +125,7 @@ function SortableCompanyItem({
export function CompanyRail() {
const { companies, selectedCompanyId, setSelectedCompanyId } = useCompany();
- const { openOnboarding } = useDialog();
+ const { openOnboarding } = useDialogActions();
const navigate = useNavigate();
const location = useLocation();
const isInstanceRoute = location.pathname.startsWith("/instance/");
diff --git a/ui/src/components/IssueChatThread.test.tsx b/ui/src/components/IssueChatThread.test.tsx
index 5ec92b11de..6837fe0da9 100644
--- a/ui/src/components/IssueChatThread.test.tsx
+++ b/ui/src/components/IssueChatThread.test.tsx
@@ -8,17 +8,40 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Agent } from "@paperclipai/shared";
import {
IssueChatThread,
+ VIRTUALIZED_THREAD_ROW_THRESHOLD,
canStopIssueChatRun,
+ findLatestCommentMessageIndex,
resolveAssistantMessageFoldedState,
resolveIssueChatHumanAuthor,
} from "./IssueChatThread";
+import { ToastProvider } from "../context/ToastContext";
+import { ToastViewport } from "./ToastViewport";
import type {
AskUserQuestionsInteraction,
RequestConfirmationInteraction,
SuggestTasksInteraction,
} from "../lib/issue-thread-interactions";
+import {
+ issueChatLongThreadAgentMap,
+ issueChatLongThreadComments,
+ issueChatLongThreadEvents,
+ issueChatLongThreadLinkedRuns,
+ issueChatLongThreadTranscriptsByRunId,
+} from "../fixtures/issueChatLongThreadFixture";
+import type {
+ IssueChatLinkedRun,
+ IssueChatTranscriptEntry,
+} from "../lib/issue-chat-messages";
+
+function hasSmoothScrollBehavior(arg: unknown) {
+ return typeof arg === "object"
+ && arg !== null
+ && "behavior" in arg
+ && (arg as ScrollToOptions).behavior === "smooth";
+}
-const { markdownEditorFocusMock } = vi.hoisted(() => ({
+const { markdownBodyRenderMock, markdownEditorFocusMock } = vi.hoisted(() => ({
+ markdownBodyRenderMock: vi.fn(),
markdownEditorFocusMock: vi.fn(),
}));
@@ -59,7 +82,10 @@ vi.mock("../lib/issue-chat-scroll", async (importOriginal) => {
});
vi.mock("./MarkdownBody", () => ({
- MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ MarkdownBody: ({ children }: { children: ReactNode }) => {
+ markdownBodyRenderMock(children);
+ return <div>{children}</div>;
+ },
}));
vi.mock("./MarkdownEditor", () => ({
@@ -273,6 +299,7 @@ describe("IssueChatThread", () => {
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
+ window.scrollTo = vi.fn();
localStorage.clear();
});
@@ -284,6 +311,7 @@ describe("IssueChatThread", () => {
captureComposerViewportSnapshotMock.mockClear();
restoreComposerViewportSnapshotMock.mockClear();
shouldPreserveComposerViewportMock.mockClear();
+ markdownBodyRenderMock.mockClear();
});
it("drops the count heading and does not use an internal scrollbox", () => {
@@ -318,6 +346,644 @@ describe("IssueChatThread", () => {
});
});
+ it("virtualizes long merged threads so only a windowed slice mounts", () => {
+ const root = createRoot(container);
+ const totalMergedRows =
+ issueChatLongThreadComments.length
+ + issueChatLongThreadEvents.length
+ + issueChatLongThreadLinkedRuns.length;
+ expect(totalMergedRows).toBeGreaterThanOrEqual(VIRTUALIZED_THREAD_ROW_THRESHOLD);
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const virtualizer = container.querySelector(
+ '[data-testid="issue-chat-thread-virtualizer"]',
+ ) as HTMLDivElement | null;
+ expect(virtualizer).not.toBeNull();
+ expect(virtualizer?.dataset.virtualCount).toBe(String(totalMergedRows));
+
+ const rows = container.querySelectorAll('[data-testid="issue-chat-message-row"]');
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.length).toBeLessThan(totalMergedRows);
+
+ const virtualRows = container.querySelectorAll(
+ '[data-testid="issue-chat-thread-virtual-row"]',
+ );
+ expect(virtualRows.length).toBe(rows.length);
+ for (const row of Array.from(virtualRows)) {
+ const transform = (row as HTMLDivElement).style.transform;
+ expect(transform).toMatch(/translateY\(/);
+ }
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("measures tall virtual rows before positioning following rows", async () => {
+ const root = createRoot(container);
+ const requestAnimationFrameMock = vi
+ .spyOn(window, "requestAnimationFrame")
+ .mockImplementation((callback) => {
+ callback(0);
+ return 0;
+ });
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const virtualRows = container.querySelectorAll<HTMLDivElement>(
+ '[data-testid="issue-chat-thread-virtual-row"]',
+ );
+ expect(virtualRows.length).toBeGreaterThan(1);
+
+ Object.defineProperty(virtualRows[0], "getBoundingClientRect", {
+ configurable: true,
+ value: () => ({
+ x: 0,
+ y: 0,
+ width: 700,
+ height: 800,
+ top: 0,
+ right: 700,
+ bottom: 800,
+ left: 0,
+ toJSON: () => ({}),
+ }),
+ });
+
+ await act(async () => {
+ virtualRows[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ const nextTransform = virtualRows[1].style.transform;
+ const translateY = Number(nextTransform.match(/translateY\(([-\d.]+)px\)/)?.[1] ?? "0");
+ expect(translateY).toBeGreaterThanOrEqual(800);
+
+ act(() => {
+ root.unmount();
+ });
+ requestAnimationFrameMock.mockRestore();
+ });
+
+ it("scrolls loaded hash targets through the virtualized message index", () => {
+ const root = createRoot(container);
+ const targetComment = issueChatLongThreadComments.at(-1);
+ expect(targetComment).toBeDefined();
+ const scrollToMock = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+
+ act(() => {
+ root.render(
+ <MemoryRouter initialEntries={[`/issues/PAP-1#comment-${targetComment!.id}`]}>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(scrollToMock.mock.calls.some(([arg]) => hasSmoothScrollBehavior(arg))).toBe(true);
+
+ scrollToMock.mockRestore();
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("uses the virtualizer when jumping to the latest long-thread row", () => {
+ const root = createRoot(container);
+ const scrollToMock = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const jump = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Jump to latest",
+ ) as HTMLButtonElement | undefined;
+ expect(jump).toBeDefined();
+
+ act(() => {
+ jump?.click();
+ });
+
+ expect(scrollToMock.mock.calls.some(([arg]) => hasSmoothScrollBehavior(arg))).toBe(true);
+
+ scrollToMock.mockRestore();
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ // Regression for PAP-2660: on the real issue page the chat thread is wrapped
+ // in `<main id="main-content" overflow-auto>`, so the virtualizer must bind
+ // to that ancestor's scroll instead of `window` (which never moves on
+ // desktop). When mounted inside an overflow-auto ancestor the jump-to-latest
+ // action must drive that element's scrollTo, not window.scrollTo.
+ it("targets an overflow-auto ancestor instead of window scroll on jump-to-latest", () => {
+ container.remove();
+ const scrollHost = document.createElement("main");
+ scrollHost.id = "main-content";
+ scrollHost.style.overflowY = "auto";
+ scrollHost.style.overflow = "auto";
+ scrollHost.style.height = "640px";
+ document.body.appendChild(scrollHost);
+ container = document.createElement("div");
+ scrollHost.appendChild(container);
+
+ const root = createRoot(container);
+ const windowScrollToMock = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+ const elementScrollToMock = vi.fn();
+ scrollHost.scrollTo = elementScrollToMock as unknown as typeof scrollHost.scrollTo;
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const jump = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Jump to latest",
+ ) as HTMLButtonElement | undefined;
+ expect(jump).toBeDefined();
+
+ windowScrollToMock.mockClear();
+ elementScrollToMock.mockClear();
+
+ act(() => {
+ jump?.click();
+ });
+
+ expect(elementScrollToMock.mock.calls.some(([arg]) => hasSmoothScrollBehavior(arg))).toBe(true);
+ expect(windowScrollToMock.mock.calls.some(([arg]) => hasSmoothScrollBehavior(arg))).toBe(false);
+
+ windowScrollToMock.mockRestore();
+ act(() => {
+ root.unmount();
+ });
+ scrollHost.remove();
+ });
+
+ // Regression for PAP-2672: when the merged feed ends with a non-comment row
+ // (run/timeline/embedded output) we still want Jump to latest to land on the
+ // last comment, not whichever activity row sorts last.
+ it("targets the latest comment row when trailing rows are non-comments (PAP-2672)", () => {
+ const lastComment = issueChatLongThreadComments.at(-1);
+ expect(lastComment).toBeDefined();
+ const trailingRunStart = new Date(new Date(lastComment!.createdAt).getTime() + 60_000);
+ const trailingRun: IssueChatLinkedRun = {
+ runId: "trailing-run-pap-2672",
+ status: "failed",
+ agentId: "agent-perf-codex",
+ agentName: "TrailingRunner",
+ adapterType: "codex_local",
+ createdAt: trailingRunStart,
+ startedAt: trailingRunStart,
+ finishedAt: trailingRunStart,
+ hasStoredOutput: true,
+ };
+ const trailingTranscriptEntries: readonly IssueChatTranscriptEntry[] = [
+ {
+ kind: "assistant",
+ ts: trailingRunStart.toISOString(),
+ text: "Trailing run posted after the latest comment.",
+ },
+ ];
+ const transcriptsByRunId = new Map(issueChatLongThreadTranscriptsByRunId);
+ transcriptsByRunId.set(trailingRun.runId, trailingTranscriptEntries);
+ const linkedRuns: IssueChatLinkedRun[] = [
+ ...issueChatLongThreadLinkedRuns,
+ trailingRun,
+ ];
+
+ container.remove();
+ const scrollHost = document.createElement("main");
+ scrollHost.id = "main-content";
+ scrollHost.style.overflowY = "auto";
+ scrollHost.style.overflow = "auto";
+ scrollHost.style.height = "800px";
+ Object.defineProperty(scrollHost, "scrollHeight", {
+ configurable: true,
+ get: () => 200_000,
+ });
+ Object.defineProperty(scrollHost, "clientHeight", {
+ configurable: true,
+ get: () => 800,
+ });
+ document.body.appendChild(scrollHost);
+ container = document.createElement("div");
+ scrollHost.appendChild(container);
+
+ const elementScrollToMock = vi.fn();
+ scrollHost.scrollTo = elementScrollToMock as unknown as typeof scrollHost.scrollTo;
+
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={linkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={transcriptsByRunId}
+ hasOutputForRun={(runId) => transcriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const virtualizerEl = container.querySelector<HTMLDivElement>(
+ '[data-testid="issue-chat-thread-virtualizer"]',
+ );
+ expect(virtualizerEl).not.toBeNull();
+ const totalMergedRows = Number(virtualizerEl?.dataset.virtualCount ?? "0");
+ expect(totalMergedRows).toBeGreaterThan(VIRTUALIZED_THREAD_ROW_THRESHOLD);
+
+ elementScrollToMock.mockClear();
+
+ const jump = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Jump to latest",
+ ) as HTMLButtonElement | undefined;
+ expect(jump).toBeDefined();
+
+ act(() => {
+ jump?.click();
+ });
+
+ const smoothCalls = elementScrollToMock.mock.calls
+ .map((call) => call[0] as ScrollToOptions)
+ .filter(hasSmoothScrollBehavior);
+ expect(smoothCalls.length).toBeGreaterThan(0);
+
+ // For align="end" with the very last index, tanstack-virtual short-circuits
+ // to getMaxScrollOffset() (= scrollHeight - clientHeight = 199_200 here).
+ // A jump to the latest comment row (one slot earlier) lands at item.end -
+ // clientHeight, which is strictly less. Asserting top < maxScrollOffset
+ // proves the button isn't routing to the trailing run row.
+ const maxScrollOffset = 200_000 - 800;
+ const lastTop = smoothCalls[smoothCalls.length - 1]?.top;
+ expect(typeof lastTop).toBe("number");
+ expect(lastTop as number).toBeLessThan(maxScrollOffset);
+ expect(lastTop as number).toBeGreaterThan(0);
+
+ act(() => {
+ root.unmount();
+ });
+ scrollHost.remove();
+ });
+
+ // Regression for PAP-2672 follow-up: clicking Jump to latest must refresh
+ // the comments page so a comment that arrived after the initial load is
+ // present before we scroll. Otherwise the user lands on the latest *loaded*
+ // comment but not the absolute newest.
+ it("invokes onRefreshLatestComments before scrolling on Jump to latest", async () => {
+ const refreshMock = vi.fn(async () => undefined);
+ const directComments = issueChatLongThreadComments.slice(0, 8);
+
+ const root = createRoot(container);
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={directComments}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ enableLiveTranscriptPolling={false}
+ onRefreshLatestComments={refreshMock}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const jump = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Jump to latest",
+ ) as HTMLButtonElement | undefined;
+ expect(jump).toBeDefined();
+
+ act(() => {
+ jump?.click();
+ });
+
+ expect(refreshMock).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("findLatestCommentMessageIndex prefers the last comment-anchored row (PAP-2672)", () => {
+ const messages = [
+ { metadata: { custom: { anchorId: "comment-a" } } },
+ { metadata: { custom: { anchorId: "run-1" } } },
+ { metadata: { custom: { anchorId: "comment-b" } } },
+ { metadata: { custom: { anchorId: "run-2" } } },
+ { metadata: { custom: { anchorId: "activity-3" } } },
+ ];
+ expect(findLatestCommentMessageIndex(messages as never)).toBe(2);
+ expect(
+ findLatestCommentMessageIndex([
+ { metadata: { custom: { anchorId: "run-only" } } },
+ ] as never),
+ ).toBe(-1);
+ expect(findLatestCommentMessageIndex([] as never)).toBe(-1);
+ });
+
+ it("keeps the direct render path for short threads under the virtualization threshold", () => {
+ const root = createRoot(container);
+ const directComments = issueChatLongThreadComments.slice(0, 12);
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={directComments}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(
+ container.querySelector('[data-testid="issue-chat-thread-virtualizer"]'),
+ ).toBeNull();
+ const rows = container.querySelectorAll('[data-testid="issue-chat-message-row"]');
+ expect(rows.length).toBe(directComments.length);
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("renders virtualized rows with the same role/kind metadata as the direct path", () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={async () => {}}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ const rows = container.querySelectorAll('[data-testid="issue-chat-message-row"]');
+ expect(rows.length).toBeGreaterThan(0);
+ const roles = new Set<string>();
+ const kinds = new Set<string>();
+ for (const row of Array.from(rows)) {
+ const element = row as HTMLDivElement;
+ const role = element.dataset.messageRole;
+ const kind = element.dataset.messageKind;
+ if (role) roles.add(role);
+ if (kind) kinds.add(kind);
+ }
+ expect(roles.size).toBeGreaterThan(0);
+ expect(kinds.size).toBeGreaterThan(0);
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("does not re-render long-thread markdown rows for unrelated layout updates", () => {
+ const root = createRoot(container);
+ const onAdd = async () => {};
+ const hasOutputForRun = (runId: string) => issueChatLongThreadTranscriptsByRunId.has(runId);
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={onAdd}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={hasOutputForRun}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(markdownBodyRenderMock).toHaveBeenCalled();
+ markdownBodyRenderMock.mockClear();
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={[]}
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={onAdd}
+ showComposer={false}
+ showJumpToLatest
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={hasOutputForRun}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(markdownBodyRenderMock).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("does not re-render unchanged markdown when feedback votes change", () => {
+ const root = createRoot(container);
+ const onAdd = async () => {};
+ const onVote = async () => {};
+ const comments = [{
+ id: "comment-agent-feedback",
+ companyId: "company-1",
+ issueId: "issue-1",
+ authorAgentId: "agent-1",
+ authorUserId: null,
+ body: "Agent summary with **markdown**",
+ createdAt: new Date("2026-04-06T12:00:00.000Z"),
+ updatedAt: new Date("2026-04-06T12:00:00.000Z"),
+ }];
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={comments}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ onAdd={onAdd}
+ onVote={onVote}
+ feedbackVotes={[]}
+ showComposer={false}
+ enableLiveTranscriptPolling={false}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(markdownBodyRenderMock).toHaveBeenCalled();
+ markdownBodyRenderMock.mockClear();
+
+ act(() => {
+ root.render(
+ <MemoryRouter>
+ <IssueChatThread
+ comments={comments}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ onAdd={onAdd}
+ onVote={onVote}
+ feedbackVotes={[{
+ id: "feedback-1",
+ companyId: "company-1",
+ issueId: "issue-1",
+ targetType: "issue_comment",
+ targetId: "comment-agent-feedback",
+ authorUserId: "user-1",
+ vote: "up",
+ reason: null,
+ sharedWithLabs: false,
+ sharedAt: null,
+ consentVersion: null,
+ redactionSummary: null,
+ createdAt: new Date("2026-04-06T12:01:00.000Z"),
+ updatedAt: new Date("2026-04-06T12:01:00.000Z"),
+ }]}
+ showComposer={false}
+ enableLiveTranscriptPolling={false}
+ />
+ </MemoryRouter>,
+ );
+ });
+
+ expect(markdownBodyRenderMock).not.toHaveBeenCalled();
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
it("shows explicit follow-up badges and event copy", () => {
const root = createRoot(container);
@@ -1258,6 +1924,127 @@ describe("IssueChatThread", () => {
});
});
+ it("warns once before sending a reply with no assignee selected", async () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ToastProvider>
+ <ToastViewport />
+ <MemoryRouter>
+ <IssueChatThread
+ comments={[]}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ onAdd={async () => {}}
+ enableReassign
+ reassignOptions={[
+ { id: "", label: "No assignee" },
+ { id: "agent:agent-1", label: "Agent 1" },
+ ]}
+ currentAssigneeValue=""
+ suggestedAssigneeValue=""
+ enableLiveTranscriptPolling={false}
+ />
+ </MemoryRouter>
+ </ToastProvider>,
+ );
+ });
+
+ const editor = container.querySelector('textarea[aria-label="Issue chat editor"]') as HTMLTextAreaElement | null;
+ const submitButton = Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent === "Send",
+ ) as HTMLButtonElement | undefined;
+ expect(editor).not.toBeNull();
+ expect(submitButton).toBeDefined();
+
+ act(() => {
+ const valueSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLTextAreaElement.prototype,
+ "value",
+ )?.set;
+ valueSetter?.call(editor, "Reply without assignee");
+ editor?.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ await act(async () => {
+ submitButton?.click();
+ });
+
+ expect(appendMock).not.toHaveBeenCalled();
+ expect(document.body.textContent).toContain("No assignee selected");
+
+ await act(async () => {
+ submitButton?.click();
+ });
+
+ expect(appendMock).toHaveBeenCalledTimes(1);
+ expect(appendMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: [{ type: "text", text: "Reply without assignee" }],
+ }),
+ );
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("does not warn when sending a reply with an assignee selected", async () => {
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ToastProvider>
+ <ToastViewport />
+ <MemoryRouter>
+ <IssueChatThread
+ comments={[]}
+ linkedRuns={[]}
+ timelineEvents={[]}
+ liveRuns={[]}
+ onAdd={async () => {}}
+ enableReassign
+ reassignOptions={[
+ { id: "", label: "No assignee" },
+ { id: "agent:agent-1", label: "Agent 1" },
+ ]}
+ currentAssigneeValue="agent:agent-1"
+ suggestedAssigneeValue="agent:agent-1"
+ enableLiveTranscriptPolling={false}
+ />
+ </MemoryRouter>
+ </ToastProvider>,
+ );
+ });
+
+ const editor = container.querySelector('textarea[aria-label="Issue chat editor"]') as HTMLTextAreaElement | null;
+ const submitButton = Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent === "Send",
+ ) as HTMLButtonElement | undefined;
+
+ act(() => {
+ const valueSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLTextAreaElement.prototype,
+ "value",
+ )?.set;
+ valueSetter?.call(editor, "Reply with assignee");
+ editor?.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ await act(async () => {
+ submitButton?.click();
+ });
+
+ expect(appendMock).toHaveBeenCalledTimes(1);
+ expect(document.body.textContent).not.toContain("No assignee selected");
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
it("exposes a composer focus handle that forwards to the editor", () => {
const root = createRoot(container);
const composerRef = createRef<{ focus: () => void; restoreDraft: (submittedBody: string) => void }>();
diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx
index bc9dc2cf63..6a89c073ef 100644
--- a/ui/src/components/IssueChatThread.tsx
+++ b/ui/src/components/IssueChatThread.tsx
@@ -12,6 +12,8 @@ import {
createContext,
Component,
forwardRef,
+ memo,
+ useCallback,
useContext,
useEffect,
useImperativeHandle,
@@ -88,6 +90,7 @@ import {
shouldPreserveComposerViewport,
} from "../lib/issue-chat-scroll";
import { formatAssigneeUserLabel } from "../lib/assignees";
+import { useOptionalToastActions } from "../context/ToastContext";
import type { CompanyUserProfile } from "../lib/company-members";
import { timeAgo } from "../lib/timeAgo";
import {
@@ -107,24 +110,20 @@ import { AlertTriangle, ArrowRight, Brain, Check, ChevronDown, Copy, Hammer, Loa
import { IssueBlockedNotice } from "./IssueBlockedNotice";
interface IssueChatMessageContext {
- feedbackVoteByTargetId: Map<string, FeedbackVoteValue>;
feedbackDataSharingPreference: FeedbackDataSharingPreference;
feedbackTermsUrl: string | null;
agentMap?: Map<string, Agent>;
currentUserId?: string | null;
userLabelMap?: ReadonlyMap<string, string> | null;
userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
- activeRunIds: ReadonlySet<string>;
onVote?: (
commentId: string,
vote: FeedbackVoteValue,
options?: { allowSharing?: boolean; reason?: string },
) => Promise<void>;
onStopRun?: (runId: string) => Promise<void>;
- stoppingRunId?: string | null;
onInterruptQueued?: (runId: string) => Promise<void>;
onCancelQueued?: (commentId: string) => void;
- interruptingQueuedRunId?: string | null;
onImageClick?: (src: string) => void;
onAcceptInteraction?: (
interaction: SuggestTasksInteraction | RequestConfirmationInteraction,
@@ -141,10 +140,8 @@ interface IssueChatMessageContext {
}
const IssueChatCtx = createContext<IssueChatMessageContext>({
- feedbackVoteByTargetId: new Map(),
feedbackDataSharingPreference: "prompt",
feedbackTermsUrl: null,
- activeRunIds: new Set<string>(),
});
export function resolveAssistantMessageFoldedState(args: {
@@ -209,6 +206,21 @@ function useLiveElapsed(startMs: number | null | undefined, active: boolean): st
return formatDurationWords(Date.now() - startMs);
}
+function useStableEvent<T extends (...args: never[]) => unknown>(callback: T | undefined): T | undefined {
+ const callbackRef = useRef(callback);
+ useLayoutEffect(() => {
+ callbackRef.current = callback;
+ }, [callback]);
+
+ return useMemo(() => {
+ if (!callback) return undefined;
+ return ((...args: Parameters<T>) => callbackRef.current?.(...args)) as T;
+ // Keep the wrapper stable while the callback identity changes; the ref above
+ // carries the current callback implementation.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [Boolean(callback)]);
+}
+
interface CommentReassignment {
assigneeAgentId: string | null;
assigneeUserId: string | null;
@@ -297,6 +309,12 @@ interface IssueChatThreadProps {
answers: AskUserQuestionsAnswer[],
) => Promise<void> | void;
composerRef?: Ref<IssueChatComposerHandle>;
+ /**
+ * Hook for the parent to refetch comments when the user explicitly asks
+ * to jump to the latest comment. Used to make sure the absolute newest
+ * comment is in the loaded set before we scroll to it.
+ */
+ onRefreshLatestComments?: () => Promise<unknown> | void;
}
type IssueChatErrorBoundaryProps = {
@@ -538,6 +556,10 @@ function shouldImplicitlyReopenComment(issueStatus: string | undefined, assignee
return resumesToTodo && assigneeValue.startsWith("agent:");
}
+function isUnassignedReassignValue(value: string): boolean {
+ return !value || value === "__none__";
+}
+
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
function commentDateLabel(date: Date | string | undefined): string {
@@ -547,7 +569,7 @@ function commentDateLabel(date: Date | string | undefined): string {
return formatShortDate(date);
}
-function IssueChatTextPart({ text, recessed }: { text: string; recessed?: boolean }) {
+const IssueChatTextPart = memo(function IssueChatTextPart({ text, recessed }: { text: string; recessed?: boolean }) {
const { onImageClick } = useContext(IssueChatCtx);
return (
<MarkdownBody
@@ -559,7 +581,7 @@ function IssueChatTextPart({ text, recessed }: { text: string; recessed?: boolea
{text}
</MarkdownBody>
);
-}
+});
function humanizeValue(value: string | null) {
if (!value) return "None";
@@ -1047,7 +1069,7 @@ function getThreadMessageCopyText(message: ThreadMessage) {
.join("\n\n");
}
-function IssueChatTextParts({
+const IssueChatTextParts = memo(function IssueChatTextParts({
message,
recessed = false,
}: {
@@ -1067,7 +1089,7 @@ function IssueChatTextParts({
))}
</>
);
-}
+});
function groupAssistantParts(
content: readonly ThreadMessage["content"][number][],
@@ -1105,16 +1127,17 @@ function groupAssistantParts(
return groups;
}
-function IssueChatAssistantParts({
+const IssueChatAssistantParts = memo(function IssueChatAssistantParts({
message,
hasCoT,
}: {
message: ThreadMessage;
hasCoT: boolean;
}) {
+ const groupedParts = useMemo(() => groupAssistantParts(message.content), [message.content]);
return (
<>
- {groupAssistantParts(message.content).map((group) => {
+ {groupedParts.map((group) => {
if (group.type === "text") {
return (
<IssueChatTextPart
@@ -1134,13 +1157,18 @@ function IssueChatAssistantParts({
})}
</>
);
-}
+});
-function IssueChatUserMessage({ message }: { message: ThreadMessage }) {
+function IssueChatUserMessage({
+ message,
+ isInterruptingQueuedRun,
+}: {
+ message: ThreadMessage;
+ isInterruptingQueuedRun: boolean;
+}) {
const {
onInterruptQueued,
onCancelQueued,
- interruptingQueuedRunId,
currentUserId,
userProfileMap,
} = useContext(IssueChatCtx);
@@ -1201,10 +1229,10 @@ function IssueChatUserMessage({ message }: { message: ThreadMessage }) {
size="sm"
variant="outline"
className="h-6 border-red-300 px-2 text-[11px] text-red-700 hover:bg-red-50 hover:text-red-800 dark:border-red-500/40 dark:text-red-300 dark:hover:bg-red-500/10"
- disabled={interruptingQueuedRunId === queueTargetRunId}
+ disabled={isInterruptingQueuedRun}
onClick={() => void onInterruptQueued(queueTargetRunId)}
>
- {interruptingQueuedRunId === queueTargetRunId ? "Interrupting..." : "Interrupt"}
+ {isInterruptingQueuedRun ? "Interrupting..." : "Interrupt"}
</Button>
) : null}
{onCancelQueued ? (
@@ -1290,16 +1318,23 @@ function IssueChatUserMessage({ message }: { message: ThreadMessage }) {
);
}
-function IssueChatAssistantMessage({ message }: { message: ThreadMessage }) {
+function IssueChatAssistantMessage({
+ message,
+ activeVote,
+ isRunActive,
+ isStoppingRun,
+}: {
+ message: ThreadMessage;
+ activeVote: FeedbackVoteValue | null;
+ isRunActive: boolean;
+ isStoppingRun: boolean;
+}) {
const {
- feedbackVoteByTargetId,
feedbackDataSharingPreference,
feedbackTermsUrl,
onVote,
agentMap,
- activeRunIds,
onStopRun,
- stoppingRunId,
} = useContext(IssueChatCtx);
const custom = message.metadata.custom as Record<string, unknown>;
const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
@@ -1321,7 +1356,7 @@ function IssueChatAssistantMessage({ message }: { message: ThreadMessage }) {
const waitingText = typeof custom.waitingText === "string" ? custom.waitingText : "";
const isRunning = message.role === "assistant" && message.status?.type === "running";
const runHref = runId && runAgentId ? `/agents/${runAgentId}/runs/${runId}` : null;
- const canStopRun = canStopIssueChatRun({ runId, runStatus, activeRunIds });
+ const canStopRun = Boolean(runId) && (isRunActive || runStatus === "queued" || runStatus === "running");
const chainOfThoughtLabel = typeof custom.chainOfThoughtLabel === "string" ? custom.chainOfThoughtLabel : null;
const hasCoT = message.content.some((p) => p.type === "reasoning" || p.type === "tool-call");
const isFoldable = !isRunning && !!chainOfThoughtLabel;
@@ -1355,7 +1390,6 @@ function IssueChatAssistantMessage({ message }: { message: ThreadMessage }) {
await onVote(commentId, vote, options);
};
- const activeVote = commentId ? feedbackVoteByTargetId.get(commentId) ?? null : null;
const followUpRequested = custom.followUpRequested === true;
return (
@@ -1493,14 +1527,14 @@ function IssueChatAssistantMessage({ message }: { message: ThreadMessage }) {
</DropdownMenuItem>
{canStopRun && onStopRun && runId ? (
<DropdownMenuItem
- disabled={stoppingRunId === runId}
+ disabled={isStoppingRun}
className="text-red-700 focus:text-red-800 dark:text-red-300 dark:focus:text-red-200"
onSelect={() => {
void onStopRun(runId);
}}
>
<Square className="mr-2 h-3.5 w-3.5 fill-current" />
- {stoppingRunId === runId ? "Stopping…" : "Stop run"}
+ {isStoppingRun ? "Stopping…" : "Stop run"}
</DropdownMenuItem>
) : null}
{runHref ? (
@@ -2022,6 +2056,546 @@ function IssueChatSystemMessage({ message }: { message: ThreadMessage }) {
return null;
}
+function issueChatMessageCustom(message: ThreadMessage): Record<string, unknown> {
+ return (message.metadata?.custom ?? {}) as Record<string, unknown>;
+}
+
+function issueChatMessageKind(message: ThreadMessage): string {
+ const custom = issueChatMessageCustom(message);
+ return typeof custom.kind === "string" ? custom.kind : message.role;
+}
+
+function issueChatMessageCommentId(message: ThreadMessage): string | null {
+ const custom = issueChatMessageCustom(message);
+ return typeof custom.commentId === "string" ? custom.commentId : null;
+}
+
+function issueChatMessageRunId(message: ThreadMessage): string | null {
+ const custom = issueChatMessageCustom(message);
+ return typeof custom.runId === "string" ? custom.runId : null;
+}
+
+function issueChatMessageQueueTargetRunId(message: ThreadMessage): string | null {
+ const custom = issueChatMessageCustom(message);
+ return typeof custom.queueTargetRunId === "string" ? custom.queueTargetRunId : null;
+}
+
+function issueChatMessageActiveVote(
+ message: ThreadMessage,
+ feedbackVoteByTargetId: ReadonlyMap<string, FeedbackVoteValue>,
+): FeedbackVoteValue | null {
+ const commentId = issueChatMessageCommentId(message);
+ return commentId ? feedbackVoteByTargetId.get(commentId) ?? null : null;
+}
+
+function issueChatMessageRunIsActive(
+ message: ThreadMessage,
+ activeRunIds: ReadonlySet<string>,
+): boolean {
+ const runId = issueChatMessageRunId(message);
+ return Boolean(runId && activeRunIds.has(runId));
+}
+
+function issueChatMessageRunIsStopping(
+ message: ThreadMessage,
+ stoppingRunId: string | null | undefined,
+): boolean {
+ const runId = issueChatMessageRunId(message);
+ return Boolean(runId && stoppingRunId === runId);
+}
+
+function issueChatMessageQueuedRunIsInterrupting(
+ message: ThreadMessage,
+ interruptingQueuedRunId: string | null | undefined,
+): boolean {
+ const queueTargetRunId = issueChatMessageQueueTargetRunId(message);
+ return Boolean(queueTargetRunId && interruptingQueuedRunId === queueTargetRunId);
+}
+
+// Above ~150 merged rows the direct render path forces React to mount and
+// re-render hundreds of Markdown bodies, feedback controls, and avatars on
+// unrelated parent updates. Above this threshold we switch to a windowed
+// render path so only visible rows plus overscan stay mounted.
+export const VIRTUALIZED_THREAD_ROW_THRESHOLD = 150;
+const VIRTUALIZED_THREAD_OVERSCAN = 6;
+// Rough "average row" estimate. The virtualizer measures real heights as
+// rows mount, so this only affects offscreen rows it has not seen yet.
+const VIRTUALIZED_THREAD_ROW_ESTIMATE_PX = 220;
+const VIRTUALIZED_THREAD_GAP_FULL_PX = 16;
+const VIRTUALIZED_THREAD_GAP_EMBEDDED_PX = 12;
+
+interface VirtualizedIssueChatThreadListProps {
+ messages: readonly ThreadMessage[];
+ feedbackVoteByTargetId: ReadonlyMap<string, FeedbackVoteValue>;
+ activeRunIds: ReadonlySet<string>;
+ stoppingRunId?: string | null;
+ interruptingQueuedRunId?: string | null;
+ variant: "full" | "embedded";
+}
+
+interface VirtualizedIssueChatThreadListHandle {
+ scrollToIndex: (
+ index: number,
+ options?: { align?: "start" | "center" | "end" | "auto"; behavior?: ScrollBehavior },
+ ) => void;
+ scrollToLatest: (options?: { behavior?: ScrollBehavior }) => void;
+ measure: () => void;
+}
+
+function issueChatMessageAnchorId(message: ThreadMessage): string | null {
+ const custom = message.metadata.custom as { anchorId?: unknown } | undefined;
+ return typeof custom?.anchorId === "string" ? custom.anchorId : null;
+}
+
+function findMessageAnchorIndex(messages: readonly ThreadMessage[], anchorId: string): number {
+ return messages.findIndex((message) => issueChatMessageAnchorId(message) === anchorId);
+}
+
+export function findLatestCommentMessageIndex(messages: readonly ThreadMessage[]): number {
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
+ const anchorId = issueChatMessageAnchorId(messages[index]);
+ if (anchorId && anchorId.startsWith("comment-")) return index;
+ }
+ return -1;
+}
+
+type VirtualizedVisibleAnchorSnapshot = {
+ anchorId: string;
+ index: number;
+ viewportTop: number;
+};
+
+type VirtualizedScrollMode =
+ | { kind: "window" }
+ | { kind: "element"; element: HTMLElement };
+
+type SimpleVirtualItem = {
+ index: number;
+ key: React.Key;
+ start: number;
+ size: number;
+};
+
+function useIssueThreadVirtualizer({
+ count,
+ estimateSize,
+ overscan,
+ scrollMargin,
+ gap,
+ getItemKey,
+ mode,
+}: {
+ count: number;
+ estimateSize: () => number;
+ overscan: number;
+ scrollMargin: number;
+ gap: number;
+ getItemKey: (index: number) => React.Key;
+ mode: VirtualizedScrollMode;
+}) {
+ const measuredSizeByKeyRef = useRef(new Map<React.Key, number>());
+ const [, rerender] = useState(0);
+ const estimatedSize = estimateSize();
+
+ const itemStarts: number[] = [];
+ const itemSizes: number[] = [];
+ let nextStart = scrollMargin;
+ for (let index = 0; index < count; index += 1) {
+ const key = getItemKey(index);
+ const size = measuredSizeByKeyRef.current.get(key) ?? estimatedSize;
+ itemStarts.push(nextStart);
+ itemSizes.push(size);
+ nextStart += size + gap;
+ }
+ const totalSize = Math.max(0, nextStart - scrollMargin - gap);
+
+ const viewportHeight = () => (mode.kind === "window" ? window.innerHeight : mode.element.clientHeight);
+ const scrollOffset = () => (mode.kind === "window" ? window.scrollY : mode.element.scrollTop);
+ const maxScrollOffset = () => {
+ const targetScrollHeight = mode.kind === "window"
+ ? document.documentElement.scrollHeight
+ : mode.element.scrollHeight;
+ return Math.max(0, Math.max(targetScrollHeight, totalSize) - viewportHeight());
+ };
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ const target: Window | HTMLElement = mode.kind === "window" ? window : mode.element;
+ const update = () => rerender((value) => value + 1);
+ target.addEventListener("scroll", update, { passive: true });
+ window.addEventListener("resize", update);
+ return () => {
+ target.removeEventListener("scroll", update);
+ window.removeEventListener("resize", update);
+ };
+ }, [mode]);
+
+ const rawStart = Math.max(scrollMargin, scrollOffset());
+ const rawEnd = rawStart + viewportHeight();
+ let visibleStartIndex = 0;
+ while (
+ visibleStartIndex < count - 1
+ && itemStarts[visibleStartIndex] + itemSizes[visibleStartIndex] < rawStart
+ ) {
+ visibleStartIndex += 1;
+ }
+ let visibleEndIndex = visibleStartIndex;
+ while (visibleEndIndex < count - 1 && itemStarts[visibleEndIndex] <= rawEnd) {
+ visibleEndIndex += 1;
+ }
+ const startIndex = Math.max(0, visibleStartIndex - overscan);
+ const endIndex = Math.min(count - 1, visibleEndIndex + overscan);
+ const virtualItems: SimpleVirtualItem[] = [];
+ for (let index = startIndex; index <= endIndex; index += 1) {
+ virtualItems.push({
+ index,
+ key: getItemKey(index),
+ start: itemStarts[index] ?? scrollMargin,
+ size: itemSizes[index] ?? estimatedSize,
+ });
+ }
+
+ const scrollToIndex = (
+ index: number,
+ options?: { align?: "start" | "center" | "end" | "auto"; behavior?: ScrollBehavior },
+ ) => {
+ const clampedIndex = Math.max(0, Math.min(index, count - 1));
+ const targetMax = maxScrollOffset();
+ let top = itemStarts[clampedIndex] ?? scrollMargin;
+ if (options?.align === "center") {
+ top = top - viewportHeight() / 2 + (itemSizes[clampedIndex] ?? estimatedSize) / 2;
+ } else if (options?.align === "end") {
+ top = top + (itemSizes[clampedIndex] ?? estimatedSize) - viewportHeight();
+ }
+ top = Math.max(0, Math.min(top, targetMax));
+ if (mode.kind === "window") {
+ window.scrollTo({ top, behavior: options?.behavior });
+ } else {
+ mode.element.scrollTo({ top, behavior: options?.behavior });
+ }
+ rerender((value) => value + 1);
+ };
+
+ return {
+ getVirtualItems: () => virtualItems,
+ getTotalSize: () => totalSize,
+ scrollToIndex,
+ measure: () => undefined,
+ measureElement: (element?: HTMLElement | null) => {
+ if (!element) return;
+ const index = Number(element.dataset.index);
+ if (!Number.isInteger(index) || index < 0 || index >= count) return;
+ const measuredSize = element.getBoundingClientRect().height || element.offsetHeight;
+ if (!Number.isFinite(measuredSize) || measuredSize <= 0) return;
+ const key = getItemKey(index);
+ const previousSize = measuredSizeByKeyRef.current.get(key) ?? estimatedSize;
+ if (Math.abs(previousSize - measuredSize) < 1) return;
+ measuredSizeByKeyRef.current.set(key, measuredSize);
+ rerender((value) => value + 1);
+ },
+ };
+}
+
+// The chat thread renders inside `<main id="main-content">` on the real issue
+// page (overflow-auto on desktop), but lives at document scope on mobile (main
+// is overflow-visible) and in the auth-free perf fixture. Walk the DOM to find
+// the actual scroll container so the virtualizer binds to the right offset
+// source — otherwise it stays anchored at offset 0 forever and the visible
+// chat area renders blank past the first viewport (PAP-2660).
+function findScrollContainer(el: HTMLElement | null): HTMLElement | null {
+ if (!el || typeof window === "undefined") return null;
+ let current: HTMLElement | null = el.parentElement;
+ while (current && current !== document.body && current !== document.documentElement) {
+ const overflowY = window.getComputedStyle(current).overflowY;
+ if (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") {
+ return current;
+ }
+ current = current.parentElement;
+ }
+ return null;
+}
+
+const VirtualizedIssueChatThreadList = forwardRef<VirtualizedIssueChatThreadListHandle, VirtualizedIssueChatThreadListProps>(function VirtualizedIssueChatThreadList(props, ref) {
+ const probeRef = useRef<HTMLDivElement | null>(null);
+ // Default to window scroll on first render so the imperative handle is
+ // available immediately for hash-target / submit-scroll effects. After mount
+ // we probe the DOM and remount via key={modeKey} if the actual scroll
+ // container is an element ancestor (e.g. desktop <main id="main-content">).
+ const [mode, setMode] = useState<VirtualizedScrollMode>({ kind: "window" });
+
+ useLayoutEffect(() => {
+ if (typeof window === "undefined") return;
+ const detect = () => {
+ const probe = probeRef.current;
+ if (!probe) return;
+ const container = findScrollContainer(probe);
+ setMode((prev) => {
+ if (container === null) {
+ return prev.kind === "window" ? prev : { kind: "window" };
+ }
+ if (prev.kind === "element" && prev.element === container) return prev;
+ return { kind: "element", element: container };
+ });
+ };
+ detect();
+ window.addEventListener("resize", detect);
+ return () => {
+ window.removeEventListener("resize", detect);
+ };
+ }, []);
+
+ return (
+ <VirtualizedIssueChatThreadListInner
+ key={mode.kind === "window" ? "window" : "element"}
+ ref={ref}
+ probeRef={probeRef}
+ mode={mode}
+ {...props}
+ />
+ );
+});
+
+interface VirtualizedIssueChatThreadListInnerProps extends VirtualizedIssueChatThreadListProps {
+ mode: VirtualizedScrollMode;
+ probeRef: React.MutableRefObject<HTMLDivElement | null>;
+}
+
+const VirtualizedIssueChatThreadListInner = forwardRef<
+ VirtualizedIssueChatThreadListHandle,
+ VirtualizedIssueChatThreadListInnerProps
+>(function VirtualizedIssueChatThreadListInner({
+ messages,
+ feedbackVoteByTargetId,
+ activeRunIds,
+ stoppingRunId,
+ interruptingQueuedRunId,
+ variant,
+ mode,
+ probeRef,
+}, ref) {
+ const parentRef = useRef<HTMLDivElement | null>(null);
+ const [scrollMargin, setScrollMargin] = useState(0);
+ const pendingPrependAnchorRef = useRef<VirtualizedVisibleAnchorSnapshot | null>(null);
+
+ const setRefs = useCallback((element: HTMLDivElement | null) => {
+ parentRef.current = element;
+ probeRef.current = element;
+ }, [probeRef]);
+
+ useLayoutEffect(() => {
+ const element = parentRef.current;
+ if (!element || typeof window === "undefined") return;
+ const update = () => {
+ if (!parentRef.current) return;
+ const rect = parentRef.current.getBoundingClientRect();
+ const offset = mode.kind === "window"
+ ? rect.top + window.scrollY
+ : rect.top - mode.element.getBoundingClientRect().top + mode.element.scrollTop;
+ setScrollMargin((previous) => (Math.abs(previous - offset) < 0.5 ? previous : offset));
+ };
+ update();
+ window.addEventListener("resize", update);
+ return () => {
+ window.removeEventListener("resize", update);
+ };
+ }, [mode]);
+
+ const gap = variant === "embedded"
+ ? VIRTUALIZED_THREAD_GAP_EMBEDDED_PX
+ : VIRTUALIZED_THREAD_GAP_FULL_PX;
+
+ const virtualizer = useIssueThreadVirtualizer({
+ count: messages.length,
+ estimateSize: () => VIRTUALIZED_THREAD_ROW_ESTIMATE_PX,
+ overscan: VIRTUALIZED_THREAD_OVERSCAN,
+ scrollMargin,
+ gap,
+ getItemKey: (index) => messages[index]?.id ?? index,
+ mode,
+ });
+
+ useImperativeHandle(ref, () => ({
+ scrollToIndex: (index, options) => {
+ if (index < 0 || index >= messages.length) return;
+ virtualizer.scrollToIndex(index, {
+ align: options?.align ?? "center",
+ behavior: options?.behavior ?? "smooth",
+ });
+ },
+ scrollToLatest: (options) => {
+ if (messages.length === 0) return;
+ virtualizer.scrollToIndex(messages.length - 1, {
+ align: "end",
+ behavior: options?.behavior ?? "smooth",
+ });
+ },
+ measure: () => {
+ virtualizer.measure();
+ },
+ }), [messages.length, virtualizer]);
+
+ useLayoutEffect(() => {
+ return () => {
+ const element = parentRef.current;
+ if (!element || typeof window === "undefined") return;
+ const rows = Array.from(
+ element.querySelectorAll<HTMLElement>("[data-anchor-id][data-index]"),
+ );
+ const visibleRow = rows.find((row) => row.getBoundingClientRect().bottom >= 0);
+ if (!visibleRow) return;
+ const anchorId = visibleRow.dataset.anchorId;
+ const index = Number(visibleRow.dataset.index);
+ if (!anchorId || !Number.isFinite(index)) return;
+ pendingPrependAnchorRef.current = {
+ anchorId,
+ index,
+ viewportTop: visibleRow.getBoundingClientRect().top,
+ };
+ };
+ }, [messages]);
+
+ useLayoutEffect(() => {
+ const pendingAnchor = pendingPrependAnchorRef.current;
+ pendingPrependAnchorRef.current = null;
+ virtualizer.measure();
+ if (!pendingAnchor || typeof window === "undefined") return;
+ const nextIndex = findMessageAnchorIndex(messages, pendingAnchor.anchorId);
+ if (nextIndex <= pendingAnchor.index) return;
+
+ virtualizer.scrollToIndex(nextIndex, { align: "start", behavior: "auto" });
+ requestAnimationFrame(() => {
+ const element = document.getElementById(pendingAnchor.anchorId);
+ if (!element) return;
+ const delta = element.getBoundingClientRect().top - pendingAnchor.viewportTop;
+ if (Math.abs(delta) > 1) {
+ if (mode.kind === "window") {
+ window.scrollBy({ top: delta, behavior: "auto" });
+ } else {
+ mode.element.scrollBy({ top: delta, behavior: "auto" });
+ }
+ }
+ virtualizer.measure();
+ });
+ }, [messages, virtualizer, mode]);
+
+ const virtualItems = virtualizer.getVirtualItems();
+ const totalSize = virtualizer.getTotalSize();
+
+ return (
+ <div
+ ref={setRefs}
+ data-testid="issue-chat-thread-virtualizer"
+ data-virtual-count={messages.length}
+ style={{ position: "relative", width: "100%", height: totalSize }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const message = messages[virtualItem.index];
+ if (!message) return null;
+ const anchorId = issueChatMessageAnchorId(message);
+ return (
+ <div
+ key={virtualItem.key}
+ data-index={virtualItem.index}
+ data-anchor-id={anchorId ?? undefined}
+ data-testid="issue-chat-thread-virtual-row"
+ ref={(element) => {
+ if (element) virtualizer.measureElement(element);
+ }}
+ onLoadCapture={(event) => {
+ virtualizer.measureElement(event.currentTarget);
+ }}
+ onClickCapture={(event) => {
+ const row = event.currentTarget;
+ requestAnimationFrame(() => {
+ virtualizer.measureElement(row);
+ });
+ }}
+ onTransitionEndCapture={(event) => {
+ virtualizer.measureElement(event.currentTarget);
+ }}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ right: 0,
+ transform: `translateY(${virtualItem.start - scrollMargin}px)`,
+ }}
+ >
+ <IssueChatMessageRow
+ message={message}
+ feedbackVoteByTargetId={feedbackVoteByTargetId}
+ activeRunIds={activeRunIds}
+ stoppingRunId={stoppingRunId}
+ interruptingQueuedRunId={interruptingQueuedRunId}
+ />
+ </div>
+ );
+ })}
+ </div>
+ );
+});
+
+interface IssueChatMessageRowProps {
+ message: ThreadMessage;
+ feedbackVoteByTargetId: ReadonlyMap<string, FeedbackVoteValue>;
+ activeRunIds: ReadonlySet<string>;
+ stoppingRunId?: string | null;
+ interruptingQueuedRunId?: string | null;
+}
+
+const IssueChatMessageRow = memo(function IssueChatMessageRow({
+ message,
+ feedbackVoteByTargetId,
+ activeRunIds,
+ stoppingRunId,
+ interruptingQueuedRunId,
+}: IssueChatMessageRowProps) {
+ const kind = issueChatMessageKind(message);
+ const activeVote = issueChatMessageActiveVote(message, feedbackVoteByTargetId);
+ const isRunActive = issueChatMessageRunIsActive(message, activeRunIds);
+ const isStoppingRun = issueChatMessageRunIsStopping(message, stoppingRunId);
+ const isInterruptingQueuedRun = issueChatMessageQueuedRunIsInterrupting(message, interruptingQueuedRunId);
+ const renderedMessage = message.role === "user"
+ ? (
+ <IssueChatUserMessage
+ message={message}
+ isInterruptingQueuedRun={isInterruptingQueuedRun}
+ />
+ )
+ : message.role === "assistant"
+ ? (
+ <IssueChatAssistantMessage
+ message={message}
+ activeVote={activeVote}
+ isRunActive={isRunActive}
+ isStoppingRun={isStoppingRun}
+ />
+ )
+ : <IssueChatSystemMessage message={message} />;
+
+ return (
+ <div
+ data-testid="issue-chat-message-row"
+ data-message-role={message.role}
+ data-message-kind={kind}
+ >
+ {renderedMessage}
+ </div>
+ );
+}, areIssueChatMessageRowPropsEqual);
+
+function areIssueChatMessageRowPropsEqual(
+ prev: IssueChatMessageRowProps,
+ next: IssueChatMessageRowProps,
+) {
+ if (prev.message !== next.message) return false;
+ if (issueChatMessageActiveVote(prev.message, prev.feedbackVoteByTargetId) !== issueChatMessageActiveVote(next.message, next.feedbackVoteByTargetId)) return false;
+ if (issueChatMessageRunIsActive(prev.message, prev.activeRunIds) !== issueChatMessageRunIsActive(next.message, next.activeRunIds)) return false;
+ if (issueChatMessageRunIsStopping(prev.message, prev.stoppingRunId) !== issueChatMessageRunIsStopping(next.message, next.stoppingRunId)) return false;
+ if (issueChatMessageQueuedRunIsInterrupting(prev.message, prev.interruptingQueuedRunId) !== issueChatMessageQueuedRunIsInterrupting(next.message, next.interruptingQueuedRunId)) return false;
+ return true;
+}
+
const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerProps>(function IssueChatComposer({
onImageUpload,
onAttachImage,
@@ -2037,6 +2611,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
issueStatus,
}, forwardedRef) {
const api = useAui();
+ const toastActions = useOptionalToastActions();
const [body, setBody] = useState("");
const [submitting, setSubmitting] = useState(false);
const [attaching, setAttaching] = useState(false);
@@ -2045,6 +2620,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
const dragDepthRef = useRef(0);
const effectiveSuggestedAssigneeValue = suggestedAssigneeValue ?? currentAssigneeValue;
const [reassignTarget, setReassignTarget] = useState(effectiveSuggestedAssigneeValue);
+ const [unassignedConfirmed, setUnassignedConfirmed] = useState(false);
const attachInputRef = useRef<HTMLInputElement | null>(null);
const editorRef = useRef<MarkdownEditorRef>(null);
const composerContainerRef = useRef<HTMLDivElement | null>(null);
@@ -2091,6 +2667,10 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
setReassignTarget(effectiveSuggestedAssigneeValue);
}, [effectiveSuggestedAssigneeValue]);
+ useEffect(() => {
+ setUnassignedConfirmed(false);
+ }, [reassignTarget]);
+
useImperativeHandle(forwardedRef, () => ({
focus: focusComposer,
restoreDraft: (submittedBody: string) => {
@@ -2108,6 +2688,22 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
const trimmed = body.trim();
if (!trimmed || submitting) return;
+ const composerHasAssigneePicker = enableReassign && reassignOptions.length > 0;
+ if (
+ composerHasAssigneePicker
+ && isUnassignedReassignValue(reassignTarget)
+ && !unassignedConfirmed
+ ) {
+ toastActions?.pushToast({
+ title: "No assignee selected",
+ body: "Pick an assignee or click Send again to post without one.",
+ tone: "warn",
+ dedupeKey: `issue-chat-no-assignee:${draftKey ?? ""}`,
+ });
+ setUnassignedConfirmed(true);
+ return;
+ }
+
const hasReassignment = enableReassign && reassignTarget !== currentAssigneeValue;
const reassignment = hasReassignment ? parseReassignment(reassignTarget) : undefined;
const reopen = shouldImplicitlyReopenComment(
@@ -2119,6 +2715,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
setSubmitting(true);
setBody("");
+ setUnassignedConfirmed(false);
try {
const appendPromise = api.thread().append({
role: "user",
@@ -2491,9 +3088,11 @@ export function IssueChatThread({
onRejectInteraction,
onSubmitInteractionAnswers,
composerRef,
+ onRefreshLatestComments,
}: IssueChatThreadProps) {
const location = useLocation();
- const hasScrolledRef = useRef(false);
+ const lastScrolledHashRef = useRef<string | null>(null);
+ const virtualizedThreadRef = useRef<VirtualizedIssueChatThreadListHandle | null>(null);
const bottomAnchorRef = useRef<HTMLDivElement | null>(null);
const composerViewportAnchorRef = useRef<HTMLDivElement | null>(null);
const composerViewportSnapshotRef = useRef<ReturnType<typeof captureComposerViewportSnapshot>>(null);
@@ -2614,6 +3213,42 @@ export function IssueChatThread({
}
return map;
}, [feedbackVotes]);
+ const useVirtualizedThread = messages.length >= VIRTUALIZED_THREAD_ROW_THRESHOLD;
+ const messageAnchorIndex = useMemo(() => {
+ const map = new Map<string, number>();
+ messages.forEach((message, index) => {
+ const anchorId = issueChatMessageAnchorId(message);
+ if (anchorId) map.set(anchorId, index);
+ });
+ return map;
+ }, [messages]);
+
+ function scrollToThreadAnchor(
+ anchorId: string,
+ options?: { align?: "start" | "center" | "end" | "auto"; behavior?: ScrollBehavior },
+ ) {
+ const virtualIndex = messageAnchorIndex.get(anchorId);
+ if (useVirtualizedThread && virtualIndex !== undefined) {
+ if (!virtualizedThreadRef.current) return false;
+ virtualizedThreadRef.current.scrollToIndex(virtualIndex, {
+ align: options?.align ?? "center",
+ behavior: options?.behavior ?? "smooth",
+ });
+ return true;
+ }
+
+ const element = document.getElementById(anchorId);
+ if (!element) return false;
+ element.scrollIntoView({
+ behavior: options?.behavior ?? "smooth",
+ block: options?.align === "start"
+ ? "start"
+ : options?.align === "end"
+ ? "end"
+ : "center",
+ });
+ return true;
+ }
const runtime = usePaperclipIssueRuntime({
messages,
@@ -2643,14 +3278,13 @@ export function IssueChatThread({
spacerInitialReserveRef.current = reserve;
setBottomSpacerHeight(reserve);
requestAnimationFrame(() => {
- const el = document.getElementById(anchorId);
- el?.scrollIntoView({ behavior: "smooth", block: "start" });
+ scrollToThreadAnchor(anchorId, { align: "start", behavior: "smooth" });
});
}
}
lastUserMessageIdRef.current = lastUserId;
- }, [messages]);
+ }, [messageAnchorIndex, messages, useVirtualizedThread]);
useLayoutEffect(() => {
const anchorId = spacerBaselineAnchorRef.current;
@@ -2683,7 +3317,7 @@ export function IssueChatThread({
}, [messages]);
useEffect(() => {
- const hash = location.hash;
+ const hash = location.hash || (typeof window !== "undefined" ? window.location.hash : "");
if (
!(
hash.startsWith("#comment-")
@@ -2692,58 +3326,141 @@ export function IssueChatThread({
|| hash.startsWith("#interaction-")
)
) return;
- if (messages.length === 0 || hasScrolledRef.current) return;
+ if (messages.length === 0 || lastScrolledHashRef.current === hash) return;
const targetId = hash.slice(1);
- const element = document.getElementById(targetId);
- if (!element) return;
- hasScrolledRef.current = true;
- element.scrollIntoView({ behavior: "smooth", block: "center" });
- }, [location.hash, messages]);
+ let cancelled = false;
+ const attemptScroll = (finalAttempt = false) => {
+ if (cancelled || lastScrolledHashRef.current === hash) return;
+ const didScroll = scrollToThreadAnchor(targetId, { align: "center", behavior: "smooth" });
+ if (!didScroll) return;
+ if (finalAttempt || !useVirtualizedThread || document.getElementById(targetId)) {
+ lastScrolledHashRef.current = hash;
+ }
+ };
- function handleJumpToLatest() {
+ attemptScroll();
+ const frame = requestAnimationFrame(() => attemptScroll());
+ const timeout = window.setTimeout(() => attemptScroll(true), 250);
+ return () => {
+ cancelled = true;
+ cancelAnimationFrame(frame);
+ window.clearTimeout(timeout);
+ };
+ }, [location.hash, messageAnchorIndex, messages, useVirtualizedThread]);
+
+ function jumpToLatestFallback() {
+ if (useVirtualizedThread) {
+ virtualizedThreadRef.current?.scrollToLatest({ behavior: "smooth" });
+ return;
+ }
bottomAnchorRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
}
+ // Walks the thread by anchor and lands on the latest `comment-*` row, with
+ // a short series of settle passes. The virtualizer estimates row sizes for
+ // unmeasured rows, and that estimate undershoots tall markdown comments —
+ // so the first scroll often lands above the actual bottom and the user
+ // ends up clicking Jump to latest repeatedly to converge. Re-issuing the
+ // scroll after measurements catch up lets one click reach the actual
+ // latest comment (PAP-2672 follow-up).
+ function scrollToLatestCommentWithSettle() {
+ const latestCommentIndex = findLatestCommentMessageIndex(messages);
+ if (latestCommentIndex < 0) {
+ jumpToLatestFallback();
+ return;
+ }
+ const latestCommentAnchor = issueChatMessageAnchorId(messages[latestCommentIndex]);
+ if (!latestCommentAnchor) {
+ jumpToLatestFallback();
+ return;
+ }
+
+ const initial = scrollToThreadAnchor(latestCommentAnchor, { align: "end", behavior: "smooth" });
+ if (!initial) {
+ jumpToLatestFallback();
+ return;
+ }
+
+ if (typeof window === "undefined") return;
+
+ const settleDelays = [380, 760, 1140];
+ settleDelays.forEach((delay) => {
+ window.setTimeout(() => {
+ const el = document.getElementById(latestCommentAnchor);
+ if (el) {
+ el.scrollIntoView({ behavior: "smooth", block: "end" });
+ return;
+ }
+ // The row may still be outside the virtualizer's render buffer; nudge
+ // the offset so it gets mounted, then the next pass can align with
+ // real DOM measurements.
+ virtualizedThreadRef.current?.scrollToIndex(latestCommentIndex, {
+ align: "end",
+ behavior: "auto",
+ });
+ }, delay);
+ });
+ }
+
+ function handleJumpToLatest() {
+ if (onRefreshLatestComments) {
+ // Refetching from page 0 (newest first) brings any comments that
+ // arrived after the initial load into the cache before we scroll —
+ // otherwise we'd land on the latest *loaded* row rather than the
+ // absolute newest, which is what PAP-2672 reopened on.
+ const refreshed = onRefreshLatestComments();
+ if (refreshed && typeof (refreshed as Promise<unknown>).then === "function") {
+ (refreshed as Promise<unknown>).then(
+ () => scrollToLatestCommentWithSettle(),
+ () => scrollToLatestCommentWithSettle(),
+ );
+ return;
+ }
+ }
+ scrollToLatestCommentWithSettle();
+ }
+
+ const stableOnVote = useStableEvent(onVote);
+ const stableOnStopRun = useStableEvent(onStopRun);
+ const stableOnInterruptQueued = useStableEvent(onInterruptQueued);
+ const stableOnCancelQueued = useStableEvent(onCancelQueued);
+ const stableOnImageClick = useStableEvent(onImageClick);
+ const stableOnAcceptInteraction = useStableEvent(onAcceptInteraction);
+ const stableOnRejectInteraction = useStableEvent(onRejectInteraction);
+ const stableOnSubmitInteractionAnswers = useStableEvent(onSubmitInteractionAnswers);
+
const chatCtx = useMemo<IssueChatMessageContext>(
() => ({
- feedbackVoteByTargetId,
feedbackDataSharingPreference,
feedbackTermsUrl,
agentMap,
currentUserId,
userLabelMap,
userProfileMap,
- activeRunIds,
- onVote,
- onStopRun,
- stoppingRunId,
- onInterruptQueued,
- onCancelQueued,
- interruptingQueuedRunId,
- onImageClick,
- onAcceptInteraction,
- onRejectInteraction,
- onSubmitInteractionAnswers,
+ onVote: stableOnVote,
+ onStopRun: stableOnStopRun,
+ onInterruptQueued: stableOnInterruptQueued,
+ onCancelQueued: stableOnCancelQueued,
+ onImageClick: stableOnImageClick,
+ onAcceptInteraction: stableOnAcceptInteraction,
+ onRejectInteraction: stableOnRejectInteraction,
+ onSubmitInteractionAnswers: stableOnSubmitInteractionAnswers,
}),
[
- feedbackVoteByTargetId,
feedbackDataSharingPreference,
feedbackTermsUrl,
agentMap,
currentUserId,
userLabelMap,
userProfileMap,
- activeRunIds,
- onVote,
- onStopRun,
- stoppingRunId,
- onInterruptQueued,
- onCancelQueued,
- interruptingQueuedRunId,
- onImageClick,
- onAcceptInteraction,
- onRejectInteraction,
- onSubmitInteractionAnswers,
+ stableOnVote,
+ stableOnStopRun,
+ stableOnInterruptQueued,
+ stableOnCancelQueued,
+ stableOnImageClick,
+ stableOnAcceptInteraction,
+ stableOnRejectInteraction,
+ stableOnSubmitInteractionAnswers,
],
);
@@ -2752,10 +3469,13 @@ export function IssueChatThread({
?? (variant === "embedded"
? "No run output yet."
: "This issue conversation is empty. Start with a message below.");
- const errorBoundaryResetKey = useMemo(
- () => messages.map((message) => `${message.id}:${message.role}:${message.content.length}:${message.status?.type ?? "none"}`).join("|"),
- [messages],
- );
+ const previousErrorBoundaryMessagesRef = useRef<readonly ThreadMessage[] | null>(null);
+ const errorBoundaryResetVersionRef = useRef(0);
+ if (previousErrorBoundaryMessagesRef.current !== messages) {
+ previousErrorBoundaryMessagesRef.current = messages;
+ errorBoundaryResetVersionRef.current += 1;
+ }
+ const errorBoundaryResetKey = String(errorBoundaryResetVersionRef.current);
return (
<AssistantRuntimeProvider runtime={runtime}>
@@ -2793,19 +3513,30 @@ export function IssueChatThread({
)}>
{resolvedEmptyMessage}
</div>
+ ) : messages.length >= VIRTUALIZED_THREAD_ROW_THRESHOLD ? (
+ <VirtualizedIssueChatThreadList
+ ref={virtualizedThreadRef}
+ messages={messages}
+ feedbackVoteByTargetId={feedbackVoteByTargetId}
+ activeRunIds={activeRunIds}
+ stoppingRunId={stoppingRunId}
+ interruptingQueuedRunId={interruptingQueuedRunId}
+ variant={variant}
+ />
) : (
// Keep transcript rendering independent from assistant-ui's
// index-scoped message providers; live transcripts can shrink
// or regroup while the runtime still holds stale indices.
- messages.map((message) => {
- if (message.role === "user") {
- return <IssueChatUserMessage key={message.id} message={message} />;
- }
- if (message.role === "assistant") {
- return <IssueChatAssistantMessage key={message.id} message={message} />;
- }
- return <IssueChatSystemMessage key={message.id} message={message} />;
- })
+ messages.map((message) => (
+ <IssueChatMessageRow
+ key={message.id}
+ message={message}
+ feedbackVoteByTargetId={feedbackVoteByTargetId}
+ activeRunIds={activeRunIds}
+ stoppingRunId={stoppingRunId}
+ interruptingQueuedRunId={interruptingQueuedRunId}
+ />
+ ))
)}
{showComposer ? (
<div data-testid="issue-chat-thread-notices" className="space-y-2">
diff --git a/ui/src/components/IssueRow.tsx b/ui/src/components/IssueRow.tsx
index d6969d2332..664990b1e1 100644
--- a/ui/src/components/IssueRow.tsx
+++ b/ui/src/components/IssueRow.tsx
@@ -1,7 +1,7 @@
import type { ReactNode } from "react";
import type { Issue } from "@paperclipai/shared";
import { Link } from "@/lib/router";
-import { X } from "lucide-react";
+import { Eye, X } from "lucide-react";
import {
createIssueDetailPath,
rememberIssueDetailLocationState,
@@ -9,6 +9,7 @@ import {
} from "../lib/issueDetailBreadcrumb";
import { cn } from "../lib/utils";
import { StatusIcon } from "./StatusIcon";
+import { productivityReviewTriggerLabel } from "./ProductivityReviewBadge";
type UnreadState = "hidden" | "visible" | "fading";
@@ -63,6 +64,19 @@ export function IssueRow({
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
const selectedStatusClass = selected ? "!text-muted-foreground !border-muted-foreground" : undefined;
const detailState = withIssueDetailHeaderSeed(issueLinkState, issue);
+ const productivityReview = issue.productivityReview ?? null;
+ const productivityReviewIndicator = productivityReview ? (
+ <span
+ className={cn(
+ "inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-300",
+ selected ? "border-muted-foreground text-muted-foreground" : null,
+ )}
+ title={`Productivity review: ${productivityReviewTriggerLabel(productivityReview.trigger)}`}
+ aria-label="Productivity review open"
+ >
+ <Eye className="h-2.5 w-2.5" aria-hidden />
+ </span>
+ ) : null;
const hasChecklistStep = checklistStepNumber !== null;
const checklistStep = hasChecklistStep ? (
<span className="shrink-0 font-mono text-xs text-muted-foreground" aria-hidden="true">
@@ -87,8 +101,9 @@ export function IssueRow({
className,
)}
>
- <span className="shrink-0 pt-px sm:hidden">
+ <span className="flex shrink-0 items-center gap-1 pt-px sm:hidden">
{mobileLeading ?? <StatusIcon status={issue.status} blockerAttention={issue.blockerAttention} className={selectedStatusClass} />}
+ {productivityReviewIndicator}
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1 sm:contents">
<span className={cn("line-clamp-2 text-sm sm:order-2 sm:min-w-0 sm:flex-1 sm:truncate sm:line-clamp-none", titleClassName)}>
@@ -105,8 +120,9 @@ export function IssueRow({
) : null}
{desktopMetaLeading ?? (
<>
- <span className="hidden shrink-0 sm:inline-flex">
+ <span className="hidden shrink-0 items-center gap-1 sm:inline-flex">
<StatusIcon status={issue.status} blockerAttention={issue.blockerAttention} className={selectedStatusClass} />
+ {productivityReviewIndicator}
</span>
{checklistStep}
<span className="shrink-0 font-mono text-xs text-muted-foreground">
diff --git a/ui/src/components/IssuesList.test.tsx b/ui/src/components/IssuesList.test.tsx
index ba615dc2b2..9ca8166594 100644
--- a/ui/src/components/IssuesList.test.tsx
+++ b/ui/src/components/IssuesList.test.tsx
@@ -48,6 +48,7 @@ vi.mock("../context/CompanyContext", () => ({
vi.mock("../context/DialogContext", () => ({
useDialog: () => dialogState,
+ useDialogActions: () => dialogState,
}));
vi.mock("@/lib/router", () => ({
@@ -221,6 +222,20 @@ async function waitForMicrotaskAssertion(assertion: () => void, attempts = 20) {
throw lastError;
}
+function setDocumentScrollMetrics({
+ innerHeight,
+ scrollY,
+ scrollHeight,
+}: {
+ innerHeight: number;
+ scrollY: number;
+ scrollHeight: number;
+}) {
+ Object.defineProperty(window, "innerHeight", { configurable: true, value: innerHeight });
+ Object.defineProperty(window, "scrollY", { configurable: true, value: scrollY });
+ Object.defineProperty(document.documentElement, "scrollHeight", { configurable: true, value: scrollHeight });
+}
+
function renderWithQueryClient(node: ReactNode, container: HTMLDivElement) {
const root = createRoot(container);
const queryClient = new QueryClient({
@@ -268,6 +283,7 @@ describe("IssuesList", () => {
mockExecutionWorkspacesApi.list.mockResolvedValue([]);
mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([]);
mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: false });
+ setDocumentScrollMetrics({ innerHeight: 600, scrollY: 0, scrollHeight: 2400 });
localStorage.clear();
});
@@ -853,6 +869,142 @@ describe("IssuesList", () => {
});
});
+ it("keeps rendering local issue batches while the user stays near the bottom", async () => {
+ const manyIssues = Array.from({ length: 420 }, (_, index) =>
+ createIssue({
+ id: `issue-${index + 1}`,
+ identifier: `PAP-${index + 1}`,
+ title: `Issue ${index + 1}`,
+ }),
+ );
+
+ const { root } = renderWithQueryClient(
+ <IssuesList
+ issues={manyIssues}
+ agents={[]}
+ projects={[]}
+ viewStateKey="paperclip:test-issues"
+ onUpdateIssue={() => undefined}
+ />,
+ container,
+ );
+
+ await waitForAssertion(() => {
+ expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(100);
+ });
+
+ act(() => {
+ setDocumentScrollMetrics({ innerHeight: 600, scrollY: 1500, scrollHeight: 2000 });
+ window.dispatchEvent(new Event("scroll"));
+ });
+
+ await waitForAssertion(() => {
+ expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(250);
+ expect(container.textContent).toContain("Rendering 250 of 420 issues");
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("waits for the desktop main scroll container before rendering more local rows", async () => {
+ const manyIssues = Array.from({ length: 420 }, (_, index) =>
+ createIssue({
+ id: `issue-${index + 1}`,
+ identifier: `PAP-${index + 1}`,
+ title: `Issue ${index + 1}`,
+ }),
+ );
+ const main = document.createElement("main");
+ main.id = "main-content";
+ main.style.overflowY = "auto";
+ document.body.appendChild(main);
+ main.appendChild(container);
+ Object.defineProperty(main, "clientHeight", { configurable: true, value: 600 });
+ Object.defineProperty(main, "scrollHeight", { configurable: true, value: 2000 });
+ Object.defineProperty(main, "scrollTop", { configurable: true, writable: true, value: 0 });
+ setDocumentScrollMetrics({ innerHeight: 600, scrollY: 0, scrollHeight: 600 });
+
+ const { root } = renderWithQueryClient(
+ <IssuesList
+ issues={manyIssues}
+ agents={[]}
+ projects={[]}
+ viewStateKey="paperclip:test-issues"
+ onUpdateIssue={() => undefined}
+ />,
+ container,
+ );
+
+ await waitForAssertion(() => {
+ expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(100);
+ });
+
+ await flush();
+ await flush();
+ expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(100);
+
+ act(() => {
+ main.scrollTop = 1500;
+ main.dispatchEvent(new Event("scroll"));
+ });
+
+ await waitForAssertion(() => {
+ expect(container.querySelectorAll('[data-testid="issue-row"]').length).toBeGreaterThan(100);
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
+ it("requests more server issues after scrolling past the rendered rows", async () => {
+ const visibleIssues = Array.from({ length: 100 }, (_, index) =>
+ createIssue({
+ id: `issue-${index + 1}`,
+ identifier: `PAP-${index + 1}`,
+ title: `Issue ${index + 1}`,
+ }),
+ );
+ const onLoadMoreIssues = vi.fn();
+ setDocumentScrollMetrics({ innerHeight: 2000, scrollY: 0, scrollHeight: 1000 });
+
+ const { root } = renderWithQueryClient(
+ <IssuesList
+ issues={visibleIssues}
+ agents={[]}
+ projects={[]}
+ viewStateKey="paperclip:test-issues"
+ hasMoreIssues
+ onLoadMoreIssues={onLoadMoreIssues}
+ onUpdateIssue={() => undefined}
+ />,
+ container,
+ );
+
+ await waitForAssertion(() => {
+ expect(container.querySelectorAll('[data-testid="issue-row"]')).toHaveLength(100);
+ });
+ await flush();
+ expect(onLoadMoreIssues).toHaveBeenCalledTimes(1);
+ await flush();
+ expect(onLoadMoreIssues).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ setDocumentScrollMetrics({ innerHeight: 600, scrollY: 1500, scrollHeight: 2000 });
+ window.dispatchEvent(new Event("scroll"));
+ });
+
+ await waitForAssertion(() => {
+ expect(onLoadMoreIssues).toHaveBeenCalledTimes(2);
+ });
+
+ act(() => {
+ root.unmount();
+ });
+ });
+
it("skips deferred row sizing for expanded parent rows with visible children", async () => {
const parentIssue = createIssue({
id: "issue-parent",
diff --git a/ui/src/components/IssuesList.tsx b/ui/src/components/IssuesList.tsx
index cce4e50273..9cf1a48d84 100644
--- a/ui/src/components/IssuesList.tsx
+++ b/ui/src/components/IssuesList.tsx
@@ -1,7 +1,7 @@
import { startTransition, useDeferredValue, useEffect, useMemo, useState, useCallback, useRef } from "react";
import { useQueries, useQuery } from "@tanstack/react-query";
import { accessApi } from "../api/access";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { Link } from "@/lib/router";
import { executionWorkspacesApi } from "../api/execution-workspaces";
@@ -72,7 +72,20 @@ const ISSUE_SEARCH_RESULT_LIMIT = 200;
const ISSUE_BOARD_COLUMN_RESULT_LIMIT = 200;
const INITIAL_ISSUE_ROW_RENDER_LIMIT = 100;
const ISSUE_ROW_RENDER_BATCH_SIZE = 150;
-const ISSUE_ROW_RENDER_BATCH_DELAY_MS = 0;
+const ISSUE_SCROLL_LOAD_THRESHOLD_PX = 320;
+
+function findIssuesScrollContainer(element: HTMLElement | null): HTMLElement | null {
+ if (!element || typeof window === "undefined") return null;
+ let current = element.parentElement;
+ while (current && current !== document.body && current !== document.documentElement) {
+ const overflowY = window.getComputedStyle(current).overflowY;
+ if (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") {
+ return current;
+ }
+ current = current.parentElement;
+ }
+ return null;
+}
const boardIssueStatuses = ISSUE_STATUSES;
const issueStatusLabels: Record<IssueStatus, string> = {
backlog: "Backlog",
@@ -306,8 +319,11 @@ interface IssuesListProps {
defaultSortField?: IssueSortField;
showProgressSummary?: boolean;
enableRoutineVisibilityFilter?: boolean;
+ hasMoreIssues?: boolean;
+ isLoadingMoreIssues?: boolean;
mutedIssueIds?: Set<string>;
issueBadgeById?: Map<string, string>;
+ onLoadMoreIssues?: () => void;
onSearchChange?: (search: string) => void;
onUpdateIssue: (id: string, data: Record<string, unknown>) => void;
}
@@ -475,13 +491,17 @@ export function IssuesList({
defaultSortField,
showProgressSummary = false,
enableRoutineVisibilityFilter = false,
+ hasMoreIssues = false,
+ isLoadingMoreIssues = false,
mutedIssueIds,
issueBadgeById,
+ onLoadMoreIssues,
onSearchChange,
onUpdateIssue,
}: IssuesListProps) {
+ const rootRef = useRef<HTMLDivElement | null>(null);
const { selectedCompanyId } = useCompany();
- const { openNewIssue } = useDialog();
+ const { openNewIssue } = useDialogActions();
const { data: session } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
@@ -512,6 +532,8 @@ export function IssuesList({
const [issueSearch, setIssueSearch] = useState(initialSearch ?? "");
const [renderedIssueRowLimit, setRenderedIssueRowLimit] = useState(INITIAL_ISSUE_ROW_RENDER_LIMIT);
const [visibleIssueColumns, setVisibleIssueColumns] = useState<InboxIssueColumn[]>(() => loadIssueColumns(scopedKey));
+ const renderedIssueIdsRef = useRef("");
+ const initialServerFillRequestedRef = useRef(false);
const deferredIssueSearch = useDeferredValue(issueSearch);
const normalizedIssueSearch = deferredIssueSearch.trim().toLowerCase();
@@ -966,23 +988,86 @@ export function IssuesList({
useEffect(() => {
if (viewState.viewMode !== "list") return;
- setRenderedIssueRowLimit(Math.min(filtered.length, INITIAL_ISSUE_ROW_RENDER_LIMIT));
+ const nextIssueIds = filtered.map((issue) => issue.id).join("|");
+ const previousIssueIds = renderedIssueIdsRef.current;
+ renderedIssueIdsRef.current = nextIssueIds;
+
+ setRenderedIssueRowLimit((current) => {
+ const nextInitialLimit = Math.min(filtered.length, INITIAL_ISSUE_ROW_RENDER_LIMIT);
+ const listAppended = previousIssueIds.length > 0
+ && nextIssueIds.startsWith(previousIssueIds)
+ && filtered.length >= current;
+ if (listAppended) return Math.min(filtered.length, Math.max(current, nextInitialLimit));
+ return nextInitialLimit;
+ });
}, [filtered, viewState.viewMode]);
- useEffect(() => {
+ const hasMoreRenderedRows = viewState.viewMode === "list" && renderedIssueRowLimit < filtered.length;
+ const remainingIssueRowCount = Math.max(filtered.length - renderedIssueRowLimit, 0);
+ const loadMoreIssueRows = useCallback(() => {
if (viewState.viewMode !== "list") return;
- if (renderedIssueRowLimit >= filtered.length) return;
-
- const timeoutId = window.setTimeout(() => {
+ if (hasMoreRenderedRows) {
startTransition(() => {
setRenderedIssueRowLimit((current) => Math.min(filtered.length, current + ISSUE_ROW_RENDER_BATCH_SIZE));
});
- }, ISSUE_ROW_RENDER_BATCH_DELAY_MS);
+ return;
+ }
+ if (hasMoreIssues && !isLoadingMoreIssues) {
+ onLoadMoreIssues?.();
+ }
+ }, [
+ filtered.length,
+ hasMoreIssues,
+ hasMoreRenderedRows,
+ isLoadingMoreIssues,
+ onLoadMoreIssues,
+ viewState.viewMode,
+ ]);
- return () => window.clearTimeout(timeoutId);
- }, [filtered.length, renderedIssueRowLimit, viewState.viewMode]);
+ const canLoadMoreIssues = viewState.viewMode === "list"
+ && !isLoading
+ && (hasMoreRenderedRows || (hasMoreIssues && !isLoadingMoreIssues));
- const remainingIssueRowCount = Math.max(filtered.length - renderedIssueRowLimit, 0);
+ useEffect(() => {
+ if (!canLoadMoreIssues) return;
+ let animationFrameId: number | null = null;
+ const scrollContainer = findIssuesScrollContainer(rootRef.current);
+ const scrollTarget: Window | HTMLElement = scrollContainer ?? window;
+
+ const checkScrollPosition = (trigger: "initial" | "scroll" | "resize" = "scroll") => {
+ if (animationFrameId !== null) return;
+ animationFrameId = window.requestAnimationFrame(() => {
+ animationFrameId = null;
+ const scrollHeight = scrollContainer?.scrollHeight ?? document.documentElement.scrollHeight;
+ if (scrollHeight === 0) return;
+ const viewportHeight = scrollContainer?.clientHeight ?? window.innerHeight;
+ const scrollBottom = scrollContainer
+ ? scrollContainer.scrollTop + scrollContainer.clientHeight
+ : window.scrollY + window.innerHeight;
+ const hasScrollableOverflow = scrollHeight > viewportHeight + 1;
+ const threshold = scrollHeight - ISSUE_SCROLL_LOAD_THRESHOLD_PX;
+ if (scrollBottom >= threshold) {
+ if (trigger === "initial" && !hasMoreRenderedRows && hasMoreIssues && !hasScrollableOverflow) {
+ if (initialServerFillRequestedRef.current) return;
+ initialServerFillRequestedRef.current = true;
+ }
+ loadMoreIssueRows();
+ }
+ });
+ };
+
+ const handleScroll = () => checkScrollPosition("scroll");
+ const handleResize = () => checkScrollPosition("resize");
+ scrollTarget.addEventListener("scroll", handleScroll, { passive: true });
+ window.addEventListener("resize", handleResize);
+ checkScrollPosition("initial");
+
+ return () => {
+ scrollTarget.removeEventListener("scroll", handleScroll);
+ window.removeEventListener("resize", handleResize);
+ if (animationFrameId !== null) window.cancelAnimationFrame(animationFrameId);
+ };
+ }, [canLoadMoreIssues, hasMoreIssues, hasMoreRenderedRows, loadMoreIssueRows]);
const newIssueDefaults = useCallback((groupKey?: string) => {
const defaults: Record<string, unknown> = { ...(baseCreateIssueDefaults ?? {}) };
@@ -1036,7 +1121,7 @@ export function IssuesList({
let remainingRowsToRender = viewState.viewMode === "list" ? renderedIssueRowLimit : Number.POSITIVE_INFINITY;
return (
- <div className="space-y-4">
+ <div ref={rootRef} className="space-y-4">
{progressSummary ? (
<SubIssueProgressSummaryStrip summary={progressSummary} issueLinkState={issueLinkState} />
) : null}
@@ -1556,10 +1641,16 @@ export function IssuesList({
</Collapsible>
);
})}
- {remainingIssueRowCount > 0 && (
- <p className="text-xs text-muted-foreground">
- Rendering {Math.min(renderedIssueRowLimit, filtered.length)} of {filtered.length} issues
- </p>
+ {(remainingIssueRowCount > 0 || hasMoreIssues || isLoadingMoreIssues) && (
+ <div className="py-2" data-testid="issues-load-more-sentinel">
+ <p className="text-xs text-muted-foreground">
+ {isLoadingMoreIssues
+ ? "Loading more issues..."
+ : remainingIssueRowCount > 0
+ ? `Rendering ${Math.min(renderedIssueRowLimit, filtered.length)} of ${filtered.length} issues`
+ : "Scroll to load more issues"}
+ </p>
+ </div>
)}
</>
)}
diff --git a/ui/src/components/Layout.test.tsx b/ui/src/components/Layout.test.tsx
index 9ea147a85b..2dfd1a9f08 100644
--- a/ui/src/components/Layout.test.tsx
+++ b/ui/src/components/Layout.test.tsx
@@ -100,6 +100,10 @@ vi.mock("../context/DialogContext", () => ({
openNewIssue: vi.fn(),
openOnboarding: vi.fn(),
}),
+ useDialogActions: () => ({
+ openNewIssue: vi.fn(),
+ openOnboarding: vi.fn(),
+ }),
}));
vi.mock("../context/PanelContext", () => ({
diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx
index b0281df7f0..9ad6a82227 100644
--- a/ui/src/components/Layout.tsx
+++ b/ui/src/components/Layout.tsx
@@ -18,7 +18,7 @@ import { MobileBottomNav } from "./MobileBottomNav";
import { WorktreeBanner } from "./WorktreeBanner";
import { DevRestartBanner } from "./DevRestartBanner";
import { SidebarAccountMenu } from "./SidebarAccountMenu";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { GeneralSettingsProvider } from "../context/GeneralSettingsContext";
import { usePanel } from "../context/PanelContext";
import { useCompany } from "../context/CompanyContext";
@@ -54,7 +54,7 @@ function readRememberedInstanceSettingsPath(): string {
export function Layout() {
const { sidebarOpen, setSidebarOpen, toggleSidebar, isMobile } = useSidebar();
- const { openNewIssue, openOnboarding } = useDialog();
+ const { openNewIssue, openOnboarding } = useDialogActions();
const { togglePanelVisible } = usePanel();
const {
companies,
diff --git a/ui/src/components/MobileBottomNav.tsx b/ui/src/components/MobileBottomNav.tsx
index 6bfefdfa2b..81006b59ae 100644
--- a/ui/src/components/MobileBottomNav.tsx
+++ b/ui/src/components/MobileBottomNav.tsx
@@ -8,7 +8,7 @@ import {
Inbox,
} from "lucide-react";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { SIDEBAR_SCROLL_RESET_STATE } from "../lib/navigation-scroll";
import { cn } from "../lib/utils";
import { useInboxBadge } from "../hooks/useInboxBadge";
@@ -37,7 +37,7 @@ type MobileNavItem = MobileNavLinkItem | MobileNavActionItem;
export function MobileBottomNav({ visible }: MobileBottomNavProps) {
const location = useLocation();
const { selectedCompanyId } = useCompany();
- const { openNewIssue } = useDialog();
+ const { openNewIssue } = useDialogActions();
const inboxBadge = useInboxBadge(selectedCompanyId);
const items = useMemo<MobileNavItem[]>(
diff --git a/ui/src/components/NewIssueDialog.test.tsx b/ui/src/components/NewIssueDialog.test.tsx
index 0285c4306e..f938af87e5 100644
--- a/ui/src/components/NewIssueDialog.test.tsx
+++ b/ui/src/components/NewIssueDialog.test.tsx
@@ -372,6 +372,56 @@ describe("NewIssueDialog", () => {
act(() => root.unmount());
});
+ it("submits the latest locally typed title and description", async () => {
+ const { root } = renderDialog(container);
+ await flush();
+
+ const titleInput = container.querySelector('textarea[placeholder="Issue title"]') as HTMLTextAreaElement | null;
+ const descriptionInput = container.querySelector('textarea[aria-label="Add description..."]') as HTMLTextAreaElement | null;
+ expect(titleInput).not.toBeNull();
+ expect(descriptionInput).not.toBeNull();
+
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(
+ HTMLTextAreaElement.prototype,
+ "value",
+ )?.set;
+ valueSetter?.call(titleInput, "Typed issue");
+ titleInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await flush();
+
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(
+ HTMLTextAreaElement.prototype,
+ "value",
+ )?.set;
+ valueSetter?.call(descriptionInput, "Typed description");
+ descriptionInput!.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await flush();
+
+ const submitButton = Array.from(container.querySelectorAll("button"))
+ .find((button) => button.textContent?.includes("Create Issue"));
+ expect(submitButton).not.toBeUndefined();
+ expect(submitButton?.hasAttribute("disabled")).toBe(false);
+
+ await act(async () => {
+ submitButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ await flush();
+
+ expect(mockIssuesApi.create).toHaveBeenCalledWith(
+ "company-1",
+ expect.objectContaining({
+ title: "Typed issue",
+ description: "Typed description",
+ }),
+ );
+
+ act(() => root.unmount());
+ });
+
it("submits the parent assignee when a sub-issue opens with inherited defaults", async () => {
dialogState.newIssueDefaults = {
parentId: "issue-1",
diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx
index fa91a9c143..b5623322ac 100644
--- a/ui/src/components/NewIssueDialog.tsx
+++ b/ui/src/components/NewIssueDialog.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useRef, useCallback, useMemo, type ChangeEvent, type DragEvent } from "react";
+import { memo, useState, useEffect, useRef, useCallback, useMemo, type ChangeEvent, type DragEvent, type RefObject } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { pickTextColorForSolidBg } from "@/lib/color-contrast";
import { useDialog } from "../context/DialogContext";
@@ -269,6 +269,111 @@ function defaultExecutionWorkspaceModeForProject(project: { executionWorkspacePo
return "shared_workspace";
}
+const IssueTitleTextarea = memo(function IssueTitleTextarea({
+ value,
+ pending,
+ assigneeValue,
+ projectId,
+ descriptionEditorRef,
+ assigneeSelectorRef,
+ projectSelectorRef,
+ onChange,
+}: {
+ value: string;
+ pending: boolean;
+ assigneeValue: string;
+ projectId: string;
+ descriptionEditorRef: RefObject<MarkdownEditorRef | null>;
+ assigneeSelectorRef: RefObject<HTMLButtonElement | null>;
+ projectSelectorRef: RefObject<HTMLButtonElement | null>;
+ onChange: (value: string) => void;
+}) {
+ const [draftValue, setDraftValue] = useState(value);
+
+ useEffect(() => {
+ setDraftValue(value);
+ }, [value]);
+
+ return (
+ <textarea
+ className="w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50"
+ placeholder="Issue title"
+ rows={1}
+ value={draftValue}
+ onChange={(e) => {
+ const nextValue = e.target.value;
+ setDraftValue(nextValue);
+ onChange(nextValue);
+ e.target.style.height = "auto";
+ e.target.style.height = `${e.target.scrollHeight}px`;
+ }}
+ readOnly={pending}
+ onKeyDown={(e) => {
+ if (
+ e.key === "Enter" &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ !e.nativeEvent.isComposing
+ ) {
+ e.preventDefault();
+ descriptionEditorRef.current?.focus();
+ }
+ if (e.key === "Tab" && !e.shiftKey) {
+ e.preventDefault();
+ if (assigneeValue) {
+ if (projectId) {
+ descriptionEditorRef.current?.focus();
+ } else {
+ projectSelectorRef.current?.focus();
+ }
+ } else {
+ assigneeSelectorRef.current?.focus();
+ }
+ }
+ }}
+ autoFocus
+ />
+ );
+});
+
+const IssueDescriptionEditor = memo(function IssueDescriptionEditor({
+ value,
+ expanded,
+ mentions,
+ descriptionEditorRef,
+ imageUploadHandler,
+ onChange,
+}: {
+ value: string;
+ expanded: boolean;
+ mentions: MentionOption[];
+ descriptionEditorRef: RefObject<MarkdownEditorRef | null>;
+ imageUploadHandler: (file: File) => Promise<string>;
+ onChange: (value: string) => void;
+}) {
+ const [draftValue, setDraftValue] = useState(value);
+
+ useEffect(() => {
+ setDraftValue(value);
+ }, [value]);
+
+ return (
+ <MarkdownEditor
+ ref={descriptionEditorRef}
+ value={draftValue}
+ onChange={(nextValue) => {
+ setDraftValue(nextValue);
+ onChange(nextValue);
+ }}
+ placeholder="Add description..."
+ bordered={false}
+ mentions={mentions}
+ contentClassName={cn("text-sm text-muted-foreground pb-12", expanded ? "min-h-[220px]" : "min-h-[120px]")}
+ imageUploadHandler={imageUploadHandler}
+ />
+ );
+});
+
function issueExecutionWorkspaceModeForExistingWorkspace(mode: string | null | undefined) {
if (mode === "isolated_workspace" || mode === "operator_branch" || mode === "shared_workspace") {
return mode;
@@ -286,6 +391,10 @@ export function NewIssueDialog() {
const { pushToast } = useToastActions();
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
+ const titleRef = useRef("");
+ const descriptionRef = useRef("");
+ const [titleHasText, setTitleHasText] = useState(false);
+ const [draftHasText, setDraftHasText] = useState(false);
const [status, setStatus] = useState("todo");
const [priority, setPriority] = useState("");
const [assigneeValue, setAssigneeValue] = useState("");
@@ -463,6 +572,10 @@ export function NewIssueDialog() {
return assetsApi.uploadImage(effectiveCompanyId, file, "issues/drafts");
},
});
+ const uploadDescriptionImageHandler = useCallback(async (file: File) => {
+ const asset = await uploadDescriptionImage.mutateAsync(file);
+ return asset.contentPath;
+ }, [uploadDescriptionImage.mutateAsync]);
// Debounced draft saving
const scheduleSave = useCallback(
@@ -475,12 +588,22 @@ export function NewIssueDialog() {
[],
);
- // Save draft on meaningful changes
- useEffect(() => {
+ const setIssueText = useCallback((nextTitle: string, nextDescription: string) => {
+ titleRef.current = nextTitle;
+ descriptionRef.current = nextDescription;
+ setTitle(nextTitle);
+ setDescription(nextDescription);
+ setTitleHasText(nextTitle.trim().length > 0);
+ setDraftHasText(nextTitle.trim().length > 0 || nextDescription.trim().length > 0);
+ }, []);
+
+ const queueDraftSave = useCallback((overrides: { title?: string; description?: string } = {}) => {
if (!newIssueOpen) return;
+ const nextTitle = overrides.title ?? titleRef.current;
+ const nextDescription = overrides.description ?? descriptionRef.current;
scheduleSave({
- title,
- description,
+ title: nextTitle,
+ description: nextDescription,
status,
priority,
assigneeValue,
@@ -495,8 +618,43 @@ export function NewIssueDialog() {
selectedExecutionWorkspaceId,
});
}, [
- title,
- description,
+ newIssueOpen,
+ scheduleSave,
+ status,
+ priority,
+ assigneeValue,
+ reviewerValue,
+ approverValue,
+ projectId,
+ projectWorkspaceId,
+ assigneeModelOverride,
+ assigneeThinkingEffort,
+ assigneeChrome,
+ executionWorkspaceMode,
+ selectedExecutionWorkspaceId,
+ ]);
+
+ const handleTitleChange = useCallback((nextTitle: string) => {
+ titleRef.current = nextTitle;
+ const nextTitleHasText = nextTitle.trim().length > 0;
+ const nextDraftHasText = nextTitleHasText || descriptionRef.current.trim().length > 0;
+ setTitleHasText((current) => current === nextTitleHasText ? current : nextTitleHasText);
+ setDraftHasText((current) => current === nextDraftHasText ? current : nextDraftHasText);
+ queueDraftSave({ title: nextTitle });
+ }, [queueDraftSave]);
+
+ const handleDescriptionChange = useCallback((nextDescription: string) => {
+ descriptionRef.current = nextDescription;
+ const nextDraftHasText = titleRef.current.trim().length > 0 || nextDescription.trim().length > 0;
+ setDraftHasText((current) => current === nextDraftHasText ? current : nextDraftHasText);
+ queueDraftSave({ description: nextDescription });
+ }, [queueDraftSave]);
+
+ // Save draft on meaningful changes
+ useEffect(() => {
+ if (!newIssueOpen) return;
+ queueDraftSave();
+ }, [
status,
priority,
assigneeValue,
@@ -510,7 +668,7 @@ export function NewIssueDialog() {
executionWorkspaceMode,
selectedExecutionWorkspaceId,
newIssueOpen,
- scheduleSave,
+ queueDraftSave,
]);
// Restore draft or apply defaults when dialog opens
@@ -528,8 +686,7 @@ export function NewIssueDialog() {
const defaultExecutionWorkspaceMode = newIssueDefaults.executionWorkspaceId
? "reuse_existing"
: (newIssueDefaults.executionWorkspaceMode ?? defaultExecutionWorkspaceModeForProject(defaultProject));
- setTitle(newIssueDefaults.title ?? "");
- setDescription(newIssueDefaults.description ?? "");
+ setIssueText(newIssueDefaults.title ?? "", newIssueDefaults.description ?? "");
setStatus(newIssueDefaults.status ?? "todo");
setPriority(newIssueDefaults.priority ?? "");
setProjectId(defaultProjectId);
@@ -542,8 +699,7 @@ export function NewIssueDialog() {
setSelectedExecutionWorkspaceId(newIssueDefaults.executionWorkspaceId ?? "");
executionWorkspaceDefaultProjectId.current = defaultProjectId || null;
} else if (newIssueDefaults.title) {
- setTitle(newIssueDefaults.title);
- setDescription(newIssueDefaults.description ?? "");
+ setIssueText(newIssueDefaults.title, newIssueDefaults.description ?? "");
setStatus(newIssueDefaults.status ?? "todo");
setPriority(newIssueDefaults.priority ?? "");
const defaultProjectId = newIssueDefaults.projectId ?? "";
@@ -564,8 +720,7 @@ export function NewIssueDialog() {
} else if (draft && draft.title.trim()) {
const restoredProjectId = newIssueDefaults.projectId ?? draft.projectId;
const restoredProject = orderedProjects.find((project) => project.id === restoredProjectId);
- setTitle(draft.title);
- setDescription(draft.description);
+ setIssueText(draft.title, draft.description);
setStatus(draft.status || "todo");
setPriority(draft.priority);
setAssigneeValue(
@@ -591,6 +746,7 @@ export function NewIssueDialog() {
} else {
const defaultProjectId = newIssueDefaults.projectId ?? "";
const defaultProject = orderedProjects.find((project) => project.id === defaultProjectId);
+ setIssueText("", "");
setStatus(newIssueDefaults.status ?? "todo");
setPriority(newIssueDefaults.priority ?? "");
setProjectId(defaultProjectId);
@@ -607,7 +763,7 @@ export function NewIssueDialog() {
setSelectedExecutionWorkspaceId("");
executionWorkspaceDefaultProjectId.current = defaultProjectId || null;
}
- }, [newIssueOpen, newIssueDefaults, orderedProjects]);
+ }, [newIssueOpen, newIssueDefaults, orderedProjects, setIssueText]);
useEffect(() => {
if (!supportsAssigneeOverrides) {
@@ -637,8 +793,7 @@ export function NewIssueDialog() {
}, []);
function reset() {
- setTitle("");
- setDescription("");
+ setIssueText("", "");
setStatus("todo");
setPriority("");
setAssigneeValue("");
@@ -687,7 +842,9 @@ export function NewIssueDialog() {
}
function handleSubmit() {
- if (!effectiveCompanyId || !title.trim() || createIssue.isPending) return;
+ const currentTitle = titleRef.current.trim();
+ const currentDescription = descriptionRef.current.trim();
+ if (!effectiveCompanyId || !currentTitle || createIssue.isPending) return;
const assigneeAdapterOverrides = buildAssigneeAdapterOverrides({
adapterType: assigneeAdapterType,
modelOverride: assigneeModelOverride,
@@ -716,8 +873,8 @@ export function NewIssueDialog() {
createIssue.mutate({
companyId: effectiveCompanyId,
stagedFiles,
- title: title.trim(),
- description: description.trim() || undefined,
+ title: currentTitle,
+ description: currentDescription || undefined,
status,
priority: priority || "medium",
...(selectedAssigneeAgentId ? { assigneeAgentId: selectedAssigneeAgentId } : {}),
@@ -806,7 +963,7 @@ export function NewIssueDialog() {
setStagedFiles((current) => current.filter((file) => file.id !== id));
}
- const hasDraft = title.trim().length > 0 || description.trim().length > 0 || stagedFiles.length > 0;
+ const hasDraft = draftHasText || stagedFiles.length > 0;
const currentStatus = statuses.find((s) => s.value === status) ?? statuses[1]!;
const currentPriority = priorities.find((p) => p.value === priority);
const currentAssignee = selectedAssigneeAgentId
@@ -884,7 +1041,7 @@ export function NewIssueDialog() {
})),
[orderedProjects],
);
- const savedDraft = loadDraft();
+ const savedDraft = useMemo(() => newIssueOpen ? loadDraft() : null, [newIssueOpen]);
const hasSavedDraft = Boolean(savedDraft?.title.trim() || savedDraft?.description.trim());
const canDiscardDraft = hasDraft || hasSavedDraft;
const createIssueErrorMessage =
@@ -1056,42 +1213,15 @@ export function NewIssueDialog() {
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
{/* Title */}
<div className="px-4 pt-4 pb-2">
- <textarea
- className="w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50"
- placeholder="Issue title"
- rows={1}
- value={title}
- onChange={(e) => {
- setTitle(e.target.value);
- e.target.style.height = "auto";
- e.target.style.height = `${e.target.scrollHeight}px`;
- }}
- readOnly={createIssue.isPending}
- onKeyDown={(e) => {
- if (
- e.key === "Enter" &&
- !e.metaKey &&
- !e.ctrlKey &&
- !e.nativeEvent.isComposing
- ) {
- e.preventDefault();
- descriptionEditorRef.current?.focus();
- }
- if (e.key === "Tab" && !e.shiftKey) {
- e.preventDefault();
- if (assigneeValue) {
- // Assignee already set — skip to project or description
- if (projectId) {
- descriptionEditorRef.current?.focus();
- } else {
- projectSelectorRef.current?.focus();
- }
- } else {
- assigneeSelectorRef.current?.focus();
- }
- }
- }}
- autoFocus
+ <IssueTitleTextarea
+ value={title}
+ pending={createIssue.isPending}
+ assigneeValue={assigneeValue}
+ projectId={projectId}
+ descriptionEditorRef={descriptionEditorRef}
+ assigneeSelectorRef={assigneeSelectorRef}
+ projectSelectorRef={projectSelectorRef}
+ onChange={handleTitleChange}
/>
</div>
@@ -1466,18 +1596,13 @@ export function NewIssueDialog() {
isFileDragOver && "bg-accent/20",
)}
>
- <MarkdownEditor
- ref={descriptionEditorRef}
+ <IssueDescriptionEditor
value={description}
- onChange={setDescription}
- placeholder="Add description..."
- bordered={false}
+ expanded={expanded}
mentions={mentionOptions}
- contentClassName={cn("text-sm text-muted-foreground pb-12", expanded ? "min-h-[220px]" : "min-h-[120px]")}
- imageUploadHandler={async (file) => {
- const asset = await uploadDescriptionImage.mutateAsync(file);
- return asset.contentPath;
- }}
+ descriptionEditorRef={descriptionEditorRef}
+ imageUploadHandler={uploadDescriptionImageHandler}
+ onChange={handleDescriptionChange}
/>
</div>
{stagedFiles.length > 0 ? (
@@ -1682,7 +1807,7 @@ export function NewIssueDialog() {
<Button
size="sm"
className="min-w-[8.5rem] disabled:opacity-100"
- disabled={!title.trim() || createIssue.isPending}
+ disabled={!titleHasText || createIssue.isPending}
onClick={handleSubmit}
aria-busy={createIssue.isPending}
>
diff --git a/ui/src/components/ProductivityReviewBadge.tsx b/ui/src/components/ProductivityReviewBadge.tsx
new file mode 100644
index 0000000000..7b6b04c6cb
--- /dev/null
+++ b/ui/src/components/ProductivityReviewBadge.tsx
@@ -0,0 +1,77 @@
+import { Eye } from "lucide-react";
+import type { IssueProductivityReview } from "@paperclipai/shared";
+import { Link } from "../lib/router";
+import { cn } from "../lib/utils";
+import { createIssueDetailPath } from "../lib/issueDetailBreadcrumb";
+import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
+
+const TRIGGER_LABELS: Record<string, string> = {
+ no_comment_streak: "No-comment streak",
+ long_active_duration: "Long active duration",
+ high_churn: "High churn",
+};
+
+const REVIEW_STATUS_LABELS: Record<string, string> = {
+ todo: "Open",
+ in_progress: "In progress",
+ in_review: "In review",
+ blocked: "Blocked",
+ backlog: "Open",
+};
+
+export function productivityReviewTriggerLabel(
+ trigger: IssueProductivityReview["trigger"],
+): string {
+ if (!trigger) return "Productivity review";
+ return TRIGGER_LABELS[trigger] ?? "Productivity review";
+}
+
+export function ProductivityReviewBadge({
+ review,
+ className,
+ hideLabel = false,
+}: {
+ review: IssueProductivityReview;
+ className?: string;
+ hideLabel?: boolean;
+}) {
+ const label = productivityReviewTriggerLabel(review.trigger);
+ const reviewIdentifier = review.reviewIdentifier ?? review.reviewIssueId.slice(0, 8);
+ const reviewPath = createIssueDetailPath(review.reviewIdentifier ?? review.reviewIssueId);
+ const statusLabel = REVIEW_STATUS_LABELS[review.status] ?? review.status.replace(/_/g, " ");
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link
+ to={reviewPath}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300 shrink-0 hover:bg-amber-500/20 transition-colors",
+ className,
+ )}
+ aria-label={`Under review · productivity review ${reviewIdentifier} (${label})`}
+ >
+ <Eye className="h-3 w-3" aria-hidden />
+ {hideLabel ? null : <span>Under review</span>}
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent>
+ <div className="space-y-1 text-xs">
+ <div className="font-semibold">Productivity review open</div>
+ <div>
+ <span className="text-muted-foreground">Trigger:</span> {label}
+ </div>
+ {typeof review.noCommentStreak === "number" && review.noCommentStreak > 0 ? (
+ <div>
+ <span className="text-muted-foreground">No-comment streak:</span>{" "}
+ {review.noCommentStreak} runs
+ </div>
+ ) : null}
+ <div>
+ <span className="text-muted-foreground">Review:</span> {reviewIdentifier} ({statusLabel})
+ </div>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/ui/src/components/RoutineVariablesEditor.tsx b/ui/src/components/RoutineVariablesEditor.tsx
index f6ecd32259..cae1b0bc75 100644
--- a/ui/src/components/RoutineVariablesEditor.tsx
+++ b/ui/src/components/RoutineVariablesEditor.tsx
@@ -1,8 +1,15 @@
import { useEffect, useMemo, useState } from "react";
-import { ChevronDown, ChevronRight } from "lucide-react";
+import { ChevronDown, ChevronRight, HelpCircle } from "lucide-react";
import { syncRoutineVariablesWithTemplate, type RoutineVariable } from "@paperclipai/shared";
import { Badge } from "@/components/ui/badge";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
@@ -65,8 +72,8 @@ export function RoutineVariablesEditor({
}
return (
- <Collapsible open={open} onOpenChange={setOpen}>
- <CollapsibleTrigger className="flex w-full items-center justify-between rounded-lg border border-border/70 px-3 py-2 text-left">
+ <Collapsible open={open} onOpenChange={setOpen} className="overflow-hidden rounded-lg border border-border/70">
+ <CollapsibleTrigger className="flex w-full items-center justify-between px-3 py-2 text-left">
<div>
<p className="text-sm font-medium">Variables</p>
<p className="text-xs text-muted-foreground">
@@ -75,9 +82,9 @@ export function RoutineVariablesEditor({
</div>
{open ? <ChevronDown className="h-4 w-4 text-muted-foreground" /> : <ChevronRight className="h-4 w-4 text-muted-foreground" />}
</CollapsibleTrigger>
- <CollapsibleContent className="space-y-3 pt-3">
+ <CollapsibleContent className="divide-y divide-border/70 border-t border-border/70">
{syncedVariables.map((variable) => (
- <div key={variable.name} className="rounded-lg border border-border/70 p-4">
+ <div key={variable.name} className="p-4">
<div className="mb-3 flex flex-wrap items-center gap-2">
<Badge variant="outline" className="font-mono text-xs">
{`{{${variable.name}}}`}
@@ -225,10 +232,108 @@ export function RoutineVariablesEditor({
);
}
+type BuiltinVariableDoc = {
+ name: string;
+ example: string;
+ description: string;
+};
+
+const BUILTIN_VARIABLE_DOCS: BuiltinVariableDoc[] = [
+ {
+ name: "date",
+ example: "2026-04-28",
+ description: "Current date in YYYY-MM-DD format (UTC) at the time the routine runs.",
+ },
+ {
+ name: "timestamp",
+ example: "April 28, 2026 at 12:17 PM UTC",
+ description: "Human-readable date and time (UTC) at the time the routine runs.",
+ },
+];
+
export function RoutineVariablesHint() {
+ const [helpOpen, setHelpOpen] = useState(false);
+
return (
- <div className="rounded-lg border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground">
- Use `{"{{variable_name}}"}` placeholders in the instructions to prompt for inputs when the routine runs.
- </div>
+ <>
+ <div className="flex items-center justify-between gap-2 rounded-lg border border-dashed border-border/70 px-3 py-2 text-xs text-muted-foreground">
+ <span>
+ Use `{"{{variable_name}}"}` placeholders in the instructions to prompt for inputs when the routine runs.
+ </span>
+ <button
+ type="button"
+ onClick={() => setHelpOpen(true)}
+ className="shrink-0 rounded-full p-0.5 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ aria-label="Show variable help"
+ >
+ <HelpCircle className="h-3.5 w-3.5" />
+ </button>
+ </div>
+
+ <Dialog open={helpOpen} onOpenChange={setHelpOpen}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle>Routine variables</DialogTitle>
+ <DialogDescription>
+ How to prompt for inputs and which variables Paperclip fills in automatically.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-5 text-sm">
+ <section className="space-y-2">
+ <h3 className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
+ Custom variables
+ </h3>
+ <p className="text-muted-foreground">
+ Type{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-xs text-foreground">
+ {"{{variable_name}}"}
+ </code>{" "}
+ anywhere in the title or instructions. Paperclip detects each placeholder, lists it
+ under <span className="font-medium text-foreground">Variables</span>, and prompts
+ for a value before each run.
+ </p>
+ <ul className="list-disc space-y-1 pl-5 text-muted-foreground">
+ <li>Names must start with a letter and may use letters, numbers, and underscores.</li>
+ <li>Pick a type (text, textarea, number, boolean, select), default value, and whether it is required.</li>
+ <li>The same name reused across the title and instructions is treated as one variable.</li>
+ </ul>
+ </section>
+
+ <section className="space-y-2">
+ <h3 className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
+ Built-in variables
+ </h3>
+ <p className="text-muted-foreground">
+ These are filled in automatically — no setup needed and they will not appear in the
+ Variables list.
+ </p>
+ <div className="overflow-hidden rounded-lg border border-border/70">
+ <table className="w-full text-left text-xs">
+ <thead className="bg-muted/40 text-muted-foreground">
+ <tr>
+ <th className="px-3 py-2 font-medium">Placeholder</th>
+ <th className="px-3 py-2 font-medium">Example</th>
+ <th className="px-3 py-2 font-medium">Description</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-border/70">
+ {BUILTIN_VARIABLE_DOCS.map((entry) => (
+ <tr key={entry.name} className="align-top">
+ <td className="px-3 py-2">
+ <Badge variant="outline" className="font-mono text-xs">{`{{${entry.name}}}`}</Badge>
+ </td>
+ <td className="px-3 py-2 font-mono text-muted-foreground">{entry.example}</td>
+ <td className="px-3 py-2 text-muted-foreground">{entry.description}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </section>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/ui/src/components/Sidebar.test.tsx b/ui/src/components/Sidebar.test.tsx
index 6d52ddc3f2..6bfcd9aee7 100644
--- a/ui/src/components/Sidebar.test.tsx
+++ b/ui/src/components/Sidebar.test.tsx
@@ -35,6 +35,9 @@ vi.mock("../context/DialogContext", () => ({
useDialog: () => ({
openNewIssue: vi.fn(),
}),
+ useDialogActions: () => ({
+ openNewIssue: vi.fn(),
+ }),
}));
vi.mock("../context/CompanyContext", () => ({
diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx
index 28e8957d3f..6828014a72 100644
--- a/ui/src/components/Sidebar.tsx
+++ b/ui/src/components/Sidebar.tsx
@@ -18,7 +18,7 @@ import { SidebarSection } from "./SidebarSection";
import { SidebarNavItem } from "./SidebarNavItem";
import { SidebarProjects } from "./SidebarProjects";
import { SidebarAgents } from "./SidebarAgents";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { heartbeatsApi } from "../api/heartbeats";
import { instanceSettingsApi } from "../api/instanceSettings";
@@ -29,7 +29,7 @@ import { PluginSlotOutlet } from "@/plugins/slots";
import { SidebarCompanyMenu } from "./SidebarCompanyMenu";
export function Sidebar() {
- const { openNewIssue } = useDialog();
+ const { openNewIssue } = useDialogActions();
const { selectedCompanyId, selectedCompany } = useCompany();
const inboxBadge = useInboxBadge(selectedCompanyId);
const { data: experimentalSettings } = useQuery({
diff --git a/ui/src/components/SidebarAgents.test.tsx b/ui/src/components/SidebarAgents.test.tsx
index c75327fb76..ee3ef2aac4 100644
--- a/ui/src/components/SidebarAgents.test.tsx
+++ b/ui/src/components/SidebarAgents.test.tsx
@@ -61,6 +61,9 @@ vi.mock("../context/DialogContext", () => ({
useDialog: () => ({
openNewAgent: mockOpenNewAgent,
}),
+ useDialogActions: () => ({
+ openNewAgent: mockOpenNewAgent,
+ }),
}));
vi.mock("../context/SidebarContext", () => ({
diff --git a/ui/src/components/SidebarAgents.tsx b/ui/src/components/SidebarAgents.tsx
index e2efa56eb5..6075bfe7c8 100644
--- a/ui/src/components/SidebarAgents.tsx
+++ b/ui/src/components/SidebarAgents.tsx
@@ -10,7 +10,7 @@ import {
Plus,
} from "lucide-react";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useSidebar } from "../context/SidebarContext";
import { useToastActions } from "../context/ToastContext";
import { agentsApi } from "../api/agents";
@@ -158,7 +158,7 @@ export function SidebarAgents() {
const [pendingAgentIds, setPendingAgentIds] = useState<Set<string>>(() => new Set());
const queryClient = useQueryClient();
const { selectedCompanyId } = useCompany();
- const { openNewAgent } = useDialog();
+ const { openNewAgent } = useDialogActions();
const { isMobile, setSidebarOpen } = useSidebar();
const { pushToast } = useToastActions();
const location = useLocation();
diff --git a/ui/src/components/SidebarProjects.tsx b/ui/src/components/SidebarProjects.tsx
index 2f8b2aeed0..b48bc96794 100644
--- a/ui/src/components/SidebarProjects.tsx
+++ b/ui/src/components/SidebarProjects.tsx
@@ -13,7 +13,7 @@ import {
import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useSidebar } from "../context/SidebarContext";
import { authApi } from "../api/auth";
import { projectsApi } from "../api/projects";
@@ -124,7 +124,7 @@ function SortableProjectItem({
export function SidebarProjects() {
const [open, setOpen] = useState(true);
const { selectedCompany, selectedCompanyId } = useCompany();
- const { openNewProject } = useDialog();
+ const { openNewProject } = useDialogActions();
const { isMobile, setSidebarOpen } = useSidebar();
const location = useLocation();
diff --git a/ui/src/context/DialogContext.test.tsx b/ui/src/context/DialogContext.test.tsx
new file mode 100644
index 0000000000..8e4c01c6b5
--- /dev/null
+++ b/ui/src/context/DialogContext.test.tsx
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it } from "vitest";
+import { DialogProvider, useDialogActions, useDialogState } from "./DialogContext";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("DialogContext", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ });
+
+ it("keeps action-only consumers from rerendering when dialog state changes", () => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ let actionRenderCount = 0;
+ let stateRenderCount = 0;
+
+ function ActionOnlyConsumer() {
+ actionRenderCount += 1;
+ const { openNewIssue } = useDialogActions();
+ return <button onClick={() => openNewIssue()}>Open issue</button>;
+ }
+
+ function StateConsumer() {
+ stateRenderCount += 1;
+ const { newIssueOpen } = useDialogState();
+ return <span>{newIssueOpen ? "open" : "closed"}</span>;
+ }
+
+ act(() => {
+ root.render(
+ <DialogProvider>
+ <ActionOnlyConsumer />
+ <StateConsumer />
+ </DialogProvider>,
+ );
+ });
+
+ expect(actionRenderCount).toBe(1);
+ expect(stateRenderCount).toBe(1);
+
+ const button = host.querySelector("button");
+ act(() => {
+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+
+ expect(host.textContent).toContain("open");
+ expect(actionRenderCount).toBe(1);
+ expect(stateRenderCount).toBe(2);
+
+ act(() => root.unmount());
+ });
+});
diff --git a/ui/src/context/DialogContext.tsx b/ui/src/context/DialogContext.tsx
index bf18c7db92..697a68905a 100644
--- a/ui/src/context/DialogContext.tsx
+++ b/ui/src/context/DialogContext.tsx
@@ -1,4 +1,4 @@
-import { createContext, useCallback, useContext, useState, type ReactNode } from "react";
+import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
interface NewIssueDefaults {
status?: string;
@@ -48,7 +48,22 @@ interface DialogContextValue {
closeOnboarding: () => void;
}
-const DialogContext = createContext<DialogContextValue | null>(null);
+type DialogStateValue = Pick<
+ DialogContextValue,
+ | "newIssueOpen"
+ | "newIssueDefaults"
+ | "newProjectOpen"
+ | "newGoalOpen"
+ | "newGoalDefaults"
+ | "newAgentOpen"
+ | "onboardingOpen"
+ | "onboardingOptions"
+>;
+
+type DialogActionsValue = Omit<DialogContextValue, keyof DialogStateValue>;
+
+const DialogStateContext = createContext<DialogStateValue | null>(null);
+const DialogActionsContext = createContext<DialogActionsValue | null>(null);
export function DialogProvider({ children }: { children: ReactNode }) {
const [newIssueOpen, setNewIssueOpen] = useState(false);
@@ -106,38 +121,84 @@ export function DialogProvider({ children }: { children: ReactNode }) {
setOnboardingOptions({});
}, []);
+ const stateValue = useMemo<DialogStateValue>(
+ () => ({
+ newIssueOpen,
+ newIssueDefaults,
+ newProjectOpen,
+ newGoalOpen,
+ newGoalDefaults,
+ newAgentOpen,
+ onboardingOpen,
+ onboardingOptions,
+ }),
+ [
+ newIssueOpen,
+ newIssueDefaults,
+ newProjectOpen,
+ newGoalOpen,
+ newGoalDefaults,
+ newAgentOpen,
+ onboardingOpen,
+ onboardingOptions,
+ ],
+ );
+
+ const actionsValue = useMemo<DialogActionsValue>(
+ () => ({
+ openNewIssue,
+ closeNewIssue,
+ openNewProject,
+ closeNewProject,
+ openNewGoal,
+ closeNewGoal,
+ openNewAgent,
+ closeNewAgent,
+ openOnboarding,
+ closeOnboarding,
+ }),
+ [
+ openNewIssue,
+ closeNewIssue,
+ openNewProject,
+ closeNewProject,
+ openNewGoal,
+ closeNewGoal,
+ openNewAgent,
+ closeNewAgent,
+ openOnboarding,
+ closeOnboarding,
+ ],
+ );
+
return (
- <DialogContext.Provider
- value={{
- newIssueOpen,
- newIssueDefaults,
- openNewIssue,
- closeNewIssue,
- newProjectOpen,
- openNewProject,
- closeNewProject,
- newGoalOpen,
- newGoalDefaults,
- openNewGoal,
- closeNewGoal,
- newAgentOpen,
- openNewAgent,
- closeNewAgent,
- onboardingOpen,
- onboardingOptions,
- openOnboarding,
- closeOnboarding,
- }}
- >
- {children}
- </DialogContext.Provider>
+ <DialogActionsContext.Provider value={actionsValue}>
+ <DialogStateContext.Provider value={stateValue}>
+ {children}
+ </DialogStateContext.Provider>
+ </DialogActionsContext.Provider>
);
}
-export function useDialog() {
- const ctx = useContext(DialogContext);
+export function useDialogActions() {
+ const ctx = useContext(DialogActionsContext);
if (!ctx) {
- throw new Error("useDialog must be used within DialogProvider");
+ throw new Error("useDialogActions must be used within DialogProvider");
}
return ctx;
}
+
+export function useDialogState() {
+ const ctx = useContext(DialogStateContext);
+ if (!ctx) {
+ throw new Error("useDialogState must be used within DialogProvider");
+ }
+ return ctx;
+}
+
+export function useDialog() {
+ return {
+ ...useDialogState(),
+ ...useDialogActions(),
+ };
+}
diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsx
index 77720d3177..0374c065ed 100644
--- a/ui/src/context/ToastContext.tsx
+++ b/ui/src/context/ToastContext.tsx
@@ -186,6 +186,10 @@ export function useToastActions() {
return context;
}
+export function useOptionalToastActions() {
+ return useContext(ToastActionsContext);
+}
+
export function useToast() {
const toasts = useToastState();
const actions = useToastActions();
diff --git a/ui/src/fixtures/issueChatLongThreadFixture.test.ts b/ui/src/fixtures/issueChatLongThreadFixture.test.ts
new file mode 100644
index 0000000000..5660e46d9d
--- /dev/null
+++ b/ui/src/fixtures/issueChatLongThreadFixture.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import {
+ issueChatLongThreadAgentMap,
+ issueChatLongThreadComments,
+ issueChatLongThreadEvents,
+ issueChatLongThreadLinkedRuns,
+ issueChatLongThreadMarkdownCommentIds,
+ issueChatLongThreadTranscriptsByRunId,
+ LONG_THREAD_COMMENT_COUNT,
+ LONG_THREAD_MARKDOWN_COMMENT_COUNT,
+} from "./issueChatLongThreadFixture";
+import { buildIssueChatMessages } from "../lib/issue-chat-messages";
+
+describe("issueChatLongThreadFixture", () => {
+ it("builds a deterministic long issue-thread shape", () => {
+ const messages = buildIssueChatMessages({
+ comments: issueChatLongThreadComments,
+ timelineEvents: issueChatLongThreadEvents,
+ linkedRuns: issueChatLongThreadLinkedRuns,
+ liveRuns: [],
+ agentMap: issueChatLongThreadAgentMap,
+ currentUserId: "user-board",
+ transcriptsByRunId: issueChatLongThreadTranscriptsByRunId,
+ hasOutputForRun: (runId) => issueChatLongThreadTranscriptsByRunId.has(runId),
+ });
+
+ expect(issueChatLongThreadComments).toHaveLength(LONG_THREAD_COMMENT_COUNT);
+ expect(issueChatLongThreadMarkdownCommentIds.size).toBe(LONG_THREAD_MARKDOWN_COMMENT_COUNT);
+ expect(messages.length).toBeGreaterThanOrEqual(450);
+ expect(messages.filter((message) => message.role === "assistant").length).toBeGreaterThanOrEqual(
+ LONG_THREAD_MARKDOWN_COMMENT_COUNT,
+ );
+ });
+
+ it("keeps markdown rows markdown-heavy enough to exercise MarkdownBody", () => {
+ const markdownComments = issueChatLongThreadComments.filter((comment) =>
+ issueChatLongThreadMarkdownCommentIds.has(comment.id),
+ );
+
+ expect(markdownComments).toHaveLength(LONG_THREAD_MARKDOWN_COMMENT_COUNT);
+ for (const comment of markdownComments.slice(0, 5)) {
+ expect(comment.body).toContain("## Baseline note");
+ expect(comment.body).toContain("```ts");
+ expect(comment.body).toContain("| Metric | Value |");
+ }
+ });
+});
diff --git a/ui/src/fixtures/issueChatLongThreadFixture.ts b/ui/src/fixtures/issueChatLongThreadFixture.ts
new file mode 100644
index 0000000000..96c9392fa8
--- /dev/null
+++ b/ui/src/fixtures/issueChatLongThreadFixture.ts
@@ -0,0 +1,214 @@
+import type { Agent } from "@paperclipai/shared";
+import type { LiveRunForIssue } from "../api/heartbeats";
+import type {
+ IssueChatComment,
+ IssueChatLinkedRun,
+ IssueChatTranscriptEntry,
+} from "../lib/issue-chat-messages";
+import type { IssueTimelineEvent } from "../lib/issue-timeline-events";
+
+export const LONG_THREAD_COMMENT_COUNT = 469;
+export const LONG_THREAD_MARKDOWN_COMMENT_COUNT = 150;
+export const LONG_THREAD_EVENT_COUNT = 12;
+export const LONG_THREAD_LINKED_RUN_COUNT = 6;
+
+const baseTime = new Date("2026-04-28T14:00:00.000Z").getTime();
+
+function atMinute(offset: number) {
+ return new Date(baseTime + offset * 60_000);
+}
+
+function createAgent(id: string, name: string, icon: string, urlKey: string): Agent {
+ const now = new Date("2026-04-28T14:00:00.000Z");
+ return {
+ id,
+ companyId: "company-long-thread",
+ name,
+ urlKey,
+ role: "engineer",
+ title: null,
+ icon,
+ status: "active",
+ reportsTo: null,
+ capabilities: null,
+ adapterType: "codex_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ budgetMonthlyCents: 0,
+ spentMonthlyCents: 0,
+ lastHeartbeatAt: null,
+ metadata: null,
+ createdAt: now,
+ updatedAt: now,
+ pauseReason: null,
+ pausedAt: null,
+ permissions: { canCreateAgents: false },
+ };
+}
+
+const primaryAgent = createAgent("agent-perf-codex", "CodexCoder", "code", "codexcoder");
+const reviewerAgent = createAgent("agent-perf-reviewer", "ReviewBot", "sparkles", "reviewbot");
+
+export const issueChatLongThreadAgentMap = new Map<string, Agent>([
+ [primaryAgent.id, primaryAgent],
+ [reviewerAgent.id, reviewerAgent],
+]);
+
+function markdownBody(index: number) {
+ return [
+ `## Baseline note ${index}`,
+ "",
+ `This assistant update captures a deterministic markdown-heavy row for long-thread rendering. It references [PAP-${2600 + index}](/PAP/issues/PAP-${2600 + index}) and includes enough structure to exercise markdown parsing.`,
+ "",
+ "- Parsed checklist item one with inline `code`",
+ "- Parsed checklist item two with **bold** and _italic_ text",
+ "- Parsed checklist item three with a link to [Paperclip](/PAP/dashboard)",
+ "",
+ "| Metric | Value |",
+ "| --- | ---: |",
+ `| Fixture row | ${index} |`,
+ `| Synthetic tokens | ${1200 + index} |`,
+ "",
+ "```ts",
+ `const fixtureRow${index} = { markdown: true, deterministic: true };`,
+ "```",
+ ].join("\n");
+}
+
+function plainUserBody(index: number) {
+ return `Board checkpoint ${index}: keep the issue-detail page responsive while the thread is full of historical comments.`;
+}
+
+function plainAssistantBody(index: number) {
+ return `Processed checkpoint ${index}. The current direct-render path should keep this row mounted with the rest of the thread.`;
+}
+
+function createComment(index: number): IssueChatComment {
+ const isMarkdown = index < LONG_THREAD_MARKDOWN_COMMENT_COUNT;
+ const isAssistant = isMarkdown || index % 4 === 1 || index % 4 === 2;
+ const authorAgentId = isAssistant
+ ? (index % 7 === 0 ? reviewerAgent.id : primaryAgent.id)
+ : null;
+
+ return {
+ id: `long-thread-comment-${String(index + 1).padStart(3, "0")}`,
+ companyId: "company-long-thread",
+ issueId: "issue-long-thread",
+ authorAgentId,
+ authorUserId: authorAgentId ? null : "user-board",
+ body: isMarkdown
+ ? markdownBody(index + 1)
+ : authorAgentId
+ ? plainAssistantBody(index + 1)
+ : plainUserBody(index + 1),
+ createdAt: atMinute(index),
+ updatedAt: atMinute(index),
+ };
+}
+
+export const issueChatLongThreadComments: IssueChatComment[] = Array.from(
+ { length: LONG_THREAD_COMMENT_COUNT },
+ (_, index) => createComment(index),
+);
+
+export const issueChatLongThreadMarkdownCommentIds = new Set(
+ issueChatLongThreadComments
+ .slice(0, LONG_THREAD_MARKDOWN_COMMENT_COUNT)
+ .map((comment) => comment.id),
+);
+
+export const issueChatLongThreadEvents: IssueTimelineEvent[] = Array.from(
+ { length: LONG_THREAD_EVENT_COUNT },
+ (_, index) => ({
+ id: `long-thread-event-${index + 1}`,
+ createdAt: atMinute(index * 36 + 18),
+ actorType: index % 3 === 0 ? "user" : "agent",
+ actorId: index % 3 === 0 ? "user-board" : primaryAgent.id,
+ statusChange: index % 2 === 0
+ ? { from: index === 0 ? "todo" : "in_progress", to: "in_progress" }
+ : undefined,
+ assigneeChange: index % 2 === 1
+ ? {
+ from: { agentId: null, userId: null },
+ to: { agentId: index % 4 === 1 ? primaryAgent.id : reviewerAgent.id, userId: null },
+ }
+ : undefined,
+ }),
+);
+
+export const issueChatLongThreadLinkedRuns: IssueChatLinkedRun[] = Array.from(
+ { length: LONG_THREAD_LINKED_RUN_COUNT },
+ (_, index) => ({
+ runId: `long-thread-run-${index + 1}`,
+ status: index % 3 === 0 ? "failed" : index % 3 === 1 ? "timed_out" : "succeeded",
+ agentId: index % 2 === 0 ? primaryAgent.id : reviewerAgent.id,
+ agentName: index % 2 === 0 ? primaryAgent.name : reviewerAgent.name,
+ adapterType: "codex_local",
+ createdAt: atMinute(index * 72 + 12),
+ startedAt: atMinute(index * 72 + 12),
+ finishedAt: atMinute(index * 72 + 16),
+ hasStoredOutput: true,
+ }),
+);
+
+export const issueChatLongThreadLiveRuns: LiveRunForIssue[] = [];
+
+export const issueChatLongThreadTranscriptsByRunId = new Map<string, readonly IssueChatTranscriptEntry[]>(
+ issueChatLongThreadLinkedRuns.map((run, index) => [
+ run.runId,
+ [
+ {
+ kind: "thinking",
+ ts: atMinute(index * 72 + 13).toISOString(),
+ text: `Inspecting long-thread segment ${index + 1}.`,
+ },
+ {
+ kind: "tool_call",
+ ts: atMinute(index * 72 + 14).toISOString(),
+ name: "read_file",
+ toolUseId: `long-thread-tool-${index + 1}`,
+ input: { path: "ui/src/components/IssueChatThread.tsx" },
+ },
+ {
+ kind: "tool_result",
+ ts: atMinute(index * 72 + 15).toISOString(),
+ toolUseId: `long-thread-tool-${index + 1}`,
+ content: "Confirmed the direct-render fixture keeps the full message subtree mounted.",
+ isError: run.status !== "succeeded",
+ },
+ {
+ kind: "assistant",
+ ts: atMinute(index * 72 + 16).toISOString(),
+ text: `Run ${index + 1} produced a compact transcript row for adjacent run context.`,
+ },
+ ],
+ ]),
+);
+
+export const issueChatLongThreadFixtureContext = {
+ issue: {
+ identifier: "PAP-PERF",
+ title: "Long-thread rendering baseline fixture",
+ status: "in_progress",
+ priority: "medium",
+ projectName: "Paperclip App",
+ },
+ documents: [
+ "Implementation Plan",
+ "Profiler Notes",
+ "Release Checklist",
+ "QA Readout",
+ ],
+ subIssues: [
+ "Phase 1: Add long-thread perf fixture and baseline",
+ "Phase 2: Isolate issue-thread row rendering and Markdown work",
+ "Phase 3: Apply virtualization and guard scroll behavior",
+ "Phase 4: Verify production issue profile improvement",
+ ],
+ sidebarStats: [
+ ["Comments", String(LONG_THREAD_COMMENT_COUNT)],
+ ["Markdown bodies", String(LONG_THREAD_MARKDOWN_COMMENT_COUNT)],
+ ["Timeline events", String(LONG_THREAD_EVENT_COUNT)],
+ ["Linked runs", String(LONG_THREAD_LINKED_RUN_COUNT)],
+ ],
+} as const;
diff --git a/ui/src/index.css b/ui/src/index.css
index 7d42f87ed7..d0957f757b 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -442,13 +442,15 @@
align-items: center;
gap: 0.25rem;
margin: 0 0.1rem;
- padding: 0.05rem 0.45rem;
+ padding: 0 0.45rem;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.75rem;
- line-height: 1.3;
+ line-height: 1.25;
text-decoration: none;
- vertical-align: baseline;
+ vertical-align: middle;
+ position: relative;
+ top: -1px;
white-space: nowrap;
user-select: none;
}
@@ -860,15 +862,19 @@ span.paperclip-project-mention-chip {
align-items: center;
gap: 0.25rem;
margin: 0 0.1rem;
- padding: 0.05rem 0.45rem;
+ padding: 0 0.45rem;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.75rem;
- line-height: 1.3;
+ line-height: 1.25;
text-decoration: none;
- /* Align the pill relative to the surrounding text baseline instead of its
- x-height midpoint so it sits on the text line rather than floating above. */
- vertical-align: baseline;
+ /* Center the pill on the surrounding x-height so it sits on the text line
+ instead of hanging below it. inline-flex baseline alignment is unreliable
+ across browsers, so use vertical-align: middle for a predictable result.
+ Nudge up 1px so it visually centers with the cap height of the text. */
+ vertical-align: middle;
+ position: relative;
+ top: -1px;
white-space: nowrap;
}
diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx
index daf293e3b5..0eca94412b 100644
--- a/ui/src/pages/AgentDetail.tsx
+++ b/ui/src/pages/AgentDetail.tsx
@@ -19,7 +19,7 @@ import { usePanel } from "../context/PanelContext";
import { useSidebar } from "../context/SidebarContext";
import { useCompany } from "../context/CompanyContext";
import { useToastActions } from "../context/ToastContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { AgentConfigForm } from "../components/AgentConfigForm";
@@ -626,7 +626,7 @@ export function AgentDetail() {
}>();
const { companies, selectedCompanyId, setSelectedCompanyId } = useCompany();
const { closePanel } = usePanel();
- const { openNewIssue } = useDialog();
+ const { openNewIssue } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
const navigate = useNavigate();
diff --git a/ui/src/pages/Agents.tsx b/ui/src/pages/Agents.tsx
index 6e3f0f3dc5..179a7c065e 100644
--- a/ui/src/pages/Agents.tsx
+++ b/ui/src/pages/Agents.tsx
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
import { agentsApi, type OrgNode } from "../api/agents";
import { heartbeatsApi } from "../api/heartbeats";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useSidebar } from "../context/SidebarContext";
import { queryKeys } from "../lib/queryKeys";
@@ -55,7 +55,7 @@ function filterOrgTree(nodes: OrgNode[], tab: FilterTab, showTerminated: boolean
export function Agents() {
const { selectedCompanyId } = useCompany();
- const { openNewAgent } = useDialog();
+ const { openNewAgent } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const navigate = useNavigate();
const location = useLocation();
diff --git a/ui/src/pages/Companies.tsx b/ui/src/pages/Companies.tsx
index 6844850dc8..58590d66cf 100644
--- a/ui/src/pages/Companies.tsx
+++ b/ui/src/pages/Companies.tsx
@@ -1,7 +1,7 @@
import { useState, useEffect } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { companiesApi } from "../api/companies";
import { queryKeys } from "../lib/queryKeys";
@@ -36,7 +36,7 @@ export function Companies() {
loading,
error,
} = useCompany();
- const { openOnboarding } = useDialog();
+ const { openOnboarding } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
diff --git a/ui/src/pages/Dashboard.tsx b/ui/src/pages/Dashboard.tsx
index eda0e2f838..cf9675b6f4 100644
--- a/ui/src/pages/Dashboard.tsx
+++ b/ui/src/pages/Dashboard.tsx
@@ -9,7 +9,7 @@ import { agentsApi } from "../api/agents";
import { projectsApi } from "../api/projects";
import { buildCompanyUserProfileMap } from "../lib/company-members";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { MetricCard } from "../components/MetricCard";
@@ -36,7 +36,7 @@ function getRecentIssues(issues: Issue[]): Issue[] {
export function Dashboard() {
const { selectedCompanyId, companies } = useCompany();
- const { openOnboarding } = useDialog();
+ const { openOnboarding } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
const [animatedActivityIds, setAnimatedActivityIds] = useState<Set<string>>(new Set());
const seenActivityIdsRef = useRef<Set<string>>(new Set());
diff --git a/ui/src/pages/GoalDetail.tsx b/ui/src/pages/GoalDetail.tsx
index 169622eb72..4d52988d61 100644
--- a/ui/src/pages/GoalDetail.tsx
+++ b/ui/src/pages/GoalDetail.tsx
@@ -6,7 +6,7 @@ import { projectsApi } from "../api/projects";
import { assetsApi } from "../api/assets";
import { usePanel } from "../context/PanelContext";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { GoalProperties } from "../components/GoalProperties";
@@ -49,7 +49,7 @@ export function GoalPropertiesToggleButton({
export function GoalDetail() {
const { goalId } = useParams<{ goalId: string }>();
const { selectedCompanyId, setSelectedCompanyId } = useCompany();
- const { openNewGoal } = useDialog();
+ const { openNewGoal } = useDialogActions();
const { openPanel, closePanel, panelVisible, setPanelVisible } = usePanel();
const { setBreadcrumbs } = useBreadcrumbs();
const queryClient = useQueryClient();
diff --git a/ui/src/pages/Goals.tsx b/ui/src/pages/Goals.tsx
index 490bb048ce..7dca9e18dd 100644
--- a/ui/src/pages/Goals.tsx
+++ b/ui/src/pages/Goals.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { goalsApi } from "../api/goals";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { GoalTree } from "../components/GoalTree";
@@ -13,7 +13,7 @@ import { Target, Plus } from "lucide-react";
export function Goals() {
const { selectedCompanyId } = useCompany();
- const { openNewGoal } = useDialog();
+ const { openNewGoal } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
useEffect(() => {
diff --git a/ui/src/pages/IssueChatLongThreadPerf.tsx b/ui/src/pages/IssueChatLongThreadPerf.tsx
new file mode 100644
index 0000000000..1ede09f2ce
--- /dev/null
+++ b/ui/src/pages/IssueChatLongThreadPerf.tsx
@@ -0,0 +1,213 @@
+import { Profiler, useEffect, useLayoutEffect, useMemo, useRef, useState, type ProfilerOnRenderCallback } from "react";
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { IssueChatThread } from "../components/IssueChatThread";
+import {
+ issueChatLongThreadAgentMap,
+ issueChatLongThreadComments,
+ issueChatLongThreadEvents,
+ issueChatLongThreadFixtureContext,
+ issueChatLongThreadLinkedRuns,
+ issueChatLongThreadLiveRuns,
+ issueChatLongThreadMarkdownCommentIds,
+ issueChatLongThreadTranscriptsByRunId,
+ LONG_THREAD_COMMENT_COUNT,
+ LONG_THREAD_MARKDOWN_COMMENT_COUNT,
+} from "../fixtures/issueChatLongThreadFixture";
+
+const noop = async () => {};
+
+type RenderMetrics = {
+ commitCount: number;
+ mountActualDuration: number | null;
+ latestActualDuration: number | null;
+ maxActualDuration: number;
+ totalActualDuration: number;
+};
+
+const initialMetrics: RenderMetrics = {
+ commitCount: 0,
+ mountActualDuration: null,
+ latestActualDuration: null,
+ maxActualDuration: 0,
+ totalActualDuration: 0,
+};
+
+function formatMs(value: number | null) {
+ if (value === null || !Number.isFinite(value)) return "pending";
+ return `${value.toFixed(1)} ms`;
+}
+
+function MetricTile({ label, value, testId }: { label: string; value: string; testId: string }) {
+ return (
+ <div className="rounded-md border border-border bg-background px-3 py-2">
+ <div className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
+ {label}
+ </div>
+ <div data-testid={testId} className="mt-1 font-mono text-sm text-foreground">
+ {value}
+ </div>
+ </div>
+ );
+}
+
+export function IssueChatLongThreadPerf() {
+ const [metrics, setMetrics] = useState<RenderMetrics>(initialMetrics);
+ const metricsRef = useRef<RenderMetrics>(initialMetrics);
+ const renderStartedAtRef = useRef(performance.now());
+ const publishTimerRef = useRef<number | null>(null);
+ const publishedRef = useRef(false);
+ const fixture = issueChatLongThreadFixtureContext;
+ const rowTarget = useMemo(
+ () => LONG_THREAD_COMMENT_COUNT + issueChatLongThreadEvents.length + issueChatLongThreadLinkedRuns.length,
+ [],
+ );
+
+ useEffect(() => () => {
+ if (publishTimerRef.current !== null) {
+ window.clearTimeout(publishTimerRef.current);
+ }
+ }, []);
+
+ useLayoutEffect(() => {
+ if (publishedRef.current || metricsRef.current.commitCount > 0) return;
+ const mountDuration = performance.now() - renderStartedAtRef.current;
+ const next = {
+ commitCount: 1,
+ mountActualDuration: mountDuration,
+ latestActualDuration: mountDuration,
+ maxActualDuration: mountDuration,
+ totalActualDuration: mountDuration,
+ };
+ metricsRef.current = next;
+ publishedRef.current = true;
+ setMetrics(next);
+ }, []);
+
+ const handleRender: ProfilerOnRenderCallback = (_id, phase, actualDuration) => {
+ const current = metricsRef.current;
+ metricsRef.current = {
+ commitCount: current.commitCount + 1,
+ mountActualDuration: phase === "mount" && current.mountActualDuration === null
+ ? actualDuration
+ : current.mountActualDuration,
+ latestActualDuration: actualDuration,
+ maxActualDuration: Math.max(current.maxActualDuration, actualDuration),
+ totalActualDuration: current.totalActualDuration + actualDuration,
+ };
+
+ if (publishedRef.current || publishTimerRef.current !== null) return;
+ publishTimerRef.current = window.setTimeout(() => {
+ publishTimerRef.current = null;
+ publishedRef.current = true;
+ setMetrics(metricsRef.current);
+ }, 0);
+ };
+
+ return (
+ <div data-testid="issue-chat-long-thread-perf" className="space-y-5">
+ <div className="flex flex-col gap-3 border-b border-border pb-5 lg:flex-row lg:items-end lg:justify-between">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <Badge variant="outline" className="font-mono text-[11px]">
+ {fixture.issue.identifier}
+ </Badge>
+ <Badge variant="secondary">{fixture.issue.status.replace(/_/g, " ")}</Badge>
+ <Badge variant="outline">{fixture.issue.projectName}</Badge>
+ </div>
+ <h1 className="mt-3 text-2xl font-semibold tracking-tight">{fixture.issue.title}</h1>
+ <p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">
+ Deterministic local fixture for measuring the current direct-render issue chat path with
+ hundreds of merged thread rows, markdown-heavy assistant bodies, linked runs, documents,
+ sub-issues, and sidebar context.
+ </p>
+ </div>
+ <div className="grid min-w-[280px] grid-cols-2 gap-2">
+ <MetricTile label="Fixture rows" value={String(rowTarget)} testId="perf-fixture-row-target" />
+ <MetricTile label="Markdown rows" value={String(LONG_THREAD_MARKDOWN_COMMENT_COUNT)} testId="perf-fixture-markdown-rows" />
+ </div>
+ </div>
+
+ <div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]">
+ <main className="min-w-0 space-y-4">
+ <Card className="border-border/70">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">Issue documents</CardTitle>
+ </CardHeader>
+ <CardContent className="grid gap-2 sm:grid-cols-2">
+ {fixture.documents.map((document) => (
+ <div key={document} className="rounded-md border border-border bg-muted/30 px-3 py-2 text-sm">
+ {document}
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+
+ <Card className="border-border/70">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">Sub-issues</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-2">
+ {fixture.subIssues.map((subIssue, index) => (
+ <div key={subIssue} className="flex items-center gap-3 rounded-md border border-border bg-background px-3 py-2 text-sm">
+ <span className="font-mono text-xs text-muted-foreground">#{index + 1}</span>
+ <span>{subIssue}</span>
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+
+ <Profiler id="issue-chat-long-thread" onRender={handleRender}>
+ <IssueChatThread
+ comments={issueChatLongThreadComments}
+ linkedRuns={issueChatLongThreadLinkedRuns}
+ timelineEvents={issueChatLongThreadEvents}
+ liveRuns={issueChatLongThreadLiveRuns}
+ issueStatus="in_progress"
+ agentMap={issueChatLongThreadAgentMap}
+ currentUserId="user-board"
+ onAdd={noop}
+ showComposer={false}
+ showJumpToLatest={false}
+ enableLiveTranscriptPolling={false}
+ transcriptsByRunId={issueChatLongThreadTranscriptsByRunId}
+ hasOutputForRun={(runId) => issueChatLongThreadTranscriptsByRunId.has(runId)}
+ />
+ </Profiler>
+ </main>
+
+ <aside className="space-y-4 xl:sticky xl:top-4 xl:self-start">
+ <Card className="border-border/70">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">Baseline metrics</CardTitle>
+ </CardHeader>
+ <CardContent className="grid gap-2">
+ <MetricTile label="Profiler commits" value={String(metrics.commitCount)} testId="perf-commit-count" />
+ <MetricTile label="Mount duration" value={formatMs(metrics.mountActualDuration)} testId="perf-mount-duration" />
+ <MetricTile label="Latest duration" value={formatMs(metrics.latestActualDuration)} testId="perf-latest-duration" />
+ <MetricTile label="Max duration" value={formatMs(metrics.maxActualDuration)} testId="perf-max-duration" />
+ <MetricTile label="Total duration" value={formatMs(metrics.totalActualDuration)} testId="perf-total-duration" />
+ </CardContent>
+ </Card>
+
+ <Card className="border-border/70">
+ <CardHeader className="pb-2">
+ <CardTitle className="text-base">Fixture shape</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-2">
+ {fixture.sidebarStats.map(([label, value]) => (
+ <div key={label} className="flex items-center justify-between gap-3 text-sm">
+ <span className="text-muted-foreground">{label}</span>
+ <span className="font-mono">{value}</span>
+ </div>
+ ))}
+ <div className="hidden" data-testid="perf-markdown-comment-id-sample">
+ {[...issueChatLongThreadMarkdownCommentIds].slice(0, 3).join(",")}
+ </div>
+ </CardContent>
+ </Card>
+ </aside>
+ </div>
+ </div>
+ );
+}
diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx
index 4ae3733b05..a926c162af 100644
--- a/ui/src/pages/IssueDetail.test.tsx
+++ b/ui/src/pages/IssueDetail.test.tsx
@@ -134,6 +134,9 @@ vi.mock("../context/DialogContext", () => ({
useDialog: () => ({
openNewIssue: vi.fn(),
}),
+ useDialogActions: () => ({
+ openNewIssue: vi.fn(),
+ }),
}));
vi.mock("../context/PanelContext", () => ({
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index fd207835fd..be4707e85b 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -13,7 +13,7 @@ import { agentsApi } from "../api/agents";
import { authApi } from "../api/auth";
import { projectsApi } from "../api/projects";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { usePanel } from "../context/PanelContext";
import { useSidebar } from "../context/SidebarContext";
import { useToastActions } from "../context/ToastContext";
@@ -77,6 +77,7 @@ import { ImageGalleryModal } from "../components/ImageGalleryModal";
import { ScrollToBottom } from "../components/ScrollToBottom";
import { StatusIcon } from "../components/StatusIcon";
import { PriorityIcon } from "../components/PriorityIcon";
+import { ProductivityReviewBadge } from "../components/ProductivityReviewBadge";
import { Identity } from "../components/Identity";
import { PluginSlotMount, PluginSlotOutlet, usePluginSlots } from "@/plugins/slots";
import { PluginLauncherOutlet } from "@/plugins/launchers";
@@ -108,6 +109,7 @@ import {
Check,
ChevronRight,
Copy,
+ Eye,
EyeOff,
Hexagon,
ListTree,
@@ -558,6 +560,7 @@ type IssueDetailChatTabProps = {
hasOlderComments: boolean;
commentsLoadingOlder: boolean;
onLoadOlderComments: () => void;
+ onRefreshLatestComments: () => Promise<unknown> | void;
composerRef: Ref<IssueChatComposerHandle>;
feedbackVotes?: FeedbackVote[];
feedbackDataSharingPreference: "allowed" | "not_allowed" | "prompt";
@@ -611,6 +614,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
hasOlderComments,
commentsLoadingOlder,
onLoadOlderComments,
+ onRefreshLatestComments,
composerRef,
feedbackVotes,
feedbackDataSharingPreference,
@@ -835,6 +839,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
}
: undefined}
onImageClick={onImageClick}
+ onRefreshLatestComments={onRefreshLatestComments}
/>
</div>
);
@@ -1023,7 +1028,7 @@ function IssueDetailActivityTab({
export function IssueDetail() {
const { issueId } = useParams<{ issueId: string }>();
const { selectedCompanyId } = useCompany();
- const { openNewIssue } = useDialog();
+ const { openNewIssue } = useDialogActions();
const { openPanel, closePanel, panelVisible, setPanelVisible } = usePanel();
const { setBreadcrumbs, setMobileToolbar } = useBreadcrumbs();
const queryClient = useQueryClient();
@@ -1090,6 +1095,7 @@ export function IssueDetail() {
isFetchingNextPage: commentsLoadingOlder,
hasNextPage: hasOlderComments,
fetchNextPage: fetchOlderComments,
+ refetch: refetchComments,
} = useInfiniteQuery({
queryKey: queryKeys.issues.comments(issueId!),
queryFn: ({ pageParam }) =>
@@ -2554,6 +2560,13 @@ export function IssueDetail() {
const loadOlderComments = useCallback(() => {
void fetchOlderComments();
}, [fetchOlderComments]);
+ const refetchLatestComments = useCallback(async () => {
+ // Refetch the entire infinite-query (page 0 first), so any comments that
+ // arrived after the initial load — including ones live updates may have
+ // missed during reconnects — are present before we scroll the user to
+ // the absolute newest.
+ await refetchComments();
+ }, [refetchComments]);
useEffect(() => {
if (!shouldPrefetchOlderComments) return;
void fetchOlderComments();
@@ -2906,6 +2919,20 @@ export function IssueDetail() {
</Link>
)}
+ {issue.productivityReview ? (
+ <ProductivityReviewBadge review={issue.productivityReview} />
+ ) : null}
+
+ {issue.originKind === "issue_productivity_review" ? (
+ <span
+ className="inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300 shrink-0"
+ title="This task is a productivity review."
+ >
+ <Eye className="h-3 w-3" />
+ Productivity review
+ </span>
+ ) : null}
+
{issue.projectId ? (
<Link
to={`/projects/${issue.projectId}`}
@@ -3402,6 +3429,7 @@ export function IssueDetail() {
hasOlderComments={hasOlderComments}
commentsLoadingOlder={commentsLoadingOlder}
onLoadOlderComments={loadOlderComments}
+ onRefreshLatestComments={refetchLatestComments}
composerRef={commentComposerRef}
feedbackVotes={feedbackVotes}
feedbackDataSharingPreference={feedbackDataSharingPreference}
diff --git a/ui/src/pages/Issues.test.tsx b/ui/src/pages/Issues.test.tsx
index 1234242bae..b959c86951 100644
--- a/ui/src/pages/Issues.test.tsx
+++ b/ui/src/pages/Issues.test.tsx
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
-import { buildIssuesSearchUrl } from "./Issues";
+import type { Issue } from "@paperclipai/shared";
+import { buildIssuesSearchUrl, getNextIssuesPageOffset, mergeIssuePagesStable } from "./Issues";
+
+function createIssue(id: string, title: string): Issue {
+ return { id, title } as Issue;
+}
describe("buildIssuesSearchUrl", () => {
it("preserves trailing spaces in the synced search param", () => {
@@ -14,3 +19,29 @@ describe("buildIssuesSearchUrl", () => {
expect(buildIssuesSearchUrl("http://localhost:3100/issues?q=bug+", "bug ")).toBeNull();
});
});
+
+describe("issues page pagination helpers", () => {
+ it("advances to the next offset when the current page is full", () => {
+ expect(getNextIssuesPageOffset(500, 0)).toBe(500);
+ expect(getNextIssuesPageOffset(500, 500)).toBe(1000);
+ expect(getNextIssuesPageOffset(1000, 2000, 1000)).toBe(3000);
+ });
+
+ it("stops requesting issue pages when the current page is partial", () => {
+ expect(getNextIssuesPageOffset(499, 0)).toBeUndefined();
+ expect(getNextIssuesPageOffset(999, 2000, 1000)).toBeUndefined();
+ });
+
+ it("dedupes overlapping pages without moving the original issue position", () => {
+ const first = createIssue("issue-1", "Original first");
+ const second = createIssue("issue-2", "Second");
+ const duplicateFirst = createIssue("issue-1", "Duplicate first");
+ const third = createIssue("issue-3", "Third");
+
+ expect(mergeIssuePagesStable([[first, second], [duplicateFirst, third]])).toEqual([
+ first,
+ second,
+ third,
+ ]);
+ });
+});
diff --git a/ui/src/pages/Issues.tsx b/ui/src/pages/Issues.tsx
index 63eb7704fc..c8be8cedce 100644
--- a/ui/src/pages/Issues.tsx
+++ b/ui/src/pages/Issues.tsx
@@ -1,6 +1,6 @@
-import { useEffect, useMemo, useCallback } from "react";
+import { useEffect, useMemo, useCallback, useRef, useState } from "react";
import { useLocation, useSearchParams } from "@/lib/router";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { useInfiniteQuery, useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { issuesApi } from "../api/issues";
import { agentsApi } from "../api/agents";
import { projectsApi } from "../api/projects";
@@ -13,8 +13,33 @@ import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
import { EmptyState } from "../components/EmptyState";
import { IssuesList } from "../components/IssuesList";
import { CircleDot } from "lucide-react";
+import type { Issue } from "@paperclipai/shared";
const WORKSPACE_FILTER_ISSUE_LIMIT = 1000;
+const ISSUES_PAGE_SIZE = 500;
+
+export function getNextIssuesPageOffset(
+ loadedPageSize: number,
+ currentOffset: number,
+ pageSize: number = ISSUES_PAGE_SIZE,
+): number | undefined {
+ return loadedPageSize >= pageSize ? currentOffset + pageSize : undefined;
+}
+
+export function mergeIssuePagesStable(pages: Issue[][]): Issue[] {
+ const seenIssueIds = new Set<string>();
+ const merged: Issue[] = [];
+
+ for (const page of pages) {
+ for (const issue of page) {
+ if (seenIssueIds.has(issue.id)) continue;
+ seenIssueIds.add(issue.id);
+ merged.push(issue);
+ }
+ }
+
+ return merged;
+}
export function buildIssuesSearchUrl(currentHref: string, search: string): string | null {
const url = new URL(currentHref);
@@ -36,15 +61,27 @@ export function Issues() {
const location = useLocation();
const [searchParams] = useSearchParams();
const queryClient = useQueryClient();
-
- const initialSearch = searchParams.get("q") ?? "";
+ const fetchNextPageInFlightRef = useRef(false);
+
+ const urlSearch = searchParams.get("q") ?? "";
+ const [searchOverride, setSearchOverride] = useState<{ search: string; locationSearch: string } | null>(null);
+ const syncedSearch = useMemo(() => {
+ if (typeof window !== "undefined" && searchOverride?.locationSearch === window.location.search) {
+ return searchOverride.search;
+ }
+ return urlSearch;
+ }, [searchOverride, urlSearch, location.search]);
const participantAgentId = searchParams.get("participantAgentId") ?? undefined;
const initialWorkspaces = searchParams.getAll("workspace").filter((workspaceId) => workspaceId.length > 0);
const workspaceIdFilter = initialWorkspaces.length === 1 ? initialWorkspaces[0] : undefined;
const handleSearchChange = useCallback((search: string) => {
const nextUrl = buildIssuesSearchUrl(window.location.href, search);
- if (!nextUrl) return;
+ if (!nextUrl) {
+ setSearchOverride(null);
+ return;
+ }
window.history.replaceState(window.history.state, "", nextUrl);
+ setSearchOverride({ search, locationSearch: window.location.search });
}, []);
const { data: agents } = useQuery({
@@ -82,7 +119,16 @@ export function Issues() {
setBreadcrumbs([{ label: "Issues" }]);
}, [setBreadcrumbs]);
- const { data: issues, isLoading, error } = useQuery({
+ const issuePageSize = workspaceIdFilter ? WORKSPACE_FILTER_ISSUE_LIMIT : ISSUES_PAGE_SIZE;
+
+ const {
+ data: issuePages,
+ isLoading,
+ isFetchingNextPage,
+ error,
+ hasNextPage,
+ fetchNextPage,
+ } = useInfiniteQuery({
queryKey: [
...queryKeys.issues.list(selectedCompanyId!),
"participant-agent",
@@ -90,16 +136,34 @@ export function Issues() {
"workspace",
workspaceIdFilter ?? "__all__",
"with-routine-executions",
+ "infinite",
+ issuePageSize,
],
- queryFn: () => issuesApi.list(selectedCompanyId!, {
+ queryFn: ({ pageParam }) => issuesApi.list(selectedCompanyId!, {
participantAgentId,
workspaceId: workspaceIdFilter,
includeRoutineExecutions: true,
- ...(workspaceIdFilter ? { limit: WORKSPACE_FILTER_ISSUE_LIMIT } : {}),
+ limit: issuePageSize,
+ offset: pageParam,
}),
+ initialPageParam: 0,
+ getNextPageParam: (lastPage, _allPages, lastPageParam) =>
+ getNextIssuesPageOffset(lastPage.length, lastPageParam, issuePageSize),
enabled: !!selectedCompanyId,
+ placeholderData: (previousData) => previousData,
});
+ const issues = useMemo(() => mergeIssuePagesStable(issuePages?.pages ?? []), [issuePages]);
+ const hasMoreServerIssues = syncedSearch.trim().length === 0
+ && hasNextPage === true;
+ const loadMoreServerIssues = useCallback(() => {
+ if (!hasNextPage || isFetchingNextPage || fetchNextPageInFlightRef.current) return;
+ fetchNextPageInFlightRef.current = true;
+ void fetchNextPage({ cancelRefetch: false }).finally(() => {
+ fetchNextPageInFlightRef.current = false;
+ });
+ }, [fetchNextPage, hasNextPage, isFetchingNextPage]);
+
const updateIssue = useMutation({
mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
issuesApi.update(id, data),
@@ -116,6 +180,7 @@ export function Issues() {
<IssuesList
issues={issues ?? []}
isLoading={isLoading}
+ isLoadingMoreIssues={isFetchingNextPage}
error={error as Error | null}
agents={agents}
projects={projects}
@@ -124,9 +189,11 @@ export function Issues() {
issueLinkState={issueLinkState}
initialAssignees={searchParams.get("assignee") ? [searchParams.get("assignee")!] : undefined}
initialWorkspaces={initialWorkspaces.length > 0 ? initialWorkspaces : undefined}
- initialSearch={initialSearch}
+ initialSearch={syncedSearch}
onSearchChange={handleSearchChange}
enableRoutineVisibilityFilter
+ hasMoreIssues={hasMoreServerIssues}
+ onLoadMoreIssues={loadMoreServerIssues}
onUpdateIssue={(id, data) => updateIssue.mutate({ id, data })}
searchFilters={participantAgentId || workspaceIdFilter ? { participantAgentId, workspaceId: workspaceIdFilter } : undefined}
/>
diff --git a/ui/src/pages/Projects.tsx b/ui/src/pages/Projects.tsx
index 886a2b6076..08d246a856 100644
--- a/ui/src/pages/Projects.tsx
+++ b/ui/src/pages/Projects.tsx
@@ -2,7 +2,7 @@ import { useEffect, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { projectsApi } from "../api/projects";
import { useCompany } from "../context/CompanyContext";
-import { useDialog } from "../context/DialogContext";
+import { useDialogActions } from "../context/DialogContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { queryKeys } from "../lib/queryKeys";
import { EntityRow } from "../components/EntityRow";
@@ -15,7 +15,7 @@ import { Hexagon, Plus } from "lucide-react";
export function Projects() {
const { selectedCompanyId } = useCompany();
- const { openNewProject } = useDialog();
+ const { openNewProject } = useDialogActions();
const { setBreadcrumbs } = useBreadcrumbs();
useEffect(() => {
diff --git a/ui/src/pages/RoutineDetail.tsx b/ui/src/pages/RoutineDetail.tsx
index 3ccbcfa74d..bb36f1d48e 100644
--- a/ui/src/pages/RoutineDetail.tsx
+++ b/ui/src/pages/RoutineDetail.tsx
@@ -20,18 +20,20 @@ import { heartbeatsApi } from "../api/heartbeats";
import { LiveRunWidget } from "../components/LiveRunWidget";
import { agentsApi } from "../api/agents";
import { projectsApi } from "../api/projects";
+import { accessApi } from "../api/access";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useToastActions } from "../context/ToastContext";
import { queryKeys } from "../lib/queryKeys";
import { buildRoutineTriggerPatch } from "../lib/routine-trigger-patch";
+import { buildMarkdownMentionOptions } from "../lib/company-members";
import { timeAgo } from "../lib/timeAgo";
import { ToggleSwitch } from "@/components/ui/toggle-switch";
import { EmptyState } from "../components/EmptyState";
import { PageSkeleton } from "../components/PageSkeleton";
import { AgentIcon } from "../components/AgentIconPicker";
import { InlineEntitySelector, type InlineEntityOption } from "../components/InlineEntitySelector";
-import { MarkdownEditor, type MarkdownEditorRef } from "../components/MarkdownEditor";
+import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "../components/MarkdownEditor";
import {
RoutineRunVariablesDialog,
type RoutineRunDialogSubmitData,
@@ -350,6 +352,11 @@ export function RoutineDetail() {
queryFn: () => projectsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
const routineDefaults = useMemo(
() =>
@@ -649,6 +656,13 @@ export function RoutineDetail() {
})),
[projects],
);
+ const mentionOptions = useMemo<MentionOption[]>(() => {
+ return buildMarkdownMentionOptions({
+ agents,
+ projects,
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users, projects]);
const currentAssignee = editDraft.assigneeAgentId ? agentById.get(editDraft.assigneeAgentId) ?? null : null;
const currentProject = editDraft.projectId ? projectById.get(editDraft.projectId) ?? null : null;
@@ -882,6 +896,7 @@ export function RoutineDetail() {
placeholder="Add instructions..."
bordered={false}
contentClassName="min-h-[120px] text-[15px] leading-7"
+ mentions={mentionOptions}
onSubmit={() => {
if (!saveRoutine.isPending && editDraft.title.trim()) {
saveRoutine.mutate();
diff --git a/ui/src/pages/Routines.test.tsx b/ui/src/pages/Routines.test.tsx
index aba2412cf5..23f6211a05 100644
--- a/ui/src/pages/Routines.test.tsx
+++ b/ui/src/pages/Routines.test.tsx
@@ -12,6 +12,7 @@ let currentSearch = "";
const navigateMock = vi.fn();
const routinesListMock = vi.fn<(companyId: string) => Promise<RoutineListItem[]>>();
const issuesListMock = vi.fn<(companyId: string, filters?: Record<string, unknown>) => Promise<Issue[]>>();
+const markdownEditorRenderMock = vi.fn((props: { mentions?: Array<{ id: string; name: string }> }) => props);
const issuesListRenderMock = vi.fn(({ issues }: { issues: Issue[] }) => (
<div data-testid="issues-list">{issues.map((issue) => issue.title).join(", ")}</div>
));
@@ -158,6 +159,24 @@ vi.mock("../api/projects", () => ({
},
}));
+vi.mock("../api/access", () => ({
+ accessApi: {
+ listUserDirectory: vi.fn(async () => ({
+ users: [
+ {
+ principalId: "user-1",
+ status: "active",
+ user: {
+ name: "Taylor",
+ email: "[email protected]",
+ image: null,
+ },
+ },
+ ],
+ })),
+ },
+}));
+
vi.mock("../api/instanceSettings", () => ({
instanceSettingsApi: {
getExperimental: vi.fn(async () => ({ enableIsolatedWorkspaces: false })),
@@ -186,7 +205,10 @@ vi.mock("@/components/ui/tabs", () => ({
}));
vi.mock("../components/MarkdownEditor", () => ({
- MarkdownEditor: () => <div />,
+ MarkdownEditor: (props: { mentions?: Array<{ id: string; name: string }> }) => {
+ markdownEditorRenderMock(props);
+ return <div data-testid="markdown-editor" />;
+ },
}));
vi.mock("../components/InlineEntitySelector", () => ({
@@ -303,6 +325,7 @@ describe("Routines page", () => {
navigateMock.mockReset();
routinesListMock.mockReset();
issuesListMock.mockReset();
+ markdownEditorRenderMock.mockClear();
issuesListRenderMock.mockClear();
localStorage.clear();
});
@@ -334,6 +357,70 @@ describe("Routines page", () => {
expect(groups[1]?.items.map((item) => item.title)).toEqual(["Weekly digest"]);
});
+ it("passes company mention options to the routine description editor", async () => {
+ routinesListMock.mockResolvedValue([]);
+ issuesListMock.mockResolvedValue([]);
+
+ const root = createRoot(container);
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+
+ await act(async () => {
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Routines />
+ </QueryClientProvider>,
+ );
+ await flush();
+ });
+
+ let createButton = Array.from(container.querySelectorAll("button")).find((button) =>
+ button.textContent?.includes("Create routine"),
+ );
+ for (let attempts = 0; attempts < 5 && !createButton; attempts += 1) {
+ await act(async () => {
+ await flush();
+ });
+ createButton = Array.from(container.querySelectorAll("button")).find((button) =>
+ button.textContent?.includes("Create routine"),
+ );
+ }
+
+ expect(createButton).toBeTruthy();
+
+ await act(async () => {
+ createButton?.click();
+ await flush();
+ });
+
+ for (let attempts = 0; attempts < 5; attempts += 1) {
+ const hasMentionOptions = markdownEditorRenderMock.mock.calls.some(([props]) => (props.mentions ?? []).length > 0);
+ if (hasMentionOptions) break;
+ await act(async () => {
+ await flush();
+ });
+ }
+
+ const callsWithMentions = markdownEditorRenderMock.mock.calls
+ .map(([props]) => props.mentions ?? [])
+ .filter((mentions) => mentions.length > 0);
+
+ expect(callsWithMentions.at(-1)?.map((mention) => mention.id)).toEqual([
+ "user:user-1",
+ "agent:agent-1",
+ "agent:agent-2",
+ "project:project-1",
+ "project:project-2",
+ ]);
+
+ await act(async () => {
+ root.unmount();
+ });
+ });
+
it("shows recent runs through the issues list scoped to routine execution issues", async () => {
currentSearch = "tab=runs";
routinesListMock.mockResolvedValue([createRoutine({ id: "routine-1" })]);
diff --git a/ui/src/pages/Routines.tsx b/ui/src/pages/Routines.tsx
index 3c00462fbc..59e521c158 100644
--- a/ui/src/pages/Routines.tsx
+++ b/ui/src/pages/Routines.tsx
@@ -7,9 +7,11 @@ import { agentsApi } from "../api/agents";
import { projectsApi } from "../api/projects";
import { issuesApi } from "../api/issues";
import { heartbeatsApi } from "../api/heartbeats";
+import { accessApi } from "../api/access";
import { useCompany } from "../context/CompanyContext";
import { useBreadcrumbs } from "../context/BreadcrumbContext";
import { useToastActions } from "../context/ToastContext";
+import { buildMarkdownMentionOptions } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import { groupBy } from "../lib/groupBy";
import { createIssueDetailLocationState } from "../lib/issueDetailBreadcrumb";
@@ -23,7 +25,7 @@ import { PageSkeleton } from "../components/PageSkeleton";
import { PageTabBar } from "../components/PageTabBar";
import { AgentIcon } from "../components/AgentIconPicker";
import { InlineEntitySelector, type InlineEntityOption } from "../components/InlineEntitySelector";
-import { MarkdownEditor, type MarkdownEditorRef } from "../components/MarkdownEditor";
+import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "../components/MarkdownEditor";
import {
RoutineRunVariablesDialog,
type RoutineRunDialogSubmitData,
@@ -353,6 +355,11 @@ export function Routines() {
queryFn: () => projectsApi.list(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
+ const { data: companyMembers } = useQuery({
+ queryKey: queryKeys.access.companyUserDirectory(selectedCompanyId!),
+ queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
+ enabled: !!selectedCompanyId,
+ });
const { data: routineExecutionIssues, isLoading: recentRunsLoading, error: recentRunsError } = useQuery({
queryKey: [...queryKeys.issues.list(selectedCompanyId!), "routine-executions"],
queryFn: () => issuesApi.list(selectedCompanyId!, { originKind: "routine_execution" }),
@@ -369,6 +376,14 @@ export function Routines() {
autoResizeTextarea(titleInputRef.current);
}, [draft.title, composerOpen]);
+ const mentionOptions = useMemo<MentionOption[]>(() => {
+ return buildMarkdownMentionOptions({
+ agents,
+ projects,
+ members: companyMembers?.users,
+ });
+ }, [agents, companyMembers?.users, projects]);
+
const createRoutine = useMutation({
mutationFn: () =>
routinesApi.create(selectedCompanyId!, buildRoutineMutationPayload(draft)),
@@ -808,6 +823,7 @@ export function Routines() {
placeholder="Add instructions..."
bordered={false}
contentClassName="min-h-[160px] text-sm text-muted-foreground"
+ mentions={mentionOptions}
onSubmit={() => {
if (!createRoutine.isPending && draft.title.trim() && draft.projectId && draft.assigneeAgentId) {
createRoutine.mutate();
diff --git a/ui/storybook/stories/forms-editors.stories.tsx b/ui/storybook/stories/forms-editors.stories.tsx
index c8e49573ac..2a5e6b8c4e 100644
--- a/ui/storybook/stories/forms-editors.stories.tsx
+++ b/ui/storybook/stories/forms-editors.stories.tsx
@@ -92,6 +92,8 @@ Ship criteria for the board UI refresh:
- [x] Keep comments and task updates auditable
- [ ] Attach screenshots after QA
+Tooling: lean on [/react-perf-optimizer](skill://skill-react-perf?s=react-perf-optimizer) and [/vercel-react-best-practices](skill://skill-vercel-react?s=vercel-react-best-practices) so we don't regress render performance on the page it's open to. Inline skill chips like [/release-changelog](skill://skill-release?s=release-changelog) must sit on the surrounding text line, not hang below it.
+
| Surface | Owner | State |
| --- | --- | --- |
| Issues | CodexCoder | In progress |
diff --git a/ui/storybook/stories/status-language.stories.tsx b/ui/storybook/stories/status-language.stories.tsx
index 137fc320ab..4358becfb8 100644
--- a/ui/storybook/stories/status-language.stories.tsx
+++ b/ui/storybook/stories/status-language.stories.tsx
@@ -1,7 +1,11 @@
import { useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { AGENT_STATUSES, ISSUE_PRIORITIES, ISSUE_STATUSES } from "@paperclipai/shared";
-import type { IssueBlockerAttention, IssueRelationIssueSummary } from "@paperclipai/shared";
+import type {
+ IssueBlockerAttention,
+ IssueProductivityReview,
+ IssueRelationIssueSummary,
+} from "@paperclipai/shared";
import { Bot, CheckCircle2, Clock3, DollarSign, FolderKanban, Inbox, MessageSquare, Users } from "lucide-react";
import { CopyText } from "@/components/CopyText";
import { EmptyState } from "@/components/EmptyState";
@@ -10,6 +14,7 @@ import { IssueBlockedNotice } from "@/components/IssueBlockedNotice";
import { IssueRow } from "@/components/IssueRow";
import { MetricCard } from "@/components/MetricCard";
import { PriorityIcon } from "@/components/PriorityIcon";
+import { ProductivityReviewBadge } from "@/components/ProductivityReviewBadge";
import { QuotaBar } from "@/components/QuotaBar";
import { StatusBadge } from "@/components/StatusBadge";
import { StatusIcon } from "@/components/StatusIcon";
@@ -370,6 +375,114 @@ function CoveredBlockedSurface({ mode, size }: { mode: "light" | "dark"; size: "
);
}
+type ProductivityReviewFixture = {
+ label: string;
+ description: string;
+ review: IssueProductivityReview;
+};
+
+const productivityReviewFixtures: ProductivityReviewFixture[] = [
+ {
+ label: "No-comment streak",
+ description: "Source issue has had 12 completed runs without a run-created comment.",
+ review: {
+ reviewIssueId: "review-issue-1",
+ reviewIdentifier: "PAP-2702",
+ status: "todo",
+ priority: "high",
+ trigger: "no_comment_streak",
+ noCommentStreak: 12,
+ createdAt: new Date("2026-04-28T13:30:00.000Z"),
+ updatedAt: new Date("2026-04-28T13:55:00.000Z"),
+ },
+ },
+ {
+ label: "Long active duration",
+ description: "Source issue has been actively running for over 6 hours.",
+ review: {
+ reviewIssueId: "review-issue-2",
+ reviewIdentifier: "PAP-2703",
+ status: "in_progress",
+ priority: "medium",
+ trigger: "long_active_duration",
+ noCommentStreak: null,
+ createdAt: new Date("2026-04-28T08:30:00.000Z"),
+ updatedAt: new Date("2026-04-28T13:00:00.000Z"),
+ },
+ },
+ {
+ label: "High churn",
+ description: "Source issue is producing >10 runs/comments per hour.",
+ review: {
+ reviewIssueId: "review-issue-3",
+ reviewIdentifier: "PAP-2704",
+ status: "todo",
+ priority: "high",
+ trigger: "high_churn",
+ noCommentStreak: 4,
+ createdAt: new Date("2026-04-28T13:45:00.000Z"),
+ updatedAt: new Date("2026-04-28T13:55:00.000Z"),
+ },
+ },
+];
+
+const productivityReviewIssueRowFixtures = productivityReviewFixtures.map((fixture, index) =>
+ createIssue({
+ id: `issue-productivity-source-${index + 1}`,
+ identifier: `PAP-${2710 + index}`,
+ issueNumber: 2710 + index,
+ title: `Source issue under review · ${fixture.label}`,
+ status: index === 1 ? "in_progress" : "in_progress",
+ priority: fixture.review.priority,
+ productivityReview: fixture.review,
+ lastActivityAt: fixture.review.updatedAt,
+ updatedAt: fixture.review.updatedAt,
+ }),
+);
+
+function ProductivityReviewMatrix() {
+ return (
+ <div className="space-y-5">
+ <div className="grid gap-3 md:grid-cols-3">
+ {productivityReviewFixtures.map((fixture) => (
+ <div
+ key={fixture.label}
+ className="flex flex-col gap-3 rounded-lg border border-border bg-background/70 p-4"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="text-sm font-medium">{fixture.label}</div>
+ <div className="mt-1 text-xs text-muted-foreground">{fixture.description}</div>
+ </div>
+ <ProductivityReviewBadge review={fixture.review} />
+ </div>
+ <div className="rounded-md bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-muted-foreground">
+ Trigger {fixture.review.trigger ?? "unknown"} · review {fixture.review.reviewIdentifier}
+ </div>
+ </div>
+ ))}
+ </div>
+ <div className="rounded-lg border border-border">
+ <div className="border-b border-border px-3 py-2 text-xs font-medium text-muted-foreground">
+ IssueRow with productivity-review indicator
+ </div>
+ <div>
+ {productivityReviewIssueRowFixtures.map((issue) => (
+ <IssueRow key={issue.id} issue={issue} mobileMeta={<StatusBadge status={issue.status} />} />
+ ))}
+ </div>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ On the source issue header the amber pill reads <strong>Under review</strong> and links to the open
+ productivity-review child — describing the state the task is in. The productivity-review issue itself
+ carries a static <strong>Productivity review</strong> pill identifying what kind of issue it is.
+ List rows get a smaller eye glyph next to the status icon so operators can spot yellow tasks without
+ the clickable label.
+ </p>
+ </div>
+ );
+}
+
function StatusLanguage() {
const [priority, setPriority] = useState("high");
@@ -466,6 +579,10 @@ function StatusLanguage() {
</p>
</Section>
+ <Section eyebrow="Productivity review" title="Yellow accountability state on source issues">
+ <ProductivityReviewMatrix />
+ </Section>
+
<Section eyebrow="Priority" title="Static labels and editable popover trigger">
<div className="grid gap-4 lg:grid-cols-[1fr_320px]">
<div className="grid gap-3 sm:grid-cols-2">