Skip to content

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

[codex] Graduate experimental conference room defaults (#8628)

Dotta841742fc1a08
diff --git a/tests/e2e/conference-room-typing-intro.spec.ts b/tests/e2e/conference-room-typing-intro.spec.ts
index b4726401be..0a3bd134ab 100644
--- a/tests/e2e/conference-room-typing-intro.spec.ts
+++ b/tests/e2e/conference-room-typing-intro.spec.ts
@@ -1,35 +1,22 @@
import { test, expect } from "@playwright/test";
/**
- * E2E: post-wizard Conference Room typing intro (PAP-134, plan PAP-133).
+ * E2E: post-wizard onboarding launch.
*
- * Completing the onboarding wizard must land the user in the Conference Room
- * with a staged intro: three-dot typing bubble first (~2s), then the CEO
- * welcome message, then the suggestion chips. This is the regression spec
- * from the PAP-133 investigation, checked in so the intro can't silently
- * vanish again (it already did once — PAP-54 dropped the dots CSS during a
- * theme migration).
- *
- * The wizard is driven end-to-end against real endpoints with two
- * deterministic intercepts so no live LLM/CLI is needed:
- * - the adapter env-test returns an instant pass, and
- * - the team-lead hire is re-issued server-side as a REAL hire with an
- * inert `http` adapter (dead URL, heartbeat disabled), so a real CEO
- * agent exists for the welcome bubble but no agent process ever runs.
+ * Completing the onboarding wizard now creates the first assigned task and
+ * lands the user on the company dashboard. The chat intro still has unit
+ * coverage in BoardChat tests; the wizard handoff no longer routes there.
*/
const COMPANY_NAME = `E2E-TypingIntro-${Date.now()}`;
-const MISSION = "Verify the typing-dots intro survives the wizard handoff.";
+const MISSION = "Verify the dashboard launch survives the wizard handoff.";
+const FIRST_TASK_TITLE = "Hire your first engineer and create a hiring plan";
-test.describe("Conference Room typing intro after onboarding wizard", () => {
- test("shows typing dots first, then welcome, then chips", async ({
+test.describe("Dashboard launch after onboarding wizard", () => {
+ test("creates the first task and opens the dashboard", async ({
page,
baseURL,
}) => {
- // The dots animation is intentionally disabled under reduced motion —
- // pin the e2e run to full motion so the animation guard is deterministic.
- await page.emulateMedia({ reducedMotion: "no-preference" });
-
// Intercept env-test → instant pass (avoid running a real CLI check).
await page.route("**/test-environment", (route) =>
route.fulfill({
@@ -65,13 +52,6 @@ test.describe("Conference Room typing intro after onboarding wizard", () => {
});
});
- // New-NUX surfaces are flag-gated default-OFF (PAP-136/137/138): turn the
- // experimental flag on for this throwaway instance before driving them.
- const flagRes = await page.request.patch("/api/instance/settings/experimental", {
- data: { enableConferenceRoomChat: true },
- });
- expect(flagRes.ok()).toBe(true);
-
await page.goto("/onboarding");
// Launcher card path (existing companies) — enter the wizard if the
@@ -102,41 +82,24 @@ test.describe("Conference Room typing intro after onboarding wizard", () => {
// Step 4: adapter (claude_local default); heartbeat is intercepted.
await page.getByRole("button", { name: /Give it a heartbeat/ }).click();
- // Step 5: review → Get started hands off to the Conference Room.
+ // Step 5: review → Get started creates the first task and opens dashboard.
const getStarted = page.getByRole("button", { name: /Get started/ });
await getStarted.waitFor({ timeout: 20_000 });
await getStarted.click();
- // Dots-first: the typing bubble must be on screen before the welcome.
- const dots = page.locator(".typing-dots");
- await expect(dots).toBeVisible({ timeout: 5_000 });
-
- // Atomic snapshot — dots and welcome state read in one evaluation so a
- // slow assertion can't race the 2s reveal timer.
- const snapshot = await page.evaluate(() => ({
- dots: document.querySelectorAll(".typing-dots").length,
- welcomeVisible: document.body.textContent?.includes("Welcome to") ?? false,
- }));
- expect(snapshot.dots).toBeGreaterThan(0);
- expect(snapshot.welcomeVisible).toBe(false);
+ await expect(page).toHaveURL(/\/dashboard$/, { timeout: 30_000 });
- // Animation-presence guard (PAP-54 failure mode): the dots must carry a
- // real computed animation, not silently render as static circles after
- // the CSS block gets dropped in a refactor.
- const animationName = await dots
- .locator("span")
- .first()
- .evaluate((el) => getComputedStyle(el).animationName);
- expect(animationName).not.toBe("none");
- expect(animationName).toBeTruthy();
+ const companiesRes = await page.request.get("/api/companies");
+ expect(companiesRes.ok()).toBe(true);
+ const companies = await companiesRes.json();
+ const company = companies.find((candidate: { name: string }) => candidate.name === COMPANY_NAME);
+ expect(company).toBeTruthy();
- // Staged reveal completes: welcome bubble (~2s) then chips (~+700ms).
- await expect(page.getByText(/Welcome to/).first()).toBeVisible({
- timeout: 10_000,
- });
- await expect(
- page.getByRole("button", { name: "Draft a Company Brief" }),
- ).toBeVisible({ timeout: 5_000 });
- await expect(dots).toHaveCount(0);
+ const issuesRes = await page.request.get(`/api/companies/${company.id}/issues`);
+ expect(issuesRes.ok()).toBe(true);
+ const issues = await issuesRes.json();
+ const firstTask = issues.find((candidate: { title: string }) => candidate.title === FIRST_TASK_TITLE);
+ expect(firstTask).toBeTruthy();
+ await expect(page.getByText(FIRST_TASK_TITLE).first()).toBeVisible({ timeout: 15_000 });
});
});
diff --git a/tests/e2e/planning-mode-visual-verification.spec.ts b/tests/e2e/planning-mode-visual-verification.spec.ts
index aa3c557ac6..84026eb9f2 100644
--- a/tests/e2e/planning-mode-visual-verification.spec.ts
+++ b/tests/e2e/planning-mode-visual-verification.spec.ts
@@ -1,80 +1,74 @@
import { expect, test } from "@playwright/test";
-const SKIP_LLM = process.env.PAPERCLIP_E2E_SKIP_LLM !== "false";
-
-const AGENT_NAME = "CEO";
-const TASK_TITLE = "PAP-3413 planning mode evidence";
+const AGENT_NAME = "Chief of staff";
+const TASK_TITLE = "Hire your first engineer and create a hiring plan";
test("captures planning mode UI for desktop and mobile", async ({ page }) => {
const timestamp = Date.now();
const companyName = `PAP-3413-${timestamp}`;
const screenshotDir = "test-results/planning-mode";
- // This spec captures the CLASSIC (flag-off) wizard + composer; pin the
- // experimental flag off in case an earlier spec on this shared instance
- // turned it on (the NUX specs do).
- const flagRes = await page.request.patch("/api/instance/settings/experimental", {
- data: { enableConferenceRoomChat: false },
+ await page.route("**/test-environment", (route) =>
+ route.fulfill({
+ contentType: "application/json",
+ body: JSON.stringify({ status: "pass", checks: [] }),
+ }),
+ );
+
+ await page.route("**/agent-hires", async (route) => {
+ const req = route.request();
+ const body = JSON.parse(req.postData() || "{}");
+ const auth = req.headers().authorization;
+ const real = await fetch(new URL(req.url()).toString(), {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(auth ? { Authorization: auth } : {}),
+ },
+ body: JSON.stringify({
+ name: body.name,
+ role: body.role,
+ adapterType: "http",
+ adapterConfig: { url: "http://127.0.0.1:1/dead" },
+ runtimeConfig: { heartbeat: { enabled: false } },
+ }),
+ });
+ await route.fulfill({
+ status: real.status,
+ contentType: "application/json",
+ body: await real.text(),
+ });
});
- expect(flagRes.ok()).toBe(true);
await page.goto("/onboarding");
- await expect(page.locator("h3", { hasText: "Name your company" })).toBeVisible({ timeout: 5_000 });
+ const startBtn = page.getByRole("button", { name: /Start Onboarding|New Company|Add Agent/ });
+ if (await startBtn.count()) await startBtn.first().click();
+
+ const createCard = page.getByRole("button", { name: /Build a new team/ });
+ if (await createCard.count()) await createCard.first().click();
+
+ await expect(page.getByRole("heading", { name: "Name your team" })).toBeVisible({ timeout: 15_000 });
await page.locator('input[placeholder="Acme Corp"]').fill(companyName);
- await page.getByRole("button", { name: "Next" }).click();
-
- await expect(page.locator("h3", { hasText: "Create your first agent" })).toBeVisible({ timeout: 30_000 });
- await expect(page.locator('input[placeholder="CEO"]')).toHaveValue(AGENT_NAME);
- await page.getByRole("button", { name: "Next" }).click();
-
- await expect(page.locator("h3", { hasText: "Give it something to do" })).toBeVisible({ timeout: 30_000 });
- const baseUrl = page.url().split("/").slice(0, 3).join("/");
-
- if (SKIP_LLM) {
- const companiesAfterAgentRes = await page.request.get(`${baseUrl}/api/companies`);
- expect(companiesAfterAgentRes.ok()).toBe(true);
- const companiesAfterAgent = await companiesAfterAgentRes.json();
- const companyAfterAgent = companiesAfterAgent.find((c: { name: string }) => c.name === companyName);
- expect(companyAfterAgent).toBeTruthy();
-
- const agentsAfterCreateRes = await page.request.get(`${baseUrl}/api/companies/${companyAfterAgent.id}/agents`);
- expect(agentsAfterCreateRes.ok()).toBe(true);
- const agentsAfterCreate = await agentsAfterCreateRes.json();
- const ceoAgentAfterCreate = agentsAfterCreate.find((a: { name: string }) => a.name === AGENT_NAME);
- expect(ceoAgentAfterCreate).toBeTruthy();
-
- const disableWakeRes = await page.request.patch(
- `${baseUrl}/api/agents/${ceoAgentAfterCreate.id}?companyId=${encodeURIComponent(companyAfterAgent.id)}`,
- {
- data: {
- runtimeConfig: {
- heartbeat: {
- enabled: false,
- intervalSec: 300,
- wakeOnDemand: false,
- cooldownSec: 10,
- maxConcurrentRuns: 5,
- },
- },
- },
- },
- );
- expect(disableWakeRes.ok()).toBe(true);
- }
-
- const taskTitleInput = page.locator('input[placeholder="e.g. Research competitor pricing"]');
- await taskTitleInput.clear();
- await taskTitleInput.fill(TASK_TITLE);
- await page.getByRole("button", { name: "Next" }).click();
-
- await expect(page.locator("h3", { hasText: "Ready to launch" })).toBeVisible({ timeout: 30_000 });
- await page.getByRole("button", { name: "Create & Open Task" }).click();
- await expect(page).toHaveURL(/\/issues\//, { timeout: 30_000 });
-
- const openedIssueUrl = page.url();
- const openedIssueIdentifier = openedIssueUrl.split("/").filter(Boolean).pop();
- const baseOrigin = new URL(openedIssueUrl).origin;
+ await page.getByRole("button", { name: /^Next/ }).click();
+
+ await expect(page.getByRole("heading", { name: "Define your mission" })).toBeVisible({ timeout: 30_000 });
+ await page
+ .getByPlaceholder("What is your team trying to achieve?")
+ .fill("Capture planning mode visual evidence for the graduated task UI.");
+ await page.getByRole("button", { name: /Confirm mission/ }).click();
+
+ await page.waitForSelector('input[placeholder="Chief of staff"]', { timeout: 30_000 });
+ await expect(page.locator('input[placeholder="Chief of staff"]')).toHaveValue(AGENT_NAME);
+
+ await page.getByRole("button", { name: /^Next/ }).click();
+ await page.getByRole("button", { name: /Give it a heartbeat/ }).click();
+
+ await expect(page.getByRole("heading", { name: "Review" })).toBeVisible({ timeout: 30_000 });
+ await page.getByRole("button", { name: /Get started/ }).click();
+ await expect(page).toHaveURL(/\/dashboard$/, { timeout: 30_000 });
+
+ const baseOrigin = new URL(page.url()).origin;
const companyRes = await page.request.get(`${baseOrigin}/api/companies`);
expect(companyRes.ok()).toBe(true);
const companies = await companyRes.json();
@@ -85,7 +79,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
const issues = await issueRes.json();
const planningSeedIssue = issues.find(
(candidate: { id: string; identifier?: string; title: string }) =>
- candidate.identifier === openedIssueIdentifier || candidate.id === openedIssueIdentifier || candidate.title === TASK_TITLE,
+ candidate.title === TASK_TITLE,
);
expect(planningSeedIssue).toBeTruthy();
@@ -113,7 +107,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await setMode("planning");
await page.goto(issuePath);
- await expect(page.getByText("Planning").first()).toBeVisible();
+ await expect(page.getByText("Plan mode").first()).toBeVisible();
await expect(page.getByTestId("issue-chat-composer")).toHaveAttribute("data-pending-work-mode", "planning");
const desktopPlanningToggle = page.getByTestId("issue-chat-composer-work-mode-toggle");
await expect(desktopPlanningToggle).toBeVisible();
@@ -127,7 +121,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await page.goto(`/${companyPrefix}/issues`);
await expect(page.locator(issueLinkSelector)).toBeVisible();
- await expect(page.locator(issueLinkSelector)).not.toContainText("Planning");
+ await expect(page.locator(issueLinkSelector)).not.toContainText("Plan mode");
await page.screenshot({
path: `${screenshotDir}/desktop-planning-row-${timestamp}.png`,
fullPage: true,
@@ -147,7 +141,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await setMode("planning");
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(issuePath);
- await expect(page.getByText("Planning").first()).toBeVisible();
+ await expect(page.getByText("Plan mode").first()).toBeVisible();
const mobilePlanningToggle = page.getByTestId("issue-chat-composer-work-mode-toggle");
await expect(mobilePlanningToggle).toBeVisible();
await expect(mobilePlanningToggle).toHaveAttribute("data-pending-work-mode", "planning");
@@ -159,7 +153,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await page.goto(`/${companyPrefix}/issues`);
await expect(page.locator(issueLinkSelector)).toBeVisible();
- await expect(page.locator(issueLinkSelector)).not.toContainText("Planning");
+ await expect(page.locator(issueLinkSelector)).not.toContainText("Plan mode");
await page.screenshot({
path: `${screenshotDir}/mobile-planning-row-${timestamp}.png`,
fullPage: true,
diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx
index f4887e2ba0..7e3d651940 100644
--- a/ui/src/components/IssueChatThread.tsx
+++ b/ui/src/components/IssueChatThread.tsx
@@ -3796,8 +3796,8 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
);
}
- const workModeOptions = workModeMetaList(true);
- const pendingWorkModeMeta = workModeMetaFor(pendingWorkMode, true);
+ const workModeOptions = workModeMetaList();
+ const pendingWorkModeMeta = workModeMetaFor(pendingWorkMode);
const PendingWorkModeIcon = pendingWorkModeMeta.icon;
function handleComposerKeyDown(evt: ReactKeyboardEvent<HTMLDivElement>) {
@@ -3809,7 +3809,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
const isPeriod = evt.code === "Period" || evt.key === ".";
if (!(evt.metaKey || evt.ctrlKey) || !isPeriod) return;
evt.preventDefault();
- setPendingWorkMode((current) => nextWorkMode(current, true));
+ setPendingWorkMode((current) => nextWorkMode(current));
}
return (
@@ -3962,7 +3962,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
aria-expanded={workModeMenuOpen}
aria-pressed={pendingWorkMode !== "standard"}
aria-keyshortcuts="Meta+Period Control+Period"
- title={titleForPendingWorkMode(pendingWorkMode, true)}
+ title={titleForPendingWorkMode(pendingWorkMode)}
className={cn(
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-semibold transition-colors",
pendingWorkModeMeta.classes.chip,
diff --git a/ui/src/components/IssueChatThreadClassic.tsx b/ui/src/components/IssueChatThreadClassic.tsx
deleted file mode 100644
index f7188e259c..0000000000
--- a/ui/src/components/IssueChatThreadClassic.tsx
+++ /dev/null
@@ -1,4600 +0,0 @@
-/**
- * CLASSIC FORK — do not extend (PAP-136 / PAP-139).
- *
- * Frozen copy of `IssueChatThread.tsx` at merge-base e3aada1d
- * (`git show e3aada1d:ui/src/components/IssueChatThread.tsx`), selected by
- * `IssueDetail` / `RunChatSurface` when the "Conference Room Chat"
- * experimental flag is OFF so task threads (bubbles, metadata rows, plan
- * cards, action rows, composer chrome) look exactly like master. New features
- * go in `IssueChatThread.tsx`; delete this file when the flag graduates or
- * dies.
- */
-import {
- AssistantRuntimeProvider,
- useAui,
-} from "@assistant-ui/react";
-import type {
- ReasoningMessagePart,
- TextMessagePart,
- ThreadMessage,
- ToolCallMessagePart,
-} from "@assistant-ui/react";
-import {
- createContext,
- Component,
- forwardRef,
- memo,
- useCallback,
- useContext,
- useEffect,
- useId,
- useImperativeHandle,
- useLayoutEffect,
- useMemo,
- useRef,
- useState,
- type ChangeEvent,
- type DragEvent as ReactDragEvent,
- type ErrorInfo,
- type KeyboardEvent as ReactKeyboardEvent,
- type Ref,
- type ReactNode,
-} from "react";
-import { Link, useLocation } from "@/lib/router";
-import type {
- Agent,
- FeedbackDataSharingPreference,
- FeedbackVote,
- FeedbackVoteValue,
- IssueAttachment,
- IssueBlockerAttention,
- IssueRecoveryAction,
- IssueRelationIssueSummary,
- IssueScheduledRetry,
- SuccessfulRunHandoffState,
- IssueWorkMode,
-} from "@paperclipai/shared";
-import type { ActiveRunForIssue, LiveRunForIssue } from "../api/heartbeats";
-import { useLiveRunTranscripts } from "./transcript/useLiveRunTranscripts";
-import { usePaperclipIssueRuntime, type PaperclipIssueRuntimeReassignment } from "../hooks/usePaperclipIssueRuntime";
-import { copyTextToClipboard } from "../lib/clipboard";
-import {
- buildIssueChatMessages,
- formatDurationWords,
- isCoTSegmentActive,
- stabilizeThreadMessages,
- type IssueChatComment,
- type IssueChatLinkedRun,
- type StableThreadMessageCacheEntry,
- type IssueChatTranscriptEntry,
- type SegmentTiming,
-} from "../lib/issue-chat-messages";
-import type {
- AskUserQuestionsAnswer,
- AskUserQuestionsInteraction,
- IssueThreadInteraction,
- RequestCheckboxConfirmationInteraction,
- RequestConfirmationInteraction,
- SuggestTasksInteraction,
-} from "../lib/issue-thread-interactions";
-import { buildIssueThreadInteractionSummary, isIssueThreadInteraction } from "../lib/issue-thread-interactions";
-import { resolveIssueChatTranscriptRuns } from "../lib/issueChatTranscriptRuns";
-import {
- formatTimelineWorkspaceLabel,
- type IssueTimelineAssignee,
- type IssueTimelineEvent,
- type IssueTimelineWorkspace,
-} from "../lib/issue-timeline-events";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import { MarkdownBody } from "./MarkdownBody";
-import { WorkspaceFileMarkdownBody } from "./WorkspaceFileMarkdownBody";
-import { MarkdownEditor, type MentionOption, type MarkdownEditorRef } from "./MarkdownEditor";
-import { Identity } from "./Identity";
-import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
-import { IssueThreadInteractionCardClassic } from "./IssueThreadInteractionCardClassic";
-import { AgentIcon } from "./AgentIconPicker";
-import { RunStatusBadge } from "./interrupt-handoff/InterruptHandoffViews";
-import { restoreSubmittedCommentDraft } from "../lib/comment-submit-draft";
-import {
- captureComposerViewportSnapshot,
- restoreComposerViewportSnapshot,
- 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 {
- isSuccessfulRunHandoffComment,
- isSuccessfulRunHandoffEscalationComment,
-} from "../lib/successful-run-handoff";
-import {
- SystemNotice,
- type SystemNoticeMetadataRow,
- type SystemNoticeMetadataSection,
-} from "./SystemNotice";
-import {
- buildSystemNoticeProps,
- mapCommentMetadataToSystemNoticeSections,
-} from "../lib/system-notice-comment";
-import type {
- IssueCommentMetadata,
- IssueCommentPresentation,
- SourceTrustMetadata,
-} from "@paperclipai/shared";
-import {
- describeToolInput,
- displayToolName,
- formatToolPayload,
- isCommandTool,
- parseToolPayload,
- summarizeToolInput,
- summarizeToolResult,
-} from "../lib/transcriptPresentation";
-import { cn, formatDateTime, formatShortDate } from "../lib/utils";
-import { nextWorkMode, titleForPendingWorkMode, workModeMetaFor, workModeMetaList } from "../lib/work-mode-meta";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { Textarea } from "@/components/ui/textarea";
-import { AlertTriangle, ArrowRight, Brain, Check, ChevronDown, ClipboardList, Copy, Hammer, Loader2, MoreHorizontal, Paperclip, PauseCircle, Search, Square, ThumbsDown, ThumbsUp, Trash2 } from "lucide-react";
-import { IssueBlockedNotice } from "./IssueBlockedNotice";
-import { IssueAssignedBacklogNotice } from "./IssueAssignedBacklogNotice";
-import { IssueRecoveryActionCard, type RecoveryResolveOutcome } from "./IssueRecoveryActionCard";
-import { SourceTrustBadge } from "./SourceTrustBadge";
-
-interface IssueChatMessageContext {
- feedbackDataSharingPreference: FeedbackDataSharingPreference;
- feedbackTermsUrl: string | null;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
- userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
- onVote?: (
- commentId: string,
- vote: FeedbackVoteValue,
- options?: { allowSharing?: boolean; reason?: string },
- ) => Promise<void>;
- onStopRun?: (runId: string) => Promise<void>;
- stopRunLabel?: string;
- stoppingRunLabel?: string;
- stopRunVariant?: "stop" | "pause";
- runFinalizationActions?: readonly IssueChatRunFinalizationAction[];
- onInterruptQueued?: (runId: string) => Promise<void>;
- onCancelQueued?: (commentId: string) => void;
- onDeleteComment?: (commentId: string) => Promise<void> | void;
- onImageClick?: (src: string) => void;
- onAcceptInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- selectedClientKeys?: string[],
- selectedOptionIds?: string[],
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- reason?: string,
- ) => Promise<void> | void;
- onSubmitInteractionAnswers?: (
- interaction: AskUserQuestionsInteraction,
- answers: AskUserQuestionsAnswer[],
- ) => Promise<void> | void;
- onCancelInteraction?: (
- interaction: AskUserQuestionsInteraction,
- ) => Promise<void> | void;
- issueStatus?: string;
- successfulRunHandoff?: SuccessfulRunHandoffState | null;
-}
-
-const IssueChatCtx = createContext<IssueChatMessageContext>({
- feedbackDataSharingPreference: "prompt",
- feedbackTermsUrl: null,
- issueStatus: undefined,
- successfulRunHandoff: null,
-});
-
-export type IssueChatRunFinalizationAction = {
- id: "cancel" | "done";
- label: string;
- pendingLabel: string;
- onSelect: (runId: string) => Promise<void> | void;
- isPending?: boolean;
- disabled?: boolean;
-};
-
-export function resolveAssistantMessageFoldedState(args: {
- messageId: string;
- currentFolded: boolean;
- isFoldable: boolean;
- previousMessageId: string | null;
- previousIsFoldable: boolean;
-}) {
- const {
- messageId,
- currentFolded,
- isFoldable,
- previousMessageId,
- previousIsFoldable,
- } = args;
-
- if (messageId !== previousMessageId) return isFoldable;
- if (!isFoldable) return false;
- if (!previousIsFoldable) return true;
- return currentFolded;
-}
-
-export function canStopIssueChatRun(args: {
- runId: string | null;
- runStatus: string | null;
- activeRunIds: ReadonlySet<string>;
-}) {
- const { runId, runStatus, activeRunIds } = args;
- if (!runId) return false;
- if (activeRunIds.has(runId)) return true;
- return runStatus === "queued" || runStatus === "running";
-}
-
-function findCoTSegmentIndex(
- messageParts: ReadonlyArray<{ type: string }>,
- cotParts: ReadonlyArray<{ type: string }>,
-): number {
- if (cotParts.length === 0) return -1;
- const firstPart = cotParts[0];
- let segIdx = -1;
- let inCoT = false;
- for (const part of messageParts) {
- if (part.type === "reasoning" || part.type === "tool-call") {
- if (!inCoT) { segIdx++; inCoT = true; }
- if (part === firstPart) return segIdx;
- } else {
- inCoT = false;
- }
- }
- return -1;
-}
-
-function useLiveElapsed(startMs: number | null | undefined, active: boolean): string | null {
- const [, rerender] = useState(0);
- useEffect(() => {
- if (!active || !startMs) return;
- const interval = setInterval(() => rerender((n) => n + 1), 1000);
- return () => clearInterval(interval);
- }, [active, startMs]);
- if (!active || !startMs) return null;
- 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;
-}
-
-export interface IssueChatComposerHandle {
- focus: () => void;
- restoreDraft: (submittedBody: string) => void;
-}
-
-interface IssueChatComposerProps {
- onImageUpload?: (file: File) => Promise<string>;
- onAttachImage?: (file: File) => Promise<IssueAttachment | void>;
- draftKey?: string;
- enableReassign?: boolean;
- reassignOptions?: InlineEntityOption[];
- currentAssigneeValue?: string;
- suggestedAssigneeValue?: string;
- mentions?: MentionOption[];
- agentMap?: Map<string, Agent>;
- composerDisabledReason?: string | null;
- composerHint?: string | null;
- issueStatus?: string;
- issueWorkMode?: IssueWorkMode;
- onWorkModeChange?: (workMode: IssueWorkMode) => Promise<void> | void;
-}
-
-interface IssueChatThreadProps {
- comments: IssueChatComment[];
- interactions?: IssueThreadInteraction[];
- feedbackVotes?: FeedbackVote[];
- feedbackDataSharingPreference?: FeedbackDataSharingPreference;
- feedbackTermsUrl?: string | null;
- linkedRuns?: IssueChatLinkedRun[];
- timelineEvents?: IssueTimelineEvent[];
- liveRuns?: LiveRunForIssue[];
- activeRun?: ActiveRunForIssue | null;
- issueId?: string | null;
- blockedBy?: IssueRelationIssueSummary[];
- blockerAttention?: IssueBlockerAttention | null;
- successfulRunHandoff?: SuccessfulRunHandoffState | null;
- scheduledRetry?: IssueScheduledRetry | null;
- recoveryAction?: IssueRecoveryAction | null;
- onResolveRecoveryAction?: (outcome: RecoveryResolveOutcome) => void;
- canFalsePositiveRecoveryAction?: boolean;
- legacyRecoverySourceIssue?: {
- identifier: string | null;
- href: string;
- title?: string | null;
- } | null;
- assigneeUserId?: string | null;
- onResumeFromBacklog?: () => Promise<void> | void;
- resumeFromBacklogPending?: boolean;
- companyId?: string | null;
- projectId?: string | null;
- issueStatus?: string;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
- userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
- onVote?: (
- commentId: string,
- vote: FeedbackVoteValue,
- options?: { allowSharing?: boolean; reason?: string },
- ) => Promise<void>;
- onAdd: (body: string, reopen?: boolean, reassignment?: CommentReassignment) => Promise<void>;
- onCancelRun?: () => Promise<void>;
- onStopRun?: (runId: string) => Promise<void>;
- stopRunLabel?: string;
- stoppingRunLabel?: string;
- stopRunVariant?: "stop" | "pause";
- runFinalizationActions?: readonly IssueChatRunFinalizationAction[];
- imageUploadHandler?: (file: File) => Promise<string>;
- onAttachImage?: (file: File) => Promise<IssueAttachment | void>;
- draftKey?: string;
- enableReassign?: boolean;
- reassignOptions?: InlineEntityOption[];
- currentAssigneeValue?: string;
- suggestedAssigneeValue?: string;
- mentions?: MentionOption[];
- composerDisabledReason?: string | null;
- composerHint?: string | null;
- onWorkModeChange?: (workMode: IssueWorkMode) => Promise<void> | void;
- showComposer?: boolean;
- showJumpToLatest?: boolean;
- emptyMessage?: string;
- footer?: ReactNode;
- variant?: "full" | "embedded";
- enableLiveTranscriptPolling?: boolean;
- transcriptsByRunId?: ReadonlyMap<string, readonly IssueChatTranscriptEntry[]>;
- hasOutputForRun?: (runId: string) => boolean;
- includeSucceededRunsWithoutOutput?: boolean;
- onInterruptQueued?: (runId: string) => Promise<void>;
- onCancelQueued?: (commentId: string) => void;
- onDeleteComment?: (commentId: string) => Promise<void> | void;
- interruptingQueuedRunId?: string | null;
- stoppingRunId?: string | null;
- onImageClick?: (src: string) => void;
- onAcceptInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- selectedClientKeys?: string[],
- selectedOptionIds?: string[],
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- reason?: string,
- ) => Promise<void> | void;
- onSubmitInteractionAnswers?: (
- interaction: AskUserQuestionsInteraction,
- answers: AskUserQuestionsAnswer[],
- ) => Promise<void> | void;
- onCancelInteraction?: (
- interaction: AskUserQuestionsInteraction,
- ) => Promise<void> | void;
- composerRef?: Ref<IssueChatComposerHandle>;
- issueWorkMode?: IssueWorkMode;
- /**
- * 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 = {
- resetKey: string;
- messages: readonly ThreadMessage[];
- emptyMessage: string;
- variant: "full" | "embedded";
- children: ReactNode;
-};
-
-type IssueChatErrorBoundaryState = {
- hasError: boolean;
-};
-
-class IssueChatErrorBoundary extends Component<IssueChatErrorBoundaryProps, IssueChatErrorBoundaryState> {
- override state: IssueChatErrorBoundaryState = { hasError: false };
-
- static getDerivedStateFromError(): IssueChatErrorBoundaryState {
- return { hasError: true };
- }
-
- override componentDidCatch(error: unknown, info: ErrorInfo): void {
- console.error("Issue chat renderer failed; falling back to safe transcript view", {
- error,
- info: info.componentStack,
- });
- }
-
- override componentDidUpdate(prevProps: IssueChatErrorBoundaryProps): void {
- if (this.state.hasError && prevProps.resetKey !== this.props.resetKey) {
- this.setState({ hasError: false });
- }
- }
-
- override render() {
- if (this.state.hasError) {
- return (
- <IssueChatFallbackThread
- messages={this.props.messages}
- emptyMessage={this.props.emptyMessage}
- variant={this.props.variant}
- />
- );
- }
- return this.props.children;
- }
-}
-
-function IssueAssigneePausedNotice({ agent }: { agent: Agent | null }) {
- if (!agent || agent.status !== "paused") return null;
-
- const pauseDetail =
- agent.pauseReason === "budget"
- ? "It was paused by a budget hard stop."
- : agent.pauseReason === "system"
- ? "It was paused by the system."
- : "It was paused manually.";
-
- return (
- <div className="mb-3 rounded-md border border-orange-300/70 bg-orange-50/90 px-3 py-2.5 text-sm text-orange-950 shadow-sm dark:border-orange-500/40 dark:bg-orange-500/10 dark:text-orange-100">
- <div className="flex items-start gap-2">
- <PauseCircle className="mt-0.5 h-4 w-4 shrink-0 text-orange-600 dark:text-orange-300" />
- <p className="min-w-0 leading-5">
- <span className="font-medium">{agent.name}</span> is paused. New runs will not start until the agent is resumed. {pauseDetail}
- </p>
- </div>
- </div>
- );
-}
-
-function fallbackAuthorLabel(message: ThreadMessage) {
- const custom = message.metadata?.custom as Record<string, unknown> | undefined;
- if (typeof custom?.["authorName"] === "string") return custom["authorName"];
- if (typeof custom?.["runAgentName"] === "string") return custom["runAgentName"];
- if (message.role === "assistant") return "Agent";
- if (message.role === "user") return "You";
- return "System";
-}
-
-function fallbackTextParts(message: ThreadMessage) {
- const contentLines: string[] = [];
- for (const part of message.content) {
- if (part.type === "text" || part.type === "reasoning") {
- if (part.text.trim().length > 0) contentLines.push(part.text);
- continue;
- }
- if (part.type === "tool-call") {
- const lines = [`Tool: ${part.toolName}`];
- if (part.argsText?.trim()) lines.push(`Args:\n${part.argsText}`);
- if (typeof part.result === "string" && part.result.trim()) lines.push(`Result:\n${part.result}`);
- contentLines.push(lines.join("\n\n"));
- }
- }
-
- const custom = message.metadata?.custom as Record<string, unknown> | undefined;
- if (contentLines.length === 0 && typeof custom?.["waitingText"] === "string" && custom["waitingText"].trim()) {
- contentLines.push(custom["waitingText"]);
- }
- return contentLines;
-}
-
-function IssueChatFallbackThread({
- messages,
- emptyMessage,
- variant,
-}: {
- messages: readonly ThreadMessage[];
- emptyMessage: string;
- variant: "full" | "embedded";
-}) {
- return (
- <div className={cn(variant === "embedded" ? "space-y-3" : "space-y-4")}>
- <div className="rounded-xl border border-amber-300/60 bg-amber-50/80 px-4 py-3 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-950/20 dark:text-amber-200">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
- <div className="space-y-1">
- <p className="font-medium">Chat renderer hit an internal state error.</p>
- <p className="text-xs opacity-80">
- Showing a safe fallback transcript instead of crashing the tasks page.
- </p>
- </div>
- </div>
- </div>
-
- {messages.length === 0 ? (
- <div className={cn(
- "text-center text-sm text-muted-foreground",
- variant === "embedded"
- ? "rounded-xl border border-dashed border-border/70 bg-background/60 px-4 py-6"
- : "rounded-2xl border border-dashed border-border bg-card px-6 py-10",
- )}>
- {emptyMessage}
- </div>
- ) : (
- <div className={cn(variant === "embedded" ? "space-y-3" : "space-y-4")}>
- {messages.map((message) => {
- const lines = fallbackTextParts(message);
- return (
- <div key={message.id} className="rounded-xl border border-border/60 bg-card/70 px-4 py-3">
- <div className="mb-2 flex items-center gap-2 text-sm">
- <span className="font-medium text-foreground">{fallbackAuthorLabel(message)}</span>
- {message.createdAt ? (
- <span className="text-[11px] text-muted-foreground">
- {commentDateLabel(message.createdAt)}
- </span>
- ) : null}
- </div>
- <div className="space-y-2">
- {lines.length > 0 ? lines.map((line, index) => (
- <MarkdownBody key={`${message.id}:fallback:${index}`}>{line}</MarkdownBody>
- )) : (
- <p className="text-sm text-muted-foreground">No message content.</p>
- )}
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-}
-
-const DRAFT_DEBOUNCE_MS = 800;
-const COMPOSER_FOCUS_SCROLL_PADDING_PX = 96;
-const SUBMIT_SCROLL_RESERVE_VH = 0.4;
-
-type ComposerAttachmentItem = {
- id: string;
- name: string;
- size: number;
- status: "uploading" | "attached" | "error";
- inline: boolean;
- contentPath?: string;
- error?: string;
-};
-
-function hasFilePayload(evt: ReactDragEvent<HTMLDivElement>) {
- return Array.from(evt.dataTransfer?.types ?? []).includes("Files");
-}
-
-function formatAttachmentSize(bytes: number) {
- if (!Number.isFinite(bytes) || bytes <= 0) return "";
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
-}
-
-function toIsoString(value: string | Date | null | undefined): string | null {
- if (!value) return null;
- return typeof value === "string" ? value : value.toISOString();
-}
-
-function loadDraft(draftKey: string): string {
- try {
- return localStorage.getItem(draftKey) ?? "";
- } catch {
- return "";
- }
-}
-
-function saveDraft(draftKey: string, value: string) {
- try {
- if (value.trim()) {
- localStorage.setItem(draftKey, value);
- } else {
- localStorage.removeItem(draftKey);
- }
- } catch {
- // Ignore localStorage failures.
- }
-}
-
-function clearDraft(draftKey: string) {
- try {
- localStorage.removeItem(draftKey);
- } catch {
- // Ignore localStorage failures.
- }
-}
-
-function parseReassignment(target: string): PaperclipIssueRuntimeReassignment | null {
- if (!target || target === "__none__") {
- return { assigneeAgentId: null, assigneeUserId: null };
- }
- if (target.startsWith("agent:")) {
- const assigneeAgentId = target.slice("agent:".length);
- return assigneeAgentId ? { assigneeAgentId, assigneeUserId: null } : null;
- }
- if (target.startsWith("user:")) {
- const assigneeUserId = target.slice("user:".length);
- return assigneeUserId ? { assigneeAgentId: null, assigneeUserId } : null;
- }
- return null;
-}
-
-function shouldImplicitlyReopenComment(issueStatus: string | undefined, assigneeValue: string) {
- const resumesToTodo = issueStatus === "done" || issueStatus === "cancelled" || issueStatus === "blocked";
- 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 {
- if (!date) return "";
- const then = new Date(date).getTime();
- if (Date.now() - then < WEEK_MS) return timeAgo(date);
- return formatShortDate(date);
-}
-
-const IssueChatTextPart = memo(function IssueChatTextPart({ text, recessed }: { text: string; recessed?: boolean }) {
- const { onImageClick } = useContext(IssueChatCtx);
- if (isSuccessfulRunHandoffComment(text)) {
- return <SuccessfulRunHandoffCommentCallout text={text} recessed={recessed} onImageClick={onImageClick} />;
- }
- return (
- <WorkspaceFileMarkdownBody
- className="text-sm leading-6"
- style={recessed ? { opacity: 0.55 } : undefined}
- softBreaks
- onImageClick={onImageClick}
- >
- {text}
- </WorkspaceFileMarkdownBody>
- );
-});
-
-export function SuccessfulRunHandoffCommentCallout({
- text,
- recessed,
- onImageClick,
-}: {
- text: string;
- recessed?: boolean;
- onImageClick?: (src: string) => void;
-}) {
- const escalated = isSuccessfulRunHandoffEscalationComment(text);
- return (
- <div
- className={cn(
- "rounded-md border px-3 py-2.5 text-sm shadow-sm",
- escalated
- ? "border-red-500/35 bg-red-500/10 text-red-950 dark:text-red-100"
- : "border-amber-300/70 bg-amber-50/90 text-amber-950 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100",
- )}
- style={recessed ? { opacity: 0.55 } : undefined}
- >
- <div className="flex items-start gap-2">
- <AlertTriangle
- className={cn(
- "mt-1 h-4 w-4 shrink-0",
- escalated ? "text-red-600 dark:text-red-300" : "text-amber-600 dark:text-amber-300",
- )}
- />
- <MarkdownBody className="min-w-0 text-sm leading-6" softBreaks onImageClick={onImageClick}>
- {text}
- </MarkdownBody>
- </div>
- </div>
- );
-}
-
-function humanizeValue(value: string | null) {
- if (!value) return "None";
- return value.replace(/_/g, " ");
-}
-
-function formatTimelineAssigneeLabel(
- assignee: IssueTimelineAssignee,
- agentMap?: Map<string, Agent>,
- currentUserId?: string | null,
- userLabelMap?: ReadonlyMap<string, string> | null,
-) {
- if (assignee.agentId) {
- return agentMap?.get(assignee.agentId)?.name ?? assignee.agentId.slice(0, 8);
- }
- if (assignee.userId) {
- return formatAssigneeUserLabel(assignee.userId, currentUserId, userLabelMap) ?? "Board";
- }
- return "Unassigned";
-}
-
-function initialsForName(name: string) {
- const parts = name.trim().split(/\s+/);
- if (parts.length >= 2) {
- return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
- }
- return name.slice(0, 2).toUpperCase();
-}
-
-function formatInteractionActorLabel(args: {
- agentId?: string | null;
- userId?: string | null;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
-}) {
- const { agentId, userId, agentMap, currentUserId, userLabelMap } = args;
- if (agentId) return agentMap?.get(agentId)?.name ?? agentId.slice(0, 8);
- if (userId) {
- return userLabelMap?.get(userId)
- ?? formatAssigneeUserLabel(userId, currentUserId, userLabelMap)
- ?? "Board";
- }
- return "System";
-}
-
-export function resolveIssueChatHumanAuthor(args: {
- authorName?: string | null;
- authorUserId?: string | null;
- currentUserId?: string | null;
- userProfileMap?: ReadonlyMap<string, CompanyUserProfile> | null;
-}) {
- const { authorName, authorUserId, currentUserId, userProfileMap } = args;
- const profile = authorUserId ? userProfileMap?.get(authorUserId) ?? null : null;
- const isCurrentUser = Boolean(authorUserId && currentUserId && authorUserId === currentUserId);
- const resolvedAuthorName = profile?.label?.trim()
- || authorName?.trim()
- || (authorUserId === "local-board" ? "Board" : (isCurrentUser ? "You" : "User"));
-
- return {
- isCurrentUser,
- authorName: resolvedAuthorName,
- avatarUrl: profile?.image ?? null,
- };
-}
-
-function toolCountSummary(toolParts: ToolCallMessagePart[]): string | null {
- if (toolParts.length === 0) return null;
- let commands = 0;
- let other = 0;
- for (const tool of toolParts) {
- if (isCommandTool(tool.toolName, tool.args)) commands++;
- else other++;
- }
- const parts: string[] = [];
- if (commands > 0) parts.push(`ran ${commands} command${commands === 1 ? "" : "s"}`);
- if (other > 0) parts.push(`called ${other} tool${other === 1 ? "" : "s"}`);
- return parts.join(", ");
-}
-
-function cleanToolDisplayText(tool: ToolCallMessagePart): string {
- const name = displayToolName(tool.toolName, tool.args);
- if (isCommandTool(tool.toolName, tool.args)) return name;
- const summary = tool.result === undefined
- ? summarizeToolInput(tool.toolName, tool.args)
- : null;
- return summary ? `${name} ${summary}` : name;
-}
-
-type IssueChatCoTPart = ReasoningMessagePart | ToolCallMessagePart;
-
-function IssueChatChainOfThought({
- message,
- cotParts,
-}: {
- message: ThreadMessage;
- cotParts: readonly IssueChatCoTPart[];
-}) {
- const { agentMap } = useContext(IssueChatCtx);
- const custom = message.metadata.custom as Record<string, unknown>;
- const runAgentId = typeof custom.runAgentId === "string" ? custom.runAgentId : null;
- const authorAgentId = typeof custom.authorAgentId === "string" ? custom.authorAgentId : null;
- const agentId = authorAgentId ?? runAgentId;
- const agentIcon = agentId ? agentMap?.get(agentId)?.icon : undefined;
- const isMessageRunning = message.role === "assistant" && message.status?.type === "running";
-
- const myIndex = useMemo(
- () => findCoTSegmentIndex(message.content, cotParts),
- [message.content, cotParts],
- );
-
- const allReasoningText = cotParts
- .filter((p): p is { type: "reasoning"; text: string } => p.type === "reasoning" && !!p.text)
- .map((p) => p.text)
- .join("\n");
- const toolParts = cotParts.filter(
- (p): p is ToolCallMessagePart => p.type === "tool-call",
- );
-
- const rawSegments = Array.isArray(custom.chainOfThoughtSegments)
- ? (custom.chainOfThoughtSegments as SegmentTiming[])
- : [];
- const segmentTiming = myIndex >= 0 ? rawSegments[myIndex] ?? null : null;
- const isActive = isCoTSegmentActive({
- isMessageRunning,
- segmentIndex: myIndex,
- segmentCount: rawSegments.length,
- });
- const [expanded, setExpanded] = useState(isActive);
- const liveElapsed = useLiveElapsed(segmentTiming?.startMs, isActive);
-
- useEffect(() => {
- if (isActive) setExpanded(true);
- }, [isActive]);
-
- let headerVerb: string;
- let headerSuffix: string | null = null;
- if (isActive) {
- headerVerb = "Working";
- if (liveElapsed) headerSuffix = `for ${liveElapsed}`;
- } else if (segmentTiming) {
- const durationMs = segmentTiming.endMs - segmentTiming.startMs;
- const durationText = formatDurationWords(durationMs);
- headerVerb = "Worked";
- if (durationText) headerSuffix = `for ${durationText}`;
- } else {
- headerVerb = "Worked";
- }
-
- const toolSummary = toolCountSummary(toolParts);
- const hasContent = allReasoningText.trim().length > 0 || toolParts.length > 0;
-
- return (
- <div>
- <button
- type="button"
- className="group flex w-full items-center gap-2.5 rounded-lg px-1 py-2 text-left transition-colors hover:bg-accent/5"
- onClick={() => hasContent && setExpanded((v) => !v)}
- >
- <span className="inline-flex items-center gap-2 text-sm font-medium text-foreground/80">
- {agentIcon ? (
- <AgentIcon icon={agentIcon} className="h-4 w-4 shrink-0" />
- ) : isActive ? (
- <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />
- ) : (
- <span className="flex h-4 w-4 shrink-0 items-center justify-center">
- <span className="h-1.5 w-1.5 rounded-full bg-emerald-500/70" />
- </span>
- )}
- {isActive ? (
- <span className="shimmer-text">{headerVerb}</span>
- ) : (
- headerVerb
- )}
- </span>
- {headerSuffix ? (
- <span className="text-xs text-muted-foreground/60">{headerSuffix}</span>
- ) : null}
- {toolSummary ? (
- <span className="text-xs text-muted-foreground/40">· {toolSummary}</span>
- ) : null}
- {hasContent ? (
- <ChevronDown className={cn("ml-auto h-4 w-4 shrink-0 text-muted-foreground/50 transition-transform", expanded && "rotate-180")} />
- ) : null}
- </button>
- {expanded && hasContent ? (
- <div className="space-y-1 py-1">
- {isActive ? (
- <>
- {allReasoningText ? <IssueChatReasoningPart text={allReasoningText} /> : null}
- {toolParts.length > 0 ? <IssueChatRollingToolPart toolParts={toolParts} /> : null}
- </>
- ) : (
- <>
- {allReasoningText ? <IssueChatReasoningPart text={allReasoningText} /> : null}
- {toolParts.map((tool) => (
- <IssueChatToolPart
- key={tool.toolCallId}
- toolName={tool.toolName}
- args={tool.args}
- argsText={tool.argsText}
- result={tool.result}
- isError={false}
- />
- ))}
- </>
- )}
- </div>
- ) : null}
- </div>
- );
-}
-
-function IssueChatReasoningPart({ text }: { text: string }) {
- const lines = text.split("\n").filter((l) => l.trim());
- const lastLine = lines[lines.length - 1] ?? text.slice(-200);
- const prevRef = useRef(lastLine);
- const [ticker, setTicker] = useState<{
- key: number;
- current: string;
- exiting: string | null;
- }>({ key: 0, current: lastLine, exiting: null });
-
- useEffect(() => {
- if (lastLine !== prevRef.current) {
- const prev = prevRef.current;
- prevRef.current = lastLine;
- setTicker((t) => ({ key: t.key + 1, current: lastLine, exiting: prev }));
- }
- }, [lastLine]);
-
- return (
- <div className="flex gap-2 px-1">
- <div className="flex flex-col items-center pt-0.5">
- <Brain className="h-3.5 w-3.5 shrink-0 text-muted-foreground/50" />
- </div>
- <div className="relative h-5 min-w-0 flex-1 overflow-hidden">
- {ticker.exiting !== null && (
- <span
- key={`out-${ticker.key}`}
- className="cot-line-exit absolute inset-x-0 truncate text-[13px] italic leading-5 text-muted-foreground/70"
- onAnimationEnd={() => setTicker((t) => ({ ...t, exiting: null }))}
- >
- {ticker.exiting}
- </span>
- )}
- <span
- key={`in-${ticker.key}`}
- className={cn(
- "absolute inset-x-0 truncate text-[13px] italic leading-5 text-muted-foreground/70",
- ticker.key > 0 && "cot-line-enter",
- )}
- >
- {ticker.current}
- </span>
- </div>
- </div>
- );
-}
-
-function IssueChatRollingToolPart({ toolParts }: { toolParts: ToolCallMessagePart[] }) {
- const latest = toolParts[toolParts.length - 1];
- if (!latest) return null;
-
- const fullText = cleanToolDisplayText(latest);
-
- const prevRef = useRef(fullText);
- const [ticker, setTicker] = useState<{
- key: number;
- current: string;
- exiting: string | null;
- }>({ key: 0, current: fullText, exiting: null });
-
- useEffect(() => {
- if (fullText !== prevRef.current) {
- const prev = prevRef.current;
- prevRef.current = fullText;
- setTicker((t) => ({ key: t.key + 1, current: fullText, exiting: prev }));
- }
- }, [fullText]);
-
- const ToolIcon = getToolIcon(latest.toolName);
- const isRunning = latest.result === undefined;
-
- return (
- <div className="flex gap-2 px-1">
- <div className="flex flex-col items-center pt-0.5">
- {isRunning ? (
- <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground/50" />
- ) : (
- <ToolIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground/50" />
- )}
- </div>
- <div className="relative h-5 min-w-0 flex-1 overflow-hidden">
- {ticker.exiting !== null && (
- <span
- key={`out-${ticker.key}`}
- className="cot-line-exit absolute inset-x-0 truncate text-[13px] leading-5 text-muted-foreground/70"
- onAnimationEnd={() => setTicker((t) => ({ ...t, exiting: null }))}
- >
- {ticker.exiting}
- </span>
- )}
- <span
- key={`in-${ticker.key}`}
- className={cn(
- "absolute inset-x-0 truncate text-[13px] leading-5 text-muted-foreground/70",
- ticker.key > 0 && "cot-line-enter",
- )}
- >
- {ticker.current}
- </span>
- </div>
- </div>
- );
-}
-
-function CopyablePreBlock({ children, className }: { children: string; className?: string }) {
- const [copied, setCopied] = useState(false);
- const toastActions = useOptionalToastActions();
- return (
- <div className="group/pre relative">
- <pre className={className}>{children}</pre>
- <button
- type="button"
- className={cn(
- "absolute right-1.5 top-1.5 inline-flex h-6 w-6 items-center justify-center rounded-md bg-background/80 text-muted-foreground opacity-0 backdrop-blur-sm transition-opacity hover:text-foreground group-hover/pre:opacity-100",
- copied && "opacity-100",
- )}
- title="Copy"
- aria-label="Copy"
- onClick={() => {
- void copyTextToClipboard(children).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy text",
- tone: "error",
- });
- });
- }}
- >
- {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
- </button>
- </div>
- );
-}
-
-const TOOL_ICON_MAP: Record<string, React.ComponentType<{ className?: string }>> = {
- // Extend with specific tool icons as they become known
-};
-
-function getToolIcon(toolName: string): React.ComponentType<{ className?: string }> {
- return TOOL_ICON_MAP[toolName] ?? Hammer;
-}
-
-function IssueChatToolPart({
- toolName,
- args,
- argsText,
- result,
- isError,
-}: {
- toolName: string;
- args?: unknown;
- argsText?: string;
- result?: unknown;
- isError?: boolean;
-}) {
- const [open, setOpen] = useState(false);
- const rawArgsText = argsText ?? "";
- const parsedArgs = args ?? parseToolPayload(rawArgsText);
- const resultText =
- typeof result === "string"
- ? result
- : result === undefined
- ? ""
- : formatToolPayload(result);
- const inputDetails = describeToolInput(toolName, parsedArgs);
- const displayName = displayToolName(toolName, parsedArgs);
- const isCommand = isCommandTool(toolName, parsedArgs);
- const summary = isCommand
- ? null
- : result === undefined
- ? summarizeToolInput(toolName, parsedArgs)
- : summarizeToolResult(resultText, false);
- const ToolIcon = getToolIcon(toolName);
-
- const intentDetail = inputDetails.find((d) => d.label === "Intent");
- const title = intentDetail?.value ?? displayName;
- const nonIntentDetails = inputDetails.filter((d) => d.label !== "Intent");
-
- return (
- <div className="flex gap-2 px-1">
- <div className="flex flex-col items-center pt-1">
- <ToolIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground/50" />
- {open ? <div className="mt-1 w-px flex-1 bg-border/40" /> : null}
- </div>
-
- <div className="min-w-0 flex-1">
- <button
- type="button"
- className="flex w-full items-center gap-2 rounded-md py-0.5 text-left transition-colors hover:bg-accent/5"
- onClick={() => setOpen((current) => !current)}
- >
- <span className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground/80">
- {title}
- {!intentDetail && summary ? <span className="ml-1.5 text-muted-foreground/50">{summary}</span> : null}
- </span>
- {result === undefined ? (
- <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground/50" />
- ) : null}
- <ChevronDown className={cn("h-3.5 w-3.5 shrink-0 text-muted-foreground/40 transition-transform", open && "rotate-180")} />
- </button>
-
- {open ? (
- <div className="mt-1 space-y-2 pb-1">
- {nonIntentDetails.length > 0 ? (
- <div>
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/60">
- Input
- </div>
- <dl className="space-y-1.5">
- {nonIntentDetails.map((detail) => (
- <div key={`${detail.label}:${detail.value}`}>
- <dt className="text-[10px] font-medium text-muted-foreground/60">
- {detail.label}
- </dt>
- <dd className={cn("text-xs leading-5 text-foreground/70", detail.tone === "code" && "font-mono text-[11px]")}>
- {detail.value}
- </dd>
- </div>
- ))}
- </dl>
- </div>
- ) : rawArgsText ? (
- <div>
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/60">
- Input
- </div>
- <CopyablePreBlock className="overflow-x-auto rounded-md bg-accent/30 p-2 text-[11px] leading-4 text-foreground/70">{rawArgsText}</CopyablePreBlock>
- </div>
- ) : null}
- {result !== undefined ? (
- <div>
- <div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/60">
- Result
- </div>
- <CopyablePreBlock className="overflow-x-auto rounded-md bg-accent/30 p-2 text-[11px] leading-4 text-foreground/70">{resultText}</CopyablePreBlock>
- </div>
- ) : null}
- </div>
- ) : null}
- </div>
- </div>
- );
-}
-
-function getThreadMessageCopyText(message: ThreadMessage) {
- return message.content
- .filter((part): part is TextMessagePart => part.type === "text")
- .map((part) => part.text)
- .join("\n\n");
-}
-
-const IssueChatTextParts = memo(function IssueChatTextParts({
- message,
- recessed = false,
-}: {
- message: ThreadMessage;
- recessed?: boolean;
-}) {
- return (
- <>
- {message.content
- .filter((part): part is TextMessagePart => part.type === "text")
- .map((part, index) => (
- <IssueChatTextPart
- key={`${message.id}:text:${index}`}
- text={part.text}
- recessed={recessed}
- />
- ))}
- </>
- );
-});
-
-function groupAssistantParts(
- content: readonly ThreadMessage["content"][number][],
-): Array<
- | { type: "text"; part: TextMessagePart; index: number }
- | { type: "cot"; parts: IssueChatCoTPart[]; startIndex: number }
-> {
- const groups: Array<
- | { type: "text"; part: TextMessagePart; index: number }
- | { type: "cot"; parts: IssueChatCoTPart[]; startIndex: number }
- > = [];
- let pendingCoT: IssueChatCoTPart[] = [];
- let pendingStartIndex = -1;
-
- const flushCoT = () => {
- if (pendingCoT.length === 0) return;
- groups.push({ type: "cot", parts: pendingCoT, startIndex: pendingStartIndex });
- pendingCoT = [];
- pendingStartIndex = -1;
- };
-
- content.forEach((part, index) => {
- if (part.type === "reasoning" || part.type === "tool-call") {
- if (pendingCoT.length === 0) pendingStartIndex = index;
- pendingCoT.push(part);
- return;
- }
- flushCoT();
- if (part.type === "text") {
- groups.push({ type: "text", part, index });
- }
- });
- flushCoT();
-
- return groups;
-}
-
-const IssueChatAssistantParts = memo(function IssueChatAssistantParts({
- message,
- hasCoT,
-}: {
- message: ThreadMessage;
- hasCoT: boolean;
-}) {
- const groupedParts = useMemo(() => groupAssistantParts(message.content), [message.content]);
- return (
- <>
- {groupedParts.map((group) => {
- if (group.type === "text") {
- return (
- <IssueChatTextPart
- key={`${message.id}:text:${group.index}`}
- text={group.part.text}
- recessed={hasCoT}
- />
- );
- }
- return (
- <IssueChatChainOfThought
- key={`${message.id}:cot:${group.startIndex}`}
- message={message}
- cotParts={group.parts}
- />
- );
- })}
- </>
- );
-});
-
-function IssueChatUserMessage({
- message,
- isInterruptingQueuedRun,
-}: {
- message: ThreadMessage;
- isInterruptingQueuedRun: boolean;
-}) {
- const {
- onInterruptQueued,
- onCancelQueued,
- onDeleteComment,
- currentUserId,
- userProfileMap,
- } = useContext(IssueChatCtx);
- const custom = message.metadata.custom as Record<string, unknown>;
- const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
- const commentId = typeof custom.commentId === "string" ? custom.commentId : message.id;
- const authorName = typeof custom.authorName === "string" ? custom.authorName : null;
- const authorUserId = typeof custom.authorUserId === "string" ? custom.authorUserId : null;
- const queued = custom.queueState === "queued" || custom.clientStatus === "queued";
- const sourceTrust = isSourceTrustMetadata(custom.sourceTrust) ? custom.sourceTrust : null;
- const followUpRequested = custom.followUpRequested === true;
- const queueReason = typeof custom.queueReason === "string" ? custom.queueReason : null;
- const queueBadgeLabel = queueReason === "hold" ? "\u23f8 Deferred wake" : "Queued";
- const pending = custom.clientStatus === "pending";
- const deleted = Boolean(custom.deletedAt);
- const queueTargetRunId = typeof custom.queueTargetRunId === "string" ? custom.queueTargetRunId : null;
- const [copied, setCopied] = useState(false);
- const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
- const toastActions = useOptionalToastActions();
- const {
- isCurrentUser,
- authorName: resolvedAuthorName,
- avatarUrl,
- } = resolveIssueChatHumanAuthor({
- authorName,
- authorUserId,
- currentUserId,
- userProfileMap,
- });
- const authorAvatar = (
- <Avatar size="sm" className="shrink-0">
- {avatarUrl ? <AvatarImage src={avatarUrl} alt={resolvedAuthorName} /> : null}
- <AvatarFallback>{initialsForName(resolvedAuthorName)}</AvatarFallback>
- </Avatar>
- );
- const canDeleteComment = Boolean(onDeleteComment && isCurrentUser && !queued && !pending && !deleted);
- const handleDeleteComment = () => {
- if (!canDeleteComment) return;
- setDeleteDialogOpen(true);
- };
- const confirmDeleteComment = () => {
- if (!canDeleteComment) return;
- setDeleteDialogOpen(false);
- void onDeleteComment?.(commentId);
- };
- const messageBody = (
- <div className={cn("flex min-w-0 max-w-[85%] flex-col", isCurrentUser && "items-end")}>
- <div className={cn("mb-1 flex items-center gap-2 px-1", isCurrentUser ? "justify-end" : "justify-start")}>
- <span className="text-sm font-medium text-foreground">{resolvedAuthorName}</span>
- <SourceTrustBadge sourceTrust={sourceTrust} artifactLabel="comment" />
- {followUpRequested ? (
- <Badge variant="outline" className="text-[10px] uppercase tracking-[0.14em]">
- Follow-up
- </Badge>
- ) : null}
- </div>
- <div
- className={cn(
- "min-w-0 max-w-full overflow-hidden break-all rounded-2xl px-4 py-2.5",
- queued
- ? "bg-amber-50/80 dark:bg-amber-500/10"
- : deleted
- ? "bg-muted/50 text-muted-foreground"
- : "bg-muted",
- pending && "opacity-80",
- )}
- >
- {queued ? (
- <div className="mb-1.5 flex items-center gap-2">
- <span className="inline-flex items-center rounded-full border border-amber-400/60 bg-amber-100/70 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-amber-800 dark:border-amber-400/40 dark:bg-amber-500/20 dark:text-amber-200">
- {queueBadgeLabel}
- </span>
- {queueTargetRunId && onInterruptQueued ? (
- <Button
- 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={isInterruptingQueuedRun}
- onClick={() => void onInterruptQueued(queueTargetRunId)}
- >
- {isInterruptingQueuedRun ? "Interrupting..." : "Interrupt"}
- </Button>
- ) : null}
- {onCancelQueued ? (
- <Button
- size="sm"
- variant="outline"
- className="h-6 border-amber-300 px-2 text-[11px] text-amber-900 hover:bg-amber-100/80 hover:text-amber-950 dark:border-amber-500/40 dark:text-amber-100 dark:hover:bg-amber-500/10"
- onClick={() => onCancelQueued(commentId)}
- >
- Cancel
- </Button>
- ) : null}
- </div>
- ) : null}
- {deleted ? (
- <div className="text-sm italic text-muted-foreground">Comment deleted</div>
- ) : (
- <div className="min-w-0 max-w-full space-y-3">
- <IssueChatTextParts message={message} />
- </div>
- )}
- </div>
-
- {pending ? (
- <div className={cn("mt-1 flex px-1 text-[11px] text-muted-foreground", isCurrentUser ? "justify-end" : "justify-start")}>
- Sending...
- </div>
- ) : (
- <div
- className={cn(
- "mt-1 flex items-center gap-1.5 px-1 opacity-0 transition-opacity group-hover:opacity-100",
- isCurrentUser ? "justify-end" : "justify-start",
- )}
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-[11px] text-muted-foreground hover:text-foreground hover:underline"
- >
- {message.createdAt ? commentDateLabel(message.createdAt) : ""}
- </a>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- {message.createdAt ? formatDateTime(message.createdAt) : ""}
- </TooltipContent>
- </Tooltip>
- {!deleted ? (
- <button
- type="button"
- className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
- title="Copy message"
- aria-label="Copy message"
- onClick={() => {
- const text = message.content
- .filter((p): p is { type: "text"; text: string } => p.type === "text")
- .map((p) => p.text)
- .join("\n\n");
- void copyTextToClipboard(text).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy message",
- tone: "error",
- });
- });
- }}
- >
- {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
- </button>
- ) : null}
- {canDeleteComment ? (
- <button
- type="button"
- className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-destructive"
- title="Delete comment"
- aria-label="Delete comment"
- onClick={handleDeleteComment}
- >
- <Trash2 className="h-3.5 w-3.5" />
- </button>
- ) : null}
- </div>
- )}
- </div>
- );
-
- return (
- <>
- <div id={anchorId}>
- <div className={cn("group flex items-start gap-2.5", isCurrentUser && "justify-end")}>
- {isCurrentUser ? (
- <>
- {messageBody}
- {authorAvatar}
- </>
- ) : (
- <>
- {authorAvatar}
- {messageBody}
- </>
- )}
- </div>
- </div>
- <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Delete comment?</DialogTitle>
- <DialogDescription>
- This will replace the comment with a deleted-comment marker.
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
- Cancel
- </Button>
- <Button variant="destructive" onClick={confirmDeleteComment}>
- Delete comment
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
- );
-}
-
-function IssueChatAssistantMessage({
- message,
- activeVote,
- isRunActive,
- isStoppingRun,
-}: {
- message: ThreadMessage;
- activeVote: FeedbackVoteValue | null;
- isRunActive: boolean;
- isStoppingRun: boolean;
-}) {
- const {
- feedbackDataSharingPreference,
- feedbackTermsUrl,
- onVote,
- agentMap,
- onStopRun,
- stopRunLabel = "Stop run",
- stoppingRunLabel = "Stopping...",
- stopRunVariant = "stop",
- runFinalizationActions = [],
- } = useContext(IssueChatCtx);
- const custom = message.metadata.custom as Record<string, unknown>;
- const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
- const authorName = typeof custom.authorName === "string"
- ? custom.authorName
- : typeof custom.runAgentName === "string"
- ? custom.runAgentName
- : "Agent";
- const authorAgentId = typeof custom.authorAgentId === "string" ? custom.authorAgentId : null;
- const runId = typeof custom.runId === "string" ? custom.runId : null;
- const runAgentId = typeof custom.runAgentId === "string" ? custom.runAgentId : null;
- const runStatus = typeof custom.runStatus === "string" ? custom.runStatus : null;
- const agentId = authorAgentId ?? runAgentId;
- const agentIcon = agentId ? agentMap?.get(agentId)?.icon : undefined;
- const commentId = typeof custom.commentId === "string" ? custom.commentId : null;
- const sourceTrust = isSourceTrustMetadata(custom.sourceTrust) ? custom.sourceTrust : null;
- const notices = Array.isArray(custom.notices)
- ? custom.notices.filter((notice): notice is string => typeof notice === "string" && notice.length > 0)
- : [];
- 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 = 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 deleted = Boolean(custom.deletedAt);
- const isFoldable = !isRunning && !!chainOfThoughtLabel;
- const [folded, setFolded] = useState(isFoldable);
- const [prevFoldKey, setPrevFoldKey] = useState({ messageId: message.id, isFoldable });
- const [copied, setCopied] = useState(false);
- const toastActions = useOptionalToastActions();
- const copyText = deleted ? "" : getThreadMessageCopyText(message);
-
- // Derive fold state synchronously during render (not in useEffect) so the
- // browser never paints the un-folded intermediate state — prevents the
- // visible "jump" when loading a page with already-folded work sections.
- if (message.id !== prevFoldKey.messageId || isFoldable !== prevFoldKey.isFoldable) {
- const nextFolded = resolveAssistantMessageFoldedState({
- messageId: message.id,
- currentFolded: folded,
- isFoldable,
- previousMessageId: prevFoldKey.messageId,
- previousIsFoldable: prevFoldKey.isFoldable,
- });
- setPrevFoldKey({ messageId: message.id, isFoldable });
- if (nextFolded !== folded) {
- setFolded(nextFolded);
- }
- }
-
- const handleVote = async (
- vote: FeedbackVoteValue,
- options?: { allowSharing?: boolean; reason?: string },
- ) => {
- if (!commentId || !onVote) return;
- await onVote(commentId, vote, options);
- };
-
- const followUpRequested = custom.followUpRequested === true;
-
- return (
- <div id={anchorId}>
- <div className="flex items-start gap-2.5 py-1.5">
- <Avatar size="sm" className="shrink-0">
- {agentIcon ? (
- <AvatarFallback><AgentIcon icon={agentIcon} className="h-3.5 w-3.5" /></AvatarFallback>
- ) : (
- <AvatarFallback>{initialsForName(authorName)}</AvatarFallback>
- )}
- </Avatar>
-
- <div className="min-w-0 flex-1">
- {isFoldable ? (
- <button
- type="button"
- className="group flex w-full items-center gap-2 py-0.5 text-left"
- onClick={() => setFolded((v) => !v)}
- >
- <span className="text-sm font-medium text-foreground">{authorName}</span>
- <SourceTrustBadge sourceTrust={sourceTrust} artifactLabel="comment" />
- <span className="text-xs text-muted-foreground/60">{chainOfThoughtLabel?.toLowerCase()}</span>
- <span className="ml-auto flex items-center gap-1.5">
- {message.createdAt ? (
- <span className="text-[11px] text-muted-foreground/50">
- {commentDateLabel(message.createdAt)}
- </span>
- ) : null}
- <ChevronDown className={cn("h-3.5 w-3.5 text-muted-foreground/40 transition-transform", !folded && "rotate-180")} />
- </span>
- </button>
- ) : (
- <div className="mb-1.5 flex items-center gap-2">
- <span className="text-sm font-medium text-foreground">{authorName}</span>
- <SourceTrustBadge sourceTrust={sourceTrust} artifactLabel="comment" />
- {followUpRequested ? (
- <Badge variant="outline" className="text-[10px] uppercase tracking-[0.14em]">
- Follow-up
- </Badge>
- ) : null}
- {isRunning ? (
- <span className="inline-flex items-center gap-1 rounded-full border border-cyan-400/40 bg-cyan-500/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-cyan-700 dark:text-cyan-200">
- <Loader2 className="h-3 w-3 animate-spin" />
- Running
- </span>
- ) : null}
- </div>
- )}
-
- {deleted ? (
- <div className="rounded-sm bg-muted/40 px-3 py-2 text-sm italic text-muted-foreground">
- Comment deleted
- </div>
- ) : !folded ? (
- <>
- <div className="space-y-3">
- <IssueChatAssistantParts message={message} hasCoT={hasCoT} />
- {message.content.length === 0 && waitingText ? (
- <div className="flex items-center gap-2.5 rounded-lg px-1 py-2">
- <span className="inline-flex items-center gap-2 text-sm font-medium text-foreground/80">
- {agentIcon ? (
- <AgentIcon icon={agentIcon} className="h-4 w-4 shrink-0" />
- ) : (
- <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />
- )}
- <span className="shimmer-text">{waitingText}</span>
- </span>
- </div>
- ) : null}
- {notices.length > 0 ? (
- <div className="space-y-2">
- {notices.map((notice, index) => (
- <div
- key={`${message.id}:notice:${index}`}
- className="rounded-sm border border-border/60 bg-accent/20 px-3 py-2 text-sm text-muted-foreground"
- >
- {notice}
- </div>
- ))}
- </div>
- ) : null}
- </div>
-
- <div className="mt-2 flex items-center gap-1">
- <button
- type="button"
- className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
- title="Copy message"
- aria-label="Copy message"
- onClick={() => {
- void copyTextToClipboard(copyText).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy message",
- tone: "error",
- });
- });
- }}
- >
- {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
- </button>
- {commentId && onVote ? (
- <IssueChatFeedbackButtons
- activeVote={activeVote}
- sharingPreference={feedbackDataSharingPreference}
- termsUrl={feedbackTermsUrl ?? null}
- onVote={handleVote}
- />
- ) : null}
- <Tooltip>
- <TooltipTrigger asChild>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-[11px] text-muted-foreground hover:text-foreground hover:underline"
- >
- {message.createdAt ? commentDateLabel(message.createdAt) : ""}
- </a>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- {message.createdAt ? formatDateTime(message.createdAt) : ""}
- </TooltipContent>
- </Tooltip>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="icon-xs"
- className="text-muted-foreground hover:text-foreground"
- title="More actions"
- aria-label="More actions"
- >
- <MoreHorizontal className="h-3.5 w-3.5" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- onClick={() => {
- void copyTextToClipboard(copyText).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy message",
- tone: "error",
- });
- });
- }}
- >
- <Copy className="mr-2 h-3.5 w-3.5" />
- Copy message
- </DropdownMenuItem>
- {canStopRun && onStopRun && runId ? (
- <DropdownMenuItem
- disabled={isStoppingRun}
- className={cn(
- stopRunVariant === "pause"
- ? "text-amber-700 focus:text-amber-800 dark:text-amber-300 dark:focus:text-amber-200"
- : "text-red-700 focus:text-red-800 dark:text-red-300 dark:focus:text-red-200",
- )}
- onSelect={() => {
- void onStopRun(runId);
- }}
- >
- {stopRunVariant === "pause" ? (
- <PauseCircle className="mr-2 h-3.5 w-3.5" />
- ) : (
- <Square className="mr-2 h-3.5 w-3.5 fill-current" />
- )}
- {isStoppingRun ? stoppingRunLabel : stopRunLabel}
- </DropdownMenuItem>
- ) : null}
- {canStopRun && runId
- ? runFinalizationActions.map((action) => (
- <DropdownMenuItem
- key={action.id}
- disabled={isStoppingRun || action.isPending || action.disabled}
- className={cn(
- action.id === "cancel"
- ? "text-red-700 focus:text-red-800 dark:text-red-300 dark:focus:text-red-200"
- : "text-green-700 focus:text-green-800 dark:text-green-300 dark:focus:text-green-200",
- )}
- onSelect={() => {
- void action.onSelect(runId);
- }}
- >
- {action.id === "cancel" ? (
- <Square className="mr-2 h-3.5 w-3.5 fill-current" />
- ) : (
- <Check className="mr-2 h-3.5 w-3.5" />
- )}
- {action.isPending ? action.pendingLabel : action.label}
- </DropdownMenuItem>
- ))
- : null}
- {runHref ? (
- <DropdownMenuItem asChild>
- <Link to={runHref} target="_blank" rel="noreferrer noopener">
- <Search className="mr-2 h-3.5 w-3.5" />
- View run
- </Link>
- </DropdownMenuItem>
- ) : null}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </>
- ) : null}
- </div>
- </div>
- </div>
- );
-}
-
-function IssueChatFeedbackButtons({
- activeVote,
- sharingPreference = "prompt",
- termsUrl,
- onVote,
-}: {
- activeVote: FeedbackVoteValue | null;
- sharingPreference: FeedbackDataSharingPreference;
- termsUrl: string | null;
- onVote: (vote: FeedbackVoteValue, options?: { allowSharing?: boolean; reason?: string }) => Promise<void>;
-}) {
- const [isSaving, setIsSaving] = useState(false);
- const [optimisticVote, setOptimisticVote] = useState<FeedbackVoteValue | null>(null);
- const [reasonOpen, setReasonOpen] = useState(false);
- const [downvoteReason, setDownvoteReason] = useState("");
- const [pendingSharingDialog, setPendingSharingDialog] = useState<{
- vote: FeedbackVoteValue;
- reason?: string;
- } | null>(null);
- const visibleVote = optimisticVote ?? activeVote ?? null;
-
- useEffect(() => {
- if (optimisticVote && activeVote === optimisticVote) setOptimisticVote(null);
- }, [activeVote, optimisticVote]);
-
- async function doVote(
- vote: FeedbackVoteValue,
- options?: { allowSharing?: boolean; reason?: string },
- ) {
- setIsSaving(true);
- try {
- await onVote(vote, options);
- } catch {
- setOptimisticVote(null);
- } finally {
- setIsSaving(false);
- }
- }
-
- function handleVote(vote: FeedbackVoteValue, reason?: string) {
- setOptimisticVote(vote);
- if (sharingPreference === "prompt") {
- setPendingSharingDialog({ vote, ...(reason ? { reason } : {}) });
- return;
- }
- const allowSharing = sharingPreference === "allowed";
- void doVote(vote, {
- ...(allowSharing ? { allowSharing: true } : {}),
- ...(reason ? { reason } : {}),
- });
- }
-
- function handleThumbsUp() {
- handleVote("up");
- }
-
- function handleThumbsDown() {
- setOptimisticVote("down");
- setReasonOpen(true);
- // Submit the initial down vote right away
- handleVote("down");
- }
-
- function handleSubmitReason() {
- if (!downvoteReason.trim()) return;
- // Re-submit with reason attached
- if (sharingPreference === "prompt") {
- setPendingSharingDialog({ vote: "down", reason: downvoteReason });
- } else {
- const allowSharing = sharingPreference === "allowed";
- void doVote("down", {
- ...(allowSharing ? { allowSharing: true } : {}),
- reason: downvoteReason,
- });
- }
- setReasonOpen(false);
- setDownvoteReason("");
- }
-
- return (
- <>
- <button
- type="button"
- disabled={isSaving}
- className={cn(
- "inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors",
- visibleVote === "up"
- ? "text-green-600 dark:text-green-400"
- : "text-muted-foreground hover:bg-accent hover:text-foreground",
- )}
- title="Helpful"
- aria-label="Helpful"
- onClick={handleThumbsUp}
- >
- <ThumbsUp className="h-3.5 w-3.5" />
- </button>
- <Popover open={reasonOpen} onOpenChange={setReasonOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- disabled={isSaving}
- className={cn(
- "inline-flex h-7 w-7 items-center justify-center rounded-md transition-colors",
- visibleVote === "down"
- ? "text-amber-600 dark:text-amber-400"
- : "text-muted-foreground hover:bg-accent hover:text-foreground",
- )}
- title="Needs work"
- aria-label="Needs work"
- onClick={handleThumbsDown}
- >
- <ThumbsDown className="h-3.5 w-3.5" />
- </button>
- </PopoverTrigger>
- <PopoverContent side="top" align="start" className="w-80 p-3">
- <div className="mb-2 text-sm font-medium">What could have been better?</div>
- <Textarea
- value={downvoteReason}
- onChange={(event) => setDownvoteReason(event.target.value)}
- placeholder="Add a short note"
- className="min-h-20 resize-y bg-background text-sm"
- disabled={isSaving}
- />
- <div className="mt-2 flex items-center justify-end gap-2">
- <Button
- type="button"
- size="sm"
- variant="outline"
- disabled={isSaving}
- onClick={() => {
- setReasonOpen(false);
- setDownvoteReason("");
- }}
- >
- Dismiss
- </Button>
- <Button
- type="button"
- size="sm"
- disabled={isSaving || !downvoteReason.trim()}
- onClick={handleSubmitReason}
- >
- {isSaving ? "Saving..." : "Save note"}
- </Button>
- </div>
- </PopoverContent>
- </Popover>
-
- <Dialog
- open={Boolean(pendingSharingDialog)}
- onOpenChange={(open) => {
- if (!open && !isSaving) {
- setPendingSharingDialog(null);
- setOptimisticVote(null);
- }
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Save your feedback sharing preference</DialogTitle>
- <DialogDescription>
- Choose whether voted AI outputs can be shared with Paperclip Labs. This
- answer becomes the default for future thumbs up and thumbs down votes.
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-3 text-sm text-muted-foreground">
- <p>This vote is always saved locally.</p>
- <p>
- Choose <span className="font-medium text-foreground">Always allow</span> to share
- this vote and future voted AI outputs. Choose{" "}
- <span className="font-medium text-foreground">Don't allow</span> to keep this vote
- and future votes local.
- </p>
- <p>You can change this later in Instance Settings &gt; General.</p>
- {termsUrl ? (
- <a
- href={termsUrl}
- target="_blank"
- rel="noreferrer"
- className="inline-flex text-sm text-foreground underline underline-offset-4"
- >
- Read our terms of service
- </a>
- ) : null}
- </div>
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- disabled={!pendingSharingDialog || isSaving}
- onClick={() => {
- if (!pendingSharingDialog) return;
- void doVote(
- pendingSharingDialog.vote,
- pendingSharingDialog.reason ? { reason: pendingSharingDialog.reason } : undefined,
- ).then(() => setPendingSharingDialog(null));
- }}
- >
- {isSaving ? "Saving..." : "Don't allow"}
- </Button>
- <Button
- type="button"
- disabled={!pendingSharingDialog || isSaving}
- onClick={() => {
- if (!pendingSharingDialog) return;
- void doVote(pendingSharingDialog.vote, {
- allowSharing: true,
- ...(pendingSharingDialog.reason ? { reason: pendingSharingDialog.reason } : {}),
- }).then(() => setPendingSharingDialog(null));
- }}
- >
- {isSaving ? "Saving..." : "Always allow"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- </>
- );
-}
-
-function ExpiredRequestConfirmationActivity({
- message,
- anchorId,
- interaction,
-}: {
- message: ThreadMessage;
- anchorId?: string;
- interaction: RequestConfirmationInteraction;
-}) {
- const {
- agentMap,
- currentUserId,
- userLabelMap,
- onAcceptInteraction,
- onRejectInteraction,
- onCancelInteraction,
- } = useContext(IssueChatCtx);
- const [expanded, setExpanded] = useState(false);
- const hasResolvedActor = Boolean(interaction.resolvedByAgentId || interaction.resolvedByUserId);
- const actorAgentId = hasResolvedActor
- ? interaction.resolvedByAgentId ?? null
- : interaction.createdByAgentId ?? null;
- const actorUserId = hasResolvedActor
- ? interaction.resolvedByUserId ?? null
- : interaction.createdByUserId ?? null;
- const actorName = formatInteractionActorLabel({
- agentId: actorAgentId,
- userId: actorUserId,
- agentMap,
- currentUserId,
- userLabelMap,
- });
- const actorIcon = actorAgentId ? agentMap?.get(actorAgentId)?.icon : undefined;
- const isCurrentUser = Boolean(actorUserId && currentUserId && actorUserId === currentUserId);
- const detailsId = anchorId ? `${anchorId}-details` : `${interaction.id}-details`;
- const summary = buildIssueThreadInteractionSummary(interaction);
-
- const rowContent = (
- <div className="min-w-0 flex-1">
- <div className={cn("flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs", isCurrentUser && "justify-end")}>
- <span className="font-medium text-foreground">{actorName}</span>
- <span className="text-muted-foreground">updated this task</span>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
- >
- {timeAgo(message.createdAt)}
- </a>
- <button
- type="button"
- className="inline-flex items-center gap-1 rounded-md border border-border/70 bg-background/70 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground transition-colors hover:border-border hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
- aria-expanded={expanded}
- aria-controls={detailsId}
- onClick={() => setExpanded((current) => !current)}
- >
- <ChevronDown className={cn("h-3 w-3 transition-transform", expanded && "rotate-180")} />
- {expanded ? "Hide confirmation" : "Expired confirmation"}
- </button>
- </div>
- {expanded ? (
- <p className={cn("mt-1 text-xs text-muted-foreground", isCurrentUser && "text-right")}>
- {summary}
- </p>
- ) : null}
- </div>
- );
-
- return (
- <div id={anchorId}>
- {isCurrentUser ? (
- <div className="flex items-start justify-end gap-2 py-1">
- {rowContent}
- </div>
- ) : (
- <div className="flex items-start gap-2.5 py-1">
- <Avatar size="sm" className="mt-0.5">
- {actorIcon ? (
- <AvatarFallback><AgentIcon icon={actorIcon} className="h-3.5 w-3.5" /></AvatarFallback>
- ) : (
- <AvatarFallback>{initialsForName(actorName)}</AvatarFallback>
- )}
- </Avatar>
- {rowContent}
- </div>
- )}
- {expanded ? (
- <div id={detailsId} className="mt-2">
- <IssueThreadInteractionCardClassic
- interaction={interaction}
- agentMap={agentMap}
- currentUserId={currentUserId}
- userLabelMap={userLabelMap}
- onAcceptInteraction={onAcceptInteraction}
- onRejectInteraction={onRejectInteraction}
- onCancelInteraction={onCancelInteraction}
- />
- </div>
- ) : null}
- </div>
- );
-}
-
-function isIssueCommentPresentation(value: unknown): value is IssueCommentPresentation {
- if (!value || typeof value !== "object") return false;
- const v = value as Record<string, unknown>;
- return v.kind === "system_notice" || v.kind === "message";
-}
-
-function isIssueCommentMetadata(value: unknown): value is IssueCommentMetadata {
- if (!value || typeof value !== "object") return false;
- const v = value as Record<string, unknown>;
- return v.version === 1 && Array.isArray(v.sections);
-}
-
-function isSourceTrustMetadata(value: unknown): value is SourceTrustMetadata {
- if (!value || typeof value !== "object") return false;
- const v = value as Record<string, unknown>;
- return v.preset === "low_trust_review" && (
- v.disposition === "quarantined" ||
- v.disposition === "promoted"
- );
-}
-
-function issueStatusIsTerminalDisposition(issueStatus: string | undefined) {
- return issueStatus === "done" || issueStatus === "cancelled";
-}
-
-function sourceRunIdFromSuccessfulRunHandoffMetadata(metadata: IssueCommentMetadata | null) {
- if (metadata?.sourceRunId) return metadata.sourceRunId;
- const runLinks = [];
- for (const section of metadata?.sections ?? []) {
- for (const row of section.rows) {
- if (row.type === "run_link") runLinks.push(row.runId);
- }
- }
- return runLinks.length === 1 ? runLinks[0] : null;
-}
-
-function isStaleSuccessfulRunHandoffNotice(input: {
- bodyText: string;
- issueStatus?: string;
- successfulRunHandoff?: SuccessfulRunHandoffState | null;
- runId?: string | null;
- metadata: IssueCommentMetadata | null;
-}) {
- if (!isSuccessfulRunHandoffComment(input.bodyText)) return false;
-
- const currentHandoff = input.successfulRunHandoff ?? null;
- if (currentHandoff?.state === "resolved") return true;
- if (issueStatusIsTerminalDisposition(input.issueStatus)) return true;
-
- const noticeSourceRunId = sourceRunIdFromSuccessfulRunHandoffMetadata(input.metadata) ?? input.runId ?? null;
- if (
- noticeSourceRunId
- && currentHandoff?.sourceRunId
- && noticeSourceRunId !== currentHandoff.sourceRunId
- ) {
- return true;
- }
-
- return false;
-}
-
-function StaleDispositionWarningMetadataRow({ row }: { row: SystemNoticeMetadataRow }) {
- const label = (
- <span className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground">
- {row.label}
- </span>
- );
- const value = (() => {
- switch (row.kind) {
- case "text":
- return <span>{row.value}</span>;
- case "code":
- return (
- <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-foreground/80">
- {row.value}
- </code>
- );
- case "issue": {
- const content = (
- <>
- <span>{row.identifier}</span>
- {row.title ? <span className="text-muted-foreground"> - {row.title}</span> : null}
- </>
- );
- return row.href ? (
- <a href={row.href} className="font-medium text-foreground underline-offset-2 hover:underline">
- {content}
- </a>
- ) : (
- <span className="font-medium text-foreground">{content}</span>
- );
- }
- case "agent":
- return row.href ? (
- <a href={row.href} className="font-medium text-foreground underline-offset-2 hover:underline">
- {row.name}
- </a>
- ) : (
- <span className="font-medium text-foreground">{row.name}</span>
- );
- case "run": {
- const runShort = row.runId.length > 12 ? `${row.runId.slice(0, 8)}...` : row.runId;
- const content = (
- <>
- <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[11px] text-foreground/80">
- {runShort}
- </code>
- {row.status ? <span>{row.status}</span> : null}
- </>
- );
- return row.href ? (
- <a href={row.href} className="inline-flex items-center gap-1.5 underline-offset-2 hover:underline">
- {content}
- </a>
- ) : (
- <span className="inline-flex items-center gap-1.5">{content}</span>
- );
- }
- }
- })();
-
- return (
- <div className="grid grid-cols-[7.5rem_minmax(0,1fr)] gap-2 text-xs leading-5">
- {label}
- <div className="min-w-0 break-words text-foreground/80">{value}</div>
- </div>
- );
-}
-
-function metadataRowKey(row: SystemNoticeMetadataRow) {
- switch (row.kind) {
- case "issue":
- return `issue:${row.label}:${row.identifier}:${row.href ?? ""}:${row.title ?? ""}`;
- case "agent":
- return `agent:${row.label}:${row.name}:${row.href ?? ""}`;
- case "run":
- return `run:${row.label}:${row.runId}:${row.href ?? ""}:${row.status ?? ""}`;
- default:
- return `${row.kind}:${row.label}:${row.value}`;
- }
-}
-
-function metadataSectionKey(section: SystemNoticeMetadataSection) {
- return `${section.title ?? "details"}:${section.rows.map(metadataRowKey).join("|")}`;
-}
-
-function isNullableString(value: unknown): value is string | null {
- return value === null || typeof value === "string";
-}
-
-function isTimelineWorkspace(value: unknown): value is IssueTimelineWorkspace {
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
- const workspace = value as Record<string, unknown>;
- return isNullableString(workspace.label)
- && isNullableString(workspace.projectWorkspaceId)
- && isNullableString(workspace.executionWorkspaceId)
- && isNullableString(workspace.mode);
-}
-
-function isTimelineWorkspaceChange(value: unknown): value is NonNullable<IssueTimelineEvent["workspaceChange"]> {
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
- const change = value as Record<string, unknown>;
- return isTimelineWorkspace(change.from) && isTimelineWorkspace(change.to);
-}
-
-function StaleDispositionWarningDetails({
- sections,
-}: {
- sections: SystemNoticeMetadataSection[];
-}) {
- if (sections.length === 0) {
- return <div className="text-xs leading-5 text-muted-foreground">No additional details.</div>;
- }
-
- return (
- <div className="space-y-3 text-left">
- {sections.map((section) => (
- <div key={metadataSectionKey(section)} className="space-y-1.5">
- {section.title ? (
- <div className="text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground">
- {section.title}
- </div>
- ) : null}
- <div className="space-y-1">
- {section.rows.map((row) => (
- <StaleDispositionWarningMetadataRow key={metadataRowKey(row)} row={row} />
- ))}
- </div>
- </div>
- ))}
- </div>
- );
-}
-
-function StaleDispositionWarningRow({
- anchorId,
- message,
- metadata,
- runAgentId,
-}: {
- anchorId?: string;
- message: ThreadMessage;
- metadata: IssueCommentMetadata | null;
- runAgentId?: string | null;
-}) {
- const [open, setOpen] = useState(false);
- const detailsId = useId();
- const sections = mapCommentMetadataToSystemNoticeSections(metadata, { runAgentId });
-
- return (
- <div id={anchorId} data-testid="stale-disposition-warning">
- <div className="flex items-start gap-2.5 py-1.5">
- <span className="size-6 shrink-0" aria-hidden />
- <div className="min-w-0 flex-1">
- <button
- type="button"
- aria-expanded={open}
- aria-controls={detailsId}
- className="group flex w-full items-center gap-2 py-0.5 text-left"
- onClick={() => setOpen((value) => !value)}
- >
- <span className="text-sm font-medium text-foreground/80">
- Stale disposition warning
- </span>
- <span className="ml-auto flex items-center gap-1.5">
- {message.createdAt ? (
- <span data-testid="stale-disposition-warning-time" className="text-[11px] text-muted-foreground/50">
- {commentDateLabel(message.createdAt)}
- </span>
- ) : null}
- <ChevronDown className={cn("h-3.5 w-3.5 text-muted-foreground/40 transition-transform", open && "rotate-180")} />
- </span>
- </button>
- <div id={detailsId} hidden={!open} className="space-y-1 py-1">
- <StaleDispositionWarningDetails sections={sections} />
- </div>
- </div>
- </div>
- </div>
- );
-}
-
-function SystemNoticeCommentRow({
- message,
- anchorId,
-}: {
- message: ThreadMessage;
- anchorId?: string;
-}) {
- const { onImageClick, agentMap, issueStatus, successfulRunHandoff } = useContext(IssueChatCtx);
- const toastActions = useOptionalToastActions();
- const custom = message.metadata.custom as Record<string, unknown>;
- const presentation = isIssueCommentPresentation(custom.presentation) ? custom.presentation : null;
- const commentMetadata = isIssueCommentMetadata(custom.commentMetadata) ? custom.commentMetadata : null;
- const runAgentId = typeof custom.runAgentId === "string" ? custom.runAgentId : null;
- const runId = typeof custom.runId === "string" ? custom.runId : null;
- const authorType = typeof custom.authorType === "string" ? custom.authorType : null;
- const authorName = typeof custom.authorName === "string" ? custom.authorName : null;
- const bodyText = message.content
- .filter((p): p is { type: "text"; text: string } => p.type === "text")
- .map((p) => p.text)
- .join("\n\n");
- const staleSuccessfulRunHandoffNotice = isStaleSuccessfulRunHandoffNotice({
- bodyText,
- issueStatus,
- successfulRunHandoff,
- runId,
- metadata: commentMetadata,
- });
- const [copied, setCopied] = useState(false);
- const [copiedLink, setCopiedLink] = useState(false);
-
- const source = (() => {
- const runAgentName = runAgentId ? agentMap?.get(runAgentId)?.name ?? null : null;
- if (authorType === "system") {
- const label = runAgentName ?? "Paperclip";
- if (runAgentId && runId) return { label, href: `/agents/${runAgentId}/runs/${runId}` };
- return { label };
- }
- if (runAgentId && runId) {
- return { label: authorName ?? runAgentName ?? "Paperclip", href: `/agents/${runAgentId}/runs/${runId}` };
- }
- if (authorName) return { label: authorName };
- return undefined;
- })();
-
- const props = buildSystemNoticeProps({
- presentation,
- metadata: commentMetadata,
- body: (
- <MarkdownBody className="text-sm leading-6" softBreaks onImageClick={onImageClick}>
- {bodyText}
- </MarkdownBody>
- ),
- timestamp: message.createdAt ? new Date(message.createdAt).toISOString() : undefined,
- source,
- runAgentId,
- });
-
- const handleCopy = () => {
- void copyTextToClipboard(bodyText).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- }).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy system notice",
- tone: "error",
- });
- });
- };
-
- const handleCopyLink = () => {
- if (!anchorId || typeof window === "undefined") return;
- const url = `${window.location.origin}${window.location.pathname}#${anchorId}`;
- void copyTextToClipboard(url).then(() => {
- setCopiedLink(true);
- setTimeout(() => setCopiedLink(false), 2000);
- }).catch((error) => {
- toastActions?.pushToast({
- title: "Copy failed",
- body: error instanceof Error ? error.message : "Unable to copy system notice link",
- tone: "error",
- });
- });
- };
-
- if (staleSuccessfulRunHandoffNotice) {
- return (
- <StaleDispositionWarningRow
- anchorId={anchorId}
- message={message}
- metadata={commentMetadata}
- runAgentId={runAgentId}
- />
- );
- }
-
- return (
- <div id={anchorId} className="group">
- <div className="py-1">
- <SystemNotice {...props} />
- <div className="mt-1 flex items-center justify-end gap-1.5 px-1 opacity-0 transition-opacity group-hover:opacity-100">
- <Tooltip>
- <TooltipTrigger asChild>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-[11px] text-muted-foreground hover:text-foreground hover:underline"
- >
- {message.createdAt ? commentDateLabel(message.createdAt) : ""}
- </a>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- {message.createdAt ? formatDateTime(message.createdAt) : ""}
- </TooltipContent>
- </Tooltip>
- {anchorId ? (
- <button
- type="button"
- className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
- title="Copy link"
- aria-label="Copy link to system notice"
- onClick={handleCopyLink}
- >
- {copiedLink ? <Check className="h-3.5 w-3.5" /> : <Paperclip className="h-3.5 w-3.5" />}
- </button>
- ) : null}
- <button
- type="button"
- className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
- title="Copy notice text"
- aria-label="Copy system notice"
- onClick={handleCopy}
- >
- {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
- </button>
- </div>
- </div>
- </div>
- );
-}
-
-function IssueChatSystemMessage({ message }: { message: ThreadMessage }) {
- const {
- agentMap,
- currentUserId,
- userLabelMap,
- onAcceptInteraction,
- onRejectInteraction,
- onSubmitInteractionAnswers,
- onCancelInteraction,
- } = useContext(IssueChatCtx);
- const custom = message.metadata.custom as Record<string, unknown>;
- const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
- const runId = typeof custom.runId === "string" ? custom.runId : null;
- const runAgentId = typeof custom.runAgentId === "string" ? custom.runAgentId : null;
- const runAgentName = typeof custom.runAgentName === "string" ? custom.runAgentName : null;
- const runStatus = typeof custom.runStatus === "string" ? custom.runStatus : null;
- const actorName = typeof custom.actorName === "string" ? custom.actorName : null;
- const actorType = typeof custom.actorType === "string" ? custom.actorType : null;
- const actorId = typeof custom.actorId === "string" ? custom.actorId : null;
- const statusChange = typeof custom.statusChange === "object" && custom.statusChange
- ? custom.statusChange as { from: string | null; to: string | null }
- : null;
- const assigneeChange = typeof custom.assigneeChange === "object" && custom.assigneeChange
- ? custom.assigneeChange as {
- from: IssueTimelineAssignee;
- to: IssueTimelineAssignee;
- }
- : null;
- const workspaceChange = isTimelineWorkspaceChange(custom.workspaceChange) ? custom.workspaceChange : null;
- const interaction = isIssueThreadInteraction(custom.interaction)
- ? custom.interaction
- : null;
-
- if (custom.kind === "system_notice") {
- return (
- <SystemNoticeCommentRow
- message={message}
- anchorId={anchorId}
- />
- );
- }
-
- if (custom.kind === "interaction" && interaction) {
- if (interaction.kind === "request_confirmation" && interaction.status === "expired") {
- return (
- <ExpiredRequestConfirmationActivity
- message={message}
- anchorId={anchorId}
- interaction={interaction}
- />
- );
- }
-
- return (
- <div id={anchorId}>
- <div className="py-1.5">
- <IssueThreadInteractionCardClassic
- interaction={interaction}
- agentMap={agentMap}
- currentUserId={currentUserId}
- userLabelMap={userLabelMap}
- onAcceptInteraction={onAcceptInteraction}
- onRejectInteraction={onRejectInteraction}
- onSubmitInteractionAnswers={onSubmitInteractionAnswers}
- onCancelInteraction={onCancelInteraction}
- />
- </div>
- </div>
- );
- }
-
- if (custom.kind === "event" && actorName) {
- const isCurrentUser = actorType === "user" && !!currentUserId && actorId === currentUserId;
- const isAgent = actorType === "agent";
- const agentIcon = isAgent && actorId ? agentMap?.get(actorId)?.icon : undefined;
-
- const eventContent = (
- <div className="min-w-0 space-y-1">
- <div className={cn("flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5 text-xs", isCurrentUser && "justify-end")}>
- <span className="font-medium text-foreground">{actorName}</span>
- <span className="text-muted-foreground">
- {custom.followUpRequested === true ? "requested follow-up" : "updated this task"}
- </span>
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
- >
- {timeAgo(message.createdAt)}
- </a>
- </div>
-
- {statusChange ? (
- <div className={cn("flex flex-wrap items-center gap-1.5 text-xs", isCurrentUser && "justify-end")}>
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- Status
- </span>
- <span className="text-muted-foreground">{humanizeValue(statusChange.from)}</span>
- <ArrowRight className="h-3 w-3 text-muted-foreground" />
- <span className="font-medium text-foreground">{humanizeValue(statusChange.to)}</span>
- </div>
- ) : null}
-
- {assigneeChange ? (
- <div className={cn("flex flex-wrap items-center gap-1.5 text-xs", isCurrentUser && "justify-end")}>
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- Assignee
- </span>
- <span className="text-muted-foreground">
- {formatTimelineAssigneeLabel(assigneeChange.from, agentMap, currentUserId, userLabelMap)}
- </span>
- <ArrowRight className="h-3 w-3 text-muted-foreground" />
- <span className="font-medium text-foreground">
- {formatTimelineAssigneeLabel(assigneeChange.to, agentMap, currentUserId, userLabelMap)}
- </span>
- </div>
- ) : null}
-
- {workspaceChange ? (
- <div className={cn("flex flex-wrap items-center gap-1.5 text-xs", isCurrentUser && "justify-end")}>
- <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
- Workspace
- </span>
- <span className="text-muted-foreground">
- {formatTimelineWorkspaceLabel(workspaceChange.from)}
- </span>
- <ArrowRight className="h-3 w-3 text-muted-foreground" />
- <span className="font-medium text-foreground">
- {formatTimelineWorkspaceLabel(workspaceChange.to)}
- </span>
- </div>
- ) : null}
- </div>
- );
-
- if (isCurrentUser) {
- return (
- <div id={anchorId}>
- <div className="flex items-start justify-end gap-2 py-1">
- {eventContent}
- </div>
- </div>
- );
- }
-
- return (
- <div id={anchorId}>
- <div className="flex items-start gap-2.5 py-1">
- <Avatar size="sm" className="mt-0.5">
- {agentIcon ? (
- <AvatarFallback><AgentIcon icon={agentIcon} className="h-3.5 w-3.5" /></AvatarFallback>
- ) : (
- <AvatarFallback>{initialsForName(actorName)}</AvatarFallback>
- )}
- </Avatar>
- <div className="flex-1">
- {eventContent}
- </div>
- </div>
- </div>
- );
- }
-
- const displayedRunAgentName = runAgentName ?? (runAgentId ? agentMap?.get(runAgentId)?.name ?? runAgentId.slice(0, 8) : null);
- const runAgentIcon = runAgentId ? agentMap?.get(runAgentId)?.icon : undefined;
- if (custom.kind === "run" && runId && runAgentId && displayedRunAgentName && runStatus) {
- return (
- <div id={anchorId}>
- <div className="flex items-center gap-2.5 py-1">
- <Avatar size="sm">
- {runAgentIcon ? (
- <AvatarFallback><AgentIcon icon={runAgentIcon} className="h-3.5 w-3.5" /></AvatarFallback>
- ) : (
- <AvatarFallback>{initialsForName(displayedRunAgentName)}</AvatarFallback>
- )}
- </Avatar>
-
- <div className="min-w-0 flex-1">
- <div className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs">
- <Link to={`/agents/${runAgentId}`} className="font-medium text-foreground transition-colors hover:underline">
- {displayedRunAgentName}
- </Link>
- <span className="text-muted-foreground">run</span>
- <Link
- to={`/agents/${runAgentId}/runs/${runId}`}
- className="inline-flex items-center rounded-md border border-border bg-accent/40 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground"
- >
- {runId.slice(0, 8)}
- </Link>
- <RunStatusBadge
- status={runStatus}
- operatorInterrupted={custom.runOperatorInterrupted === true}
- />
- <a
- href={anchorId ? `#${anchorId}` : undefined}
- className="text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline"
- >
- {timeAgo(message.createdAt)}
- </a>
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- 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);
-}
-
-function issueChatMessageIsDeleted(message: ThreadMessage): boolean {
- const custom = issueChatMessageCustom(message);
- return Boolean(custom.deletedAt);
-}
-
-function issueChatMessageDeletedAt(message: ThreadMessage): string | null {
- const custom = issueChatMessageCustom(message);
- return typeof custom.deletedAt === "string" ? custom.deletedAt : null;
-}
-
-// 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;
-}
-
-function IssueChatDeletedComment({
- message,
- deletedAt,
-}: {
- message: ThreadMessage;
- deletedAt: string;
-}) {
- const custom = issueChatMessageCustom(message);
- const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
- const authorName = typeof custom.authorName === "string" ? custom.authorName : "Comment";
- const deletedDate = new Date(deletedAt);
- const deletedDateLabel = Number.isNaN(deletedDate.getTime()) ? "" : formatDateTime(deletedDate);
-
- return (
- <div id={anchorId} className="flex items-start gap-2.5 py-1.5">
- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border bg-muted/40 text-muted-foreground">
- <Trash2 className="h-3.5 w-3.5" />
- </div>
- <div className="min-w-0 rounded-md border border-dashed border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
- <span className="font-medium text-foreground/80">{authorName}</span>
- <span> deleted this comment</span>
- {deletedDateLabel ? <span className="text-xs"> · {deletedDateLabel}</span> : null}
- </div>
- </div>
- );
-}
-
-const IssueChatMessageRow = memo(function IssueChatMessageRow({
- message,
- feedbackVoteByTargetId,
- activeRunIds,
- stoppingRunId,
- interruptingQueuedRunId,
-}: IssueChatMessageRowProps) {
- const kind = issueChatMessageKind(message);
- const deletedAt = issueChatMessageDeletedAt(message);
- const activeVote = issueChatMessageActiveVote(message, feedbackVoteByTargetId);
- const isRunActive = issueChatMessageRunIsActive(message, activeRunIds);
- const isStoppingRun = issueChatMessageRunIsStopping(message, stoppingRunId);
- const isInterruptingQueuedRun = issueChatMessageQueuedRunIsInterrupting(message, interruptingQueuedRunId);
- const renderedMessage = deletedAt
- ? <IssueChatDeletedComment message={message} deletedAt={deletedAt} />
- : 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,
- draftKey,
- enableReassign = false,
- reassignOptions = [],
- currentAssigneeValue = "",
- suggestedAssigneeValue,
- mentions = [],
- agentMap,
- composerDisabledReason = null,
- composerHint = null,
- issueStatus,
- issueWorkMode,
- onWorkModeChange,
-}, forwardedRef) {
- const api = useAui();
- const toastActions = useOptionalToastActions();
- const [body, setBody] = useState("");
- const [submitting, setSubmitting] = useState(false);
- const [attaching, setAttaching] = useState(false);
- const [isDragOver, setIsDragOver] = useState(false);
- const [composerAttachments, setComposerAttachments] = useState<ComposerAttachmentItem[]>([]);
- const dragDepthRef = useRef(0);
- const effectiveSuggestedAssigneeValue = suggestedAssigneeValue ?? currentAssigneeValue;
- const [reassignTarget, setReassignTarget] = useState(effectiveSuggestedAssigneeValue);
- const [unassignedConfirmed, setUnassignedConfirmed] = useState(false);
- const resolvedIssueWorkMode: IssueWorkMode = issueWorkMode ?? "standard";
- const [pendingWorkMode, setPendingWorkMode] = useState<IssueWorkMode>(resolvedIssueWorkMode);
- const [workModeMenuOpen, setWorkModeMenuOpen] = useState(false);
- const canToggleWorkMode = typeof onWorkModeChange === "function";
- const attachInputRef = useRef<HTMLInputElement | null>(null);
- const editorRef = useRef<MarkdownEditorRef>(null);
- const composerContainerRef = useRef<HTMLDivElement | null>(null);
- const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
- const canAcceptFiles = Boolean(onImageUpload || onAttachImage);
-
- function queueViewportRestore(snapshot: ReturnType<typeof captureComposerViewportSnapshot>) {
- if (!snapshot) return;
- requestAnimationFrame(() => {
- restoreComposerViewportSnapshot(snapshot, composerContainerRef.current);
- });
- }
-
- function focusComposer() {
- if (typeof composerContainerRef.current?.scrollIntoView === "function") {
- composerContainerRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
- }
- requestAnimationFrame(() => {
- window.scrollBy({ top: COMPOSER_FOCUS_SCROLL_PADDING_PX, behavior: "smooth" });
- editorRef.current?.focus();
- });
- }
-
- useEffect(() => {
- if (!draftKey) return;
- setBody(loadDraft(draftKey));
- }, [draftKey]);
-
- useEffect(() => {
- if (!draftKey) return;
- if (draftTimer.current) clearTimeout(draftTimer.current);
- draftTimer.current = setTimeout(() => {
- saveDraft(draftKey, body);
- }, DRAFT_DEBOUNCE_MS);
- }, [body, draftKey]);
-
- useEffect(() => {
- return () => {
- if (draftTimer.current) clearTimeout(draftTimer.current);
- };
- }, []);
-
- useEffect(() => {
- setReassignTarget(effectiveSuggestedAssigneeValue);
- }, [effectiveSuggestedAssigneeValue]);
-
- useEffect(() => {
- setUnassignedConfirmed(false);
- }, [reassignTarget]);
-
- useEffect(() => {
- setPendingWorkMode(resolvedIssueWorkMode);
- }, [resolvedIssueWorkMode]);
-
- useImperativeHandle(forwardedRef, () => ({
- focus: focusComposer,
- restoreDraft: (submittedBody: string) => {
- setBody((current) =>
- restoreSubmittedCommentDraft({
- currentBody: current,
- submittedBody,
- }),
- );
- focusComposer();
- },
- }), []);
-
- async function handleSubmit() {
- 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(
- issueStatus,
- hasReassignment ? reassignTarget : currentAssigneeValue,
- ) ? true : undefined;
- const submittedBody = trimmed;
- const viewportSnapshot = captureComposerViewportSnapshot(composerContainerRef.current);
-
- const workModeChanged = pendingWorkMode !== resolvedIssueWorkMode;
- setSubmitting(true);
- setBody("");
- setUnassignedConfirmed(false);
- try {
- if (workModeChanged && onWorkModeChange) {
- await onWorkModeChange(pendingWorkMode);
- }
- const appendPromise = api.thread().append({
- role: "user",
- content: [{ type: "text", text: submittedBody }],
- metadata: { custom: {} },
- attachments: [],
- runConfig: {
- custom: {
- ...(reopen ? { reopen: true } : {}),
- ...(reassignment ? { reassignment } : {}),
- },
- },
- });
- queueViewportRestore(viewportSnapshot);
- await appendPromise;
- if (draftKey) clearDraft(draftKey);
- setComposerAttachments([]);
- setReassignTarget(effectiveSuggestedAssigneeValue);
- } catch {
- setBody((current) =>
- restoreSubmittedCommentDraft({
- currentBody: current,
- submittedBody,
- }),
- );
- } finally {
- setSubmitting(false);
- queueViewportRestore(viewportSnapshot);
- }
- }
-
- async function attachFile(file: File) {
- const attachmentId = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;
- const inline = Boolean(onImageUpload && file.type.startsWith("image/"));
- setComposerAttachments((prev) => [
- ...prev,
- {
- id: attachmentId,
- name: file.name,
- size: file.size,
- status: "uploading",
- inline,
- },
- ]);
-
- try {
- if (onImageUpload && file.type.startsWith("image/")) {
- const url = await onImageUpload(file);
- const safeName = file.name.replace(/[[\]]/g, "\\$&");
- const markdown = `![${safeName}](${url})`;
- setBody((prev) => prev ? `${prev}\n\n${markdown}` : markdown);
- setComposerAttachments((prev) => prev.map((item) =>
- item.id === attachmentId
- ? { ...item, status: "attached", contentPath: url }
- : item,
- ));
- } else if (onAttachImage) {
- const attachment = await onAttachImage(file);
- setComposerAttachments((prev) => prev.map((item) =>
- item.id === attachmentId
- ? {
- ...item,
- status: "attached",
- contentPath: attachment?.contentPath,
- name: attachment?.originalFilename ?? item.name,
- }
- : item,
- ));
- } else {
- setComposerAttachments((prev) => prev.map((item) =>
- item.id === attachmentId
- ? { ...item, status: "error", error: "This file type cannot be attached here" }
- : item,
- ));
- }
- } catch (err) {
- setComposerAttachments((prev) => prev.map((item) =>
- item.id === attachmentId
- ? {
- ...item,
- status: "error",
- error: err instanceof Error ? err.message : "Upload failed",
- }
- : item,
- ));
- }
- }
-
- async function handleAttachFile(evt: ChangeEvent<HTMLInputElement>) {
- const file = evt.target.files?.[0];
- if (!file) return;
- setAttaching(true);
- try {
- await attachFile(file);
- } finally {
- setAttaching(false);
- if (attachInputRef.current) attachInputRef.current.value = "";
- }
- }
-
- async function handleDroppedFiles(files: FileList | null | undefined) {
- if (!files || files.length === 0) return;
- setAttaching(true);
- try {
- for (const file of Array.from(files)) {
- await attachFile(file);
- }
- } finally {
- setAttaching(false);
- }
- }
-
- function resetDragState() {
- dragDepthRef.current = 0;
- setIsDragOver(false);
- }
-
- function handleFileDragEnter(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- evt.stopPropagation();
- dragDepthRef.current += 1;
- setIsDragOver(true);
- }
-
- function handleFileDragOver(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- evt.stopPropagation();
- evt.dataTransfer.dropEffect = "copy";
- }
-
- function handleFileDragLeave(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- evt.stopPropagation();
- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
- if (dragDepthRef.current === 0) setIsDragOver(false);
- }
-
- function handleFileDrop(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- evt.stopPropagation();
- resetDragState();
- void handleDroppedFiles(evt.dataTransfer?.files);
- }
-
- const canSubmit = !submitting && !!body.trim();
-
- if (composerDisabledReason) {
- return (
- <div className="rounded-md border border-amber-300/70 bg-amber-50/80 px-3 py-2 text-sm text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100">
- {composerDisabledReason}
- </div>
- );
- }
-
- const workModeOptions = workModeMetaList(false);
- const pendingWorkModeMeta = workModeMetaFor(pendingWorkMode, false);
- const PendingWorkModeIcon = pendingWorkModeMeta.icon;
-
- function handleComposerKeyDown(evt: ReactKeyboardEvent<HTMLDivElement>) {
- // Match the period via both `code` and `key`: iOS Safari with a hardware
- // keyboard often leaves `code` empty for cmd-period, so relying on it alone
- // lets the event fall through and triggers Safari's default cancel/dismiss
- // (which closes the view). Catching `key === "."` keeps the shortcut working
- // on iOS while preserving desktop behavior.
- const isPeriod = evt.code === "Period" || evt.key === ".";
- if (!(evt.metaKey || evt.ctrlKey) || !isPeriod) return;
- evt.preventDefault();
- setPendingWorkMode((current) => nextWorkMode(current, false));
- }
-
- return (
- <div
- ref={composerContainerRef}
- data-testid="issue-chat-composer"
- data-pending-work-mode={pendingWorkMode}
- className={cn(
- "relative rounded-md border border-border/70 bg-background/95 p-[15px] shadow-[0_-12px_28px_rgba(15,23,42,0.08)] backdrop-blur transition-[border-color,background-color,box-shadow] duration-150 supports-[backdrop-filter]:bg-background/85 dark:shadow-[0_-12px_28px_rgba(0,0,0,0.28)]",
- pendingWorkModeMeta.classes.container,
- isDragOver && "border-primary/45 bg-background shadow-[0_-12px_28px_rgba(15,23,42,0.08),0_0_0_1px_hsl(var(--primary)/0.16)]",
- )}
- onKeyDownCapture={handleComposerKeyDown}
- onDragEnterCapture={handleFileDragEnter}
- onDragOverCapture={handleFileDragOver}
- onDragLeaveCapture={handleFileDragLeave}
- onDropCapture={handleFileDrop}
- >
- {isDragOver && canAcceptFiles ? (
- <div
- data-testid="issue-chat-composer-drop-overlay"
- className="pointer-events-none absolute inset-2 z-30 flex items-center justify-center rounded-sm border border-dashed border-primary/55 bg-background/75 px-4 py-3 text-center shadow-sm backdrop-blur-[2px] dark:bg-background/65"
- >
- <div className="flex max-w-md items-center gap-3 rounded-md bg-background/80 px-3 py-2 text-left shadow-sm ring-1 ring-border/60">
- <span className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
- <Paperclip className="h-4 w-4" />
- </span>
- <div className="min-w-0">
- <div className="text-sm font-medium text-foreground">Drop to upload</div>
- <div className="mt-0.5 text-xs leading-5 text-muted-foreground">
- Images insert into the reply. Other files are added to this task.
- </div>
- </div>
- </div>
- </div>
- ) : null}
-
- <MarkdownEditor
- ref={editorRef}
- value={body}
- onChange={setBody}
- placeholder="Reply"
- mentions={mentions}
- onSubmit={handleSubmit}
- imageUploadHandler={onImageUpload}
- fileDropTarget="parent"
- bordered={false}
- contentClassName="max-h-[28dvh] overflow-y-auto pr-1 pb-2 text-sm scrollbar-auto-hide"
- />
-
- {composerHint ? (
- <div className="inline-flex items-center rounded-full border border-border/70 bg-muted/30 px-2 py-1 text-[11px] text-muted-foreground">
- {composerHint}
- </div>
- ) : null}
-
- {composerAttachments.length > 0 ? (
- <div
- data-testid="issue-chat-composer-attachments"
- className="mb-3 mt-2 space-y-1.5 rounded-md border border-dashed border-border/80 bg-muted/20 p-2"
- >
- {composerAttachments.map((attachment) => {
- const sizeLabel = formatAttachmentSize(attachment.size);
- const statusLabel =
- attachment.status === "uploading"
- ? "Uploading to task"
- : attachment.status === "error"
- ? attachment.error ?? "Upload failed"
- : attachment.inline
- ? "Inserted inline"
- : "Attached to task";
- return (
- <div
- key={attachment.id}
- className={cn(
- "flex min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-xs",
- attachment.status === "error"
- ? "bg-destructive/10 text-destructive"
- : "bg-background/70 text-muted-foreground",
- )}
- >
- {attachment.status === "uploading" ? (
- <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
- ) : attachment.status === "attached" ? (
- <Check className="h-3.5 w-3.5 shrink-0 text-green-600 dark:text-green-400" />
- ) : (
- <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
- )}
- <span className="min-w-0 flex-1 truncate font-medium text-foreground">
- {attachment.name}
- </span>
- {sizeLabel ? (
- <span className="shrink-0 text-muted-foreground">{sizeLabel}</span>
- ) : null}
- <span className="shrink-0 text-muted-foreground">{statusLabel}</span>
- </div>
- );
- })}
- </div>
- ) : null}
-
- <div className="flex flex-wrap items-center justify-end gap-3">
- <div className="mr-auto flex items-center gap-2">
- {(onImageUpload || onAttachImage) ? (
- <>
- <input
- ref={attachInputRef}
- type="file"
- className="hidden"
- onChange={handleAttachFile}
- />
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => attachInputRef.current?.click()}
- disabled={attaching}
- title="Attach file"
- >
- <Paperclip className="h-4 w-4" />
- </Button>
- </>
- ) : null}
- {canToggleWorkMode ? (
- <Popover open={workModeMenuOpen} onOpenChange={setWorkModeMenuOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- data-testid="issue-chat-composer-work-mode-toggle"
- data-pending-work-mode={pendingWorkMode}
- aria-haspopup="menu"
- aria-expanded={workModeMenuOpen}
- aria-pressed={pendingWorkMode !== "standard"}
- aria-keyshortcuts="Meta+Period Control+Period"
- title={titleForPendingWorkMode(pendingWorkMode, false)}
- className={cn(
- "inline-flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs transition-colors",
- pendingWorkModeMeta.classes.chip,
- )}
- >
- <PendingWorkModeIcon className="h-3.5 w-3.5" aria-hidden />
- <span>{pendingWorkModeMeta.label}</span>
- <ChevronDown className="h-3 w-3 opacity-60" aria-hidden />
- </button>
- </PopoverTrigger>
- <PopoverContent
- className="w-44 p-1"
- align="start"
- data-testid="issue-chat-composer-work-mode-menu"
- >
- {workModeOptions.map((option) => {
- const Icon = option.icon;
- const active = option.value === pendingWorkMode;
- return (
- <button
- key={option.value}
- type="button"
- data-testid={`issue-chat-composer-work-mode-menu-${option.value}`}
- data-pending-work-mode={pendingWorkMode}
- className={cn(
- "flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/50",
- active && "bg-accent",
- option.classes.menuItem,
- )}
- onClick={() => {
- setPendingWorkMode(option.value);
- setWorkModeMenuOpen(false);
- }}
- >
- <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />
- <span>{option.label}</span>
- {active ? <Check className="h-3.5 w-3.5 shrink-0" aria-hidden /> : null}
- </button>
- );
- })}
- <div className="mt-1 border-t px-2 py-1.5 text-[10px] text-muted-foreground">
- Cmd/Ctrl+. cycles modes
- </div>
- </PopoverContent>
- </Popover>
- ) : null}
- </div>
-
- {enableReassign && reassignOptions.length > 0 ? (
- <InlineEntitySelector
- value={reassignTarget}
- options={reassignOptions}
- placeholder="Assignee"
- noneLabel="No assignee"
- searchPlaceholder="Search assignees..."
- emptyMessage="No assignees found."
- onChange={setReassignTarget}
- className="h-8 text-xs"
- renderTriggerValue={(option) => {
- if (!option) return <span className="text-muted-foreground">Assignee</span>;
- const agentId = option.id.startsWith("agent:") ? option.id.slice("agent:".length) : null;
- const agent = agentId ? agentMap?.get(agentId) : null;
- return (
- <>
- {agent ? (
- <AgentIcon icon={agent.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- ) : null}
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- renderOption={(option) => {
- if (!option.id) return <span className="truncate">{option.label}</span>;
- const agentId = option.id.startsWith("agent:") ? option.id.slice("agent:".length) : null;
- const agent = agentId ? agentMap?.get(agentId) : null;
- return (
- <>
- {agent ? (
- <AgentIcon icon={agent.icon} className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- ) : null}
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- />
- ) : null}
-
- <Button size="sm" disabled={!canSubmit} onClick={() => void handleSubmit()}>
- {submitting ? "Posting..." : "Send"}
- </Button>
- </div>
- </div>
- );
-});
-
-export function IssueChatThreadClassic({
- comments,
- interactions = [],
- feedbackVotes = [],
- feedbackDataSharingPreference = "prompt",
- feedbackTermsUrl = null,
- linkedRuns = [],
- timelineEvents = [],
- liveRuns = [],
- activeRun = null,
- issueId = null,
- blockedBy = [],
- blockerAttention = null,
- successfulRunHandoff = null,
- scheduledRetry = null,
- recoveryAction = null,
- onResolveRecoveryAction,
- canFalsePositiveRecoveryAction = false,
- legacyRecoverySourceIssue = null,
- companyId,
- projectId,
- issueStatus,
- agentMap,
- currentUserId,
- userLabelMap,
- userProfileMap,
- onVote,
- onAdd,
- onCancelRun,
- onStopRun,
- stopRunLabel,
- stoppingRunLabel,
- stopRunVariant,
- runFinalizationActions,
- imageUploadHandler,
- onAttachImage,
- draftKey,
- enableReassign = false,
- reassignOptions = [],
- currentAssigneeValue = "",
- suggestedAssigneeValue,
- mentions = [],
- composerDisabledReason = null,
- composerHint = null,
- showComposer = true,
- showJumpToLatest,
- emptyMessage,
- footer,
- variant = "full",
- enableLiveTranscriptPolling = true,
- transcriptsByRunId,
- hasOutputForRun: hasOutputForRunOverride,
- includeSucceededRunsWithoutOutput = false,
- onInterruptQueued,
- onCancelQueued,
- onDeleteComment,
- interruptingQueuedRunId = null,
- stoppingRunId = null,
- onImageClick,
- onAcceptInteraction,
- onRejectInteraction,
- onSubmitInteractionAnswers,
- onCancelInteraction,
- composerRef,
- issueWorkMode,
- onWorkModeChange,
- onRefreshLatestComments,
- assigneeUserId = null,
- onResumeFromBacklog,
- resumeFromBacklogPending = false,
-}: IssueChatThreadProps) {
- const location = useLocation();
- 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);
- const preserveComposerViewportRef = useRef(false);
- const pendingSubmitScrollRef = useRef(false);
- const lastUserMessageIdRef = useRef<string | null>(null);
- const spacerBaselineAnchorRef = useRef<string | null>(null);
- const spacerInitialReserveRef = useRef(0);
- const latestSettleTimeoutsRef = useRef<number[]>([]);
- const latestSettleCleanupRef = useRef<(() => void) | null>(null);
- const [bottomSpacerHeight, setBottomSpacerHeight] = useState(0);
- const displayLiveRuns = useMemo(() => {
- const deduped = new Map<string, LiveRunForIssue>();
- for (const run of liveRuns) {
- deduped.set(run.id, run);
- }
- if (activeRun) {
- deduped.set(activeRun.id, {
- id: activeRun.id,
- status: activeRun.status,
- invocationSource: activeRun.invocationSource,
- triggerDetail: activeRun.triggerDetail,
- startedAt: toIsoString(activeRun.startedAt),
- finishedAt: toIsoString(activeRun.finishedAt),
- createdAt: toIsoString(activeRun.createdAt) ?? new Date().toISOString(),
- agentId: activeRun.agentId,
- agentName: activeRun.agentName,
- adapterType: activeRun.adapterType,
- logBytes: activeRun.logBytes,
- lastOutputBytes: activeRun.lastOutputBytes,
- });
- }
- return [...deduped.values()].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
- }, [activeRun, liveRuns]);
- const transcriptRuns = useMemo(() => {
- return resolveIssueChatTranscriptRuns({
- linkedRuns,
- liveRuns: displayLiveRuns,
- activeRun,
- });
- }, [activeRun, displayLiveRuns, linkedRuns]);
- const activeRunIds = useMemo(() => {
- const ids = new Set<string>();
- for (const run of displayLiveRuns) {
- if (run.status === "queued" || run.status === "running") {
- ids.add(run.id);
- }
- }
- return ids;
- }, [displayLiveRuns]);
- const clearLatestSettleTimeouts = useCallback(() => {
- for (const timeout of latestSettleTimeoutsRef.current) {
- window.clearTimeout(timeout);
- }
- latestSettleTimeoutsRef.current = [];
- latestSettleCleanupRef.current?.();
- latestSettleCleanupRef.current = null;
- }, []);
-
- useEffect(() => clearLatestSettleTimeouts, [clearLatestSettleTimeouts]);
-
- const { transcriptByRun, hasOutputForRun } = useLiveRunTranscripts({
- runs: enableLiveTranscriptPolling ? transcriptRuns : [],
- companyId,
- });
- const resolvedTranscriptByRun = transcriptsByRunId ?? transcriptByRun;
- const resolvedHasOutputForRun = hasOutputForRunOverride ?? hasOutputForRun;
- const rawMessages = useMemo(
- () =>
- buildIssueChatMessages({
- comments,
- interactions,
- timelineEvents,
- linkedRuns,
- liveRuns,
- activeRun,
- transcriptsByRunId: resolvedTranscriptByRun,
- hasOutputForRun: resolvedHasOutputForRun,
- includeSucceededRunsWithoutOutput,
- companyId,
- projectId,
- agentMap,
- currentUserId,
- userLabelMap,
- }),
- [
- comments,
- interactions,
- timelineEvents,
- linkedRuns,
- liveRuns,
- activeRun,
- resolvedTranscriptByRun,
- resolvedHasOutputForRun,
- includeSucceededRunsWithoutOutput,
- companyId,
- projectId,
- agentMap,
- currentUserId,
- userLabelMap,
- ],
- );
- const stableMessagesRef = useRef<readonly ThreadMessage[]>([]);
- const stableMessageCacheRef = useRef<Map<string, StableThreadMessageCacheEntry>>(new Map());
- const messages = useMemo(() => {
- const stabilized = stabilizeThreadMessages(
- rawMessages,
- stableMessagesRef.current,
- stableMessageCacheRef.current,
- );
- stableMessagesRef.current = stabilized.messages;
- stableMessageCacheRef.current = stabilized.cache;
- return stabilized.messages;
- }, [rawMessages]);
- const latestMessagesRef = useRef<readonly ThreadMessage[]>(messages);
- latestMessagesRef.current = messages;
-
- const isRunning = displayLiveRuns.some((run) => run.status === "queued" || run.status === "running");
- const unresolvedBlockers = useMemo(
- () => blockedBy.filter((blocker) => blocker.status !== "done" && blocker.status !== "cancelled"),
- [blockedBy],
- );
- const assignedAgent = useMemo(() => {
- if (!currentAssigneeValue.startsWith("agent:")) return null;
- const assigneeAgentId = currentAssigneeValue.slice("agent:".length);
- return agentMap?.get(assigneeAgentId) ?? null;
- }, [agentMap, currentAssigneeValue]);
- const feedbackVoteByTargetId = useMemo(() => {
- const map = new Map<string, FeedbackVoteValue>();
- for (const feedbackVote of feedbackVotes) {
- if (feedbackVote.targetType !== "issue_comment") continue;
- map.set(feedbackVote.targetId, feedbackVote.vote);
- }
- 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 },
- messageSnapshot: readonly ThreadMessage[] = messages,
- ) {
- const snapshotUsesVirtualizer = messageSnapshot.length >= VIRTUALIZED_THREAD_ROW_THRESHOLD;
- const virtualIndex =
- messageSnapshot === messages
- ? messageAnchorIndex.get(anchorId)
- : findMessageAnchorIndex(messageSnapshot, anchorId);
- if (snapshotUsesVirtualizer && virtualIndex !== undefined && virtualIndex >= 0) {
- 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,
- isRunning,
- onSend: ({ body, reopen, reassignment }) => {
- pendingSubmitScrollRef.current = true;
- return onAdd(body, reopen, reassignment);
- },
- onCancel: onCancelRun,
- });
-
- useEffect(() => {
- const lastUserMessage = [...messages].reverse().find((m) => m.role === "user");
- const lastUserId = lastUserMessage?.id ?? null;
-
- if (
- pendingSubmitScrollRef.current
- && lastUserId
- && lastUserId !== lastUserMessageIdRef.current
- ) {
- pendingSubmitScrollRef.current = false;
- const custom = lastUserMessage?.metadata.custom as { anchorId?: unknown } | undefined;
- const anchorId = typeof custom?.anchorId === "string" ? custom.anchorId : null;
- if (anchorId) {
- const reserve = Math.round(window.innerHeight * SUBMIT_SCROLL_RESERVE_VH);
- spacerBaselineAnchorRef.current = anchorId;
- spacerInitialReserveRef.current = reserve;
- setBottomSpacerHeight(reserve);
- requestAnimationFrame(() => {
- scrollToThreadAnchor(anchorId, { align: "start", behavior: "smooth" });
- });
- }
- }
-
- lastUserMessageIdRef.current = lastUserId;
- }, [messageAnchorIndex, messages, useVirtualizedThread]);
-
- useLayoutEffect(() => {
- const anchorId = spacerBaselineAnchorRef.current;
- if (!anchorId || spacerInitialReserveRef.current <= 0) return;
- const userEl = document.getElementById(anchorId);
- const bottomEl = bottomAnchorRef.current;
- if (!userEl || !bottomEl) return;
- const contentBelow = Math.max(
- 0,
- bottomEl.getBoundingClientRect().top - userEl.getBoundingClientRect().bottom,
- );
- const next = Math.max(0, spacerInitialReserveRef.current - contentBelow);
- setBottomSpacerHeight((prev) => (prev === next ? prev : next));
- if (next === 0) {
- spacerBaselineAnchorRef.current = null;
- spacerInitialReserveRef.current = 0;
- }
- }, [messages]);
- useLayoutEffect(() => {
- const composerElement = composerViewportAnchorRef.current;
- if (preserveComposerViewportRef.current) {
- restoreComposerViewportSnapshot(
- composerViewportSnapshotRef.current,
- composerElement,
- );
- }
-
- composerViewportSnapshotRef.current = captureComposerViewportSnapshot(composerElement);
- preserveComposerViewportRef.current = shouldPreserveComposerViewport(composerElement);
- }, [messages]);
-
- useEffect(() => {
- const hash = location.hash || (typeof window !== "undefined" ? window.location.hash : "");
- if (
- !(
- hash.startsWith("#comment-")
- || hash.startsWith("#activity-")
- || hash.startsWith("#run-")
- || hash.startsWith("#interaction-")
- )
- ) return;
- if (messages.length === 0 || lastScrolledHashRef.current === hash) return;
- const targetId = hash.slice(1);
- if (targetId.startsWith("comment-")) {
- const targetMessage = messages.find((message) => issueChatMessageAnchorId(message) === targetId);
- if (targetMessage && issueChatMessageIsDeleted(targetMessage)) {
- lastScrolledHashRef.current = hash;
- if (typeof window !== "undefined") {
- window.history.replaceState(null, "", `${location.pathname}${location.search}`);
- }
- return;
- }
- }
- 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;
- }
- };
-
- 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" });
- }
-
- // Lands on the latest `comment-*` row and then drives the scroll the rest
- // of the way home as the virtualizer's per-row measurements arrive.
- //
- // The virtualizer estimates 220px for unmeasured rows. On long threads
- // with tall markdown comments (PAP-2536 et al.), totalSize is hugely
- // underestimated until rows render and get measured. A single scroll
- // lands above the actual bottom; rendered rows then expand, the layout
- // grows, and the user has to keep clicking Jump-to-latest to walk closer
- // to the real bottom. The convergence loop below issues `scrollIntoView`
- // on the latest comment element on every tick until the DOM bottom of
- // that element is at the scroll container's bottom (or scroll position
- // and content height stop changing).
- function scrollToLatestCommentWithSettle(messageSnapshot: readonly ThreadMessage[] = latestMessagesRef.current) {
- const latestCommentIndex = findLatestCommentMessageIndex(messageSnapshot);
- if (latestCommentIndex < 0) {
- jumpToLatestFallback();
- return;
- }
- const latestCommentAnchor = issueChatMessageAnchorId(messageSnapshot[latestCommentIndex]);
- if (!latestCommentAnchor) {
- jumpToLatestFallback();
- return;
- }
-
- const initial = scrollToThreadAnchor(
- latestCommentAnchor,
- { align: "end", behavior: "smooth" },
- messageSnapshot,
- );
- if (!initial) {
- jumpToLatestFallback();
- return;
- }
-
- if (typeof window === "undefined") return;
-
- const startedAt = (typeof performance !== "undefined" ? performance.now() : Date.now());
- const MAX_DURATION_MS = 4000;
- const TICK_MS = 80;
- const TOLERANCE_PX = 4;
-
- clearLatestSettleTimeouts();
- const resolveScrollContainer = (): HTMLElement | null =>
- (document.getElementById("main-content") as HTMLElement | null);
- const cancelTarget = resolveScrollContainer() ?? window;
-
- let lastScrollTop = -1;
- let lastScrollHeight = -1;
- let stableTicks = 0;
- let cancelled = false;
-
- const cancel = () => {
- cancelled = true;
- };
-
- const cleanup = () => {
- cancelTarget.removeEventListener("wheel", cancel);
- cancelTarget.removeEventListener("touchstart", cancel);
- };
-
- cancelTarget.addEventListener("wheel", cancel, { once: true, passive: true });
- cancelTarget.addEventListener("touchstart", cancel, { once: true, passive: true });
- latestSettleCleanupRef.current = cleanup;
-
- const finish = () => {
- cleanup();
- latestSettleCleanupRef.current = null;
- for (const timeout of latestSettleTimeoutsRef.current) {
- window.clearTimeout(timeout);
- }
- latestSettleTimeoutsRef.current = [];
- };
-
- const scheduleTick = (delay: number) => {
- const timeout = window.setTimeout(() => {
- latestSettleTimeoutsRef.current = latestSettleTimeoutsRef.current.filter((entry) => entry !== timeout);
- tick();
- }, delay);
- latestSettleTimeoutsRef.current.push(timeout);
- };
-
- const tick = () => {
- const now = (typeof performance !== "undefined" ? performance.now() : Date.now());
- if (cancelled || now - startedAt > MAX_DURATION_MS) {
- finish();
- return;
- }
-
- if (typeof document === "undefined") {
- finish();
- return;
- }
-
- const el = document.getElementById(latestCommentAnchor);
- if (!el) {
- // Row hasn't been rendered into the virtualizer's buffer yet — nudge
- // the offset (instant) so it gets mounted, then keep settling.
- virtualizedThreadRef.current?.scrollToIndex(latestCommentIndex, {
- align: "end",
- behavior: "auto",
- });
- scheduleTick(TICK_MS);
- return;
- }
-
- const container = resolveScrollContainer();
- const containerBottom = container
- ? container.getBoundingClientRect().bottom
- : window.innerHeight;
- const elBottom = el.getBoundingClientRect().bottom;
- const offBottom = elBottom - containerBottom;
-
- if (Math.abs(offBottom) > TOLERANCE_PX) {
- el.scrollIntoView({ behavior: "smooth", block: "end" });
- }
-
- const currentScrollTop = container?.scrollTop ?? window.scrollY;
- const currentScrollHeight = container?.scrollHeight ?? document.documentElement.scrollHeight;
- const scrollStable = Math.abs(currentScrollTop - lastScrollTop) < 1;
- const heightStable = currentScrollHeight === lastScrollHeight;
- const atBottom = Math.abs(offBottom) <= TOLERANCE_PX;
- if (scrollStable && heightStable && atBottom) {
- stableTicks += 1;
- if (stableTicks >= 3) {
- finish();
- return;
- }
- } else {
- stableTicks = 0;
- }
- lastScrollTop = currentScrollTop;
- lastScrollHeight = currentScrollHeight;
- scheduleTick(TICK_MS);
- };
-
- // Hold the first iteration off for one frame so the initial smooth
- // scroll has begun (and the virtualizer has rendered the buffer around
- // the target) before we start settling.
- scheduleTick(120);
- }
-
- function handleJumpToLatest() {
- if (onRefreshLatestComments) {
- // Refetching the comments query (page 0 first) brings any comment that
- // arrived after the initial load — including ones live updates may
- // have missed during reconnects — into the loaded set before we
- // resolve the latest target. Otherwise we'd land on the latest
- // *loaded* comment but not the absolute newest. (PAP-2672 follow-up.)
- const refreshed = onRefreshLatestComments();
- if (refreshed && typeof (refreshed as Promise<unknown>).then === "function") {
- (refreshed as Promise<unknown>).then(
- () => scrollToLatestCommentWithSettle(latestMessagesRef.current),
- () => scrollToLatestCommentWithSettle(latestMessagesRef.current),
- );
- return;
- }
- }
- scrollToLatestCommentWithSettle(latestMessagesRef.current);
- }
-
- const stableOnVote = useStableEvent(onVote);
- const stableOnStopRun = useStableEvent(onStopRun);
- const stableOnInterruptQueued = useStableEvent(onInterruptQueued);
- const stableOnCancelQueued = useStableEvent(onCancelQueued);
- const stableOnDeleteComment = useStableEvent(onDeleteComment);
- const stableOnImageClick = useStableEvent(onImageClick);
- const stableOnAcceptInteraction = useStableEvent(onAcceptInteraction);
- const stableOnRejectInteraction = useStableEvent(onRejectInteraction);
- const stableOnSubmitInteractionAnswers = useStableEvent(onSubmitInteractionAnswers);
- const stableOnCancelInteraction = useStableEvent(onCancelInteraction);
-
- const chatCtx = useMemo<IssueChatMessageContext>(
- () => ({
- feedbackDataSharingPreference,
- feedbackTermsUrl,
- agentMap,
- currentUserId,
- userLabelMap,
- userProfileMap,
- onVote: stableOnVote,
- onStopRun: stableOnStopRun,
- stopRunLabel,
- stoppingRunLabel,
- stopRunVariant,
- runFinalizationActions,
- onInterruptQueued: stableOnInterruptQueued,
- onCancelQueued: stableOnCancelQueued,
- onDeleteComment: stableOnDeleteComment,
- onImageClick: stableOnImageClick,
- onAcceptInteraction: stableOnAcceptInteraction,
- onRejectInteraction: stableOnRejectInteraction,
- onSubmitInteractionAnswers: stableOnSubmitInteractionAnswers,
- onCancelInteraction: stableOnCancelInteraction,
- issueStatus,
- successfulRunHandoff,
- }),
- [
- feedbackDataSharingPreference,
- feedbackTermsUrl,
- agentMap,
- currentUserId,
- userLabelMap,
- userProfileMap,
- stableOnVote,
- stableOnStopRun,
- stopRunLabel,
- stoppingRunLabel,
- stopRunVariant,
- runFinalizationActions,
- stableOnInterruptQueued,
- stableOnCancelQueued,
- stableOnDeleteComment,
- stableOnImageClick,
- stableOnAcceptInteraction,
- stableOnRejectInteraction,
- stableOnSubmitInteractionAnswers,
- stableOnCancelInteraction,
- issueStatus,
- successfulRunHandoff,
- ],
- );
-
- const resolvedShowJumpToLatest = showJumpToLatest ?? variant === "full";
- const resolvedEmptyMessage = emptyMessage
- ?? (variant === "embedded"
- ? "No run output yet."
- : "This task conversation is empty. Start with a message below.");
- 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}>
- <IssueChatCtx.Provider value={chatCtx}>
- <div className={cn(variant === "embedded" ? "space-y-3" : "space-y-4")}>
- {resolvedShowJumpToLatest ? (
- <div className="flex justify-end">
- <button
- type="button"
- onClick={handleJumpToLatest}
- className="text-xs text-muted-foreground transition-colors hover:text-foreground"
- >
- Jump to latest
- </button>
- </div>
- ) : null}
-
- <IssueChatErrorBoundary
- resetKey={errorBoundaryResetKey}
- messages={messages}
- emptyMessage={resolvedEmptyMessage}
- variant={variant}
- >
- <div data-testid="thread-root">
- <div
- data-testid="thread-viewport"
- className={variant === "embedded" ? "space-y-3" : "space-y-4"}
- >
- {messages.length === 0 ? (
- <div className={cn(
- "text-center text-sm text-muted-foreground",
- variant === "embedded"
- ? "rounded-xl border border-dashed border-border/70 bg-background/60 px-4 py-6"
- : "rounded-2xl border border-dashed border-border bg-card px-6 py-10",
- )}>
- {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) => (
- <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">
- <IssueAssignedBacklogNotice
- issueStatus={issueStatus ?? ""}
- assigneeAgent={assignedAgent}
- assigneeUserId={assigneeUserId}
- onResume={onResumeFromBacklog}
- resuming={resumeFromBacklogPending}
- />
- {recoveryAction ? (
- <IssueRecoveryActionCard
- action={recoveryAction}
- agentMap={agentMap}
- onResolve={onResolveRecoveryAction}
- canFalsePositive={canFalsePositiveRecoveryAction}
- />
- ) : null}
- {legacyRecoverySourceIssue ? (
- <SystemNotice
- tone="info"
- label="Legacy recovery task"
- body={
- <span>
- Legacy recovery task. Newer recovery actions live on the source task
- {legacyRecoverySourceIssue.identifier ? (
- <>
- {" — "}
- <Link
- to={legacyRecoverySourceIssue.href}
- className="underline-offset-2 hover:underline"
- >
- {legacyRecoverySourceIssue.identifier}
- {legacyRecoverySourceIssue.title ? (
- <span className="text-muted-foreground">
- {" "}
- — {legacyRecoverySourceIssue.title}
- </span>
- ) : null}
- </Link>
- </>
- ) : (
- "."
- )}
- </span>
- }
- />
- ) : null}
- <IssueBlockedNotice
- issueId={issueId}
- issueStatus={issueStatus}
- blockers={unresolvedBlockers}
- blockerAttention={blockerAttention}
- successfulRunHandoff={recoveryAction ? null : successfulRunHandoff}
- scheduledRetry={scheduledRetry}
- agentName={
- successfulRunHandoff?.assigneeAgentId
- ? agentMap?.get(successfulRunHandoff.assigneeAgentId)?.name ?? null
- : null
- }
- />
- <IssueAssigneePausedNotice agent={assignedAgent} />
- </div>
- ) : null}
- {footer ? <div data-testid="issue-chat-thread-footer">{footer}</div> : null}
- <div ref={bottomAnchorRef} />
- {showComposer ? (
- <div
- aria-hidden
- data-testid="issue-chat-bottom-spacer"
- style={{ height: bottomSpacerHeight }}
- />
- ) : null}
- </div>
- </div>
- </IssueChatErrorBoundary>
-
- {showComposer ? (
- <div
- ref={composerViewportAnchorRef}
- data-testid="issue-chat-composer-dock"
- className="sticky bottom-[calc(env(safe-area-inset-bottom)+20px)] z-20 space-y-2 bg-gradient-to-t from-background via-background/95 to-background/0 pt-6"
- >
- <IssueChatComposer
- ref={composerRef}
- onImageUpload={imageUploadHandler}
- onAttachImage={onAttachImage}
- draftKey={draftKey}
- enableReassign={enableReassign}
- reassignOptions={reassignOptions}
- currentAssigneeValue={currentAssigneeValue}
- suggestedAssigneeValue={suggestedAssigneeValue}
- mentions={mentions}
- agentMap={agentMap}
- composerDisabledReason={composerDisabledReason}
- composerHint={composerHint}
- issueStatus={issueStatus}
- issueWorkMode={issueWorkMode}
- onWorkModeChange={onWorkModeChange}
- />
- </div>
- ) : null}
- </div>
- </IssueChatCtx.Provider>
- </AssistantRuntimeProvider>
- );
-}
diff --git a/ui/src/components/IssueThreadInteractionCardClassic.tsx b/ui/src/components/IssueThreadInteractionCardClassic.tsx
deleted file mode 100644
index 293daca3e9..0000000000
--- a/ui/src/components/IssueThreadInteractionCardClassic.tsx
+++ /dev/null
@@ -1,1890 +0,0 @@
-/**
- * CLASSIC FORK — do not extend (PAP-136 / PAP-139).
- *
- * Frozen copy of `IssueThreadInteractionCard.tsx` at merge-base e3aada1d
- * (`git show e3aada1d:ui/src/components/IssueThreadInteractionCard.tsx`),
- * rendered by `IssueChatThreadClassic` when the "Conference Room Chat"
- * experimental flag is OFF so task threads look exactly like master. New
- * features go in `IssueThreadInteractionCard.tsx`; delete this file when the
- * flag graduates or dies.
- */
-import { useEffect, useMemo, useState } from "react";
-import type { Agent } from "@paperclipai/shared";
-import { AlertTriangle, CheckCircle2, ChevronRight, CircleDashed, GitBranch, ListChecks, Loader2, MessageSquareQuote, XCircle } from "lucide-react";
-import { Link } from "@/lib/router";
-import { formatAssigneeUserLabel } from "../lib/assignees";
-import {
- buildSuggestedTaskTree,
- collectSuggestedTaskClientKeys,
- countSuggestedTaskNodes,
- getCheckboxConfirmationSelectedLabels,
- getRequestConfirmationTargetHref,
- getQuestionAnswerLabels,
- type AskUserQuestionsAnswer,
- type AskUserQuestionsInteraction,
- type IssueThreadInteraction,
- type RequestCheckboxConfirmationInteraction,
- type RequestConfirmationInteraction,
- type RequestConfirmationResult,
- type RequestConfirmationTarget,
- type SuggestTasksInteraction,
- type SuggestTasksResultCreatedTask,
- type SuggestedTaskDraft,
- type SuggestedTaskTreeNode,
-} from "../lib/issue-thread-interactions";
-import { cn, formatDateTime, formatShortDate } from "../lib/utils";
-import { MarkdownBody } from "./MarkdownBody";
-import { Button } from "./ui/button";
-import { Checkbox } from "./ui/checkbox";
-import { PriorityIcon } from "./PriorityIcon";
-import { Textarea } from "./ui/textarea";
-import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
-
-const OTHER_ANSWER_ID = "__paperclip_other__";
-
-interface IssueThreadInteractionCardProps {
- interaction: IssueThreadInteraction;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
- onAcceptInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- selectedClientKeys?: string[],
- selectedOptionIds?: string[],
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction:
- | SuggestTasksInteraction
- | RequestConfirmationInteraction
- | RequestCheckboxConfirmationInteraction,
- reason?: string,
- ) => Promise<void> | void;
- onSubmitInteractionAnswers?: (
- interaction: AskUserQuestionsInteraction,
- answers: AskUserQuestionsAnswer[],
- ) => Promise<void> | void;
- onCancelInteraction?: (
- interaction: AskUserQuestionsInteraction,
- ) => Promise<void> | void;
-}
-
-function resolveActorLabel(args: {
- agentId?: string | null;
- userId?: string | null;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
-}) {
- const { agentId, userId, agentMap, currentUserId, userLabelMap } = args;
- if (agentId) {
- return agentMap?.get(agentId)?.name ?? agentId.slice(0, 8);
- }
- if (userId) {
- return formatAssigneeUserLabel(userId, currentUserId, userLabelMap) ?? "Board";
- }
- return "Unknown";
-}
-
-function statusLabel(status: IssueThreadInteraction["status"]) {
- switch (status) {
- case "pending":
- return "Pending";
- case "accepted":
- return "Accepted";
- case "rejected":
- return "Rejected";
- case "answered":
- return "Answered";
- case "cancelled":
- return "Cancelled";
- case "expired":
- return "Expired";
- case "failed":
- return "Failed";
- default:
- return status;
- }
-}
-
-function interactionKindLabel(kind: IssueThreadInteraction["kind"]) {
- switch (kind) {
- case "suggest_tasks":
- return "Suggested tasks";
- case "ask_user_questions":
- return "Ask user questions";
- case "request_confirmation":
- return "Confirmation";
- case "request_checkbox_confirmation":
- return "Checkbox confirmation";
- default:
- return kind;
- }
-}
-
-function statusIcon(status: IssueThreadInteraction["status"]) {
- switch (status) {
- case "accepted":
- case "answered":
- return CheckCircle2;
- case "rejected":
- case "cancelled":
- case "failed":
- return XCircle;
- case "expired":
- return AlertTriangle;
- default:
- return CircleDashed;
- }
-}
-
-function statusClasses(status: IssueThreadInteraction["status"]) {
- switch (status) {
- case "accepted":
- case "answered":
- return {
- shell: "border-emerald-400/70 bg-transparent",
- badge: "border-emerald-500/60 bg-emerald-500/10 text-emerald-900 dark:bg-emerald-500/15 dark:text-emerald-100",
- };
- case "rejected":
- case "cancelled":
- return {
- shell: "border-rose-400/70 bg-transparent",
- badge: "border-rose-500/60 bg-rose-500/10 text-rose-900 dark:bg-rose-500/15 dark:text-rose-100",
- };
- case "failed":
- case "expired":
- return {
- shell: "border-amber-400/70 bg-transparent",
- badge: "border-amber-500/60 bg-amber-500/10 text-amber-900 dark:bg-amber-500/15 dark:text-amber-100",
- };
- default:
- return {
- shell: "border-sky-500/70 bg-transparent",
- badge: "border-sky-500/70 bg-sky-500/10 text-sky-900 dark:bg-sky-500/15 dark:text-sky-100",
- };
- }
-}
-
-function TaskField({
- label,
- value,
- tone = "default",
-}: {
- label: string;
- value: string;
- tone?: "default" | "subtle";
-}) {
- return (
- <span
- className={cn(
- "inline-flex items-center rounded-sm border px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.16em]",
- tone === "default"
- ? "border-border/70 bg-transparent text-foreground"
- : "border-border/60 bg-transparent text-muted-foreground",
- )}
- >
- {label}: {value}
- </span>
- );
-}
-
-function createdTaskMap(
- createdTasks: readonly SuggestTasksResultCreatedTask[] | undefined,
-) {
- return new Map(
- (createdTasks ?? []).map((entry) => [entry.clientKey, entry] as const),
- );
-}
-
-function TaskTreeNode({
- node,
- createdByClientKey,
- agentMap,
- currentUserId,
- userLabelMap,
- depth = 0,
- selectedClientKeys,
- skippedClientKeys,
- showSelection,
- onToggleSelection,
-}: {
- node: SuggestedTaskTreeNode;
- createdByClientKey: ReadonlyMap<string, SuggestTasksResultCreatedTask>;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
- depth?: number;
- selectedClientKeys?: ReadonlySet<string>;
- skippedClientKeys?: ReadonlySet<string>;
- showSelection?: boolean;
- onToggleSelection?: (node: SuggestedTaskTreeNode, checked: boolean) => void;
-}) {
- const visibleChildren = node.children.filter((child) => !child.task.hiddenInPreview);
- const hiddenChildCount = node.children
- .filter((child) => child.task.hiddenInPreview)
- .reduce((sum, child) => sum + countSuggestedTaskNodes(child), 0);
- const createdTask = createdByClientKey.get(node.task.clientKey);
- const isSelected = selectedClientKeys?.has(node.task.clientKey) ?? false;
- const isSkipped = skippedClientKeys?.has(node.task.clientKey) ?? false;
- const assigneeLabel = resolveActorLabel({
- agentId: node.task.assigneeAgentId,
- userId: node.task.assigneeUserId,
- agentMap,
- currentUserId,
- userLabelMap,
- });
- const hasExplicitAssignee = Boolean(
- node.task.assigneeAgentId || node.task.assigneeUserId,
- );
- const labels = node.task.labels ?? [];
- const hasMetadata = hasExplicitAssignee
- || Boolean(node.task.billingCode)
- || Boolean(node.task.projectId)
- || labels.length > 0;
-
- return (
- <>
- <div
- className={cn(
- "relative border-b border-border/60 px-3 py-2.5 last:border-b-0",
- depth > 0 && "before:absolute before:left-3 before:top-0 before:h-full before:w-px before:bg-border/70",
- )}
- style={depth > 0 ? { paddingLeft: `${depth * 24 + 12}px` } : undefined}
- >
- <div className="flex items-start justify-between gap-2">
- <div className="min-w-0 flex-1">
- <div className="flex items-start gap-2">
- {showSelection ? (
- <Checkbox
- checked={isSelected}
- onCheckedChange={(checked) => onToggleSelection?.(node, checked === true)}
- aria-label={`Include ${node.task.title}`}
- className="mt-0.5"
- />
- ) : null}
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 items-center gap-1.5">
- {node.task.priority ? (
- <PriorityIcon
- priority={node.task.priority}
- className="mt-px"
- />
- ) : null}
- <div className="min-w-0 truncate text-sm font-medium text-foreground">
- {node.task.title}
- </div>
- </div>
- {depth > 0 ? (
- <div className="mt-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-muted-foreground">
- Child task
- </div>
- ) : null}
- {node.task.description ? (
- <p className="mt-0.5 text-sm leading-5 text-muted-foreground">
- {node.task.description}
- </p>
- ) : null}
- </div>
- </div>
- </div>
-
- {createdTask?.issueId ? (
- <Link
- to={`/issues/${createdTask.identifier ?? createdTask.issueId}`}
- className="inline-flex shrink-0 items-center gap-1 rounded-sm border border-emerald-500/50 bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-emerald-900 transition-colors hover:bg-emerald-500/15 dark:text-emerald-100"
- >
- {createdTask.identifier ?? createdTask.issueId.slice(0, 8)}
- <ChevronRight className="h-3 w-3" />
- </Link>
- ) : isSkipped ? (
- <span className="inline-flex shrink-0 items-center rounded-sm border border-amber-500/60 bg-amber-500/10 px-2.5 py-1 text-[11px] font-medium text-amber-900 dark:text-amber-100">
- Skipped
- </span>
- ) : null}
- </div>
-
- {hasMetadata ? (
- <div className="mt-2 flex flex-wrap gap-1.5">
- {hasExplicitAssignee ? (
- <TaskField label="Assignee" value={assigneeLabel} />
- ) : null}
- {node.task.billingCode ? (
- <TaskField label="Billing" value={node.task.billingCode} />
- ) : null}
- {node.task.projectId ? (
- <TaskField label="Project" value={node.task.projectId} tone="subtle" />
- ) : null}
- {labels.map((label) => (
- <TaskField key={label} label="Label" value={label} tone="subtle" />
- ))}
- </div>
- ) : null}
-
- {hiddenChildCount > 0 ? (
- <div className="mt-2 flex items-center gap-2 rounded-sm border border-amber-500/60 bg-amber-500/10 px-3 py-2 text-xs text-amber-900 dark:text-amber-100">
- <GitBranch className="h-3.5 w-3.5 shrink-0" />
- <span>
- {hiddenChildCount === 1
- ? "1 follow-on task hidden in preview"
- : `${hiddenChildCount} follow-on tasks hidden in preview`}
- </span>
- </div>
- ) : null}
- </div>
-
- {visibleChildren.length > 0 ? (
- <>
- {visibleChildren.map((child) => (
- <TaskTreeNode
- key={child.task.clientKey}
- node={child}
- createdByClientKey={createdByClientKey}
- agentMap={agentMap}
- currentUserId={currentUserId}
- userLabelMap={userLabelMap}
- depth={depth + 1}
- selectedClientKeys={selectedClientKeys}
- skippedClientKeys={skippedClientKeys}
- showSelection={showSelection}
- onToggleSelection={onToggleSelection}
- />
- ))}
- </>
- ) : null}
- </>
- );
-}
-
-function SuggestTasksCard({
- interaction,
- agentMap,
- currentUserId,
- userLabelMap,
- onAcceptInteraction,
- onRejectInteraction,
-}: {
- interaction: SuggestTasksInteraction;
- agentMap?: Map<string, Agent>;
- currentUserId?: string | null;
- userLabelMap?: ReadonlyMap<string, string> | null;
- onAcceptInteraction?: (
- interaction: SuggestTasksInteraction,
- selectedClientKeys?: string[],
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction: SuggestTasksInteraction,
- reason?: string,
- ) => Promise<void> | void;
-}) {
- const [rejecting, setRejecting] = useState(false);
- const [working, setWorking] = useState<"accept" | "reject" | null>(null);
- const [rejectReason, setRejectReason] = useState(
- interaction.result?.rejectionReason ?? "",
- );
-
- useEffect(() => {
- setRejectReason(interaction.result?.rejectionReason ?? "");
- if (interaction.status !== "pending") {
- setRejecting(false);
- setWorking(null);
- }
- }, [interaction.result?.rejectionReason, interaction.status]);
-
- const roots = useMemo(
- () =>
- buildSuggestedTaskTree(interaction.payload.tasks).filter(
- (node) => !node.task.hiddenInPreview,
- ),
- [interaction.payload.tasks],
- );
- const createdByClientKey = useMemo(
- () => createdTaskMap(interaction.result?.createdTasks),
- [interaction.result?.createdTasks],
- );
- const skippedClientKeys = useMemo(
- () => new Set(interaction.result?.skippedClientKeys ?? []),
- [interaction.result?.skippedClientKeys],
- );
- const totalTasks = interaction.payload.tasks.length;
- const [selectedClientKeys, setSelectedClientKeys] = useState<Set<string>>(
- () => new Set(interaction.payload.tasks.map((task) => task.clientKey)),
- );
- const taskSelectionSeed = useMemo(
- () => interaction.payload.tasks.map((task) => task.clientKey).join("\n"),
- [interaction.payload.tasks],
- );
-
- useEffect(() => {
- setSelectedClientKeys(new Set(interaction.payload.tasks.map((task) => task.clientKey)));
- }, [interaction.id, interaction.status, taskSelectionSeed]);
-
- const taskByClientKey = useMemo(
- () => new Map(interaction.payload.tasks.map((task) => [task.clientKey, task] as const)),
- [interaction.payload.tasks],
- );
- const selectedCount = selectedClientKeys.size;
- const createdCount = interaction.result?.createdTasks?.length ?? 0;
- const skippedCount = interaction.result?.skippedClientKeys?.length ?? 0;
-
- async function handleAccept() {
- if (!onAcceptInteraction) return;
- setWorking("accept");
- try {
- await onAcceptInteraction(interaction, [...selectedClientKeys]);
- } finally {
- setWorking(null);
- }
- }
-
- async function handleReject() {
- if (!onRejectInteraction) return;
- setWorking("reject");
- try {
- await onRejectInteraction(interaction, rejectReason.trim() || undefined);
- setRejecting(false);
- } finally {
- setWorking(null);
- }
- }
-
- function handleToggleSelection(node: SuggestedTaskTreeNode, checked: boolean) {
- const subtreeClientKeys = collectSuggestedTaskClientKeys(node);
- setSelectedClientKeys((current) => {
- const next = new Set(current);
- if (!checked) {
- for (const clientKey of subtreeClientKeys) {
- next.delete(clientKey);
- }
- return next;
- }
-
- for (const clientKey of subtreeClientKeys) {
- next.add(clientKey);
- }
-
- let parentClientKey = taskByClientKey.get(node.task.clientKey)?.parentClientKey ?? null;
- while (parentClientKey) {
- next.add(parentClientKey);
- parentClientKey = taskByClientKey.get(parentClientKey)?.parentClientKey ?? null;
- }
- return next;
- });
- }
-
- return (
- <div className="space-y-3">
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
- <span>{totalTasks === 1 ? "1 draft task" : `${totalTasks} draft tasks`}</span>
- {interaction.payload.defaultParentId ? (
- <TaskField label="Default parent" value={interaction.payload.defaultParentId} tone="subtle" />
- ) : null}
- </div>
-
- <div className="overflow-hidden border border-border/70">
- {roots.map((root) => (
- <TaskTreeNode
- key={root.task.clientKey}
- node={root}
- createdByClientKey={createdByClientKey}
- agentMap={agentMap}
- currentUserId={currentUserId}
- userLabelMap={userLabelMap}
- selectedClientKeys={selectedClientKeys}
- skippedClientKeys={skippedClientKeys}
- showSelection={interaction.status === "pending"}
- onToggleSelection={handleToggleSelection}
- />
- ))}
- </div>
-
- {interaction.status === "accepted" ? (
- <div className="rounded-sm border border-emerald-500/60 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-900 dark:text-emerald-100">
- <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-700">
- Resolution summary
- </div>
- <p className="mt-1 leading-6">
- {skippedCount > 0
- ? `Created ${createdCount} draft ${createdCount === 1 ? "task" : "tasks"} and skipped ${skippedCount} during review.`
- : `Created all ${createdCount} draft ${createdCount === 1 ? "task" : "tasks"}.`}
- </p>
- </div>
- ) : null}
-
- {interaction.status === "rejected" ? (
- <div className="rounded-sm border border-rose-500/60 bg-rose-500/10 px-4 py-3 text-sm text-rose-900 dark:text-rose-100">
- <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-700">
- Rejection reason
- </div>
- <p className={cn(
- "mt-1 leading-6",
- !interaction.result?.rejectionReason && "text-rose-900/75",
- )}>
- {interaction.result?.rejectionReason || "No reason provided."}
- </p>
- </div>
- ) : null}
-
- {interaction.status === "pending" ? (
- <div className="space-y-3">
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
- <span>
- {selectedCount === totalTasks
- ? `All ${totalTasks} draft ${totalTasks === 1 ? "task" : "tasks"} selected`
- : `${selectedCount} of ${totalTasks} draft ${totalTasks === 1 ? "task" : "tasks"} selected`}
- </span>
- {selectedCount < totalTasks ? (
- <span>
- {totalTasks - selectedCount} will be skipped if you accept this interaction.
- </span>
- ) : null}
- </div>
-
- <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
- <Button
- size="sm"
- disabled={!onAcceptInteraction || working !== null || selectedCount === 0}
- onClick={() => void handleAccept()}
- >
- {working === "accept" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Accepting...
- </>
- ) : (
- selectedCount === totalTasks ? "Accept drafts" : "Accept selected drafts"
- )}
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => setRejecting((current) => !current)}
- >
- Reject
- </Button>
- {selectedCount < totalTasks ? (
- <Button
- size="sm"
- variant="ghost"
- disabled={working !== null}
- onClick={() => setSelectedClientKeys(new Set(interaction.payload.tasks.map((task) => task.clientKey)))}
- >
- Reset selection
- </Button>
- ) : null}
- </div>
- </div>
-
- {rejecting ? (
- <div className="space-y-3">
- <Textarea
- value={rejectReason}
- onChange={(event) => setRejectReason(event.target.value)}
- placeholder="Add a short reason for rejecting this suggestion"
- className="min-h-24 bg-background text-sm"
- />
- <div className="flex justify-end">
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => void handleReject()}
- >
- {working === "reject" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Saving...
- </>
- ) : (
- "Save rejection"
- )}
- </Button>
- </div>
- </div>
- ) : null}
- </div>
- ) : null}
- </div>
- );
-}
-
-function QuestionOptionButton({
- id,
- label,
- description,
- selected,
- selectionMode,
- onClick,
-}: {
- id: string;
- label: string;
- description?: string | null;
- selected: boolean;
- selectionMode: "single" | "multi";
- onClick: () => void;
-}) {
- return (
- <button
- type="button"
- role={selectionMode === "single" ? "radio" : "checkbox"}
- aria-checked={selected}
- className={cn(
- "w-full rounded-sm border px-4 py-3 text-left transition-colors outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
- selected
- ? "border-sky-500/80 bg-sky-500/10 text-sky-950 dark:border-sky-400/80 dark:bg-sky-400/15 dark:text-sky-50"
- : "border-border/70 bg-transparent text-foreground hover:border-sky-500/70 hover:bg-sky-500/10 dark:hover:border-sky-400/70 dark:hover:bg-sky-400/10",
- )}
- id={id}
- onClick={onClick}
- >
- <div
- className={cn(
- "text-sm font-medium",
- selected ? "text-sky-950 dark:text-sky-50" : "text-foreground",
- )}
- >
- {label}
- </div>
- {description ? (
- <div
- className={cn(
- "mt-1 text-sm leading-6",
- selected
- ? "text-sky-900/80 dark:text-sky-100/80"
- : "text-muted-foreground",
- )}
- >
- {description}
- </div>
- ) : null}
- </button>
- );
-}
-
-function AskUserQuestionsCard({
- interaction,
- onSubmitInteractionAnswers,
- onCancelInteraction,
-}: {
- interaction: AskUserQuestionsInteraction;
- onSubmitInteractionAnswers?: (
- interaction: AskUserQuestionsInteraction,
- answers: AskUserQuestionsAnswer[],
- ) => Promise<void> | void;
- onCancelInteraction?: (
- interaction: AskUserQuestionsInteraction,
- ) => Promise<void> | void;
-}) {
- const [draftAnswers, setDraftAnswers] = useState<Record<string, string[]>>(() =>
- Object.fromEntries(
- (interaction.result?.answers ?? []).map((answer) => [
- answer.questionId,
- [...answer.optionIds],
- ]),
- ),
- );
- const [draftOtherAnswers, setDraftOtherAnswers] = useState<Record<string, string>>(() =>
- Object.fromEntries(
- (interaction.result?.answers ?? [])
- .filter((answer) => answer.otherText)
- .map((answer) => [answer.questionId, answer.otherText ?? ""]),
- ),
- );
- const [otherActiveQuestions, setOtherActiveQuestions] = useState<Record<string, boolean>>(() =>
- Object.fromEntries(
- (interaction.result?.answers ?? [])
- .filter((answer) => answer.otherText)
- .map((answer) => [answer.questionId, true]),
- ),
- );
- const [working, setWorking] = useState(false);
- const [cancelling, setCancelling] = useState(false);
-
- useEffect(() => {
- setDraftAnswers(
- Object.fromEntries(
- (interaction.result?.answers ?? []).map((answer) => [
- answer.questionId,
- [...answer.optionIds],
- ]),
- ),
- );
- setDraftOtherAnswers(
- Object.fromEntries(
- (interaction.result?.answers ?? [])
- .filter((answer) => answer.otherText)
- .map((answer) => [answer.questionId, answer.otherText ?? ""]),
- ),
- );
- setOtherActiveQuestions(
- Object.fromEntries(
- (interaction.result?.answers ?? [])
- .filter((answer) => answer.otherText)
- .map((answer) => [answer.questionId, true]),
- ),
- );
- }, [interaction.result?.answers]);
-
- const questions = interaction.payload.questions;
- const requiredQuestions = questions.filter((question) => question.required);
- const canSubmit = requiredQuestions.every(
- (question) =>
- (draftAnswers[question.id] ?? []).length > 0
- || (
- otherActiveQuestions[question.id] === true
- && (draftOtherAnswers[question.id]?.trim().length ?? 0) > 0
- ),
- );
-
- function toggleOption(questionId: string, optionId: string, selectionMode: "single" | "multi") {
- if (optionId === OTHER_ANSWER_ID) {
- setOtherActiveQuestions((current) => ({
- ...current,
- [questionId]: !current[questionId],
- }));
- if (selectionMode === "single") {
- setDraftAnswers((current) => ({ ...current, [questionId]: [] }));
- }
- return;
- }
-
- setDraftAnswers((current) => {
- const existing = current[questionId] ?? [];
- if (selectionMode === "single") {
- return { ...current, [questionId]: [optionId] };
- }
- const next = existing.includes(optionId)
- ? existing.filter((value) => value !== optionId)
- : [...existing, optionId];
- return { ...current, [questionId]: next };
- });
- if (selectionMode === "single") {
- setOtherActiveQuestions((current) => ({ ...current, [questionId]: false }));
- }
- }
-
- async function handleSubmit() {
- if (!onSubmitInteractionAnswers || !canSubmit) return;
- setWorking(true);
- try {
- await onSubmitInteractionAnswers(
- interaction,
- questions.map((question) => {
- const otherText = otherActiveQuestions[question.id] === true
- ? draftOtherAnswers[question.id]?.trim() ?? ""
- : "";
- return {
- questionId: question.id,
- optionIds: draftAnswers[question.id] ?? [],
- ...(otherText ? { otherText } : {}),
- };
- }),
- );
- } finally {
- setWorking(false);
- }
- }
-
- async function handleCancel() {
- if (!onCancelInteraction) return;
- setCancelling(true);
- try {
- await onCancelInteraction(interaction);
- } finally {
- setCancelling(false);
- }
- }
-
- return (
- <div className="space-y-4">
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
- <span className="inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 font-medium uppercase tracking-[0.16em] text-foreground/70">
- <MessageSquareQuote className="h-3 w-3" />
- Ask user questions
- </span>
- <span>
- {questions.length === 1
- ? "1 question"
- : `${questions.length} questions`}
- </span>
- </div>
-
- {interaction.status === "pending" ? (
- <div className="space-y-4">
- {questions.map((question, index) => (
- <div
- key={question.id}
- className="rounded-2xl border border-border/70 bg-background/82 p-4 shadow-[0_18px_42px_rgba(15,23,42,0.06)]"
- >
- <div className="flex items-start justify-between gap-3">
- <div>
- <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground">
- Question {index + 1}
- </div>
- <div
- id={`${interaction.id}-${question.id}-prompt`}
- className="mt-1 text-sm font-semibold text-foreground"
- >
- {question.prompt}
- </div>
- {question.helpText ? (
- <p className="mt-1 text-sm leading-6 text-muted-foreground">
- {question.helpText}
- </p>
- ) : null}
- </div>
- <TaskField
- label={question.selectionMode === "single" ? "Pick" : "Pick many"}
- value={question.required ? "Required" : "Optional"}
- tone="subtle"
- />
- </div>
-
- <div className="mt-3 space-y-3">
- <div
- className="grid gap-3"
- role={question.selectionMode === "single" ? "radiogroup" : "group"}
- aria-labelledby={`${interaction.id}-${question.id}-prompt`}
- >
- {question.options.map((option) => (
- <QuestionOptionButton
- key={option.id}
- id={`${interaction.id}-${question.id}-${option.id}`}
- label={option.label}
- description={option.description}
- selected={(draftAnswers[question.id] ?? []).includes(option.id)}
- selectionMode={question.selectionMode}
- onClick={() =>
- toggleOption(question.id, option.id, question.selectionMode)}
- />
- ))}
- </div>
- <button
- type="button"
- id={`${interaction.id}-${question.id}-other`}
- aria-expanded={otherActiveQuestions[question.id] === true}
- className={cn(
- "text-sm font-medium underline underline-offset-4 transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
- otherActiveQuestions[question.id]
- ? "text-sky-700 hover:text-sky-800 dark:text-sky-300 dark:hover:text-sky-200"
- : "text-muted-foreground hover:text-foreground",
- )}
- onClick={() =>
- toggleOption(question.id, OTHER_ANSWER_ID, question.selectionMode)}
- >
- Other
- </button>
- {otherActiveQuestions[question.id] ? (
- <Textarea
- aria-label={`Other answer for ${question.prompt}`}
- value={draftOtherAnswers[question.id] ?? ""}
- onChange={(event) =>
- setDraftOtherAnswers((current) => ({
- ...current,
- [question.id]: event.target.value,
- }))}
- placeholder="Type your answer"
- className="min-h-24 bg-background text-sm"
- />
- ) : null}
- </div>
- </div>
- ))}
-
- <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border/70 bg-background/75 p-4">
- <div className="text-sm text-muted-foreground">
- Submit once after you finish the full form.
- </div>
- <div className="flex flex-wrap items-center gap-2">
- {onCancelInteraction ? (
- <Button
- size="sm"
- variant="outline"
- disabled={working || cancelling}
- onClick={() => void handleCancel()}
- >
- {cancelling ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Cancelling...
- </>
- ) : (
- "Cancel question"
- )}
- </Button>
- ) : null}
- <Button
- size="sm"
- disabled={!onSubmitInteractionAnswers || !canSubmit || working || cancelling}
- onClick={() => void handleSubmit()}
- >
- {working ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Submitting...
- </>
- ) : (
- interaction.payload.submitLabel ?? "Submit answers"
- )}
- </Button>
- </div>
- </div>
- </div>
- ) : interaction.status === "cancelled" ? (
- <div className="rounded-2xl border border-rose-300/60 bg-rose-50/85 p-4 text-sm leading-6 text-rose-950 dark:border-rose-500/40 dark:bg-rose-500/10 dark:text-rose-100">
- <div className="font-semibold">Question cancelled</div>
- {interaction.result?.cancellationReason ? (
- <p className="mt-1">{interaction.result.cancellationReason}</p>
- ) : (
- <p className="mt-1">No answer was recorded.</p>
- )}
- </div>
- ) : (
- <div className="space-y-3">
- {questions.map((question) => {
- const labels = getQuestionAnswerLabels({
- question,
- answers: interaction.result?.answers ?? [],
- });
- return (
- <div
- key={question.id}
- className="rounded-2xl border border-border/70 bg-background/82 p-4"
- >
- <div className="text-sm font-semibold text-foreground">
- {question.prompt}
- </div>
- <div className="mt-2 flex flex-wrap gap-2">
- {labels.length > 0 ? (
- labels.map((label) => (
- <TaskField key={label} label="Answer" value={label} />
- ))
- ) : (
- <span className="text-sm text-muted-foreground">No answer recorded.</span>
- )}
- </div>
- </div>
- );
- })}
-
- {interaction.result?.summaryMarkdown ? (
- <div className="rounded-2xl border border-emerald-300/60 bg-emerald-50/85 p-4">
- <div className="mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-700">
- Submitted summary
- </div>
- <MarkdownBody>{interaction.result.summaryMarkdown}</MarkdownBody>
- </div>
- ) : null}
- </div>
- )}
- </div>
- );
-}
-
-function requestConfirmationTargetLabel(target: RequestConfirmationTarget) {
- if (target.label) return target.label;
- const revision = target.revisionNumber ? ` v${target.revisionNumber}` : "";
- if (target.type === "issue_document" && target.key === "plan") {
- return `Plan${revision}`;
- }
- return `${target.key}${revision}`;
-}
-
-function RequestConfirmationTargetChip({
- issueId,
- target,
- tone = "default",
-}: {
- issueId: string;
- target: RequestConfirmationTarget | null | undefined;
- tone?: "default" | "subtle";
-}) {
- if (!target) return null;
-
- const href = getRequestConfirmationTargetHref({ issueId, target });
- const className = cn(
- "inline-flex max-w-full items-center gap-1.5 rounded-sm border px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.16em]",
- tone === "default"
- ? "border-border/70 bg-transparent text-foreground"
- : "border-border/60 bg-transparent text-muted-foreground",
- href && "transition-colors hover:border-sky-500/70 hover:bg-sky-500/10",
- );
- const content = (
- <>
- <GitBranch className="h-3 w-3 shrink-0" />
- <span className="min-w-0 truncate">{requestConfirmationTargetLabel(target)}</span>
- </>
- );
-
- if (!href) return <span className={className}>{content}</span>;
- if (/^https?:\/\//i.test(href)) {
- return (
- <a href={href} target="_blank" rel="noreferrer" className={className}>
- {content}
- </a>
- );
- }
- return (
- <Link to={href} className={className}>
- {content}
- </Link>
- );
-}
-
-function ConfirmationDeclinedBlock({
- issueId,
- result,
- target,
-}: {
- issueId: string;
- result: RequestConfirmationResult | null | undefined;
- target: RequestConfirmationTarget | null;
-}) {
- return (
- <div className="space-y-2">
- <div className="flex flex-wrap items-center gap-2 text-sm leading-6 text-foreground">
- <span className="font-medium">Declined</span>
- <RequestConfirmationTargetChip issueId={issueId} target={target} />
- </div>
- {result?.reason ? (
- <blockquote className="rounded-sm border-l-2 border-rose-500/70 bg-rose-500/10 px-3 py-2 text-sm leading-6 text-rose-900 dark:text-rose-100">
- {result.reason}
- </blockquote>
- ) : null}
- </div>
- );
-}
-
-function ConfirmationExpiredBlock({
- issueId,
- result,
- target,
-}: {
- issueId: string;
- result: RequestConfirmationResult | null | undefined;
- target: RequestConfirmationTarget | null;
-}) {
- const outcome = result?.outcome;
- const staleTarget = result?.staleTarget ?? null;
- const expiredByComment = outcome === "superseded_by_comment";
- const expiredByTargetChange = outcome === "stale_target";
- return (
- <div className="space-y-3 rounded-sm border border-amber-500/60 bg-amber-500/10 px-4 py-3 text-sm text-amber-900 dark:text-amber-100">
- <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-700">
- {expiredByComment ? "Expired by comment" : "Expired by target change"}
- </div>
- <p className="leading-6">
- {expiredByComment
- ? "A board comment superseded this request before it was resolved."
- : "The requested target changed before this request was resolved."}
- </p>
- {expiredByComment && result?.commentId ? (
- <Button asChild size="sm" variant="ghost" className="h-7 px-2 text-amber-950 hover:bg-amber-500/15 dark:text-amber-50">
- <a href={`#comment-${result.commentId}`}>Jump to comment</a>
- </Button>
- ) : null}
- {expiredByTargetChange ? (
- <div className="flex flex-wrap items-center gap-2">
- <RequestConfirmationTargetChip
- issueId={issueId}
- target={staleTarget}
- tone="subtle"
- />
- {staleTarget && target ? (
- <ChevronRight className="h-3.5 w-3.5 text-amber-700" />
- ) : null}
- <RequestConfirmationTargetChip issueId={issueId} target={target} />
- </div>
- ) : null}
- </div>
- );
-}
-
-function ConfirmationFailedBlock() {
- return (
- <p className="text-sm leading-6 text-muted-foreground">
- This request could not be resolved. Try again or create a new request.
- </p>
- );
-}
-
-function RequestConfirmationResolution({
- interaction,
-}: {
- interaction: RequestConfirmationInteraction;
-}) {
- const target = interaction.payload.target ?? null;
-
- if (interaction.status === "accepted") {
- return (
- <div className="flex flex-wrap items-center gap-2 text-sm leading-6 text-foreground">
- <span className="font-medium">Confirmed</span>
- <RequestConfirmationTargetChip issueId={interaction.issueId} target={target} />
- </div>
- );
- }
-
- if (interaction.status === "rejected") {
- return (
- <ConfirmationDeclinedBlock
- issueId={interaction.issueId}
- result={interaction.result}
- target={target}
- />
- );
- }
-
- if (interaction.status === "expired") {
- return (
- <ConfirmationExpiredBlock
- issueId={interaction.issueId}
- result={interaction.result}
- target={target}
- />
- );
- }
-
- if (interaction.status === "failed") {
- return <ConfirmationFailedBlock />;
- }
-
- return null;
-}
-
-function RequestConfirmationCard({
- interaction,
- onAcceptInteraction,
- onRejectInteraction,
-}: {
- interaction: RequestConfirmationInteraction;
- onAcceptInteraction?: (
- interaction: RequestConfirmationInteraction,
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction: RequestConfirmationInteraction,
- reason?: string,
- ) => Promise<void> | void;
-}) {
- const [rejecting, setRejecting] = useState(false);
- const [working, setWorking] = useState<"accept" | "reject" | null>(null);
- const [rejectReason, setRejectReason] = useState(interaction.result?.reason ?? "");
- const [rejectAttempted, setRejectAttempted] = useState(false);
- const [actionError, setActionError] = useState<string | null>(null);
- const rejectRequiresReason = interaction.payload.rejectRequiresReason === true;
- const allowDeclineReason = interaction.payload.allowDeclineReason !== false;
- const trimmedRejectReason = rejectReason.trim();
- const canReject = !rejectRequiresReason || trimmedRejectReason.length > 0;
- const declineReasonInvalid = rejectRequiresReason && !canReject;
- const declineReasonPlaceholder =
- interaction.payload.declineReasonPlaceholder
- ?? (interaction.payload.acceptLabel === "Approve plan"
- ? "Optional: what would you like revised?"
- : "Optional: tell the agent what you'd change.");
-
- useEffect(() => {
- setRejectReason(interaction.result?.reason ?? "");
- setRejectAttempted(false);
- setActionError(null);
- if (interaction.status !== "pending") {
- setRejecting(false);
- setWorking(null);
- }
- }, [interaction.id, interaction.result?.reason, interaction.status]);
-
- async function handleAccept() {
- if (!onAcceptInteraction) return;
- setWorking("accept");
- setActionError(null);
- try {
- await onAcceptInteraction(interaction);
- } catch {
- setActionError("Try again");
- } finally {
- setWorking(null);
- }
- }
-
- async function handleReject() {
- setRejectAttempted(true);
- if (!onRejectInteraction || !canReject) return;
- setWorking("reject");
- setActionError(null);
- try {
- await onRejectInteraction(interaction, trimmedRejectReason || undefined);
- setRejecting(false);
- } catch {
- setActionError("Try again");
- } finally {
- setWorking(null);
- }
- }
-
- return (
- <div className="space-y-4">
- {interaction.status === "pending" ? (
- <div className="space-y-3 rounded-sm border border-border/70 bg-background/75 p-4">
- <div className="text-sm leading-6 text-foreground">
- {interaction.payload.prompt}
- </div>
- {interaction.payload.detailsMarkdown ? (
- <div className="border-t border-border/60 pt-3 text-sm">
- <MarkdownBody>{interaction.payload.detailsMarkdown}</MarkdownBody>
- </div>
- ) : null}
- <RequestConfirmationTargetChip
- issueId={interaction.issueId}
- target={interaction.payload.target}
- />
- </div>
- ) : null}
-
- {interaction.status === "pending" ? (
- <div className="space-y-3">
- <div className="flex flex-wrap items-center justify-end gap-2">
- <Button
- size="sm"
- variant={rejecting ? "outline" : "default"}
- disabled={!onAcceptInteraction || working !== null}
- onClick={() => void handleAccept()}
- >
- {working === "accept" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Confirming...
- </>
- ) : (
- interaction.payload.acceptLabel ?? "Confirm"
- )}
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => {
- if (!allowDeclineReason) {
- void handleReject();
- return;
- }
- setRejectAttempted(false);
- setRejecting((current) => !current);
- }}
- >
- {interaction.payload.rejectLabel ?? "Decline"}
- </Button>
- </div>
-
- {rejecting ? (
- <div className="space-y-3 rounded-sm border border-border/70 bg-background/75 p-3">
- <Textarea
- value={rejectReason}
- onChange={(event) => setRejectReason(event.target.value)}
- placeholder={declineReasonPlaceholder}
- aria-invalid={rejectAttempted && declineReasonInvalid}
- className={cn(
- "min-h-24 bg-background text-sm",
- rejectAttempted && declineReasonInvalid
- && "border-rose-500 focus-visible:ring-rose-500/25",
- )}
- />
- {rejectAttempted && declineReasonInvalid ? (
- <p className="text-xs text-destructive">A decline reason is required.</p>
- ) : null}
- <div className="flex flex-wrap justify-end gap-2">
- <Button
- size="sm"
- variant="ghost"
- disabled={working !== null}
- onClick={() => {
- setRejecting(false);
- setRejectAttempted(false);
- }}
- >
- Cancel decline
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => void handleReject()}
- >
- {working === "reject" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Saving...
- </>
- ) : (
- interaction.payload.rejectLabel ?? "Decline"
- )}
- </Button>
- </div>
- </div>
- ) : null}
-
- {actionError ? (
- <div className="rounded-sm border border-destructive/60 bg-destructive/10 px-3 py-2 text-sm text-destructive">
- {actionError}
- </div>
- ) : null}
- </div>
- ) : (
- <RequestConfirmationResolution interaction={interaction} />
- )}
- </div>
- );
-}
-
-const CHECKBOX_SUMMARY_LABEL_LIMIT = 8;
-
-function RequestCheckboxConfirmationResolution({
- interaction,
-}: {
- interaction: RequestCheckboxConfirmationInteraction;
-}) {
- const target = interaction.payload.target ?? null;
- const [expanded, setExpanded] = useState(false);
-
- if (interaction.status === "accepted") {
- const totalOptions = interaction.payload.options.length;
- const selectedLabels = getCheckboxConfirmationSelectedLabels({
- payload: interaction.payload,
- result: interaction.result,
- });
- const selectedCount = interaction.result?.selectedOptionIds?.length ?? selectedLabels.length;
- const visibleLabels = expanded
- ? selectedLabels
- : selectedLabels.slice(0, CHECKBOX_SUMMARY_LABEL_LIMIT);
- const hiddenCount = selectedLabels.length - CHECKBOX_SUMMARY_LABEL_LIMIT;
- const hasHiddenLabels = hiddenCount > 0;
- const chipClassName =
- "inline-flex items-center rounded-sm border border-border/60 bg-transparent px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground";
-
- return (
- <div className="space-y-3">
- <div className="flex flex-wrap items-center gap-2 text-sm leading-6 text-foreground">
- <span className="font-medium">
- {selectedCount === 0
- ? "Confirmed with no options selected"
- : `Confirmed ${selectedCount} of ${totalOptions} ${totalOptions === 1 ? "option" : "options"}`}
- </span>
- <RequestConfirmationTargetChip issueId={interaction.issueId} target={target} />
- </div>
- {visibleLabels.length > 0 ? (
- <div className="flex flex-wrap gap-1.5">
- {visibleLabels.map((label, index) => (
- <TaskField key={`${label}-${index}`} label="Selected" value={label} />
- ))}
- {hasHiddenLabels ? (
- <button
- type="button"
- onClick={() => setExpanded((current) => !current)}
- className={cn(
- chipClassName,
- "cursor-pointer transition-colors hover:border-border hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",
- )}
- aria-expanded={expanded}
- >
- {expanded ? "Show less" : `+${hiddenCount} more`}
- </button>
- ) : null}
- </div>
- ) : null}
- </div>
- );
- }
-
- if (interaction.status === "rejected") {
- return (
- <ConfirmationDeclinedBlock
- issueId={interaction.issueId}
- result={interaction.result}
- target={target}
- />
- );
- }
-
- if (interaction.status === "expired") {
- return (
- <ConfirmationExpiredBlock
- issueId={interaction.issueId}
- result={interaction.result}
- target={target}
- />
- );
- }
-
- if (interaction.status === "failed") {
- return <ConfirmationFailedBlock />;
- }
-
- return null;
-}
-
-function CheckboxOptionRow({
- id,
- label,
- description,
- checked,
- disabled,
- onToggle,
-}: {
- id: string;
- label: string;
- description?: string | null;
- checked: boolean;
- disabled: boolean;
- onToggle: (checked: boolean) => void;
-}) {
- return (
- <label
- htmlFor={id}
- className={cn(
- "flex cursor-pointer items-start gap-2.5 border-b border-border/60 px-3 py-2 last:border-b-0 transition-colors",
- checked ? "bg-sky-500/10" : "hover:bg-sky-500/5",
- disabled && "cursor-not-allowed opacity-60",
- )}
- >
- <Checkbox
- id={id}
- checked={checked}
- disabled={disabled}
- onCheckedChange={(value) => onToggle(value === true)}
- aria-label={label}
- className="mt-0.5"
- />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium leading-5 text-foreground">{label}</div>
- {description ? (
- <p className="mt-0.5 text-sm leading-5 text-muted-foreground">{description}</p>
- ) : null}
- </div>
- </label>
- );
-}
-
-function RequestCheckboxConfirmationCard({
- interaction,
- onAcceptInteraction,
- onRejectInteraction,
-}: {
- interaction: RequestCheckboxConfirmationInteraction;
- onAcceptInteraction?: (
- interaction: RequestCheckboxConfirmationInteraction,
- selectedClientKeys: undefined,
- selectedOptionIds: string[],
- ) => Promise<void> | void;
- onRejectInteraction?: (
- interaction: RequestCheckboxConfirmationInteraction,
- reason?: string,
- ) => Promise<void> | void;
-}) {
- const options = interaction.payload.options;
- const optionIds = useMemo(() => options.map((option) => option.id), [options]);
- const validOptionIds = useMemo(() => new Set(optionIds), [optionIds]);
- const minSelected = interaction.payload.minSelected ?? 0;
- const maxSelected = interaction.payload.maxSelected ?? null;
-
- const defaultSelected = useMemo(
- () =>
- new Set(
- (interaction.payload.defaultSelectedOptionIds ?? []).filter((id) => validOptionIds.has(id)),
- ),
- [interaction.payload.defaultSelectedOptionIds, validOptionIds],
- );
-
- const [selectedOptionIds, setSelectedOptionIds] = useState<Set<string>>(() => new Set(defaultSelected));
- const [rejecting, setRejecting] = useState(false);
- const [working, setWorking] = useState<"accept" | "reject" | null>(null);
- const [rejectReason, setRejectReason] = useState(interaction.result?.reason ?? "");
- const [rejectAttempted, setRejectAttempted] = useState(false);
- const [acceptAttempted, setAcceptAttempted] = useState(false);
- const [actionError, setActionError] = useState<string | null>(null);
-
- const optionSeed = useMemo(() => optionIds.join("\n"), [optionIds]);
-
- useEffect(() => {
- setSelectedOptionIds(new Set(defaultSelected));
- setRejectReason(interaction.result?.reason ?? "");
- setRejectAttempted(false);
- setAcceptAttempted(false);
- setActionError(null);
- if (interaction.status !== "pending") {
- setRejecting(false);
- setWorking(null);
- }
- // optionSeed guards against option list identity churn for the same interaction.
- }, [interaction.id, interaction.status, interaction.result?.reason, defaultSelected, optionSeed]);
-
- const rejectRequiresReason = interaction.payload.rejectRequiresReason === true;
- const allowDeclineReason = interaction.payload.allowDeclineReason !== false;
- const trimmedRejectReason = rejectReason.trim();
- const canReject = !rejectRequiresReason || trimmedRejectReason.length > 0;
- const declineReasonInvalid = rejectRequiresReason && !canReject;
- const declineReasonPlaceholder =
- interaction.payload.declineReasonPlaceholder ?? "Optional: tell the agent what you'd change.";
-
- const selectedCount = selectedOptionIds.size;
- const totalOptions = options.length;
- const atMax = maxSelected != null && selectedCount >= maxSelected;
- const belowMin = selectedCount < minSelected;
- const aboveMax = maxSelected != null && selectedCount > maxSelected;
- const selectionValid = !belowMin && !aboveMax;
-
- const validationMessage = belowMin
- ? minSelected === 1
- ? "Select at least 1 option."
- : `Select at least ${minSelected} options.`
- : aboveMax && maxSelected != null
- ? maxSelected === 1
- ? "Select at most 1 option."
- : `Select at most ${maxSelected} options.`
- : null;
-
- function toggleOption(optionId: string, checked: boolean) {
- setSelectedOptionIds((current) => {
- const next = new Set(current);
- if (checked) {
- next.add(optionId);
- } else {
- next.delete(optionId);
- }
- return next;
- });
- }
-
- function handleSelectAll() {
- const capped = maxSelected != null ? optionIds.slice(0, maxSelected) : optionIds;
- setSelectedOptionIds(new Set(capped));
- }
-
- function handleClearSelection() {
- setSelectedOptionIds(new Set());
- }
-
- async function handleAccept() {
- setAcceptAttempted(true);
- if (!onAcceptInteraction || !selectionValid) return;
- setWorking("accept");
- setActionError(null);
- try {
- await onAcceptInteraction(interaction, undefined, [...selectedOptionIds]);
- } catch {
- setActionError("Try again");
- } finally {
- setWorking(null);
- }
- }
-
- async function handleReject() {
- setRejectAttempted(true);
- if (!onRejectInteraction || !canReject) return;
- setWorking("reject");
- setActionError(null);
- try {
- await onRejectInteraction(interaction, trimmedRejectReason || undefined);
- setRejecting(false);
- } catch {
- setActionError("Try again");
- } finally {
- setWorking(null);
- }
- }
-
- if (interaction.status !== "pending") {
- return (
- <div className="space-y-4">
- <RequestCheckboxConfirmationResolution interaction={interaction} />
- </div>
- );
- }
-
- const selectionSummary = totalOptions > 0 && selectedCount === totalOptions
- ? `All ${totalOptions} options selected`
- : `${selectedCount} of ${totalOptions} ${totalOptions === 1 ? "option" : "options"} selected`;
- const boundsHint = maxSelected != null
- ? `Pick ${minSelected === maxSelected ? `exactly ${maxSelected}` : `${minSelected}–${maxSelected}`}.`
- : minSelected > 0
- ? `Pick at least ${minSelected}.`
- : null;
-
- return (
- <div className="space-y-4">
- <div className="space-y-3 rounded-sm border border-border/70 bg-background/75 p-4">
- <div className="text-sm leading-6 text-foreground">{interaction.payload.prompt}</div>
- {interaction.payload.detailsMarkdown ? (
- <div className="border-t border-border/60 pt-3 text-sm">
- <MarkdownBody>{interaction.payload.detailsMarkdown}</MarkdownBody>
- </div>
- ) : null}
- <RequestConfirmationTargetChip
- issueId={interaction.issueId}
- target={interaction.payload.target}
- />
- </div>
-
- <div className="space-y-3">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
- <span>{selectionSummary}</span>
- {boundsHint ? <span>{boundsHint}</span> : null}
- </div>
- <div className="flex flex-wrap items-center gap-2">
- <Button
- size="sm"
- variant="ghost"
- disabled={working !== null || selectedCount === totalOptions || (maxSelected != null && selectedCount >= maxSelected)}
- onClick={handleSelectAll}
- >
- Select all
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={working !== null || selectedCount === 0}
- onClick={handleClearSelection}
- >
- Clear selection
- </Button>
- </div>
- </div>
-
- <div
- role="group"
- aria-label="Selectable options"
- className="max-h-80 overflow-y-auto rounded-sm border border-border/70"
- >
- {options.map((option) => {
- const checked = selectedOptionIds.has(option.id);
- return (
- <CheckboxOptionRow
- key={option.id}
- id={`${interaction.id}-${option.id}`}
- label={option.label}
- description={option.description}
- checked={checked}
- disabled={working !== null || (!checked && atMax)}
- onToggle={(value) => toggleOption(option.id, value)}
- />
- );
- })}
- </div>
-
- {acceptAttempted && validationMessage ? (
- <p className="text-xs text-destructive">{validationMessage}</p>
- ) : null}
-
- <div className="flex flex-wrap items-center justify-end gap-2">
- <Button
- size="sm"
- variant={rejecting ? "outline" : "default"}
- disabled={!onAcceptInteraction || working !== null}
- onClick={() => void handleAccept()}
- >
- {working === "accept" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Confirming...
- </>
- ) : (
- interaction.payload.acceptLabel ?? "Confirm selected"
- )}
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => {
- if (!allowDeclineReason) {
- void handleReject();
- return;
- }
- setRejectAttempted(false);
- setRejecting((current) => !current);
- }}
- >
- {interaction.payload.rejectLabel ?? "Request changes"}
- </Button>
- </div>
-
- {rejecting ? (
- <div className="space-y-3 rounded-sm border border-border/70 bg-background/75 p-3">
- <Textarea
- value={rejectReason}
- onChange={(event) => setRejectReason(event.target.value)}
- placeholder={declineReasonPlaceholder}
- aria-invalid={rejectAttempted && declineReasonInvalid}
- className={cn(
- "min-h-24 bg-background text-sm",
- rejectAttempted && declineReasonInvalid
- && "border-rose-500 focus-visible:ring-rose-500/25",
- )}
- />
- {rejectAttempted && declineReasonInvalid ? (
- <p className="text-xs text-destructive">A reason is required.</p>
- ) : null}
- <div className="flex flex-wrap justify-end gap-2">
- <Button
- size="sm"
- variant="ghost"
- disabled={working !== null}
- onClick={() => {
- setRejecting(false);
- setRejectAttempted(false);
- }}
- >
- Cancel
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={!onRejectInteraction || working !== null}
- onClick={() => void handleReject()}
- >
- {working === "reject" ? (
- <>
- <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
- Saving...
- </>
- ) : (
- interaction.payload.rejectLabel ?? "Request changes"
- )}
- </Button>
- </div>
- </div>
- ) : null}
-
- {actionError ? (
- <div className="rounded-sm border border-destructive/60 bg-destructive/10 px-3 py-2 text-sm text-destructive">
- {actionError}
- </div>
- ) : null}
- </div>
- </div>
- );
-}
-
-export function IssueThreadInteractionCardClassic({
- interaction,
- agentMap,
- currentUserId,
- userLabelMap,
- onAcceptInteraction,
- onRejectInteraction,
- onSubmitInteractionAnswers,
- onCancelInteraction,
-}: IssueThreadInteractionCardProps) {
- const StatusIcon = statusIcon(interaction.status);
- const styles = statusClasses(interaction.status);
- const createdByLabel = resolveActorLabel({
- agentId: interaction.createdByAgentId,
- userId: interaction.createdByUserId,
- agentMap,
- currentUserId,
- userLabelMap,
- });
- const resolvedByLabel =
- interaction.resolvedByAgentId || interaction.resolvedByUserId
- ? resolveActorLabel({
- agentId: interaction.resolvedByAgentId,
- userId: interaction.resolvedByUserId,
- agentMap,
- currentUserId,
- userLabelMap,
- })
- : null;
-
- return (
- <div className={cn("rounded-sm border p-5 shadow-none", styles.shell)}>
- <div className="flex flex-wrap items-start justify-between gap-4">
- <div className="min-w-0 flex-1 basis-64">
- <div className="flex flex-wrap items-center gap-2">
- <span className={cn("inline-flex items-center gap-1 rounded-sm border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em]", styles.badge)}>
- <StatusIcon className="h-3.5 w-3.5" />
- {interactionKindLabel(interaction.kind)}
- <span className="text-current/60">/</span>
- {statusLabel(interaction.status)}
- </span>
- {interaction.continuationPolicy === "wake_assignee"
- || interaction.continuationPolicy === "wake_assignee_on_accept" ? (
- <span className="inline-flex items-center gap-1 rounded-sm border border-border/70 bg-transparent px-2.5 py-1 text-[11px] font-medium uppercase tracking-[0.16em] text-foreground/70">
- <ListChecks className="h-3.5 w-3.5" />
- {interaction.continuationPolicy === "wake_assignee_on_accept"
- ? "Wakes on confirm"
- : "Wakes assignee"}
- </span>
- ) : null}
- </div>
-
- <div className="mt-3 text-lg font-bold text-foreground">
- {interaction.title
- ?? (interaction.kind === "suggest_tasks"
- ? "Suggested task tree"
- : interaction.kind === "ask_user_questions"
- ? interaction.payload.title ?? "Questions for the operator"
- : interaction.kind === "request_checkbox_confirmation"
- ? "Checkbox confirmation requested"
- : "Confirmation requested")}
- </div>
- {interaction.summary ? (
- <p className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">
- {interaction.summary}
- </p>
- ) : null}
- </div>
-
- <Tooltip>
- <TooltipTrigger asChild>
- <div className="rounded-sm border border-border/70 bg-transparent px-3 py-2 text-right text-xs text-muted-foreground">
- <div className="font-medium text-foreground">{formatShortDate(interaction.createdAt)}</div>
- <div>proposed by {createdByLabel}</div>
- </div>
- </TooltipTrigger>
- <TooltipContent side="bottom" className="text-xs">
- Created {formatDateTime(interaction.createdAt)}
- </TooltipContent>
- </Tooltip>
- </div>
-
- <div className="mt-5">
- {interaction.kind === "suggest_tasks" ? (
- <SuggestTasksCard
- interaction={interaction}
- agentMap={agentMap}
- currentUserId={currentUserId}
- userLabelMap={userLabelMap}
- onAcceptInteraction={onAcceptInteraction}
- onRejectInteraction={onRejectInteraction}
- />
- ) : interaction.kind === "ask_user_questions" ? (
- <AskUserQuestionsCard
- interaction={interaction}
- onSubmitInteractionAnswers={onSubmitInteractionAnswers}
- onCancelInteraction={onCancelInteraction}
- />
- ) : interaction.kind === "request_checkbox_confirmation" ? (
- <RequestCheckboxConfirmationCard
- interaction={interaction}
- onAcceptInteraction={onAcceptInteraction}
- onRejectInteraction={onRejectInteraction}
- />
- ) : (
- <RequestConfirmationCard
- interaction={interaction}
- onAcceptInteraction={onAcceptInteraction}
- onRejectInteraction={onRejectInteraction}
- />
- )}
- </div>
-
- {resolvedByLabel ? (
- <div className="mt-4 border-t border-border/60 pt-3 text-xs text-muted-foreground">
- Resolved by <span className="font-medium text-foreground">{resolvedByLabel}</span>
- {interaction.resolvedAt ? ` on ${formatShortDate(interaction.resolvedAt)}` : ""}
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/ui/src/components/NewIssueDialog.test.tsx b/ui/src/components/NewIssueDialog.test.tsx
index 0da91f007e..5be82be0af 100644
--- a/ui/src/components/NewIssueDialog.test.tsx
+++ b/ui/src/components/NewIssueDialog.test.tsx
@@ -1134,9 +1134,7 @@ describe("NewIssueDialog", () => {
act(() => root.unmount());
});
- // PAP-139/PAP-140: work-mode labels and status hues branch on the Conference
- // Room Chat experimental flag — OFF (default) must match master exactly.
- describe("Conference Room Chat flag parity (PAP-140)", () => {
+ describe("graduated work-mode labels and status hues", () => {
function workModeOption(value: string) {
return container.querySelector(`[data-issue-work-mode="${value}"]`);
}
@@ -1153,29 +1151,7 @@ describe("NewIssueDialog", () => {
return button?.querySelector("svg")?.getAttribute("class") ?? "";
}
- it("uses master's work-mode labels and status hues when the flag is off (default)", async () => {
- const { root } = renderDialog(container);
- await flush();
-
- expect(workModeOption("standard")?.textContent).toContain("Standard");
- expect(workModeOption("standard")?.textContent).not.toContain("Agent mode");
- expect(workModeOption("ask")?.textContent).toContain("Ask");
- expect(workModeOption("planning")?.textContent).toContain("Planning");
- expect(workModeOption("planning")?.textContent).not.toContain("Plan mode");
-
- // Master palette: todo → blue, in_progress → yellow.
- expect(statusOptionIconClass("Todo", "Executable — assignee will be woken")).toContain("text-blue-600");
- expect(statusOptionIconClass("In Progress")).toContain("text-yellow-600");
-
- act(() => root.unmount());
- });
-
- it("uses NUX work-mode labels and brand status hues when the flag is on", async () => {
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({
- enableConferenceRoomChat: true,
- enableIsolatedWorkspaces: false,
- });
-
+ it("uses agent-mode labels and brand status hues by default", async () => {
const { root } = renderDialog(container);
await waitForAssertion(() => {
expect(workModeOption("standard")?.textContent).toContain("Agent mode");
@@ -1185,7 +1161,6 @@ describe("NewIssueDialog", () => {
expect(workModeOption("ask")?.textContent).toContain("Ask mode");
expect(workModeOption("planning")?.textContent).toContain("Plan mode");
- // PAP-75 brand palette: todo → amber, in_progress → blue.
expect(statusOptionIconClass("Todo", "Executable — assignee will be woken")).toContain("text-amber-600");
expect(statusOptionIconClass("In Progress")).toContain("text-blue-600");
diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx
index 05f1c70112..a6564af253 100644
--- a/ui/src/components/NewIssueDialog.tsx
+++ b/ui/src/components/NewIssueDialog.tsx
@@ -65,8 +65,7 @@ import {
import { Textarea } from "@/components/ui/textarea";
import { cn } from "../lib/utils";
import { extractProviderIdWithFallback } from "../lib/model-utils";
-import { issueStatusText, issueStatusTextClassic, issueStatusTextDefault, priorityColor, priorityColorDefault } from "../lib/status-colors";
-import { useConferenceRoomChatEnabled } from "../hooks/useConferenceRoomChatEnabled";
+import { issueStatusText, issueStatusTextDefault, priorityColor, priorityColorDefault } from "../lib/status-colors";
import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor";
import { AgentIcon } from "./AgentIconPicker";
import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
@@ -214,12 +213,8 @@ function formatFileSize(file: File) {
return `${(file.size / (1024 * 1024)).toFixed(1)} MB`;
}
-// PAP-75 brand hues ship behind the Conference Room Chat flag (PAP-139); OFF
-// keeps master's palette (`issueStatusTextClassic`).
-function buildStatusOptions(
- conferenceRoomChat: boolean,
-): ReadonlyArray<{ value: string; label: string; color: string; description?: string }> {
- const palette = conferenceRoomChat ? issueStatusText : issueStatusTextClassic;
+function buildStatusOptions(): ReadonlyArray<{ value: string; label: string; color: string; description?: string }> {
+ const palette = issueStatusText;
return [
{
value: "backlog",
@@ -405,10 +400,8 @@ function issueExecutionWorkspaceModeForExistingWorkspace(mode: string | null | u
export function NewIssueDialog() {
const { newIssueOpen, newIssueDefaults, closeNewIssue } = useDialog();
const { companies, selectedCompanyId, selectedCompany } = useCompany();
- // Conference Room Chat flag (PAP-139): selects work-mode labels + status hues.
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
- const workModeOptions = useMemo(() => workModeMetaList(conferenceRoomChatEnabled), [conferenceRoomChatEnabled]);
- const statuses = useMemo(() => buildStatusOptions(conferenceRoomChatEnabled), [conferenceRoomChatEnabled]);
+ const workModeOptions = useMemo(() => workModeMetaList(), []);
+ const statuses = useMemo(() => buildStatusOptions(), []);
const queryClient = useQueryClient();
const { pushToast } = useToastActions();
const [title, setTitle] = useState("");
@@ -1039,7 +1032,7 @@ export function NewIssueDialog() {
function handleKeyDown(e: React.KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.code === "Period") {
e.preventDefault();
- setWorkMode((current) => nextWorkMode(current, conferenceRoomChatEnabled));
+ setWorkMode((current) => nextWorkMode(current));
return;
}
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
@@ -1245,7 +1238,7 @@ export function NewIssueDialog() {
},
[assigneeAdapterModels],
);
- const currentWorkMode = workModeMetaFor(workMode, conferenceRoomChatEnabled);
+ const currentWorkMode = workModeMetaFor(workMode);
const CurrentWorkModeIcon = currentWorkMode.icon;
return (
diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx
index 0ae65f5eb3..80691ce891 100644
--- a/ui/src/components/OnboardingWizard.tsx
+++ b/ui/src/components/OnboardingWizard.tsx
@@ -8,6 +8,8 @@ import { companiesApi } from "../api/companies";
import { goalsApi } from "../api/goals";
import { agentsApi } from "../api/agents";
import { approvalsApi } from "../api/approvals";
+import { issuesApi } from "../api/issues";
+import { projectsApi } from "../api/projects";
import { queryKeys } from "../lib/queryKeys";
import { Dialog, DialogPortal } from "@/components/ui/dialog";
import {
@@ -30,6 +32,12 @@ import { getAdapterDisplay } from "../adapters/adapter-display-registry";
import { defaultCreateValues } from "./agent-config-defaults";
import { parseOnboardingGoalInput } from "../lib/onboarding-goal";
import { composeCeoInstructions } from "../lib/ceo-instructions";
+import {
+ buildOnboardingIssuePayload,
+ buildOnboardingProjectPayload,
+ selectDefaultCompanyGoalId,
+ selectReusableOnboardingProject,
+} from "../lib/onboarding-launch";
import { buildNewAgentRuntimeConfig } from "../lib/new-agent-runtime-config";
import { DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX } from "@paperclipai/adapter-codex-local";
import { DEFAULT_CURSOR_LOCAL_MODEL } from "@paperclipai/adapter-cursor-local";
@@ -73,6 +81,14 @@ function buildMissionFromQuestionnaire(q1: string, q2: string, q3: string, q4: s
}
const ONBOARDING_STORAGE_KEY = "paperclip-onboarding-state";
+const DEFAULT_TASK_TITLE = "Hire your first engineer and create a hiring plan";
+const DEFAULT_TASK_DESCRIPTION = `You are the CEO. You set the direction for the company.
+
+- hire a founding engineer
+- write a hiring plan
+- break the roadmap into concrete tasks and start delegating work`;
+const INCOMPLETE_ONBOARDING_STATE_MESSAGE =
+ "Onboarding state is incomplete. Please restart onboarding and try again.";
function loadSavedState(): Record<string, unknown> | null {
try {
@@ -170,6 +186,15 @@ export function OnboardingWizard() {
string | null
>((saved?.createdCompanyPrefix as string) ?? null);
const [createdAgentId, setCreatedAgentId] = useState<string | null>((saved?.createdAgentId as string) ?? null);
+ const [createdCompanyGoalId, setCreatedCompanyGoalId] = useState<string | null>(
+ (saved?.createdCompanyGoalId as string) ?? null
+ );
+ const [createdProjectId, setCreatedProjectId] = useState<string | null>(
+ (saved?.createdProjectId as string) ?? null
+ );
+ const [createdIssueRef, setCreatedIssueRef] = useState<string | null>(
+ (saved?.createdIssueRef as string) ?? null
+ );
// Reset the route-dismissed flag when navigating to a different path.
useEffect(() => {
@@ -208,6 +233,7 @@ export function OnboardingWizard() {
step, companyName, companyGoal, missionPath, missionConfirmed,
q1, q2, q3, q4, agentName, adapterType, cwd, model, command, args, url,
createdCompanyId, createdCompanyPrefix, createdAgentId,
+ createdCompanyGoalId, createdProjectId, createdIssueRef,
onboardingPath, growWorkflows, growPainPoints, growAutomate,
};
localStorage.setItem(ONBOARDING_STORAGE_KEY, JSON.stringify(state));
@@ -215,6 +241,7 @@ export function OnboardingWizard() {
effectiveOnboardingOpen, step, companyName, companyGoal, missionPath, missionConfirmed,
q1, q2, q3, q4, agentName, adapterType, cwd, model, command, args, url,
createdCompanyId, createdCompanyPrefix, createdAgentId,
+ createdCompanyGoalId, createdProjectId, createdIssueRef,
onboardingPath, growWorkflows, growPainPoints, growAutomate,
]);
@@ -363,6 +390,9 @@ export function OnboardingWizard() {
setCreatedCompanyId(null);
setCreatedCompanyPrefix(null);
setCreatedAgentId(null);
+ setCreatedCompanyGoalId(null);
+ setCreatedProjectId(null);
+ setCreatedIssueRef(null);
}
function handleClose() {
@@ -375,11 +405,67 @@ export function OnboardingWizard() {
setRouteDismissed(true);
}
- function handleLaunchToChat() {
- const prefix = createdCompanyPrefix;
- reset();
- closeOnboarding();
- navigate(prefix ? `/${prefix}/board-chat` : "/dashboard");
+ async function handleLaunchToDashboard() {
+ if (!createdCompanyId || !createdAgentId) {
+ setError(INCOMPLETE_ONBOARDING_STATE_MESSAGE);
+ return;
+ }
+ setLoading(true);
+ setError(null);
+ try {
+ let goalId = createdCompanyGoalId;
+ if (!goalId) {
+ const goals = await goalsApi.list(createdCompanyId);
+ goalId = selectDefaultCompanyGoalId(goals);
+ setCreatedCompanyGoalId(goalId);
+ }
+
+ let projectId = createdProjectId;
+ if (!projectId) {
+ const projects = await projectsApi.list(createdCompanyId);
+ const existingOnboardingProject = selectReusableOnboardingProject(projects);
+ if (existingOnboardingProject) {
+ projectId = existingOnboardingProject.id;
+ } else {
+ const project = await projectsApi.create(
+ createdCompanyId,
+ buildOnboardingProjectPayload(goalId)
+ );
+ projectId = project.id;
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.projects.list(createdCompanyId)
+ });
+ }
+ setCreatedProjectId(projectId);
+ }
+
+ if (!createdIssueRef) {
+ const issue = await issuesApi.create(
+ createdCompanyId,
+ buildOnboardingIssuePayload({
+ title: DEFAULT_TASK_TITLE,
+ description: DEFAULT_TASK_DESCRIPTION,
+ assigneeAgentId: createdAgentId,
+ projectId,
+ goalId
+ })
+ );
+ setCreatedIssueRef(issue.identifier ?? issue.id);
+ queryClient.invalidateQueries({
+ queryKey: queryKeys.issues.list(createdCompanyId)
+ });
+ }
+
+ const prefix = createdCompanyPrefix;
+ setSelectedCompanyId(createdCompanyId);
+ reset();
+ closeOnboarding();
+ navigate(prefix ? `/${prefix}/dashboard` : "/dashboard");
+ } catch (err) {
+ setError(err instanceof Error ? err.message : "Failed to launch first task");
+ } finally {
+ setLoading(false);
+ }
}
function buildAdapterConfig(): Record<string, unknown> {
@@ -467,7 +553,7 @@ export function OnboardingWizard() {
queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
const parsedGoal = parseOnboardingGoalInput(companyGoal);
- await goalsApi.create(company.id, {
+ const goal = await goalsApi.create(company.id, {
title: parsedGoal.title,
...(parsedGoal.description
? { description: parsedGoal.description }
@@ -475,6 +561,7 @@ export function OnboardingWizard() {
level: "company",
status: "active"
});
+ setCreatedCompanyGoalId(goal.id);
queryClient.invalidateQueries({
queryKey: queryKeys.goals.list(company.id)
});
@@ -651,12 +738,15 @@ export function OnboardingWizard() {
else if (step === 2 && companyName.trim() && companyGoal.trim()) handleConfirmMission();
else if (step === 3 && agentName.trim()) setStep(4);
else if (step === 4 && agentName.trim()) handleGiveHeartbeat();
- else if (step === 5) handleLaunchToChat();
+ else if (step === 5) handleLaunchToDashboard();
}
}
if (!effectiveOnboardingOpen) return null;
+ const launchStateIncomplete = step === 5 && (!createdCompanyId || !createdAgentId);
+ const visibleError = error ?? (launchStateIncomplete ? INCOMPLETE_ONBOARDING_STATE_MESSAGE : null);
+
return (
<Dialog
open={effectiveOnboardingOpen}
@@ -1528,15 +1618,15 @@ export function OnboardingWizard() {
</p>
)}
<p className="text-xs text-muted-foreground text-center">
- Start a conversation with {agentName} to discuss strategy and plan who to bring on.
+ We'll create the first task for {agentName} and take you to the dashboard.
</p>
</div>
)}
{/* Error */}
- {error && (
+ {visibleError && (
<div className="mt-3">
- <p className="text-xs text-destructive">{error}</p>
+ <p className="text-xs text-destructive">{visibleError}</p>
</div>
)}
@@ -1608,9 +1698,17 @@ export function OnboardingWizard() {
</Button>
)}
{step === 5 && (
- <Button size="sm" onClick={handleLaunchToChat}>
- <ArrowRight className="h-3.5 w-3.5 mr-1" />
- Get started
+ <Button
+ size="sm"
+ onClick={handleLaunchToDashboard}
+ disabled={loading || launchStateIncomplete}
+ >
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
+ ) : (
+ <ArrowRight className="h-3.5 w-3.5 mr-1" />
+ )}
+ {loading ? "Launching..." : "Get started"}
</Button>
)}
</div>
diff --git a/ui/src/components/OnboardingWizardClassic.tsx b/ui/src/components/OnboardingWizardClassic.tsx
deleted file mode 100644
index 7830e7e01f..0000000000
--- a/ui/src/components/OnboardingWizardClassic.tsx
+++ /dev/null
@@ -1,1339 +0,0 @@
-import { useEffect, useState, useRef, useCallback, useMemo } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
-import type { AdapterEnvironmentTestResult } from "@paperclipai/shared";
-import { useLocation, useNavigate, useParams } from "@/lib/router";
-import { useDialog } from "../context/DialogContext";
-import { useCompany } from "../context/CompanyContext";
-import { companiesApi } from "../api/companies";
-import { goalsApi } from "../api/goals";
-import { agentsApi } from "../api/agents";
-import { approvalsApi } from "../api/approvals";
-import { issuesApi } from "../api/issues";
-import { projectsApi } from "../api/projects";
-import { queryKeys } from "../lib/queryKeys";
-import { Dialog, DialogPortal } from "@/components/ui/dialog";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger
-} from "@/components/ui/popover";
-import { Button } from "@/components/ui/button";
-import { cn } from "../lib/utils";
-import {
- extractModelName,
- extractProviderIdWithFallback
-} from "../lib/model-utils";
-import { getUIAdapter } from "../adapters";
-import { listUIAdapters } from "../adapters";
-import { isVisualAdapterChoice } from "../adapters/metadata";
-import { useDisabledAdaptersSync } from "../adapters/use-disabled-adapters";
-import { useAdapterCapabilities } from "../adapters/use-adapter-capabilities";
-import { getAdapterDisplay } from "../adapters/adapter-display-registry";
-import { defaultCreateValues } from "./agent-config-defaults";
-import { parseOnboardingGoalInput } from "../lib/onboarding-goal";
-import {
- buildOnboardingIssuePayload,
- buildOnboardingProjectPayload,
- selectDefaultCompanyGoalId
-} from "../lib/onboarding-launch";
-import { buildNewAgentRuntimeConfig } from "../lib/new-agent-runtime-config";
-import {
- DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX,
- DEFAULT_CODEX_LOCAL_MODEL
-} from "@paperclipai/adapter-codex-local";
-import { DEFAULT_CURSOR_LOCAL_MODEL } from "@paperclipai/adapter-cursor-local";
-import { DEFAULT_GEMINI_LOCAL_MODEL } from "@paperclipai/adapter-gemini-local";
-import { DEFAULT_OPENCODE_LOCAL_MODEL, isValidOpenCodeModelId } from "@paperclipai/adapter-opencode-local";
-import { resolveRouteOnboardingOptions } from "../lib/onboarding-route";
-import { AsciiArtAnimation } from "./AsciiArtAnimation";
-import {
- Building2,
- Bot,
- ListTodo,
- Rocket,
- ArrowLeft,
- ArrowRight,
- Check,
- Loader2,
- ChevronDown,
- X
-} from "lucide-react";
-
-
-type Step = 1 | 2 | 3 | 4;
-type AdapterType = string;
-
-const DEFAULT_TASK_DESCRIPTION = `You are the CEO. You set the direction for the company.
-
-- hire a founding engineer
-- write a hiring plan
-- break the roadmap into concrete tasks and start delegating work`;
-
-/**
- * Classic onboarding wizard — fork-and-freeze of master's `OnboardingWizard`
- * (PAP-136 / PAP-138, plan §3 Tier B).
- *
- * Source: `git show master:ui/src/components/OnboardingWizard.tsx` at commit
- * 2e74d32871b3fbb1c57cfe5d373b323c8e6ee93a ("PAP-10430: split Issue-to-Task
- * copy migration (#7651)"). Only the component name was changed; everything
- * else is byte-identical so the flag-off experience stays pixel-identical to
- * master. Do NOT evolve this copy — it is rendered only while the
- * "Conference Room Chat" experimental flag is off and gets deleted when the
- * flag graduates or dies.
- */
-export function OnboardingWizardClassic() {
- const { onboardingOpen, onboardingOptions, closeOnboarding } = useDialog();
- const { companies, setSelectedCompanyId, loading: companiesLoading } = useCompany();
- const queryClient = useQueryClient();
- const navigate = useNavigate();
- const location = useLocation();
- const { companyPrefix } = useParams<{ companyPrefix?: string }>();
- const [routeDismissed, setRouteDismissed] = useState(false);
-
- // Sync disabled adapter types from server so adapter grid filters them out
- const disabledTypes = useDisabledAdaptersSync();
-
- const routeOnboardingOptions =
- companyPrefix && companiesLoading
- ? null
- : resolveRouteOnboardingOptions({
- pathname: location.pathname,
- companyPrefix,
- companies,
- });
- const effectiveOnboardingOpen =
- onboardingOpen || (routeOnboardingOptions !== null && !routeDismissed);
- const effectiveOnboardingOptions = onboardingOpen
- ? onboardingOptions
- : routeOnboardingOptions ?? {};
-
- const initialStep = effectiveOnboardingOptions.initialStep ?? 1;
- const existingCompanyId = effectiveOnboardingOptions.companyId;
-
- const [step, setStep] = useState<Step>(initialStep);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [modelOpen, setModelOpen] = useState(false);
- const [modelSearch, setModelSearch] = useState("");
-
- // Step 1
- const [companyName, setCompanyName] = useState("");
- const [companyGoal, setCompanyGoal] = useState("");
-
- // Step 2
- const [agentName, setAgentName] = useState("CEO");
- const [adapterType, setAdapterType] = useState<AdapterType>("claude_local");
- const [model, setModel] = useState("");
- const [command, setCommand] = useState("");
- const [args, setArgs] = useState("");
- const [url, setUrl] = useState("");
- const [adapterEnvResult, setAdapterEnvResult] =
- useState<AdapterEnvironmentTestResult | null>(null);
- const [adapterEnvError, setAdapterEnvError] = useState<string | null>(null);
- const [adapterEnvLoading, setAdapterEnvLoading] = useState(false);
- const [forceUnsetAnthropicApiKey, setForceUnsetAnthropicApiKey] =
- useState(false);
- const [unsetAnthropicLoading, setUnsetAnthropicLoading] = useState(false);
- const [showMoreAdapters, setShowMoreAdapters] = useState(false);
-
- // Step 3
- const [taskTitle, setTaskTitle] = useState(
- "Hire your first engineer and create a hiring plan"
- );
- const [taskDescription, setTaskDescription] = useState(
- DEFAULT_TASK_DESCRIPTION
- );
-
- // Auto-grow textarea for task description
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const autoResizeTextarea = useCallback(() => {
- const el = textareaRef.current;
- if (!el) return;
- el.style.height = "auto";
- el.style.height = el.scrollHeight + "px";
- }, []);
-
- // Created entity IDs — pre-populate from existing company when skipping step 1
- const [createdCompanyId, setCreatedCompanyId] = useState<string | null>(
- existingCompanyId ?? null
- );
- const [createdCompanyPrefix, setCreatedCompanyPrefix] = useState<
- string | null
- >(null);
- const [createdCompanyGoalId, setCreatedCompanyGoalId] = useState<string | null>(
- null
- );
- const [createdAgentId, setCreatedAgentId] = useState<string | null>(null);
- const [createdProjectId, setCreatedProjectId] = useState<string | null>(null);
- const [createdIssueRef, setCreatedIssueRef] = useState<string | null>(null);
-
- useEffect(() => {
- setRouteDismissed(false);
- }, [location.pathname]);
-
- // Sync step and company when onboarding opens with options.
- // Keep this independent from company-list refreshes so Step 1 completion
- // doesn't get reset after creating a company.
- useEffect(() => {
- if (!effectiveOnboardingOpen) return;
- const cId = effectiveOnboardingOptions.companyId ?? null;
- setStep(effectiveOnboardingOptions.initialStep ?? 1);
- setCreatedCompanyId(cId);
- setCreatedCompanyPrefix(null);
- setCreatedCompanyGoalId(null);
- setCreatedProjectId(null);
- setCreatedAgentId(null);
- setCreatedIssueRef(null);
- }, [
- effectiveOnboardingOpen,
- effectiveOnboardingOptions.companyId,
- effectiveOnboardingOptions.initialStep
- ]);
-
- // Backfill issue prefix for an existing company once companies are loaded.
- useEffect(() => {
- if (!effectiveOnboardingOpen || !createdCompanyId || createdCompanyPrefix) return;
- const company = companies.find((c) => c.id === createdCompanyId);
- if (company) setCreatedCompanyPrefix(company.issuePrefix);
- }, [effectiveOnboardingOpen, createdCompanyId, createdCompanyPrefix, companies]);
-
- // Resize textarea when step 3 is shown or description changes
- useEffect(() => {
- if (step === 3) autoResizeTextarea();
- }, [step, taskDescription, autoResizeTextarea]);
-
- const { data: adapterModels } = useQuery({
- // The wizard doesn't expose an environment selector, so models always
- // resolve against the local Paperclip host (environmentId = null).
- queryKey: createdCompanyId
- ? queryKeys.agents.adapterModels(createdCompanyId, adapterType, null)
- : ["agents", "none", "adapter-models", adapterType, null],
- queryFn: () => agentsApi.adapterModels(createdCompanyId!, adapterType, { environmentId: null }),
- enabled: Boolean(createdCompanyId) && effectiveOnboardingOpen && step === 2
- });
- const getCapabilities = useAdapterCapabilities();
- const adapterCaps = getCapabilities(adapterType);
- const isLocalAdapter = adapterCaps.supportsInstructionsBundle || adapterCaps.supportsSkills || adapterCaps.supportsLocalAgentJwt;
-
- // Build adapter grids dynamically from the UI registry + display metadata.
- // External/plugin adapters automatically appear with generic defaults.
- const { recommendedAdapters, moreAdapters } = useMemo(() => {
- const SYSTEM_ADAPTER_TYPES = new Set(["process", "http"]);
- const all = listUIAdapters()
- .filter((a) =>
- !SYSTEM_ADAPTER_TYPES.has(a.type) &&
- !disabledTypes.has(a.type) &&
- isVisualAdapterChoice(a.type)
- )
- .map((a) => ({ ...getAdapterDisplay(a.type), type: a.type }));
-
- return {
- recommendedAdapters: all.filter((a) => a.recommended),
- moreAdapters: all.filter((a) => !a.recommended),
- };
- }, [disabledTypes]);
- const COMMAND_PLACEHOLDERS: Record<string, string> = {
- claude_local: "claude",
- codex_local: "codex",
- gemini_local: "gemini",
- pi_local: "pi",
- cursor: "agent",
- opencode_local: "opencode",
- };
- const effectiveAdapterCommand =
- command.trim() ||
- (COMMAND_PLACEHOLDERS[adapterType] ?? adapterType.replace(/_local$/, ""));
-
- useEffect(() => {
- if (step !== 2) return;
- setAdapterEnvResult(null);
- setAdapterEnvError(null);
- }, [step, adapterType, model, command, args, url]);
-
- const selectedModel = (adapterModels ?? []).find((m) => m.id === model);
- const hasAnthropicApiKeyOverrideCheck =
- adapterEnvResult?.checks.some(
- (check) =>
- check.code === "claude_anthropic_api_key_overrides_subscription"
- ) ?? false;
- const shouldSuggestUnsetAnthropicApiKey =
- adapterType === "claude_local" &&
- adapterEnvResult?.status === "fail" &&
- hasAnthropicApiKeyOverrideCheck;
- const filteredModels = useMemo(() => {
- const query = modelSearch.trim().toLowerCase();
- return (adapterModels ?? []).filter((entry) => {
- if (!query) return true;
- const provider = extractProviderIdWithFallback(entry.id, "");
- return (
- entry.id.toLowerCase().includes(query) ||
- entry.label.toLowerCase().includes(query) ||
- provider.toLowerCase().includes(query)
- );
- });
- }, [adapterModels, modelSearch]);
- const groupedModels = useMemo(() => {
- if (adapterType !== "opencode_local") {
- return [
- {
- provider: "models",
- entries: [...filteredModels].sort((a, b) => a.id.localeCompare(b.id))
- }
- ];
- }
- const groups = new Map<string, Array<{ id: string; label: string }>>();
- for (const entry of filteredModels) {
- const provider = extractProviderIdWithFallback(entry.id);
- const bucket = groups.get(provider) ?? [];
- bucket.push(entry);
- groups.set(provider, bucket);
- }
- return Array.from(groups.entries())
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([provider, entries]) => ({
- provider,
- entries: [...entries].sort((a, b) => a.id.localeCompare(b.id))
- }));
- }, [filteredModels, adapterType]);
-
- function reset() {
- setStep(1);
- setLoading(false);
- setError(null);
- setCompanyName("");
- setCompanyGoal("");
- setAgentName("CEO");
- setAdapterType("claude_local");
- setModel("");
- setCommand("");
- setArgs("");
- setUrl("");
- setAdapterEnvResult(null);
- setAdapterEnvError(null);
- setAdapterEnvLoading(false);
- setForceUnsetAnthropicApiKey(false);
- setUnsetAnthropicLoading(false);
- setTaskTitle("Hire your first engineer and create a hiring plan");
- setTaskDescription(DEFAULT_TASK_DESCRIPTION);
- setCreatedCompanyId(null);
- setCreatedCompanyPrefix(null);
- setCreatedCompanyGoalId(null);
- setCreatedAgentId(null);
- setCreatedProjectId(null);
- setCreatedIssueRef(null);
- }
-
- function handleClose() {
- reset();
- closeOnboarding();
- }
-
- function buildAdapterConfig(): Record<string, unknown> {
- const adapter = getUIAdapter(adapterType);
- const config = adapter.buildAdapterConfig({
- ...defaultCreateValues,
- adapterType,
- model:
- adapterType === "codex_local"
- ? model || DEFAULT_CODEX_LOCAL_MODEL
- : adapterType === "gemini_local"
- ? model || DEFAULT_GEMINI_LOCAL_MODEL
- : adapterType === "cursor"
- ? model || DEFAULT_CURSOR_LOCAL_MODEL
- : adapterType === "opencode_local"
- ? model || DEFAULT_OPENCODE_LOCAL_MODEL
- : model,
- command,
- args,
- url,
- dangerouslySkipPermissions:
- adapterType === "claude_local" || adapterType === "opencode_local",
- dangerouslyBypassSandbox:
- adapterType === "codex_local"
- ? DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX
- : defaultCreateValues.dangerouslyBypassSandbox
- });
- if (adapterType === "claude_local" && forceUnsetAnthropicApiKey) {
- const env =
- typeof config.env === "object" &&
- config.env !== null &&
- !Array.isArray(config.env)
- ? { ...(config.env as Record<string, unknown>) }
- : {};
- env.ANTHROPIC_API_KEY = { type: "plain", value: "" };
- config.env = env;
- }
- return config;
- }
-
- async function runAdapterEnvironmentTest(
- adapterConfigOverride?: Record<string, unknown>
- ): Promise<AdapterEnvironmentTestResult | null> {
- if (!createdCompanyId) {
- setAdapterEnvError(
- "Create or select a company before testing adapter environment."
- );
- return null;
- }
- setAdapterEnvLoading(true);
- setAdapterEnvError(null);
- try {
- const result = await agentsApi.testEnvironment(
- createdCompanyId,
- adapterType,
- {
- adapterConfig: adapterConfigOverride ?? buildAdapterConfig()
- }
- );
- setAdapterEnvResult(result);
- return result;
- } catch (err) {
- setAdapterEnvError(
- err instanceof Error ? err.message : "Adapter environment test failed"
- );
- return null;
- } finally {
- setAdapterEnvLoading(false);
- }
- }
-
- async function handleStep1Next() {
- setLoading(true);
- setError(null);
- try {
- const company = await companiesApi.create({ name: companyName.trim() });
- setCreatedCompanyId(company.id);
- setCreatedCompanyPrefix(company.issuePrefix);
- setSelectedCompanyId(company.id);
- queryClient.invalidateQueries({ queryKey: queryKeys.companies.all });
-
- if (companyGoal.trim()) {
- const parsedGoal = parseOnboardingGoalInput(companyGoal);
- const goal = await goalsApi.create(company.id, {
- title: parsedGoal.title,
- ...(parsedGoal.description
- ? { description: parsedGoal.description }
- : {}),
- level: "company",
- status: "active"
- });
- setCreatedCompanyGoalId(goal.id);
- queryClient.invalidateQueries({
- queryKey: queryKeys.goals.list(company.id)
- });
- } else {
- setCreatedCompanyGoalId(null);
- }
-
- setStep(2);
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to create company");
- } finally {
- setLoading(false);
- }
- }
-
- async function handleStep2Next() {
- if (!createdCompanyId) return;
- setLoading(true);
- setError(null);
- try {
- if (adapterType === "opencode_local") {
- if (!isValidOpenCodeModelId(model)) {
- setError(
- "OpenCode requires an explicit model in provider/model format."
- );
- return;
- }
- }
-
- if (isLocalAdapter) {
- const result = adapterEnvResult ?? (await runAdapterEnvironmentTest());
- if (!result) return;
- }
-
- const hire = await agentsApi.hire(createdCompanyId, {
- name: agentName.trim(),
- role: "ceo",
- adapterType,
- adapterConfig: buildAdapterConfig(),
- runtimeConfig: buildNewAgentRuntimeConfig()
- });
- if (hire.approval) {
- await approvalsApi.approve(
- hire.approval.id,
- "Approved during onboarding first-agent setup."
- );
- queryClient.invalidateQueries({
- queryKey: queryKeys.approvals.list(createdCompanyId)
- });
- }
- const agent = hire.agent;
- setCreatedAgentId(agent.id);
- queryClient.invalidateQueries({
- queryKey: queryKeys.agents.list(createdCompanyId)
- });
- setStep(3);
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to create agent");
- } finally {
- setLoading(false);
- }
- }
-
- async function handleUnsetAnthropicApiKey() {
- if (!createdCompanyId || unsetAnthropicLoading) return;
- setUnsetAnthropicLoading(true);
- setError(null);
- setAdapterEnvError(null);
- setForceUnsetAnthropicApiKey(true);
-
- const configWithUnset = (() => {
- const config = buildAdapterConfig();
- const env =
- typeof config.env === "object" &&
- config.env !== null &&
- !Array.isArray(config.env)
- ? { ...(config.env as Record<string, unknown>) }
- : {};
- env.ANTHROPIC_API_KEY = { type: "plain", value: "" };
- config.env = env;
- return config;
- })();
-
- try {
- if (createdAgentId) {
- await agentsApi.update(
- createdAgentId,
- { adapterConfig: configWithUnset },
- createdCompanyId
- );
- queryClient.invalidateQueries({
- queryKey: queryKeys.agents.list(createdCompanyId)
- });
- }
-
- const result = await runAdapterEnvironmentTest(configWithUnset);
- if (result?.status === "fail") {
- setError(
- "Retried with ANTHROPIC_API_KEY unset in adapter config, but the environment test is still failing."
- );
- }
- } catch (err) {
- setError(
- err instanceof Error
- ? err.message
- : "Failed to unset ANTHROPIC_API_KEY and retry."
- );
- } finally {
- setUnsetAnthropicLoading(false);
- }
- }
-
- async function handleStep3Next() {
- if (!createdCompanyId || !createdAgentId) return;
- setError(null);
- setStep(4);
- }
-
- async function handleLaunch() {
- if (!createdCompanyId || !createdAgentId) return;
- setLoading(true);
- setError(null);
- try {
- let goalId = createdCompanyGoalId;
- if (!goalId) {
- const goals = await goalsApi.list(createdCompanyId);
- goalId = selectDefaultCompanyGoalId(goals);
- setCreatedCompanyGoalId(goalId);
- }
-
- let projectId = createdProjectId;
- if (!projectId) {
- const project = await projectsApi.create(
- createdCompanyId,
- buildOnboardingProjectPayload(goalId)
- );
- projectId = project.id;
- setCreatedProjectId(projectId);
- queryClient.invalidateQueries({
- queryKey: queryKeys.projects.list(createdCompanyId)
- });
- }
-
- let issueRef = createdIssueRef;
- if (!issueRef) {
- const issue = await issuesApi.create(
- createdCompanyId,
- buildOnboardingIssuePayload({
- title: taskTitle,
- description: taskDescription,
- assigneeAgentId: createdAgentId,
- projectId,
- goalId
- })
- );
- issueRef = issue.identifier ?? issue.id;
- setCreatedIssueRef(issueRef);
- queryClient.invalidateQueries({
- queryKey: queryKeys.issues.list(createdCompanyId)
- });
- }
-
- setSelectedCompanyId(createdCompanyId);
- reset();
- closeOnboarding();
- navigate(
- createdCompanyPrefix
- ? `/${createdCompanyPrefix}/issues/${issueRef}`
- : `/issues/${issueRef}`
- );
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to create task");
- } finally {
- setLoading(false);
- }
- }
-
- function handleKeyDown(e: React.KeyboardEvent) {
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- if (step === 1 && companyName.trim()) handleStep1Next();
- else if (step === 2 && agentName.trim()) handleStep2Next();
- else if (step === 3 && taskTitle.trim()) handleStep3Next();
- else if (step === 4) handleLaunch();
- }
- }
-
- if (!effectiveOnboardingOpen) return null;
-
- return (
- <Dialog
- open={effectiveOnboardingOpen}
- onOpenChange={(open) => {
- if (!open) {
- setRouteDismissed(true);
- handleClose();
- }
- }}
- >
- <DialogPortal>
- {/* Plain div instead of DialogOverlay — Radix's overlay wraps in
- RemoveScroll which blocks wheel events on our custom (non-DialogContent)
- scroll container. A plain div preserves the background without scroll-locking. */}
- <div className="fixed inset-0 z-50 bg-background" />
- <div className="fixed inset-0 z-50 flex" onKeyDown={handleKeyDown}>
- {/* Close button */}
- <button
- onClick={handleClose}
- className="absolute top-4 left-4 z-10 rounded-sm p-1.5 text-muted-foreground/60 hover:text-foreground transition-colors"
- >
- <X className="h-5 w-5" />
- <span className="sr-only">Close</span>
- </button>
-
- {/* Left half — form */}
- <div
- className={cn(
- "w-full flex flex-col overflow-y-auto transition-[width] duration-500 ease-in-out",
- step === 1 ? "md:w-1/2" : "md:w-full"
- )}
- >
- <div className="w-full max-w-md mx-auto my-auto px-8 py-12 shrink-0">
- {/* Progress tabs */}
- <div className="flex items-center gap-0 mb-8 border-b border-border">
- {(
- [
- { step: 1 as Step, label: "Company", icon: Building2 },
- { step: 2 as Step, label: "Agent", icon: Bot },
- { step: 3 as Step, label: "Task", icon: ListTodo },
- { step: 4 as Step, label: "Launch", icon: Rocket }
- ] as const
- ).map(({ step: s, label, icon: Icon }) => (
- <button
- key={s}
- type="button"
- onClick={() => setStep(s)}
- className={cn(
- "flex items-center gap-1.5 px-3 py-2 text-xs font-medium border-b-2 -mb-px transition-colors cursor-pointer",
- s === step
- ? "border-foreground text-foreground"
- : "border-transparent text-muted-foreground hover:text-foreground/70 hover:border-border"
- )}
- >
- <Icon className="h-3.5 w-3.5" />
- {label}
- </button>
- ))}
- </div>
-
- {/* Step content */}
- {step === 1 && (
- <div className="space-y-5">
- <div className="flex items-center gap-3 mb-1">
- <div className="bg-muted/50 p-2">
- <Building2 className="h-5 w-5 text-muted-foreground" />
- </div>
- <div>
- <h3 className="font-medium">Name your company</h3>
- <p className="text-xs text-muted-foreground">
- This is the organization your agents will work for.
- </p>
- </div>
- </div>
- <div className="mt-3 group">
- <label
- className={cn(
- "text-xs mb-1 block transition-colors",
- companyName.trim()
- ? "text-foreground"
- : "text-muted-foreground group-focus-within:text-foreground"
- )}
- >
- Company name
- </label>
- <input
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
- placeholder="Acme Corp"
- value={companyName}
- onChange={(e) => setCompanyName(e.target.value)}
- autoFocus
- />
- </div>
- <div className="group">
- <label
- className={cn(
- "text-xs mb-1 block transition-colors",
- companyGoal.trim()
- ? "text-foreground"
- : "text-muted-foreground group-focus-within:text-foreground"
- )}
- >
- Mission / goal (optional)
- </label>
- <textarea
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50 resize-none min-h-[60px]"
- placeholder="What is this company trying to achieve?"
- value={companyGoal}
- onChange={(e) => setCompanyGoal(e.target.value)}
- />
- </div>
- </div>
- )}
-
- {step === 2 && (
- <div className="space-y-5">
- <div className="flex items-center gap-3 mb-1">
- <div className="bg-muted/50 p-2">
- <Bot className="h-5 w-5 text-muted-foreground" />
- </div>
- <div>
- <h3 className="font-medium">Create your first agent</h3>
- <p className="text-xs text-muted-foreground">
- Choose how this agent will run tasks.
- </p>
- </div>
- </div>
- <div>
- <label className="text-xs text-muted-foreground mb-1 block">
- Agent name
- </label>
- <input
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
- placeholder="CEO"
- value={agentName}
- onChange={(e) => setAgentName(e.target.value)}
- autoFocus
- />
- </div>
-
- {/* Adapter type radio cards */}
- <div>
- <label className="text-xs text-muted-foreground mb-2 block">
- Adapter type
- </label>
- <div className="grid grid-cols-2 gap-2">
- {recommendedAdapters.map((opt) => (
- <button
- key={opt.type}
- className={cn(
- "flex flex-col items-center gap-1.5 rounded-md border p-3 text-xs transition-colors relative",
- adapterType === opt.type
- ? "border-foreground bg-accent"
- : "border-border hover:bg-accent/50"
- )}
- onClick={() => {
- const nextType = opt.type;
- setAdapterType(nextType);
- if (nextType === "codex_local") {
- if (!model) {
- setModel(DEFAULT_CODEX_LOCAL_MODEL);
- }
- return;
- }
- if (nextType === "opencode_local") {
- setModel(DEFAULT_OPENCODE_LOCAL_MODEL);
- return;
- }
- setModel("");
- }}
- >
- {opt.recommended && (
- <span className="absolute -top-1.5 right-1.5 bg-green-500 text-white text-[9px] font-semibold px-1.5 py-0.5 rounded-full leading-none">
- Recommended
- </span>
- )}
- <opt.icon className="h-4 w-4" />
- <span className="font-medium">{opt.label}</span>
- <span className="text-muted-foreground text-[10px]">
- {opt.description}
- </span>
- </button>
- ))}
- </div>
-
- <button
- className="flex items-center gap-1.5 mt-3 text-xs text-muted-foreground hover:text-foreground transition-colors"
- onClick={() => setShowMoreAdapters((v) => !v)}
- >
- <ChevronDown
- className={cn(
- "h-3 w-3 transition-transform",
- showMoreAdapters ? "rotate-0" : "-rotate-90"
- )}
- />
- More Agent Adapter Types
- </button>
-
- {showMoreAdapters && (
- <div className="grid grid-cols-2 gap-2 mt-2">
- {moreAdapters.map((opt) => (
- <button
- key={opt.type}
- disabled={!!opt.comingSoon}
- className={cn(
- "flex flex-col items-center gap-1.5 rounded-md border p-3 text-xs transition-colors relative",
- opt.comingSoon
- ? "border-border opacity-40 cursor-not-allowed"
- : adapterType === opt.type
- ? "border-foreground bg-accent"
- : "border-border hover:bg-accent/50"
- )}
- onClick={() => {
- if (opt.comingSoon) return;
- const nextType = opt.type;
- setAdapterType(nextType);
- if (nextType === "gemini_local" && !model) {
- setModel(DEFAULT_GEMINI_LOCAL_MODEL);
- return;
- }
- if (nextType === "cursor" && !model) {
- setModel(DEFAULT_CURSOR_LOCAL_MODEL);
- return;
- }
- if (nextType === "opencode_local") {
- setModel(DEFAULT_OPENCODE_LOCAL_MODEL);
- return;
- }
- setModel("");
- }}
- >
- <opt.icon className="h-4 w-4" />
- <span className="font-medium">{opt.label}</span>
- <span className="text-muted-foreground text-[10px]">
- {opt.comingSoon
- ? opt.disabledLabel ?? "Coming soon"
- : opt.description}
- </span>
- </button>
- ))}
- </div>
- )}
- </div>
-
- {/* Conditional adapter fields */}
- {isLocalAdapter && (
- <div className="space-y-3">
- <div>
- <label className="text-xs text-muted-foreground mb-1 block">
- Model
- </label>
- <Popover
- open={modelOpen}
- onOpenChange={(next) => {
- setModelOpen(next);
- if (!next) setModelSearch("");
- }}
- >
- <PopoverTrigger asChild>
- <button className="inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-sm hover:bg-accent/50 transition-colors w-full justify-between">
- <span
- className={cn(
- !model && "text-muted-foreground"
- )}
- >
- {selectedModel
- ? selectedModel.label
- : model ||
- (adapterType === "opencode_local"
- ? "Select model (required)"
- : "Default")}
- </span>
- <ChevronDown className="h-3 w-3 text-muted-foreground" />
- </button>
- </PopoverTrigger>
- <PopoverContent
- className="w-[var(--radix-popover-trigger-width)] p-1"
- align="start"
- >
- <input
- className="w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50"
- placeholder="Search models..."
- value={modelSearch}
- onChange={(e) => setModelSearch(e.target.value)}
- autoFocus
- />
- {adapterType !== "opencode_local" && (
- <button
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",
- !model && "bg-accent"
- )}
- onClick={() => {
- setModel("");
- setModelOpen(false);
- }}
- >
- Default
- </button>
- )}
- <div className="max-h-[240px] overflow-y-auto">
- {groupedModels.map((group) => (
- <div
- key={group.provider}
- className="mb-1 last:mb-0"
- >
- {adapterType === "opencode_local" && (
- <div className="px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground">
- {group.provider} ({group.entries.length})
- </div>
- )}
- {group.entries.map((m) => (
- <button
- key={m.id}
- className={cn(
- "flex items-center w-full px-2 py-1.5 text-sm rounded hover:bg-accent/50",
- m.id === model && "bg-accent"
- )}
- onClick={() => {
- setModel(m.id);
- setModelOpen(false);
- }}
- >
- <span
- className="block w-full text-left truncate"
- title={m.id}
- >
- {adapterType === "opencode_local"
- ? extractModelName(m.id)
- : m.label}
- </span>
- </button>
- ))}
- </div>
- ))}
- </div>
- {filteredModels.length === 0 && (
- <p className="px-2 py-1.5 text-xs text-muted-foreground">
- No models discovered.
- </p>
- )}
- </PopoverContent>
- </Popover>
- </div>
- </div>
- )}
-
- {isLocalAdapter && (
- <div className="space-y-2 rounded-md border border-border p-3">
- <div className="flex items-center justify-between gap-2">
- <div>
- <p className="text-xs font-medium">
- Adapter environment check
- </p>
- <p className="text-[11px] text-muted-foreground">
- Runs a live probe that asks the adapter CLI to
- respond with hello.
- </p>
- </div>
- <Button
- size="sm"
- variant="outline"
- className="h-7 px-2.5 text-xs"
- disabled={adapterEnvLoading}
- onClick={() => void runAdapterEnvironmentTest()}
- >
- {adapterEnvLoading ? "Testing..." : "Test now"}
- </Button>
- </div>
-
- {adapterEnvError && (
- <div className="rounded-md border border-destructive/30 bg-destructive/10 px-2.5 py-2 text-[11px] text-destructive">
- {adapterEnvError}
- </div>
- )}
-
- {adapterEnvResult &&
- adapterEnvResult.status === "pass" ? (
- <div className="flex items-center gap-2 rounded-md border border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10 px-3 py-2 text-xs text-green-700 dark:text-green-300 animate-in fade-in slide-in-from-bottom-1 duration-300">
- <Check className="h-3.5 w-3.5 shrink-0" />
- <span className="font-medium">Passed</span>
- </div>
- ) : adapterEnvResult ? (
- <AdapterEnvironmentResult result={adapterEnvResult} />
- ) : null}
-
- {shouldSuggestUnsetAnthropicApiKey && (
- <div className="rounded-md border border-amber-300/60 bg-amber-50/40 px-2.5 py-2 space-y-2">
- <p className="text-[11px] text-amber-900/90 leading-relaxed">
- Claude failed while{" "}
- <span className="font-mono">ANTHROPIC_API_KEY</span>{" "}
- is set. You can clear it in this CEO adapter config
- and retry the probe.
- </p>
- <Button
- size="sm"
- variant="outline"
- className="h-7 px-2.5 text-xs"
- disabled={
- adapterEnvLoading || unsetAnthropicLoading
- }
- onClick={() => void handleUnsetAnthropicApiKey()}
- >
- {unsetAnthropicLoading
- ? "Retrying..."
- : "Unset ANTHROPIC_API_KEY"}
- </Button>
- </div>
- )}
-
- {adapterEnvResult && adapterEnvResult.status === "fail" && (
- <div className="rounded-md border border-border/70 bg-muted/20 px-2.5 py-2 text-[11px] space-y-1.5">
- <p className="font-medium">Manual debug</p>
- <p className="text-muted-foreground font-mono break-all">
- {adapterType === "cursor"
- ? `${effectiveAdapterCommand} -p --mode ask --output-format json \"Respond with hello.\"`
- : adapterType === "codex_local"
- ? `${effectiveAdapterCommand} exec --json -`
- : adapterType === "gemini_local"
- ? `${effectiveAdapterCommand} --output-format json "Respond with hello."`
- : adapterType === "opencode_local"
- ? `${effectiveAdapterCommand} run --format json "Respond with hello."`
- : `${effectiveAdapterCommand} --print - --output-format stream-json --verbose`}
- </p>
- <p className="text-muted-foreground">
- Prompt:{" "}
- <span className="font-mono">Respond with hello.</span>
- </p>
- {adapterType === "cursor" ||
- adapterType === "codex_local" ||
- adapterType === "gemini_local" ||
- adapterType === "opencode_local" ? (
- <p className="text-muted-foreground">
- If auth fails, set{" "}
- <span className="font-mono">
- {adapterType === "cursor"
- ? "CURSOR_API_KEY"
- : adapterType === "gemini_local"
- ? "GEMINI_API_KEY"
- : "OPENAI_API_KEY"}
- </span>{" "}
- in env or run{" "}
- <span className="font-mono">
- {adapterType === "cursor"
- ? "agent login"
- : adapterType === "codex_local"
- ? "codex login"
- : adapterType === "gemini_local"
- ? "gemini auth"
- : "opencode auth login"}
- </span>
- .
- </p>
- ) : (
- <p className="text-muted-foreground">
- If login is required, run{" "}
- <span className="font-mono">claude login</span>{" "}
- and retry.
- </p>
- )}
- </div>
- )}
- </div>
- )}
-
- {(adapterType === "http" ||
- adapterType === "openclaw_gateway") && (
- <div>
- <label className="text-xs text-muted-foreground mb-1 block">
- {adapterType === "openclaw_gateway"
- ? "Gateway URL"
- : "Webhook URL"}
- </label>
- <input
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
- placeholder={
- adapterType === "openclaw_gateway"
- ? "ws://127.0.0.1:18789"
- : "https://..."
- }
- value={url}
- onChange={(e) => setUrl(e.target.value)}
- />
- </div>
- )}
- </div>
- )}
-
- {step === 3 && (
- <div className="space-y-5">
- <div className="flex items-center gap-3 mb-1">
- <div className="bg-muted/50 p-2">
- <ListTodo className="h-5 w-5 text-muted-foreground" />
- </div>
- <div>
- <h3 className="font-medium">Give it something to do</h3>
- <p className="text-xs text-muted-foreground">
- Give your agent a small task to start with — a bug fix,
- a research question, writing a script.
- </p>
- </div>
- </div>
- <div>
- <label className="text-xs text-muted-foreground mb-1 block">
- Task title
- </label>
- <input
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50"
- placeholder="e.g. Research competitor pricing"
- value={taskTitle}
- onChange={(e) => setTaskTitle(e.target.value)}
- autoFocus
- />
- </div>
- <div>
- <label className="text-xs text-muted-foreground mb-1 block">
- Description (optional)
- </label>
- <textarea
- ref={textareaRef}
- className="w-full rounded-md border border-border bg-transparent px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-ring placeholder:text-muted-foreground/50 resize-none min-h-[120px] max-h-[300px] overflow-y-auto"
- placeholder="Add more detail about what the agent should do..."
- value={taskDescription}
- onChange={(e) => setTaskDescription(e.target.value)}
- />
- </div>
- </div>
- )}
-
- {step === 4 && (
- <div className="space-y-5">
- <div className="flex items-center gap-3 mb-1">
- <div className="bg-muted/50 p-2">
- <Rocket className="h-5 w-5 text-muted-foreground" />
- </div>
- <div>
- <h3 className="font-medium">Ready to launch</h3>
- <p className="text-xs text-muted-foreground">
- Everything is set up. Launching now will create the
- starter task, wake the agent, and open the task.
- </p>
- </div>
- </div>
- <div className="border border-border divide-y divide-border">
- <div className="flex items-center gap-3 px-3 py-2.5">
- <Building2 className="h-4 w-4 text-muted-foreground shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {companyName}
- </p>
- <p className="text-xs text-muted-foreground">Company</p>
- </div>
- <Check className="h-4 w-4 text-green-500 shrink-0" />
- </div>
- <div className="flex items-center gap-3 px-3 py-2.5">
- <Bot className="h-4 w-4 text-muted-foreground shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {agentName}
- </p>
- <p className="text-xs text-muted-foreground">
- {getUIAdapter(adapterType).label}
- </p>
- </div>
- <Check className="h-4 w-4 text-green-500 shrink-0" />
- </div>
- <div className="flex items-center gap-3 px-3 py-2.5">
- <ListTodo className="h-4 w-4 text-muted-foreground shrink-0" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium truncate">
- {taskTitle}
- </p>
- <p className="text-xs text-muted-foreground">Task</p>
- </div>
- <Check className="h-4 w-4 text-green-500 shrink-0" />
- </div>
- </div>
- </div>
- )}
-
- {/* Error */}
- {error && (
- <div className="mt-3">
- <p className="text-xs text-destructive">{error}</p>
- </div>
- )}
-
- {/* Footer navigation */}
- <div className="flex items-center justify-between mt-8">
- <div>
- {step > 1 && step > (onboardingOptions.initialStep ?? 1) && (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setStep((step - 1) as Step)}
- disabled={loading}
- >
- <ArrowLeft className="h-3.5 w-3.5 mr-1" />
- Back
- </Button>
- )}
- </div>
- <div className="flex items-center gap-2">
- {step === 1 && (
- <Button
- size="sm"
- disabled={!companyName.trim() || loading}
- onClick={handleStep1Next}
- >
- {loading ? (
- <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
- ) : (
- <ArrowRight className="h-3.5 w-3.5 mr-1" />
- )}
- {loading ? "Creating..." : "Next"}
- </Button>
- )}
- {step === 2 && (
- <Button
- size="sm"
- disabled={
- !agentName.trim() || loading || adapterEnvLoading
- }
- onClick={handleStep2Next}
- >
- {loading ? (
- <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
- ) : (
- <ArrowRight className="h-3.5 w-3.5 mr-1" />
- )}
- {loading ? "Creating..." : "Next"}
- </Button>
- )}
- {step === 3 && (
- <Button
- size="sm"
- disabled={!taskTitle.trim() || loading}
- onClick={handleStep3Next}
- >
- {loading ? (
- <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
- ) : (
- <ArrowRight className="h-3.5 w-3.5 mr-1" />
- )}
- {loading ? "Creating..." : "Next"}
- </Button>
- )}
- {step === 4 && (
- <Button size="sm" disabled={loading} onClick={handleLaunch}>
- {loading ? (
- <Loader2 className="h-3.5 w-3.5 mr-1 animate-spin" />
- ) : (
- <ArrowRight className="h-3.5 w-3.5 mr-1" />
- )}
- {loading ? "Creating..." : "Create & Open Task"}
- </Button>
- )}
- </div>
- </div>
- </div>
- </div>
-
- {/* Right half — ASCII art (hidden on mobile) */}
- <div
- className={cn(
- "hidden md:block overflow-hidden bg-[#1d1d1d] transition-[width,opacity] duration-500 ease-in-out",
- step === 1 ? "w-1/2 opacity-100" : "w-0 opacity-0"
- )}
- >
- <AsciiArtAnimation />
- </div>
- </div>
- </DialogPortal>
- </Dialog>
- );
-}
-
-function AdapterEnvironmentResult({
- result
-}: {
- result: AdapterEnvironmentTestResult;
-}) {
- const statusLabel =
- result.status === "pass"
- ? "Passed"
- : result.status === "warn"
- ? "Warnings"
- : "Failed";
- const statusClass =
- result.status === "pass"
- ? "text-green-700 dark:text-green-300 border-green-300 dark:border-green-500/40 bg-green-50 dark:bg-green-500/10"
- : result.status === "warn"
- ? "text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-500/40 bg-amber-50 dark:bg-amber-500/10"
- : "text-red-700 dark:text-red-300 border-red-300 dark:border-red-500/40 bg-red-50 dark:bg-red-500/10";
-
- return (
- <div className={`rounded-md border px-2.5 py-2 text-[11px] ${statusClass}`}>
- <div className="flex items-center justify-between gap-2">
- <span className="font-medium">{statusLabel}</span>
- <span className="opacity-80">
- {new Date(result.testedAt).toLocaleTimeString()}
- </span>
- </div>
- <div className="mt-1.5 space-y-1">
- {result.checks.map((check, idx) => (
- <div
- key={`${check.code}-${idx}`}
- className="leading-relaxed break-words"
- >
- <span className="font-medium uppercase tracking-wide opacity-80">
- {check.level}
- </span>
- <span className="mx-1 opacity-60">·</span>
- <span>{check.message}</span>
- {check.detail && (
- <span className="block opacity-75 break-all">
- ({check.detail})
- </span>
- )}
- {check.hint && (
- <span className="block opacity-90 break-words">
- Hint: {check.hint}
- </span>
- )}
- </div>
- ))}
- </div>
- </div>
- );
-}
diff --git a/ui/src/components/OnboardingWizardVariant.test.tsx b/ui/src/components/OnboardingWizardVariant.test.tsx
index 0c865e285f..0381e60698 100644
--- a/ui/src/components/OnboardingWizardVariant.test.tsx
+++ b/ui/src/components/OnboardingWizardVariant.test.tsx
@@ -2,7 +2,6 @@
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { OnboardingWizardVariant } from "./OnboardingWizardVariant";
@@ -14,41 +13,19 @@ vi.mock("@/api/instanceSettings", () => ({
instanceSettingsApi: mockInstanceSettingsApi,
}));
-// The variant wrapper only cares about *which* wizard renders, so both heavy
-// wizard components are stubbed out.
vi.mock("./OnboardingWizard", () => ({
OnboardingWizard: () => <div data-testid="wizard-capsule" />,
}));
-vi.mock("./OnboardingWizardClassic", () => ({
- OnboardingWizardClassic: () => <div data-testid="wizard-classic" />,
-}));
-
-async function flushReact() {
- for (let index = 0; index < 5; index += 1) {
- await Promise.resolve();
- await new Promise((resolve) => window.setTimeout(resolve, 0));
- }
- flushSync(() => {});
-}
-
describe("OnboardingWizardVariant (PAP-138)", () => {
let container: HTMLDivElement;
let root: Root | null = null;
- async function renderVariant() {
+ function renderVariant() {
root = createRoot(container);
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
flushSync(() => {
- root!.render(
- <QueryClientProvider client={queryClient}>
- <OnboardingWizardVariant />
- </QueryClientProvider>,
- );
+ root!.render(<OnboardingWizardVariant />);
});
- await flushReact();
}
beforeEach(() => {
@@ -65,35 +42,11 @@ describe("OnboardingWizardVariant (PAP-138)", () => {
vi.clearAllMocks();
});
- it("renders the classic wizard when the flag is off (default)", async () => {
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableConferenceRoomChat: false });
- await renderVariant();
-
- expect(container.querySelector('[data-testid="wizard-classic"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="wizard-capsule"]')).toBeNull();
- });
-
- it("renders the capsule wizard when the flag is on", async () => {
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableConferenceRoomChat: true });
- await renderVariant();
-
- expect(container.querySelector('[data-testid="wizard-capsule"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="wizard-classic"]')).toBeNull();
- });
-
- it("renders the classic wizard when the settings payload omits the flag", async () => {
+ it("renders the capsule wizard without reading the chat flag", () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({});
- await renderVariant();
+ renderVariant();
- expect(container.querySelector('[data-testid="wizard-classic"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="wizard-capsule"]')).toBeNull();
- });
-
- it("renders neither wizard while the flag is still loading (no cross-variant flash)", async () => {
- mockInstanceSettingsApi.getExperimental.mockImplementation(() => new Promise(() => {}));
- await renderVariant();
-
- expect(container.querySelector('[data-testid="wizard-classic"]')).toBeNull();
- expect(container.querySelector('[data-testid="wizard-capsule"]')).toBeNull();
+ expect(container.querySelector('[data-testid="wizard-capsule"]')).not.toBeNull();
+ expect(mockInstanceSettingsApi.getExperimental).not.toHaveBeenCalled();
});
});
diff --git a/ui/src/components/OnboardingWizardVariant.tsx b/ui/src/components/OnboardingWizardVariant.tsx
index fa8135dc7b..a6a6ee3cc0 100644
--- a/ui/src/components/OnboardingWizardVariant.tsx
+++ b/ui/src/components/OnboardingWizardVariant.tsx
@@ -1,20 +1,10 @@
-import { useConferenceRoomChatEnabled } from "@/hooks/useConferenceRoomChatEnabled";
import { OnboardingWizard } from "./OnboardingWizard";
-import { OnboardingWizardClassic } from "./OnboardingWizardClassic";
/**
- * Variant selector for the onboarding wizard (PAP-136 / PAP-138, plan §3
- * Tier B).
- *
- * Flag off (the default) renders `OnboardingWizardClassic` — the
- * fork-and-freeze of master's wizard — so the experience stays
- * pixel-identical to master. Flag on renders the new capsule wizard. While
- * the flag query is still in flight nothing renders (same `loaded` pattern
- * as `ConferenceRoomChatGate`) so a flag-on user never sees the classic
- * wizard flash in first.
+ * Default onboarding wizard. Conference-room chat is now the only surface left
+ * behind `enableConferenceRoomChat`; onboarding stays available without that
+ * experimental flag.
*/
export function OnboardingWizardVariant() {
- const { enabled, loaded } = useConferenceRoomChatEnabled();
- if (!loaded) return null;
- return enabled ? <OnboardingWizard /> : <OnboardingWizardClassic />;
+ return <OnboardingWizard />;
}
diff --git a/ui/src/components/RunChatSurface.test.tsx b/ui/src/components/RunChatSurface.test.tsx
index 938b095c2a..6d64227ac3 100644
--- a/ui/src/components/RunChatSurface.test.tsx
+++ b/ui/src/components/RunChatSurface.test.tsx
@@ -1,30 +1,15 @@
// @vitest-environment jsdom
-import { act } from "react";
+import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LiveRunForIssue } from "../api/heartbeats";
import { RunChatSurface } from "./RunChatSurface";
-/**
- * PAP-139: RunChatSurface (embedded run chat in ActiveAgentsPanel /
- * LiveRunWidget) selects the thread variant by the Conference Room Chat
- * experimental flag — NUX thread when ON, the frozen master fork when OFF.
- */
-
-const conferenceRoomChatFlag = vi.hoisted(() => ({ enabled: true }));
-vi.mock("../hooks/useConferenceRoomChatEnabled", () => ({
- useConferenceRoomChatEnabled: () => ({ enabled: conferenceRoomChatFlag.enabled, loaded: true }),
-}));
-
vi.mock("./IssueChatThread", () => ({
IssueChatThread: () => <div data-testid="nux-thread">NUX thread</div>,
}));
-vi.mock("./IssueChatThreadClassic", () => ({
- IssueChatThreadClassic: () => <div data-testid="classic-thread">Classic thread</div>,
-}));
-
const run: LiveRunForIssue = {
id: "run-1",
status: "running",
@@ -35,17 +20,21 @@ const run: LiveRunForIssue = {
finishedAt: null,
} as LiveRunForIssue;
+function act(callback: () => void) {
+ flushSync(callback);
+}
+
async function renderSurface() {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
- await act(async () => {
+ act(() => {
root.render(<RunChatSurface run={run} transcript={[]} hasOutput={false} />);
});
return {
container,
- cleanup: async () => {
- await act(async () => {
+ cleanup: () => {
+ act(() => {
root.unmount();
});
container.remove();
@@ -54,23 +43,13 @@ async function renderSurface() {
}
afterEach(() => {
- conferenceRoomChatFlag.enabled = true;
document.body.innerHTML = "";
});
-describe("RunChatSurface thread variant selection (PAP-139)", () => {
- it("renders the NUX thread when the Conference Room Chat flag is on", async () => {
+describe("RunChatSurface thread presentation", () => {
+ it("renders the graduated issue thread without a chat-flag branch", async () => {
const { container, cleanup } = await renderSurface();
expect(container.querySelector('[data-testid="nux-thread"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="classic-thread"]')).toBeNull();
- await cleanup();
- });
-
- it("renders the frozen master fork when the flag is off", async () => {
- conferenceRoomChatFlag.enabled = false;
- const { container, cleanup } = await renderSurface();
- expect(container.querySelector('[data-testid="classic-thread"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="nux-thread"]')).toBeNull();
await cleanup();
});
});
diff --git a/ui/src/components/RunChatSurface.tsx b/ui/src/components/RunChatSurface.tsx
index 9830bc3445..99e386e0b3 100644
--- a/ui/src/components/RunChatSurface.tsx
+++ b/ui/src/components/RunChatSurface.tsx
@@ -2,8 +2,6 @@ import { memo, useMemo } from "react";
import type { TranscriptEntry } from "../adapters";
import type { LiveRunForIssue } from "../api/heartbeats";
import { IssueChatThread } from "./IssueChatThread";
-import { IssueChatThreadClassic } from "./IssueChatThreadClassic";
-import { useConferenceRoomChatEnabled } from "../hooks/useConferenceRoomChatEnabled";
import type { IssueChatLinkedRun } from "../lib/issue-chat-messages";
const EMPTY_COMMENTS: [] = [];
@@ -50,13 +48,8 @@ export const RunChatSurface = memo(function RunChatSurface({
() => new Map([[run.id, transcript as readonly TranscriptEntry[]]]),
[run.id, transcript],
);
- // Conference Room Chat experimental flag (PAP-136/PAP-139): OFF renders the
- // frozen master fork so embedded run chat looks exactly like master.
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
- const ThreadComponent = conferenceRoomChatEnabled ? IssueChatThread : IssueChatThreadClassic;
-
return (
- <ThreadComponent
+ <IssueChatThread
comments={EMPTY_COMMENTS}
linkedRuns={linkedRuns}
timelineEvents={EMPTY_TIMELINE_EVENTS}
diff --git a/ui/src/components/SidebarCompanyMenu.test.tsx b/ui/src/components/SidebarCompanyMenu.test.tsx
index a84683d726..3b4341b1ef 100644
--- a/ui/src/components/SidebarCompanyMenu.test.tsx
+++ b/ui/src/components/SidebarCompanyMenu.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
-import { act } from "react";
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -24,14 +25,6 @@ const mockSidebarPreferencesApi = vi.hoisted(() => ({
updateCompanyOrder: vi.fn(),
}));
-// Team-centric copy ("Create new team...") ships behind the Conference Room
-// Chat experimental flag (PAP-139). This suite was written against the NUX
-// copy, so the flag is seeded ON; one test flips it OFF for master's copy.
-const conferenceRoomChatFlag = vi.hoisted(() => ({ enabled: true }));
-vi.mock("@/hooks/useConferenceRoomChatEnabled", () => ({
- useConferenceRoomChatEnabled: () => ({ enabled: conferenceRoomChatFlag.enabled, loaded: true }),
-}));
-
vi.mock("@/api/auth", () => ({
authApi: mockAuthApi,
}));
@@ -41,7 +34,7 @@ vi.mock("@/api/sidebarPreferences", () => ({
}));
vi.mock("@/lib/router", () => ({
- Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
+ Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
<a href={to} {...props}>{children}</a>
),
useLocation: () => mockLocation,
@@ -106,11 +99,13 @@ vi.mock("../context/SidebarContext", () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+function act(callback: () => void) {
+ flushSync(callback);
+}
+
async function flushReact() {
- await act(async () => {
- await Promise.resolve();
- await new Promise((resolve) => window.setTimeout(resolve, 0));
- });
+ await Promise.resolve();
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
}
describe("SidebarCompanyMenu", () => {
@@ -143,17 +138,15 @@ describe("SidebarCompanyMenu", () => {
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
- conferenceRoomChatFlag.enabled = true;
});
- it("keeps master's 'Add company...' copy when the Conference Room Chat flag is off (PAP-139)", async () => {
- conferenceRoomChatFlag.enabled = false;
+ it("uses team-centric create copy without the chat flag", async () => {
const root = createRoot(container);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
- await act(async () => {
+ act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<SidebarCompanyMenu />
@@ -165,16 +158,16 @@ describe("SidebarCompanyMenu", () => {
const trigger = container.querySelector('button[aria-label="Open Acme Labs workspace switcher"]');
expect(trigger).not.toBeNull();
- await act(async () => {
+ act(() => {
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
- expect(document.body.textContent).toContain("Add company...");
- expect(document.body.textContent).not.toContain("Create new team...");
+ expect(document.body.textContent).toContain("Create new team...");
+ expect(document.body.textContent).not.toContain("Add company...");
- await act(async () => {
+ act(() => {
root.unmount();
});
});
@@ -185,7 +178,7 @@ describe("SidebarCompanyMenu", () => {
defaultOptions: { queries: { retry: false } },
});
- await act(async () => {
+ act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<SidebarCompanyMenu />
@@ -200,7 +193,7 @@ describe("SidebarCompanyMenu", () => {
const trigger = container.querySelector('button[aria-label="Open Acme Labs workspace switcher"]');
expect(trigger).not.toBeNull();
- await act(async () => {
+ act(() => {
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
@@ -219,14 +212,14 @@ describe("SidebarCompanyMenu", () => {
.find((element) => element.textContent?.includes("Sign out"));
expect(signOutButton).toBeTruthy();
- await act(async () => {
+ act(() => {
signOutButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
expect(mockAuthApi.signOut).toHaveBeenCalledTimes(1);
- await act(async () => {
+ act(() => {
root.unmount();
});
});
@@ -237,7 +230,7 @@ describe("SidebarCompanyMenu", () => {
defaultOptions: { queries: { retry: false } },
});
- await act(async () => {
+ act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<SidebarCompanyMenu />
@@ -250,7 +243,7 @@ describe("SidebarCompanyMenu", () => {
const trigger = container.querySelector('button[aria-label="Open Acme Labs workspace switcher"]');
expect(trigger).not.toBeNull();
- await act(async () => {
+ act(() => {
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
@@ -260,7 +253,7 @@ describe("SidebarCompanyMenu", () => {
.find((element) => element.textContent === "Edit");
expect(editButton).toBeTruthy();
- await act(async () => {
+ act(() => {
editButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
@@ -274,7 +267,7 @@ describe("SidebarCompanyMenu", () => {
.find((element) => element.textContent?.includes("Strata"));
expect(strataItem).toBeTruthy();
- await act(async () => {
+ act(() => {
strataItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
@@ -282,7 +275,7 @@ describe("SidebarCompanyMenu", () => {
expect(mockSetSelectedCompanyId).not.toHaveBeenCalled();
expect(mockNavigate).not.toHaveBeenCalled();
- await act(async () => {
+ act(() => {
root.unmount();
});
});
@@ -294,7 +287,7 @@ describe("SidebarCompanyMenu", () => {
defaultOptions: { queries: { retry: false } },
});
- await act(async () => {
+ act(() => {
root.render(
<QueryClientProvider client={queryClient}>
<SidebarCompanyMenu />
@@ -307,7 +300,7 @@ describe("SidebarCompanyMenu", () => {
const trigger = container.querySelector('button[aria-label="Open Acme Labs workspace switcher"]');
expect(trigger).not.toBeNull();
- await act(async () => {
+ act(() => {
trigger?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0 }));
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
@@ -317,7 +310,7 @@ describe("SidebarCompanyMenu", () => {
.find((element) => element.textContent?.includes("Strata"));
expect(strataItem).toBeTruthy();
- await act(async () => {
+ act(() => {
strataItem?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
});
await flushReact();
@@ -325,7 +318,7 @@ describe("SidebarCompanyMenu", () => {
expect(mockSetSelectedCompanyId).toHaveBeenCalledWith("company-2");
expect(mockNavigate).toHaveBeenCalledWith("/STR/dashboard");
- await act(async () => {
+ act(() => {
root.unmount();
});
});
diff --git a/ui/src/components/SidebarCompanyMenu.tsx b/ui/src/components/SidebarCompanyMenu.tsx
index 48ca28ad1c..87c8367c8b 100644
--- a/ui/src/components/SidebarCompanyMenu.tsx
+++ b/ui/src/components/SidebarCompanyMenu.tsx
@@ -33,7 +33,6 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useCompany } from "@/context/CompanyContext";
-import { useConferenceRoomChatEnabled } from "@/hooks/useConferenceRoomChatEnabled";
import { useDialogActions } from "@/context/DialogContext";
import { useCompanyOrder } from "@/hooks/useCompanyOrder";
import { queryKeys } from "@/lib/queryKeys";
@@ -134,9 +133,6 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
const [isEditingOrder, setIsEditingOrder] = useState(false);
const queryClient = useQueryClient();
const { companies, selectedCompany, setSelectedCompanyId } = useCompany();
- // Team-centric copy (PAP-67) ships behind the Conference Room Chat flag
- // (PAP-139); OFF keeps master's "Add company...".
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
const { openOnboarding } = useDialogActions();
const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar();
const rail = collapsed && !peeking;
@@ -295,7 +291,7 @@ export function SidebarCompanyMenu({ open: controlledOpen, onOpenChange }: Sideb
disabled={isEditingOrder}
>
<Plus className="size-4" />
- <span>{conferenceRoomChatEnabled ? "Create new team..." : "Add company..."}</span>
+ <span>Create new team...</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem asChild disabled={isEditingOrder}>
diff --git a/ui/src/components/StatusBadge.test.tsx b/ui/src/components/StatusBadge.test.tsx
index c0c46e380e..532cf4e926 100644
--- a/ui/src/components/StatusBadge.test.tsx
+++ b/ui/src/components/StatusBadge.test.tsx
@@ -1,21 +1,9 @@
// @vitest-environment node
import { renderToStaticMarkup } from "react-dom/server";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
import { AgentStatusBadge, IssueStatusBadge, StatusBadge } from "./StatusBadge";
-import { agentStatusVar, statusBadgeClassic, taskStatusVar } from "../lib/status-colors";
-
-// The generic StatusBadge (runs/goals/approvals) keeps the PAP-75 brand palette
-// behind the Conference Room Chat flag (PAP-139). Seeded ON; the suite below
-// flips it OFF. The task/agent status chips no longer depend on this flag.
-const conferenceRoomChatFlag = vi.hoisted(() => ({ enabled: true }));
-vi.mock("../hooks/useConferenceRoomChatEnabled", () => ({
- useConferenceRoomChatEnabled: () => ({ enabled: conferenceRoomChatFlag.enabled, loaded: true }),
-}));
-
-afterEach(() => {
- conferenceRoomChatFlag.enabled = true;
-});
+import { agentStatusVar, taskStatusVar } from "../lib/status-colors";
/**
* Issue/task status chips carry the unified glyph and are recolored from the
@@ -53,8 +41,7 @@ describe("IssueStatusBadge", () => {
expect(renderToStaticMarkup(<IssueStatusBadge status="mystery" />)).toContain("var(--status-task-backlog)");
});
- it("is independent of the Conference Room Chat flag", () => {
- conferenceRoomChatFlag.enabled = false;
+ it("renders task chips without depending on the chat flag", () => {
const html = renderToStaticMarkup(<IssueStatusBadge status="todo" />);
expect(html).toContain("status-chip");
expect(html).toContain('viewBox="0 0 24 24"');
@@ -77,18 +64,8 @@ describe("AgentStatusBadge", () => {
});
});
-/** The generic badge still honors the PAP-139 Conference Room Chat palette. */
-describe("StatusBadge — Conference Room Chat flag palettes (PAP-139)", () => {
- it("keeps master's blue todo / yellow in_progress palette when the flag is OFF", () => {
- conferenceRoomChatFlag.enabled = false;
- expect(renderToStaticMarkup(<StatusBadge status="todo" />)).toContain("bg-blue-100");
- expect(renderToStaticMarkup(<StatusBadge status="in_progress" />)).toContain("bg-yellow-100");
- expect(renderToStaticMarkup(<StatusBadge status="in_progress" />)).toContain(
- statusBadgeClassic.in_progress!.split(" ")[0],
- );
- });
-
- it("uses the brand hues when the flag is ON", () => {
+describe("StatusBadge", () => {
+ it("uses the graduated brand hues", () => {
expect(renderToStaticMarkup(<StatusBadge status="todo" />)).toContain("bg-amber-100");
expect(renderToStaticMarkup(<StatusBadge status="in_progress" />)).toContain("bg-blue-100");
});
diff --git a/ui/src/components/StatusBadge.tsx b/ui/src/components/StatusBadge.tsx
index 47beee987c..774f265d99 100644
--- a/ui/src/components/StatusBadge.tsx
+++ b/ui/src/components/StatusBadge.tsx
@@ -2,7 +2,6 @@ import type { CSSProperties } from "react";
import { cn } from "../lib/utils";
import {
statusBadge,
- statusBadgeClassic,
statusBadgeDefault,
agentStatusMotion,
agentStatusVar,
@@ -10,7 +9,6 @@ import {
taskStatusVar,
taskStatusVarDefault,
} from "../lib/status-colors";
-import { useConferenceRoomChatEnabled } from "../hooks/useConferenceRoomChatEnabled";
import { StatusGlyph } from "./StatusGlyph";
/** Inline `--sc` local var pointing a status helper at a base-hue CSS var. */
@@ -25,18 +23,14 @@ function sentenceCaseStatus(status: string): string {
}
/**
- * Generic status badge for runs / goals / approvals (not task status). Keeps
- * the PAP-75 brand palette behind the Conference Room Chat flag (PAP-139); flag
- * OFF keeps master's palette. Non-issue entries are identical in both records.
+ * Generic status badge for runs / goals / approvals (not task status).
*/
export function StatusBadge({ status }: { status: string }) {
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
- const palette = conferenceRoomChatEnabled ? statusBadge : statusBadgeClassic;
return (
<span
className={cn(
"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium whitespace-nowrap shrink-0",
- palette[status] ?? statusBadgeDefault
+ statusBadge[status] ?? statusBadgeDefault
)}
>
{status.replace(/_/g, " ")}
diff --git a/ui/src/hooks/useAgentOrder.ts b/ui/src/hooks/useAgentOrder.ts
index 5886ea183c..68fa0e6050 100644
--- a/ui/src/hooks/useAgentOrder.ts
+++ b/ui/src/hooks/useAgentOrder.ts
@@ -8,7 +8,6 @@ import {
writeAgentOrder,
type AgentSidebarOrderOptions,
} from "../lib/agent-order";
-import { useConferenceRoomChatEnabled } from "./useConferenceRoomChatEnabled";
type UseAgentOrderParams = {
agents: Agent[];
@@ -34,12 +33,9 @@ function buildOrderIds(agents: Agent[], orderedIds: string[], options: AgentSide
}
export function useAgentOrder({ agents, companyId, userId }: UseAgentOrderParams) {
- // Leadership-first sidebar ordering (PAP-52) ships behind the Conference
- // Room Chat flag (PAP-139); OFF keeps master's alphabetical sibling order.
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
const sortOptions = useMemo<AgentSidebarOrderOptions>(
- () => ({ leadershipFirst: conferenceRoomChatEnabled }),
- [conferenceRoomChatEnabled],
+ () => ({ leadershipFirst: true }),
+ [],
);
const storageKey = useMemo(() => {
if (!companyId) return null;
diff --git a/ui/src/lib/agent-order.test.ts b/ui/src/lib/agent-order.test.ts
index 3b1424192a..78a0df23c5 100644
--- a/ui/src/lib/agent-order.test.ts
+++ b/ui/src/lib/agent-order.test.ts
@@ -22,7 +22,7 @@ describe("sortAgentsByDefaultSidebarOrder", () => {
expect(sorted.map((a) => a.id)).toEqual(["ceo", "ada", "board"]);
});
- it("keeps master's plain alphabetical order by default (Conference Room Chat flag off)", () => {
+ it("keeps plain alphabetical order unless leadership-first is requested", () => {
const agents = [
makeAgent({ id: "board", name: "Board", role: "general" }),
makeAgent({ id: "ceo", name: "CEO", role: "ceo" }),
diff --git a/ui/src/lib/agent-order.ts b/ui/src/lib/agent-order.ts
index 18d2aff23e..de7815e830 100644
--- a/ui/src/lib/agent-order.ts
+++ b/ui/src/lib/agent-order.ts
@@ -93,9 +93,7 @@ export function writeAgentSortMode(storageKey: string, sortMode: AgentSidebarSor
// Leadership roles surface at the top of each sibling group so the company's
// lead (typically the freshly-hired CEO) is visible without scrolling the
-// sidebar (PAP-52). Anything outside this list falls back to alphabetical.
-// Opt-in via `leadershipFirst` — gated on the Conference Room Chat experimental
-// flag (PAP-139); the default keeps master's plain alphabetical sibling order.
+// sidebar. Anything outside this list falls back to alphabetical.
const ROLE_SORT_PRIORITY: Record<string, number> = {
ceo: 0,
cto: 1,
diff --git a/ui/src/lib/onboarding-launch.test.ts b/ui/src/lib/onboarding-launch.test.ts
index 0fb758d7ed..bf4141a3f6 100644
--- a/ui/src/lib/onboarding-launch.test.ts
+++ b/ui/src/lib/onboarding-launch.test.ts
@@ -3,6 +3,7 @@ import {
buildOnboardingIssuePayload,
buildOnboardingProjectPayload,
selectDefaultCompanyGoalId,
+ selectReusableOnboardingProject,
} from "./onboarding-launch";
describe("selectDefaultCompanyGoalId", () => {
@@ -82,6 +83,22 @@ describe("selectDefaultCompanyGoalId", () => {
});
describe("onboarding launch payloads", () => {
+ it("reuses a non-cancelled Onboarding project by name", () => {
+ expect(
+ selectReusableOnboardingProject([
+ { id: "cancelled", name: "Onboarding", status: "cancelled" },
+ { id: "active", name: " onboarding ", status: "in_progress" },
+ ]),
+ ).toEqual({ id: "active", name: " onboarding ", status: "in_progress" });
+
+ expect(
+ selectReusableOnboardingProject([
+ { id: "cancelled", name: "Onboarding", status: "cancelled" },
+ { id: "other", name: "Roadmap", status: "in_progress" },
+ ]),
+ ).toBeNull();
+ });
+
it("links the onboarding project and first issue to the selected goal", () => {
expect(buildOnboardingProjectPayload("goal-1")).toEqual({
name: "Onboarding",
diff --git a/ui/src/lib/onboarding-launch.ts b/ui/src/lib/onboarding-launch.ts
index c5f69fd5c8..41487e9d5d 100644
--- a/ui/src/lib/onboarding-launch.ts
+++ b/ui/src/lib/onboarding-launch.ts
@@ -1,4 +1,4 @@
-import type { Goal } from "@paperclipai/shared";
+import type { Goal, Project } from "@paperclipai/shared";
export const ONBOARDING_PROJECT_NAME = "Onboarding";
@@ -32,6 +32,18 @@ export function buildOnboardingProjectPayload(goalId: string | null) {
};
}
+export function selectReusableOnboardingProject<T extends Pick<Project, "name" | "status">>(
+ projects: T[],
+): T | null {
+ return (
+ projects.find(
+ (project) =>
+ project.status !== "cancelled" &&
+ project.name.trim().toLowerCase() === ONBOARDING_PROJECT_NAME.toLowerCase(),
+ ) ?? null
+ );
+}
+
export function buildOnboardingIssuePayload(input: {
title: string;
description: string;
diff --git a/ui/src/lib/status-colors.ts b/ui/src/lib/status-colors.ts
index 4f552780e2..9ed38d8d49 100644
--- a/ui/src/lib/status-colors.ts
+++ b/ui/src/lib/status-colors.ts
@@ -12,11 +12,9 @@
// PAP-75 brand mapping ("blue = liveness"): todo → amber (queued), in_progress
// → blue (live). See `issueStatusColor` below for the canonical chip palette.
//
-// The brand mapping ships behind the "Conference Room Chat" experimental flag
-// (PAP-136/PAP-139): each record below also has a `*Classic` variant pinning
-// master's hues (todo → blue, in_progress → yellow). Consumers (StatusIcon,
-// StatusBadge, NewIssueDialog) select the palette by flag; delete the Classic
-// variants when the flag graduates or dies.
+// The brand mapping is the default status palette. Chat-specific gating stays
+// isolated to the Conference Room route/nav/API and does not control task
+// status presentation.
/** StatusIcon circle: text + border classes */
export const issueStatusIcon: Record<string, string> = {
@@ -29,13 +27,6 @@ export const issueStatusIcon: Record<string, string> = {
blocked: "text-red-600 border-red-600 dark:text-red-400 dark:border-red-400",
};
-/** Master hues for StatusIcon (Conference Room Chat flag OFF). */
-export const issueStatusIconClassic: Record<string, string> = {
- ...issueStatusIcon,
- todo: "text-blue-600 border-blue-600 dark:text-blue-400 dark:border-blue-400",
- in_progress: "text-yellow-600 border-yellow-600 dark:text-yellow-400 dark:border-yellow-400",
-};
-
export const issueStatusIconDefault = "text-muted-foreground border-muted-foreground";
/** Text-only color for issue statuses (dropdowns, labels) */
@@ -49,13 +40,6 @@ export const issueStatusText: Record<string, string> = {
blocked: "text-red-600 dark:text-red-400",
};
-/** Master hues for text-only issue statuses (Conference Room Chat flag OFF). */
-export const issueStatusTextClassic: Record<string, string> = {
- ...issueStatusText,
- todo: "text-blue-600 dark:text-blue-400",
- in_progress: "text-yellow-600 dark:text-yellow-400",
-};
-
export const issueStatusTextDefault = "text-muted-foreground";
// ---------------------------------------------------------------------------
@@ -104,13 +88,6 @@ export const statusBadge: Record<string, string> = {
cancelled: "bg-muted text-muted-foreground",
};
-/** Master hues for StatusBadge issue entries (Conference Room Chat flag OFF). */
-export const statusBadgeClassic: Record<string, string> = {
- ...statusBadge,
- todo: "bg-blue-100 text-blue-700 dark:bg-blue-900/50 dark:text-blue-300",
- in_progress: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/50 dark:text-yellow-300",
-};
-
export const statusBadgeDefault = "bg-muted text-muted-foreground";
// ---------------------------------------------------------------------------
diff --git a/ui/src/lib/work-mode-meta.test.ts b/ui/src/lib/work-mode-meta.test.ts
index daacea0cf5..bec8a42320 100644
--- a/ui/src/lib/work-mode-meta.test.ts
+++ b/ui/src/lib/work-mode-meta.test.ts
@@ -4,18 +4,18 @@ import { nextWorkMode, titleForPendingWorkMode, workModeMetaList } from "./work-
describe("work mode metadata", () => {
it("orders issue work modes as agent, planning, then ask", () => {
- expect(workModeMetaList(false).map((mode) => mode.value)).toEqual(["standard", "planning", "ask"]);
- expect(workModeMetaList(true).map((mode) => mode.shortLabel)).toEqual(["Agent", "Plan", "Ask"]);
+ expect(workModeMetaList().map((mode) => mode.value)).toEqual(["standard", "planning", "ask"]);
+ expect(workModeMetaList().map((mode) => mode.shortLabel)).toEqual(["Agent", "Plan", "Ask"]);
});
it("cycles issue work modes as agent, planning, ask, then agent", () => {
- expect(nextWorkMode("standard", true)).toBe("planning");
- expect(nextWorkMode("planning", true)).toBe("ask");
- expect(nextWorkMode("ask", true)).toBe("standard");
+ expect(nextWorkMode("standard")).toBe("planning");
+ expect(nextWorkMode("planning")).toBe("ask");
+ expect(nextWorkMode("ask")).toBe("standard");
});
- it("matches standard mode tooltip copy to the active surface", () => {
- expect(titleForPendingWorkMode("standard", false)).toBe("Standard mode for this submission. Click to change.");
- expect(titleForPendingWorkMode("standard", true)).toBe("Agent mode for this submission. Click to change.");
+ it("uses graduated tooltip copy", () => {
+ expect(titleForPendingWorkMode("standard")).toBe("Agent mode for this submission. Click to change.");
+ expect(titleForPendingWorkMode("planning")).toBe("Plan mode is on for this submission. Click to change.");
});
});
diff --git a/ui/src/lib/work-mode-meta.ts b/ui/src/lib/work-mode-meta.ts
index 45836587ae..abeabc6392 100644
--- a/ui/src/lib/work-mode-meta.ts
+++ b/ui/src/lib/work-mode-meta.ts
@@ -42,27 +42,27 @@ export function isIssueWorkMode(value: unknown): value is IssueWorkMode {
return value === "standard" || value === "ask" || value === "planning";
}
-export function workModeMetaList(conferenceRoomChat: boolean): WorkModeMeta[] {
+export function workModeMetaList(): WorkModeMeta[] {
return [
{
value: "standard",
- label: conferenceRoomChat ? "Agent mode" : "Standard",
- shortLabel: conferenceRoomChat ? "Agent" : "Standard",
+ label: "Agent mode",
+ shortLabel: "Agent",
icon: Hammer,
tone: "neutral",
classes: STANDARD_CLASSES,
},
{
value: "planning",
- label: conferenceRoomChat ? "Plan mode" : "Planning",
- shortLabel: conferenceRoomChat ? "Plan" : "Planning",
+ label: "Plan mode",
+ shortLabel: "Plan",
icon: ClipboardList,
tone: "planning",
classes: PLANNING_CLASSES,
},
{
value: "ask",
- label: conferenceRoomChat ? "Ask mode" : "Ask",
+ label: "Ask mode",
shortLabel: "Ask",
icon: MessageCircleQuestion,
tone: "ask",
@@ -71,23 +71,23 @@ export function workModeMetaList(conferenceRoomChat: boolean): WorkModeMeta[] {
];
}
-export function workModeMetaFor(mode: IssueWorkMode, conferenceRoomChat: boolean): WorkModeMeta {
- const modes = workModeMetaList(conferenceRoomChat);
+export function workModeMetaFor(mode: IssueWorkMode): WorkModeMeta {
+ const modes = workModeMetaList();
return modes.find((meta) => meta.value === mode) ?? modes[0]!;
}
-export function nextWorkMode(mode: IssueWorkMode, conferenceRoomChat: boolean): IssueWorkMode {
- const modes = workModeMetaList(conferenceRoomChat);
+export function nextWorkMode(mode: IssueWorkMode): IssueWorkMode {
+ const modes = workModeMetaList();
const index = modes.findIndex((meta) => meta.value === mode);
return modes[(index + 1) % modes.length]?.value ?? "standard";
}
-export function titleForPendingWorkMode(mode: IssueWorkMode, conferenceRoomChat: boolean): string {
+export function titleForPendingWorkMode(mode: IssueWorkMode): string {
if (mode === "ask") {
return "Ask mode for this submission. Click to change. The assignee will answer in this thread; no implementation work.";
}
if (mode === "planning") {
- return `${conferenceRoomChat ? "Plan" : "Planning"} mode is on for this submission. Click to change.`;
+ return "Plan mode is on for this submission. Click to change.";
}
- return `${conferenceRoomChat ? "Agent" : "Standard"} mode for this submission. Click to change.`;
+ return "Agent mode for this submission. Click to change.";
}
diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx
index 43c894c9a8..6543417401 100644
--- a/ui/src/pages/IssueDetail.test.tsx
+++ b/ui/src/pages/IssueDetail.test.tsx
@@ -252,24 +252,6 @@ vi.mock("../components/IssueChatThread", () => ({
},
}));
-// PAP-139/PAP-140: IssueDetail picks the thread variant by the Conference
-// Room Chat flag. These suites assert against the NUX thread, so the flag is
-// seeded ON (and reset in beforeEach); flag-off parity tests flip it per test.
-// The classic fork is stubbed (its real import chain pulls sandpack into
-// jsdom) but still captures props so parity tests can inspect them.
-const conferenceRoomChatFlag = vi.hoisted(() => ({ enabled: true }));
-vi.mock("../hooks/useConferenceRoomChatEnabled", () => ({
- useConferenceRoomChatEnabled: () => ({ enabled: conferenceRoomChatFlag.enabled, loaded: true }),
-}));
-
-const mockIssueChatThreadClassicRender = vi.hoisted(() => vi.fn());
-vi.mock("../components/IssueChatThreadClassic", () => ({
- IssueChatThreadClassic: (props: Record<string, unknown>) => {
- mockIssueChatThreadClassicRender(props);
- return <div data-testid="issue-chat-thread-classic">Classic chat thread</div>;
- },
-}));
-
vi.mock("../components/IssueDocumentsSection", () => ({
IssueDocumentsSection: () => <div>Documents</div>,
}));
@@ -960,10 +942,8 @@ describe("IssueDetail", () => {
enableExternalObjects: false,
});
mockIssuesApi.listAcceptedPlanDecompositions.mockResolvedValue([]);
- conferenceRoomChatFlag.enabled = true;
mockIssuesListRender.mockClear();
mockIssueChatThreadRender.mockClear();
- mockIssueChatThreadClassicRender.mockClear();
mockImageGalleryRender.mockClear();
mockIssueWorkspaceCardRender.mockClear();
});
@@ -1717,11 +1697,7 @@ describe("IssueDetail", () => {
}
});
- // PAP-140 flag-off parity: with the Conference Room Chat flag off, the task
- // thread surfaces must render master's behavior (classic fork, master copy,
- // master mention set).
- it("renders the frozen classic thread fork when the Conference Room Chat flag is off", async () => {
- conferenceRoomChatFlag.enabled = false;
+ it("renders the graduated task thread without the chat flag", async () => {
mockIssuesApi.get.mockResolvedValue(createIssue());
await act(async () => {
@@ -1733,13 +1709,11 @@ describe("IssueDetail", () => {
});
await flushReact();
- expect(container.querySelector('[data-testid="issue-chat-thread-classic"]')).not.toBeNull();
- expect(container.querySelector('[data-testid="issue-chat-thread"]')).toBeNull();
- expect(mockIssueChatThreadRender).not.toHaveBeenCalled();
+ expect(container.querySelector('[data-testid="issue-chat-thread"]')).not.toBeNull();
+ expect(mockIssueChatThreadRender).toHaveBeenCalled();
});
- it("falls back to master's Planning chip copy when the flag is off", async () => {
- conferenceRoomChatFlag.enabled = false;
+ it("uses graduated Plan mode chip copy", async () => {
mockIssuesApi.get.mockResolvedValue(createIssue({ workMode: "planning" }));
await act(async () => {
@@ -1751,11 +1725,11 @@ describe("IssueDetail", () => {
});
await flushReact();
- expect(container.textContent).toContain("Planning");
- expect(container.textContent).not.toContain("Plan mode");
+ expect(container.textContent).toContain("Plan mode");
+ expect(container.textContent).not.toContain("Planning");
});
- it("passes @task mention options to the thread only when the flag is on", async () => {
+ it("passes @task mention options to the thread by default", async () => {
const mentionPoolIssue = {
...createIssue(),
id: "issue-mention-1",
@@ -1768,7 +1742,6 @@ describe("IssueDetail", () => {
);
mockIssuesApi.get.mockResolvedValue(createIssue());
- // Flag ON: the mention pool query runs and issue options reach the thread.
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
@@ -1784,34 +1757,7 @@ describe("IssueDetail", () => {
expect.arrayContaining([expect.objectContaining({ kind: "issue", issueIdentifier: "PAP-9" })]),
);
});
-
- // Flag OFF: no mention-pool query, no issue options — master's mention set.
- conferenceRoomChatFlag.enabled = false;
- await act(async () => {
- root.unmount();
- });
- container.remove();
- container = document.createElement("div");
- document.body.appendChild(container);
- root = createRoot(container);
- queryClient.clear();
- mockIssuesApi.list.mockClear();
- mockIssueChatThreadClassicRender.mockClear();
-
- await act(async () => {
- root.render(
- <QueryClientProvider client={queryClient}>
- <IssueDetail />
- </QueryClientProvider>,
- );
- });
- await flushReact();
- await flushReact();
-
- const classicMentions = mockIssueChatThreadClassicRender.mock.calls.at(-1)?.[0]
- .mentions as Array<{ kind?: string }> | undefined;
- expect(classicMentions?.some((option) => option.kind === "issue")).toBe(false);
- expect(mockIssuesApi.list).not.toHaveBeenCalledWith(
+ expect(mockIssuesApi.list).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({ sortField: "updated" }),
);
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index 41d8593485..44a83c6363 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -68,8 +68,6 @@ import {
type IssueChatComposerHandle,
type IssueChatRunFinalizationAction,
} from "../components/IssueChatThread";
-import { IssueChatThreadClassic } from "../components/IssueChatThreadClassic";
-import { useConferenceRoomChatEnabled } from "../hooks/useConferenceRoomChatEnabled";
import { workModeMetaFor } from "../lib/work-mode-meta";
import { IssueContinuationHandoff } from "../components/IssueContinuationHandoff";
import { IssueAttachmentsSection } from "../components/IssueAttachmentsSection";
@@ -809,11 +807,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
resumeFromBacklogPending,
externalReferences,
}: IssueDetailChatTabProps) {
- // Conference Room Chat experimental flag (PAP-136/PAP-139): ON renders the
- // NUX thread (bubbles, metadata rows, composer chrome); OFF renders the
- // frozen master fork so the task thread looks exactly like master.
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
- const ThreadComponent = conferenceRoomChatEnabled ? IssueChatThread : IssueChatThreadClassic;
+ const ThreadComponent = IssueChatThread;
const { data: activity } = useQuery({
queryKey: queryKeys.issues.activity(issueId),
queryFn: () => activityApi.forIssue(issueId),
@@ -1500,15 +1494,12 @@ export function IssueDetail() {
queryFn: () => accessApi.listUserDirectory(selectedCompanyId!),
enabled: !!selectedCompanyId,
});
- // Bounded pool of recently-updated issues to back the `@task` reference picker
- // (PAP-95f). The picker filters this list client-side by identifier/title.
- // Gated on the Conference Room Chat flag (PAP-139): flag off keeps master's
- // mention set (no task options, no extra query).
- const { enabled: conferenceRoomChatEnabled } = useConferenceRoomChatEnabled();
+ // Bounded pool of recently-updated issues to back the `@task` reference picker.
+ // The picker filters this list client-side by identifier/title.
const { data: mentionIssues = [] } = useQuery({
queryKey: resolvedCompanyId ? queryKeys.issues.mentionPool(resolvedCompanyId) : ["issues", "mention-pool", "pending"],
queryFn: () => issuesApi.list(resolvedCompanyId!, { limit: 100, sortField: "updated", sortDir: "desc" }),
- enabled: !!resolvedCompanyId && conferenceRoomChatEnabled,
+ enabled: !!resolvedCompanyId,
staleTime: 60_000,
placeholderData: keepPreviousDataForSameQueryTail<Issue[]>(resolvedCompanyId ?? "pending"),
});
@@ -1644,9 +1635,9 @@ export function IssueDetail() {
agents,
projects: orderedProjects,
members: companyMembers?.users,
- issues: conferenceRoomChatEnabled ? mentionIssues : undefined,
+ issues: mentionIssues,
});
- }, [agents, companyMembers?.users, orderedProjects, mentionIssues, conferenceRoomChatEnabled]);
+ }, [agents, companyMembers?.users, orderedProjects, mentionIssues]);
const resolvedProject = useMemo(
() => (issue?.projectId ? orderedProjects.find((project) => project.id === issue.projectId) ?? issue.project ?? null : null),
@@ -3729,7 +3720,7 @@ export function IssueDetail() {
) : null}
{issue.workMode === "ask" || issue.workMode === "planning" ? (() => {
- const workModeMeta = workModeMetaFor(issue.workMode, conferenceRoomChatEnabled);
+ const workModeMeta = workModeMetaFor(issue.workMode);
const WorkModeIcon = workModeMeta.icon;
return (
<span