Skip to content

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

refactor(ui): share task composer and project/worktree controls (#15091)

Dotta2c43b3916711
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 850081d391..c30e261158 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -103,6 +103,12 @@ pnpm build-storybook
These run the `@paperclipai/ui` Storybook on port `6006` and build the static output to `ui/storybook-static/`.
+**Composer → New task** includes agent/user/project/task mentions, skill and
+routine slash commands, and populated rich chips on desktop and mobile. Agent
+mentions use the same avatars in suggestions, inserted chips, and the mocked
+creation receipt. The creation stories preserve the original Markdown references;
+they do not create real tasks or run agents.
+
Use **Components → Agent setup prompt** to review the shared setup handoff:
hover/focus logo motion, one-click copying with a prompt preview, animated
confirmation, and manual-copy recovery. Opening the preview copies immediately;
@@ -146,6 +152,41 @@ and submit the preserved draft. The composer has no question pending badge.
The demo uses real thread/form components with fixture response callbacks.
The Agent Chat stories share the same component fixture.
+Use **Composer → New task** to review task creation through the production
+`TaskChatComposer`. The editor, file menu, work modes, assignee/model picker,
+and send control are shared with task chat. An inset bar above the composer uses
+the queued-message container and holds Project on the left. Its searchable picker
+shows project colors. Worktrees sits beside Project when the selected project has
+isolation enabled. Choose a new worktree, reuse an eligible worktree from that
+project, or keep the shared project workspace. Reuse carries the worktree's source
+checkout, including a non-primary checkout. Changing projects clears the
+previous worktree choice. Switching from reuse to a new worktree or the project
+workspace restores the project default checkout. Task creation uses the selected company and has
+no separate heading or settings control.
+Fresh tasks start with an empty request and the last task assignee chosen in that
+company, including a human. If that assignee is unavailable, the CEO is the
+default, or the first eligible agent when the company has no CEO. Explicit launch
+assignees and saved drafts keep their selection. Selecting an assignee never
+inserts a mention. Clicking the assignee opens its searchable list directly;
+model and effort have a separate trigger and appear only for agents whose
+harness supports those settings.
+Fresh tasks also keep the company's last project (including No project); launch
+context and saved drafts take precedence. New projects receive a random palette
+color and become the remembered project. The shared composer remembers the last
+effort within the company and applies it only when the selected model supports
+that level. Explicit task overrides and drafts take precedence. Default model
+labels show the configured or known adapter model, otherwise simply Default.
+Claude defaults supplied by the server's host environment remain Default unless
+the agent explicitly configures the model. Project edits on an existing task
+become the remembered project only after the task update succeeds.
+Clicking or tapping outside either selector dismisses it and preserves the task
+draft and selections. Mobile sheets return focus to the trigger without reopening.
+Stories cover empty and prefilled drafts, remembered, human, and unassigned
+selections, the direct assignee picker, sub-tasks, planning, files, saving,
+retryable failures, creation, light theme, and mobile, plus worktree reuse,
+loading, empty, error, and isolation-disabled states. Story submissions use local
+fixtures and never start an agent.
+
Use **Composer → Model and effort picker** to review harness-specific model
choices. Codex uses the curated adapter catalog unless the instance declares
`PAPERCLIP_ADAPTER_MODELS`; general OpenAI API models are not Codex choices.
diff --git a/tests/e2e/new-task-picker-touch.spec.ts b/tests/e2e/new-task-picker-touch.spec.ts
index a78f25e373..32cc9cf9ea 100644
--- a/tests/e2e/new-task-picker-touch.spec.ts
+++ b/tests/e2e/new-task-picker-touch.spec.ts
@@ -7,8 +7,15 @@ async function json(response: APIResponse) {
}
async function swipeToLastOption(page: Page, picker: Locator) {
- const list = picker.locator("[data-mobile-entity-picker-list]");
- const last = list.getByRole("button").last();
+ const list = picker.getByRole("listbox");
+ const last = list.getByRole("option").last();
+ // The shared picker animates its height between views. Native touch
+ // coordinates must use the settled sheet rather than its clipped first frame.
+ await expect.poll(() => picker.evaluate((element) => {
+ const body = element.querySelector(".composer-run-settings-height");
+ return [...element.getAnimations(), ...(body?.getAnimations() ?? [])]
+ .every((animation) => animation.playState !== "running");
+ })).toBe(true);
// visualViewport resize updates React state after the browser viewport changes.
await expect.poll(async () => {
const bounds = (await picker.boundingBox())!;
@@ -73,50 +80,46 @@ test("new-task assignee and model sheets scroll by touch and retain the selected
}));
await page.goto(`/${company.issuePrefix}/dashboard`);
await page.getByRole("navigation", { name: "Mobile navigation" }).getByRole("button", { name: "New Task", exact: true }).tap();
- await page.getByPlaceholder("Task title").fill("Keep this touch selection draft");
- await page.getByRole("button", { name: "Assignee", exact: true }).tap();
- const assignees = page.getByRole("dialog", { name: "Select assignee", exact: true });
- const lastAssignee = await swipeToLastOption(page, assignees);
- await expect(lastAssignee).toHaveText("Touch Agent 22");
+ const draft = page.getByRole("textbox", { name: "editable markdown" });
+ await draft.fill("Keep this touch selection draft");
+ const assigneeTrigger = page.getByRole("button", { name: "Select assignee", exact: true });
+ const modelTrigger = page.getByRole("button", { name: "Select model and effort", exact: true });
+ await assigneeTrigger.tap();
+ const assigneePicker = page.getByRole("dialog", { name: "Select assignee", exact: true });
+ const lastAssignee = await swipeToLastOption(page, assigneePicker);
+ await expect(lastAssignee).toContainText("Touch Agent 22");
await lastAssignee.tap();
- // Assignee confirmation advances to the project picker.
- await page.getByRole("dialog", { name: "Select project", exact: true }).getByRole("button", { name: "No project", exact: true }).tap();
- await expect(page.getByRole("button", { name: "Touch Agent 22", exact: true })).toBeVisible();
-
- await page.getByRole("button", { name: "Codex options", exact: true }).tap();
- await page.getByRole("radio", { name: "Custom", exact: true }).tap();
- await page.getByRole("button", { name: "Default model", exact: true }).tap();
+ await expect(assigneePicker).toBeHidden();
+ await expect(assigneeTrigger).toBeFocused();
+ await modelTrigger.tap();
+ const picker = page.getByRole("dialog", { name: "Select model and effort", exact: true });
+ await page.getByRole("button", { name: "Choose exact model" }).tap();
// A reduced viewport exercises the space available when a phone keyboard opens.
await page.setViewportSize({ width: 390, height: 430 });
- const models = page.getByRole("dialog", { name: "Default model", exact: true });
- const lastModel = await swipeToLastOption(page, models);
- await expect(lastModel).toHaveText("Touch Model 24");
+ const lastModel = await swipeToLastOption(page, picker);
+ await expect(lastModel).toContainText("Touch Model 24");
await lastModel.tap();
+ await page.getByRole("button", { name: "Close picker" }).tap();
await page.setViewportSize({ width: 390, height: 844 });
- await expect(page.getByRole("button", { name: "Touch Model 24", exact: true })).toBeVisible();
- await expect(page.getByPlaceholder("Task title")).toHaveValue("Keep this touch selection draft");
+ await expect(assigneeTrigger).toContainText("Touch Agent 22");
+ await expect(modelTrigger).toContainText("Touch Model 24");
+ await expect(draft).toHaveText("Keep this touch selection draft");
- // Reopening and closing the nested modal must preserve the outer task draft.
- await page.getByRole("button", { name: "Touch Model 24", exact: true }).tap();
- await page.getByRole("button", { name: "Close selector", exact: true }).tap();
- await expect(models).toBeHidden();
- await expect(page.getByRole("button", { name: "Touch Model 24", exact: true })).toBeVisible();
- await expect(page.getByRole("button", { name: "Touch Agent 22", exact: true })).toBeVisible();
- await expect(page.getByRole("button", { name: "Create Task", exact: true })).toBeEnabled();
- await page.getByRole("button", { name: "Touch Model 24", exact: true }).tap();
- await page.getByPlaceholder("Search models...").press("Escape");
- await expect(models).toBeHidden();
- await expect(page.getByRole("button", { name: "Touch Model 24", exact: true })).toBeFocused();
- await page.getByRole("button", { name: "Touch Model 24", exact: true }).tap();
- await page.touchscreen.tap(4, 4);
- await expect(models).toBeHidden();
- await expect(page.getByPlaceholder("Task title")).toHaveValue("Keep this touch selection draft");
+ // Closing the nested picker preserves the outer composer draft and choices.
+ await modelTrigger.tap();
+ await page.getByRole("button", { name: "Choose exact model" }).tap();
+ await page.getByRole("searchbox", { name: "Search or paste a model ID" }).press("Escape");
+ await expect(picker).toBeHidden();
+ await expect(assigneeTrigger).toBeFocused();
+ await expect(page.getByRole("button", { name: "Create task", exact: true })).toBeEnabled();
await page.screenshot({ path: testInfo.outputPath("selected-mobile-assignee-and-model.png") });
- // The desktop popover keeps mouse opening and keyboard selection.
+ // The desktop picker uses the same selected values and supports model search.
await page.setViewportSize({ width: 1280, height: 900 });
- await page.getByRole("button", { name: "Touch Model 24", exact: true }).click();
- await page.getByPlaceholder("Search models...").fill("Touch Model 01");
- await page.getByPlaceholder("Search models...").press("Enter");
- await expect(page.getByRole("button", { name: "Touch Model 01", exact: true })).toBeVisible();
+ await modelTrigger.click();
+ await page.getByRole("button", { name: "Choose exact model" }).click();
+ await page.getByRole("searchbox", { name: "Search or paste a model ID" }).fill("Touch Model 01");
+ await page.getByRole("option", { name: "Touch Model 01 touch-model-01", exact: true }).click();
+ await page.getByRole("button", { name: "Choose exact model" }).press("Escape");
+ await expect(modelTrigger).toContainText("Touch Model 01");
});
diff --git a/ui/src/components/InlineEntitySelector.test.tsx b/ui/src/components/InlineEntitySelector.test.tsx
index bf221d605d..78cf92d4ca 100644
--- a/ui/src/components/InlineEntitySelector.test.tsx
+++ b/ui/src/components/InlineEntitySelector.test.tsx
@@ -139,6 +139,59 @@ describe("InlineEntitySelector", () => {
}
});
+ it("dismisses the mobile project sheet from its backdrop and preserves the task dialog", async () => {
+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: query === "(max-width: 40rem)",
+ media: query,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ }));
+ const onChange = vi.fn();
+ const root = createRoot(container);
+ await act(() => {
+ root.render(
+ <Dialog defaultOpen>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle>New task</DialogTitle>
+ <InlineEntitySelector
+ value="project-1"
+ options={[{ id: "project-1", label: "Board UI" }]}
+ placeholder="Project"
+ noneLabel="No project"
+ searchPlaceholder="Search projects..."
+ emptyMessage="No projects found."
+ onChange={onChange}
+ triggerTestId="project-picker"
+ openOnFocus={false}
+ />
+ </DialogContent>
+ </Dialog>,
+ );
+ });
+ try {
+ const trigger = document.querySelector<HTMLButtonElement>('[data-testid="project-picker"]')!;
+ await act(() => trigger.click());
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ const backdrop = document.querySelector<HTMLElement>("[data-mobile-entity-picker]")!.parentElement!;
+ await act(() => {
+ const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true });
+ Object.defineProperty(pointerDown, "pointerType", { value: "touch" });
+ backdrop.dispatchEvent(pointerDown);
+ backdrop.click();
+ });
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull();
+ expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull();
+ expect(trigger.textContent).toContain("Board UI");
+ expect(document.activeElement).toBe(trigger);
+ expect(onChange).not.toHaveBeenCalled();
+ await act(() => trigger.click());
+ expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull();
+ } finally {
+ await act(() => root.unmount());
+ }
+ });
+
it("keeps handled search navigation keys inside the popover", async () => {
const root = createRoot(container);
const onChange = vi.fn();
diff --git a/ui/src/components/InlineEntitySelector.tsx b/ui/src/components/InlineEntitySelector.tsx
index 700b89bbc1..31594ee654 100644
--- a/ui/src/components/InlineEntitySelector.tsx
+++ b/ui/src/components/InlineEntitySelector.tsx
@@ -1,5 +1,5 @@
import { forwardRef, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
-import { Check, X } from "lucide-react";
+import { Check, Search, X } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { orderItemsBySelectedAndRecent } from "../lib/recent-selections";
import { cn } from "../lib/utils";
@@ -16,6 +16,8 @@ interface InlineEntitySelectorProps {
options: InlineEntityOption[];
placeholder: string;
noneLabel: string;
+ /** Keep the no-selection action after the project choices. */
+ noneAtEnd?: boolean;
searchPlaceholder: string;
emptyMessage: string;
onChange: (id: string) => void;
@@ -68,6 +70,7 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
options,
placeholder,
noneLabel,
+ noneAtEnd = false,
searchPlaceholder,
emptyMessage,
onChange,
@@ -99,8 +102,9 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
const allOptions = useMemo<InlineEntityOption[]>(() => {
const baseOptions = [{ id: "", label: noneLabel, searchText: noneLabel }, ...options];
- return orderItemsBySelectedAndRecent(baseOptions, value, recentOptionIds);
- }, [noneLabel, options, recentOptionIds, value]);
+ const ordered = orderItemsBySelectedAndRecent(baseOptions, value, recentOptionIds);
+ return noneAtEnd ? [...ordered.filter((option) => option.id), baseOptions[0]!] : ordered;
+ }, [noneAtEnd, noneLabel, options, recentOptionIds, value]);
const filteredOptions = useMemo(() => {
const term = query.trim().toLowerCase();
@@ -215,51 +219,54 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
<X className="size-5" />
</button>
</div>
- <input
- ref={inputRef}
- className="w-full border-b border-border bg-transparent px-2 py-1.5 text-base outline-none placeholder:text-muted-foreground/60 md:text-sm"
- placeholder={searchPlaceholder}
- value={query}
- onChange={(event) => {
- setQuery(event.target.value);
- }}
- onKeyDown={(event) => {
- if (event.key === "ArrowDown") {
- event.preventDefault();
- event.stopPropagation();
- setHighlightedIndexValue((current) =>
- filteredOptions.length === 0 ? 0 : (current + 1) % filteredOptions.length,
- );
- return;
- }
- if (event.key === "ArrowUp") {
- event.preventDefault();
- event.stopPropagation();
- setHighlightedIndexValue((current) => {
- if (filteredOptions.length === 0) return 0;
- return current <= 0 ? filteredOptions.length - 1 : current - 1;
- });
- return;
- }
- if (event.key === "Enter") {
- event.preventDefault();
- event.stopPropagation();
- commitSelection(highlightedIndexRef.current, true);
- return;
- }
- if (event.key === "Tab" && !event.shiftKey) {
- event.preventDefault();
- event.stopPropagation();
- commitSelection(highlightedIndexRef.current, true);
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- event.stopPropagation();
- setOpen(false);
- }
- }}
- />
+ <div className="flex items-center gap-2 border-b border-border px-2">
+ <Search className="size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <input
+ ref={inputRef}
+ className="min-w-0 flex-1 bg-transparent py-2 text-base outline-none placeholder:text-muted-foreground/60 md:text-sm"
+ placeholder={searchPlaceholder}
+ value={query}
+ onChange={(event) => {
+ setQuery(event.target.value);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ event.stopPropagation();
+ setHighlightedIndexValue((current) =>
+ filteredOptions.length === 0 ? 0 : (current + 1) % filteredOptions.length,
+ );
+ return;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ event.stopPropagation();
+ setHighlightedIndexValue((current) => {
+ if (filteredOptions.length === 0) return 0;
+ return current <= 0 ? filteredOptions.length - 1 : current - 1;
+ });
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ event.stopPropagation();
+ commitSelection(highlightedIndexRef.current, true);
+ return;
+ }
+ if (event.key === "Tab" && !event.shiftKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ commitSelection(highlightedIndexRef.current, true);
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ }
+ }}
+ />
+ </div>
<div data-mobile-entity-picker-list="" className="max-h-56 overflow-y-auto overscroll-contain py-1 touch-pan-y">
{filteredOptions.length === 0 ? (
<p className="px-2 py-2 text-xs text-muted-foreground">{emptyMessage}</p>
@@ -273,6 +280,7 @@ export const InlineEntitySelector = forwardRef<HTMLButtonElement, InlineEntitySe
type="button"
className={cn(
"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm touch-manipulation",
+ noneAtEnd && !option.id && "mt-1 rounded-none border-t border-border",
isHighlighted && "bg-accent",
)}
onMouseEnter={() => setHighlightedIndexValue(index)}
diff --git a/ui/src/components/IssueProperties.test.tsx b/ui/src/components/IssueProperties.test.tsx
index 69e36f8bcc..4a6b329a04 100644
--- a/ui/src/components/IssueProperties.test.tsx
+++ b/ui/src/components/IssueProperties.test.tsx
@@ -14,6 +14,7 @@ import type {
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Issue, IssueDocument } from "@paperclipai/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getLastProjectId } from "../lib/recent-projects";
import { IssueProperties } from "./IssueProperties";
import { queryKeys } from "../lib/queryKeys";
@@ -1787,6 +1788,27 @@ describe("IssueProperties", () => {
act(() => root.unmount());
});
+ it("leaves project memory unchanged until task property edits are persisted", async () => {
+ localStorage.clear();
+ mockProjectsApi.list.mockResolvedValue([createProject({ name: "Remembered Project" })]);
+ const root = renderProperties(container, {
+ issue: createIssue(), childIssues: [], onUpdate: vi.fn(), inline: true,
+ });
+ await flush();
+ await act(() => findRowTrigger(container, "Project")!.click());
+ const option = [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Remembered Project")!;
+ expect(option).toBeDefined();
+ act(() => option.click());
+ expect(getLastProjectId("company-1")).toBeUndefined();
+ await act(() => findRowTrigger(container, "Project")!.click());
+ const none = [...document.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "No project")!;
+ act(() => none.click());
+ expect(getLastProjectId("company-1")).toBeUndefined();
+ expect(getLastProjectId("company-2")).toBeUndefined();
+ act(() => root.unmount());
+ localStorage.clear();
+ });
+
it("shows a green service link above the workspace row for a live non-main workspace", async () => {
mockProjectsApi.list.mockResolvedValue([createProject()]);
const serviceUrl = "http://127.0.0.1:62475";
diff --git a/ui/src/components/MarkdownBody.test.tsx b/ui/src/components/MarkdownBody.test.tsx
index 4f5e0124ab..7d5aba00be 100644
--- a/ui/src/components/MarkdownBody.test.tsx
+++ b/ui/src/components/MarkdownBody.test.tsx
@@ -11,6 +11,7 @@ import {
buildRoutineMentionHref,
buildSkillMentionHref,
buildUserMentionHref,
+ appearanceForPalette,
} from "@paperclipai/shared";
import { ThemeProvider } from "../context/ThemeContext";
import { MarkdownBody } from "./MarkdownBody";
@@ -51,7 +52,7 @@ vi.mock("../api/issues", () => ({
// Defaults to null (no provider) so the existing suite exercises the permissive
// path unchanged. Gating tests override the return value per-case.
-const mockUseOptionalCompany = vi.hoisted(() => vi.fn<() => { companies: Array<{ issuePrefix: string }> } | null>(() => null));
+const mockUseOptionalCompany = vi.hoisted(() => vi.fn<() => { companies: Array<{ issuePrefix: string }>; selectedCompanyId?: string } | null>(() => null));
vi.mock("../context/CompanyContext", () => ({
useOptionalCompany: mockUseOptionalCompany,
@@ -173,7 +174,8 @@ describe("MarkdownBody", () => {
expect(html).toContain('data-mention-kind="user"');
expect(html).toContain('href="/agents/agent-123"');
expect(html).toContain('data-mention-kind="agent"');
- expect(html).toContain("--paperclip-mention-icon-mask");
+ expect(html).toContain("--paperclip-mention-avatar-image");
+ expect(html).not.toContain("--paperclip-mention-icon-mask");
expect(html).toContain('href="/projects/project-456"');
expect(html).toContain('data-mention-kind="project"');
expect(html).toContain("--paperclip-mention-project-color:#336699");
@@ -191,6 +193,23 @@ describe("MarkdownBody", () => {
expect(html).not.toContain("javascript:");
});
+ it("uses the current company agent appearance for an old saved mention", () => {
+ mockUseOptionalCompany.mockReturnValue({ companies: [{ issuePrefix: "PAP" }], selectedCompanyId: "company-1" });
+ const client = new QueryClient();
+ client.setQueryData(queryKeys.agents.list("company-1"), [
+ { id: "agent-123", appearance: appearanceForPalette("electric-grove") },
+ ]);
+ const html = renderToStaticMarkup(
+ <QueryClientProvider client={client}>
+ <ThemeProvider>
+ <MarkdownBody>{`[@CodexCoder](${buildAgentMentionHref("agent-123", "code")})`}</MarkdownBody>
+ </ThemeProvider>
+ </QueryClientProvider>,
+ );
+ expect(html).toContain("/cap-v1/electric-grove/rest.png");
+ expect(html).not.toContain("mention-icon-mask");
+ });
+
it("renders raw HTML tags as escaped text", () => {
const html = renderMarkdown(
'<script>fetch("/api/secrets")</script>\n<iframe src="https://example.com"></iframe>\n<p onclick="steal()">Plain text</p>',
diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx
index feed8630b8..6c4a9f11b4 100644
--- a/ui/src/components/MarkdownBody.tsx
+++ b/ui/src/components/MarkdownBody.tsx
@@ -10,6 +10,7 @@ import { useTheme } from "../context/ThemeContext";
import { useOptionalCompany } from "../context/CompanyContext";
import { mentionChipInlineStyle, parseMentionChipHref } from "../lib/mention-chips";
import { issuesApi } from "../api/issues";
+import { agentsApi } from "../api/agents";
import { getCachedIssueDetail } from "../lib/issueDetailCache";
import { queryKeys } from "../lib/queryKeys";
import { parseIssueReferenceFromHref, remarkLinkIssueReferences } from "../lib/issue-reference";
@@ -41,10 +42,37 @@ import {
import { normalizeExternalObjectHref } from "../lib/external-object-href";
import { copyTextToClipboard } from "../lib/clipboard";
import type {
+ Agent,
ExternalObjectLivenessState,
ExternalObjectStatusCategory,
} from "@paperclipai/shared";
+function MarkdownAgentMention({ agentId, children, style }: {
+ agentId: string;
+ children: ReactNode;
+ style?: React.CSSProperties;
+}) {
+ const companyId = useOptionalCompany()?.selectedCompanyId;
+ // All mentions share the company list cache; never fetch one agent per chip.
+ const { data: agents } = useQuery<Agent[]>({
+ queryKey: queryKeys.agents.list(companyId ?? "__none__"),
+ queryFn: () => agentsApi.list(companyId!),
+ enabled: Boolean(companyId),
+ staleTime: 60_000,
+ });
+ const appearance = agents?.find((agent) => agent.id === agentId)?.appearance;
+ return (
+ <a
+ href={`/agents/${agentId}`}
+ className="paperclip-mention-chip paperclip-mention-chip--agent"
+ data-mention-kind="agent"
+ style={{ ...mergeWrapStyle(style), ...mentionChipInlineStyle({ kind: "agent", agentId, icon: null, appearance }) }}
+ >
+ {children}
+ </a>
+ );
+}
+
/**
* Host-resolved external-object metadata for inline markdown decoration.
* The renderer only consumes the host normalized fields here — plugin React
@@ -870,6 +898,13 @@ function MarkdownBodyImpl({
const parsed = href ? parseMentionChipHref(href) : null;
if (parsed) {
+ if (parsed.kind === "agent") {
+ return (
+ <MarkdownAgentMention agentId={parsed.agentId} style={linkStyle as React.CSSProperties | undefined}>
+ {linkChildren}
+ </MarkdownAgentMention>
+ );
+ }
const targetHref = parsed.kind === "project"
? `/projects/${parsed.projectId}`
: parsed.kind === "issue"
@@ -878,9 +913,7 @@ function MarkdownBodyImpl({
? `/skills/${parsed.skillId}`
: parsed.kind === "routine"
? `/routines/${parsed.routineId}`
- : parsed.kind === "user"
- ? "/company/settings/access"
- : `/agents/${parsed.agentId}`;
+ : "/company/settings/access";
return (
<a
href={targetHref}
diff --git a/ui/src/components/MarkdownEditor.test.tsx b/ui/src/components/MarkdownEditor.test.tsx
index 73c96c94b1..7a081fea85 100644
--- a/ui/src/components/MarkdownEditor.test.tsx
+++ b/ui/src/components/MarkdownEditor.test.tsx
@@ -1007,6 +1007,7 @@ describe("MarkdownEditor", () => {
).toEqual({
top: 100,
left: 250,
+ maxWidth: 542,
});
});
@@ -1019,6 +1020,7 @@ describe("MarkdownEditor", () => {
).toEqual({
top: 340,
left: 154,
+ maxWidth: 182,
});
});
@@ -1031,6 +1033,7 @@ describe("MarkdownEditor", () => {
).toEqual({
top: 12,
left: 92,
+ maxWidth: 180,
});
});
@@ -1043,6 +1046,7 @@ describe("MarkdownEditor", () => {
).toEqual({
top: 372,
left: 210,
+ maxWidth: 582,
});
});
@@ -1056,6 +1060,7 @@ describe("MarkdownEditor", () => {
).toEqual({
top: 160,
left: 130,
+ maxWidth: 182,
});
});
diff --git a/ui/src/components/MarkdownEditor.tsx b/ui/src/components/MarkdownEditor.tsx
index 1b1190939e..b7d260b26c 100644
--- a/ui/src/components/MarkdownEditor.tsx
+++ b/ui/src/components/MarkdownEditor.tsx
@@ -492,7 +492,10 @@ export function computeMentionMenuPosition(
const desiredLeft = viewport.offsetLeft + anchor.viewportLeft + MENTION_MENU_CARET_GAP;
const left = Math.max(minLeft, Math.min(desiredLeft, maxLeft));
- return { top, left };
+ // The menu can grow beyond its estimated width for long task names.
+ // Constrain its actual layout to the space remaining beside the caret.
+ const maxWidth = Math.max(0, viewport.offsetLeft + viewport.width - MENTION_MENU_PADDING - left);
+ return { top, left, maxWidth };
}
function getMentionMenuSize(optionCount: number): MentionMenuSize {
@@ -1030,7 +1033,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
const option = mentionOptionByKey.get(`agent:${parsed.agentId}`);
applyMentionChipDecoration(link, {
...parsed,
- icon: parsed.icon ?? option?.agentIcon ?? null,
+ appearance: option?.agentAppearance,
});
}
}, [mentionOptionByKey]);
@@ -1534,6 +1537,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
style={{
top: mentionMenuPosition.top,
left: mentionMenuPosition.left,
+ maxWidth: mentionMenuPosition.maxWidth,
touchAction: "pan-y",
WebkitOverflowScrolling: "touch",
}}
diff --git a/ui/src/components/NewIssueDialog.test.tsx b/ui/src/components/NewIssueDialog.test.tsx
index 8e168c10f2..b92e834bf3 100644
--- a/ui/src/components/NewIssueDialog.test.tsx
+++ b/ui/src/components/NewIssueDialog.test.tsx
@@ -6,6 +6,9 @@ import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { queryKeys } from "../lib/queryKeys";
+import { trackRecentAssignee, trackRecentAssigneeUser } from "../lib/recent-assignees";
+import { getLastProjectId, trackRecentProject } from "../lib/recent-projects";
+import { rememberComposerEffort } from "../lib/recent-composer-effort";
import { NewIssueDialog } from "./NewIssueDialog";
const dialogState = vi.hoisted(() => ({
@@ -46,6 +49,7 @@ const toastState = vi.hoisted(() => ({
const navigateMock = vi.hoisted(() => vi.fn());
const mockIssuesApi = vi.hoisted(() => ({
+ list: vi.fn(),
create: vi.fn(),
upsertDocument: vi.fn(),
uploadAttachment: vi.fn(),
@@ -82,6 +86,8 @@ vi.mock("../context/DialogContext", () => ({
useDialog: () => dialogState,
}));
+vi.mock("../context/SidebarContext", () => ({ useSidebar: () => ({ isMobile: false }) }));
+
vi.mock("../context/CompanyContext", () => ({
useCompany: () => companyState,
}));
@@ -143,10 +149,8 @@ vi.mock("../hooks/useProjectOrder", () => ({
}),
}));
-vi.mock("../lib/recent-assignees", () => ({
- getRecentAssigneeIds: () => [],
- sortAgentsByRecency: (agents: unknown[]) => agents,
- trackRecentAssignee: vi.fn(),
+vi.mock("../api/access", () => ({
+ accessApi: { listUserDirectory: async () => ({ users: [] }) },
}));
vi.mock("../lib/assignees", () => ({
@@ -157,7 +161,7 @@ vi.mock("../lib/assignees", () => ({
assigneeAgentId?: string;
assigneeUserId?: string;
}) => assigneeAgentId ? `agent:${assigneeAgentId}` : assigneeUserId ? `user:${assigneeUserId}` : "",
- currentUserAssigneeOption: () => [],
+ currentUserAssigneeOption: (id: string | null) => id ? [{ id: `user:${id}`, label: "Me" }] : [],
parseAssigneeValue: (value: string) => ({
assigneeAgentId: value.startsWith("agent:") ? value.slice("agent:".length) : null,
assigneeUserId: value.startsWith("user:") ? value.slice("user:".length) : null,
@@ -195,11 +199,13 @@ vi.mock("./InlineEntitySelector", async () => {
placeholder?: string;
className?: string;
triggerDataSlot?: string;
+ options?: { id: string; label: string }[];
+ onChange?: (id: string) => void;
renderTriggerValue?: (option: { id: string; label: string } | null) => ReactNode;
}
- >(function InlineEntitySelectorMock({ value, placeholder, className, triggerDataSlot, renderTriggerValue }, ref) {
+ >(function InlineEntitySelectorMock({ value, placeholder, className, triggerDataSlot, renderTriggerValue, options = [], onChange }, ref) {
return (
- <button ref={ref} type="button" className={className} data-slot={triggerDataSlot}>
+ <button ref={ref} type="button" className={className} data-slot={triggerDataSlot} onClick={() => onChange?.(options[options.findIndex((option) => option.id === value) + 1]?.id ?? "")}>
{(renderTriggerValue?.(value ? { id: value, label: value } : null) ?? value) || placeholder}
</button>
);
@@ -212,6 +218,7 @@ vi.mock("./AgentIconPicker", () => ({
}));
vi.mock("@/components/ui/dialog", () => ({
+ DialogTitle: ({ children, ...props }: ComponentProps<"h2">) => <h2 {...props}>{children}</h2>,
Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => (open ? <div>{children}</div> : null),
DialogContent: ({
children,
@@ -242,9 +249,17 @@ vi.mock("@/components/ui/toggle-switch", () => ({
),
}));
+vi.mock("@/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DropdownMenuItem: ({ children, onSelect, ...props }: Omit<ComponentProps<"button">, "onSelect"> & { onSelect?: () => void }) => <button {...props} onClick={onSelect}>{children}</button>,
+}));
+
vi.mock("@/components/ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => <div>{children}</div>,
PopoverTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
+ PopoverAnchor: ({ children }: { children: ReactNode }) => <>{children}</>,
PopoverContent: ({ children, disablePortal }: { children: ReactNode; disablePortal?: boolean }) => (
<div data-disable-portal={String(Boolean(disablePortal))}>{children}</div>
),
@@ -269,10 +284,10 @@ async function flush() {
});
}
-async function typeTextareaValue(textarea: HTMLTextAreaElement, value: string) {
+async function typeTextareaValue(textarea: HTMLTextAreaElement | HTMLInputElement, value: string) {
await act(async () => {
const valueSetter = Object.getOwnPropertyDescriptor(
- window.HTMLTextAreaElement.prototype,
+ textarea instanceof HTMLInputElement ? window.HTMLInputElement.prototype : window.HTMLTextAreaElement.prototype,
"value",
)?.set;
valueSetter?.call(textarea, value);
@@ -349,6 +364,7 @@ describe("NewIssueDialog", () => {
toastState.pushToast.mockReset();
navigateMock.mockReset();
mockIssuesApi.create.mockReset();
+ mockIssuesApi.list.mockReset().mockResolvedValue([]);
mockIssuesApi.upsertDocument.mockReset();
mockIssuesApi.uploadAttachment.mockReset();
mockExecutionWorkspacesApi.list.mockReset();
@@ -392,6 +408,142 @@ describe("NewIssueDialog", () => {
document.body.innerHTML = "";
});
+ const defaultAgents = [
+ { id: "worker", name: "Worker", role: "engineer", status: "idle", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} },
+ { id: "ceo", name: "CEO", role: "ceo", status: "idle", adapterType: "claude_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} },
+ ];
+
+ it.each([
+ { remembered: "project-1", expected: "project-1" },
+ { remembered: "", expected: "Project" },
+ { remembered: "deleted", expected: "Project" },
+ ])("restores the last available project ($remembered)", async ({ remembered, expected }) => {
+ trackRecentProject(remembered, "company-1");
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-slot="new-issue-compact-control"]')?.textContent).toContain(expected));
+ await typeTextareaValue(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!, "Check project memory");
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ expect(mockIssuesApi.create.mock.calls[0][1].projectId).toBe(remembered === "project-1" ? "project-1" : undefined);
+ act(() => root.unmount());
+ });
+
+ it("keeps explicit launch context ahead of another company's project history", async () => {
+ trackRecentProject("project-1", "company-2");
+ trackRecentProject("deleted", "company-1");
+ dialogState.newIssueDefaults = { projectId: "project-1" };
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-slot="new-issue-compact-control"]')?.textContent).toContain("project-1"));
+ act(() => root.unmount());
+ dialogState.newIssueDefaults = {};
+ const next = renderDialog(container);
+ await flush();
+ expect(container.querySelector('[data-slot="new-issue-compact-control"]')?.textContent).toContain("Project");
+ act(() => next.root.unmount());
+ });
+
+ it("remembers a project selection even when the composer is dismissed without submitting", async () => {
+ const { root } = renderDialog(container);
+ await flush();
+ act(() => container.querySelector<HTMLElement>('[data-slot="new-issue-compact-control"]')!.click());
+ expect(getLastProjectId("company-1")).toBe("project-1");
+ act(() => root.unmount());
+ const next = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-slot="new-issue-compact-control"]')?.textContent).toContain("project-1"));
+ act(() => next.root.unmount());
+ });
+
+ it("submits remembered effort with the agent's default model", async () => {
+ mockAgentsApi.list.mockResolvedValue(defaultAgents.map((agent) => agent.id === "ceo"
+ ? { ...agent, adapterConfig: { model: "claude-opus-5" } } : agent));
+ mockAgentsApi.adapterModels.mockResolvedValue([{ id: "claude-opus-5", label: "Claude Opus 5" }]);
+ rememberComposerEffort("company-1", "high");
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe("Claude Opus 5"));
+ await typeTextareaValue(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!, "Check effort memory");
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ expect(mockIssuesApi.create.mock.calls[0][1].assigneeAdapterOverrides).toEqual({ adapterConfig: { effort: "high" } });
+ act(() => root.unmount());
+ });
+
+ it.each([
+ { recent: "", expected: "CEO" },
+ { recent: "agent:worker", expected: "Worker" },
+ { recent: "user:user-1", expected: "Me" },
+ { recent: "agent:deleted", expected: "CEO" },
+ ])("defaults to $expected for recent selection $recent without inserting a mention", async ({ recent, expected }) => {
+ mockAgentsApi.list.mockResolvedValue(defaultAgents);
+ if (recent.startsWith("agent:")) trackRecentAssignee(recent.slice(6), "company-1");
+ if (recent.startsWith("user:")) trackRecentAssigneeUser(recent.slice(5), "company-1");
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe(expected));
+ expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("");
+ expect(container.textContent).not.toContain("@CEO");
+ act(() => root.unmount());
+ });
+
+ it("ignores another company's remembered human and keeps explicit launch assignees", async () => {
+ mockAgentsApi.list.mockResolvedValue(defaultAgents);
+ trackRecentAssigneeUser("user-1", "company-2");
+ dialogState.newIssueDefaults = { assigneeAgentId: "worker" };
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("Worker"));
+ act(() => root.unmount());
+ dialogState.newIssueDefaults = {};
+ const next = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("CEO"));
+ act(() => next.root.unmount());
+ });
+
+ it("uses older agent history only when the agent belongs to the current company", async () => {
+ mockAgentsApi.list.mockResolvedValue(defaultAgents);
+ trackRecentAssignee("worker");
+ trackRecentAssignee("another-company-agent");
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("Worker"));
+ act(() => root.unmount());
+ });
+
+ it("remembers a chosen human and leaves the request empty", async () => {
+ mockAgentsApi.list.mockResolvedValue(defaultAgents);
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("CEO"));
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Select assignee"]')!.click());
+ const me = [...container.querySelectorAll<HTMLButtonElement>('[role="option"]')].find((button) => button.textContent?.includes("Me"))!;
+ act(() => me.click());
+ expect(localStorage.getItem("paperclip:recent-assignees:company-1")).toContain("user:user-1");
+ expect(container.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull();
+ expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("");
+ act(() => root.unmount());
+ });
+
+ it("applies the default after agents load without replacing a request typed meanwhile", async () => {
+ let resolveAgents!: (agents: typeof defaultAgents) => void;
+ mockAgentsApi.list.mockReturnValue(new Promise((resolve) => { resolveAgents = resolve; }));
+ const { root } = renderDialog(container);
+ await flush();
+ await typeTextareaValue(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')!, "hello there");
+ resolveAgents(defaultAgents);
+ await waitForAssertion(() => expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("CEO"));
+ expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("hello there");
+ act(() => root.unmount());
+ });
+
+ it("keeps an explicitly chosen human while agents are still loading", async () => {
+ let resolveAgents!: (agents: typeof defaultAgents) => void;
+ mockAgentsApi.list.mockReturnValue(new Promise((resolve) => { resolveAgents = resolve; }));
+ const { root } = renderDialog(container);
+ await flush();
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Select assignee"]')!.click());
+ const me = [...container.querySelectorAll<HTMLButtonElement>('[role="option"]')].find((button) => button.textContent?.includes("Me"))!;
+ act(() => me.click());
+ resolveAgents(defaultAgents);
+ await flush();
+ expect(container.querySelector('[data-testid="task-chat-composer-assignee-label"]')?.textContent).toBe("Me");
+ act(() => root.unmount());
+ });
+
it("shows sub-issue context only when opened from a sub-issue action", async () => {
dialogState.newIssueDefaults = {
parentId: "issue-1",
@@ -408,7 +560,7 @@ describe("NewIssueDialog", () => {
expect(container.textContent).toContain("Sub-task of");
expect(container.textContent).toContain("PAP-1");
expect(container.textContent).toContain("Parent issue");
- expect(container.textContent).toContain("Create Sub-Task");
+ expect(container.querySelector('[aria-label="Create sub-task"]')).not.toBeNull();
act(() => root.unmount());
@@ -417,34 +569,32 @@ describe("NewIssueDialog", () => {
await flush();
expect(container.textContent).toContain("New task");
- expect(container.textContent).toContain("Create Task");
+ expect(container.querySelector('[aria-label="Create task"]')).not.toBeNull();
expect(container.textContent).not.toContain("Sub-task of");
act(() => rerendered.root.unmount());
});
- it("uses the compact composer control proportions for mobile task fields", async () => {
+ it("uses the task chat composer for the editor and send control", async () => {
+ mockAgentsApi.list.mockResolvedValue([{ id: "agent-1", name: "Coder", status: "active", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }]);
const { root } = renderDialog(container);
await flush();
-
- const compactControls = Array.from(
- container.querySelectorAll<HTMLElement>('[data-slot="new-issue-compact-control"]'),
- );
- const prefix = compactControls.find((control) => control.textContent === "PAP");
- const assignee = compactControls.find((control) => control.textContent === "Assignee");
- const project = compactControls.find((control) => control.textContent === "Project");
- const status = compactControls.find((control) => control.textContent?.trim() === "Todo");
- const upload = compactControls.find((control) => control.textContent?.trim() === "Upload");
- const mode = compactControls.find((control) => control.hasAttribute("data-issue-work-mode-chip"));
- const more = container.querySelector<HTMLElement>('[data-testid="new-issue-more-menu-trigger"]');
-
- expect(prefix?.className).toContain("p-1.5");
- for (const control of [assignee, project, status, upload, mode]) {
- expect(control?.className).toContain("h-8");
- expect(control?.className).toContain("px-2.5");
- }
- expect(more?.className).toContain("size-8");
-
+ const composer = container.querySelector(".paperclip-task-chat-composer");
+ expect(composer).not.toBeNull();
+ expect(composer?.querySelector('[data-testid="task-chat-composer-input"]')).not.toBeNull();
+ expect(composer?.querySelector('[aria-label="Create task"]')).not.toBeNull();
+ expect(composer?.querySelector('[aria-label="Task settings"]')).toBeNull();
+ expect(container.querySelector("h2")?.className).toBe("sr-only");
+ expect(composer?.textContent).not.toContain("PAP");
+ await waitForAssertion(() => expect(composer?.querySelector('[data-testid="task-chat-composer-assignee"]')).not.toBeNull());
+ const toolbar = composer?.querySelector('[data-testid="task-chat-composer-actions"]');
+ const context = container.querySelector('[data-testid="task-chat-composer-context"]');
+ const project = context?.querySelector('[data-slot="new-issue-compact-control"]');
+ const assignee = toolbar?.querySelector('[data-testid="task-chat-composer-assignee"]');
+ expect(project).not.toBeNull();
+ expect(context?.nextElementSibling).toBe(composer);
+ expect(assignee).not.toBeNull();
+ expect(toolbar?.querySelector('[data-slot="new-issue-compact-control"]')).toBeNull();
act(() => root.unmount());
});
@@ -491,14 +641,13 @@ describe("NewIssueDialog", () => {
await waitForAssertion(() => {
expect(mockExecutionWorkspacesApi.listSummaries).toHaveBeenCalledWith("company-1", {
projectId: "project-1",
- projectWorkspaceId: undefined,
reuseEligible: true,
});
});
expect(mockExecutionWorkspacesApi.list).not.toHaveBeenCalled();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Sub-Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create sub-task");
expect(submitButton).not.toBeUndefined();
await waitForAssertion(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -601,26 +750,10 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await waitForAssertion(() => {
- expect(container.textContent).toContain("Codex options");
- });
-
- const codexOptionsButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Codex options"));
- expect(codexOptionsButton).not.toBeUndefined();
- await act(async () => {
- codexOptionsButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(container.querySelector('[aria-label="Select model and effort"]')).not.toBeNull();
+ expect(container.querySelector('[aria-label="Effort"]')?.getAttribute("max")).toBe("6");
});
-
- const customLane = Array.from(container.querySelectorAll('button[role="radio"]'))
- .find((button) => button.textContent?.trim() === "Custom");
- expect(customLane).not.toBeUndefined();
- await act(async () => {
- customLane!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
-
- expect(container.textContent).toContain("Ultra");
- expect(container.textContent).toContain("Max");
- expect(container.textContent).not.toContain("Minimal");
+ expect(container.textContent).not.toContain("Codex options");
act(() => root.unmount());
});
@@ -661,11 +794,11 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const planningButton = container.querySelector('[data-issue-work-mode="planning"]');
- expect(planningButton?.className).toContain("bg-accent");
+ const planningButton = container.querySelector('[data-testid="composer-add-plan"]');
+ expect(container.querySelector("[data-pending-work-mode=planning]")).not.toBeNull();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -696,11 +829,11 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const askButton = container.querySelector('[data-issue-work-mode="ask"]');
- expect(askButton?.className).toContain("bg-accent");
+ const askButton = container.querySelector('[data-testid="composer-add-ask"]');
+ expect(container.querySelector("[data-pending-work-mode=ask]")).not.toBeNull();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -738,8 +871,8 @@ describe("NewIssueDialog", () => {
await flush();
expect(container.textContent).not.toContain("Execution workspace");
expect(container.querySelector('option[value="isolated_workspace"]')).toBeNull();
- await typeTextareaValue(container.querySelector('textarea[placeholder="Task title (optional)"]')!, "Managed task");
- const create = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Create Task"));
+ await typeTextareaValue(container.querySelector('textarea[aria-label="Describe a task…"]')!, "Managed task");
+ const create = Array.from(container.querySelectorAll("button")).find((button) => button.getAttribute("aria-label") === "Create task");
act(() => create!.click());
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
const payload = mockIssuesApi.create.mock.calls[0][1];
@@ -758,8 +891,8 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container, ["workspaces.isolation"]);
await flush();
expect(container.querySelector('option[value="isolated_workspace"]')).toBeNull();
- await typeTextareaValue(container.querySelector('textarea[placeholder="Task title (optional)"]')!, "Context task");
- const create = Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes(subtask ? "Create Sub-Task" : "Create Task"));
+ await typeTextareaValue(container.querySelector('textarea[aria-label="Describe a task…"]')!, "Context task");
+ const create = Array.from(container.querySelectorAll("button")).find((button) => button.getAttribute("aria-label") === (subtask ? "Create sub-task" : "Create task"));
act(() => create!.click());
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
expect(mockIssuesApi.create.mock.calls[0][1]).toMatchObject({
@@ -814,17 +947,20 @@ describe("NewIssueDialog", () => {
executionWorkspaceId: "workspace-1",
};
- const { root } = renderDialog(container);
+ const { root, queryClient } = renderDialog(container);
await flush();
- expect(container.textContent).toContain("New task");
- expect(container.textContent).not.toContain("New sub-task");
await waitForAssertion(() => {
- expect(container.textContent).toContain("Reusing PAP-100");
+ expect(queryClient.getQueryData(queryKeys.executionWorkspaces.summaryList("company-1", {
+ projectId: "project-1", reuseEligible: true,
+ }))).toEqual(expect.arrayContaining([expect.objectContaining({ id: "workspace-1" })]));
});
+ await flush();
+ expect(container.textContent).toContain("New task");
+ expect(container.textContent).not.toContain("New sub-task");
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await act(async () => {
@@ -849,57 +985,130 @@ describe("NewIssueDialog", () => {
act(() => root.unmount());
});
- it("keeps the reusable workspace search popover inside the modal", async () => {
+ function enableWorktrees(mode = "shared_workspace") {
+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: true });
mockProjectsApi.list.mockResolvedValue([
- {
- id: "project-1",
- name: "Alpha",
- description: null,
- archivedAt: null,
- color: "#445566",
- workspaces: [
- {
- id: "project-workspace-1",
- name: "Primary",
- isPrimary: true,
- },
- ],
- executionWorkspacePolicy: {
- enabled: true,
- defaultMode: "shared_workspace",
- },
- },
- ]);
- mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([
- {
- id: "workspace-1",
- name: "PAP-11446-on-mobile-the-agent-chat",
- mode: "isolated_workspace",
- status: "active",
- branchName: "PAP-11446-on-mobile-the-agent-chat",
- cwd: "/tmp/workspace-1",
- projectWorkspaceId: "project-workspace-1",
- lastUsedAt: new Date("2026-04-06T16:00:00.000Z"),
- },
+ { id: "project-1", name: "Alpha", executionWorkspacePolicy: { enabled: true, defaultMode: mode }, workspaces: [{ id: "source-1", isPrimary: true }] },
+ { id: "project-2", name: "Beta", executionWorkspacePolicy: { enabled: false }, workspaces: [] },
]);
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: true });
- dialogState.newIssueDefaults = {
- title: "Follow-up issue",
- projectId: "project-1",
- executionWorkspaceId: "workspace-1",
- };
+ dialogState.newIssueDefaults = { projectId: "project-1", description: "Fix sign-in" };
+ }
+
+ function selectWorktree(value: string) {
+ const option = container.querySelector<HTMLElement>(`[cmdk-item][data-value="${value}"]`);
+ expect(option).not.toBeNull();
+ act(() => option!.click());
+ }
+
+ it.each(["isolated_workspace", "operator_branch", "adapter_managed"])("reuses a worktree with its actual mode (%s)", async (mode) => {
+ enableWorktrees();
+ mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([{
+ id: "worktree-1", name: "Sign-in fix", mode, status: "active", branchName: "fix/sign-in",
+ cwd: "/tmp/worktree-1", projectWorkspaceId: "source-1", lastUsedAt: new Date(),
+ }]);
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[cmdk-item][data-value="reuse:worktree-1"]')).not.toBeNull());
+ const context = container.querySelector('[data-testid="task-chat-composer-context"]');
+ const project = context?.querySelector('[data-slot="new-issue-compact-control"]');
+ const worktrees = context?.querySelector('[aria-label="Worktrees"]');
+ expect(worktrees).not.toBeNull();
+ expect(project?.compareDocumentPosition(worktrees!)! & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ selectWorktree("reuse:worktree-1");
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ expect(mockIssuesApi.create.mock.calls[0][1]).toMatchObject({
+ projectId: "project-1", projectWorkspaceId: "source-1", executionWorkspaceId: "worktree-1",
+ executionWorkspacePreference: "reuse_existing",
+ executionWorkspaceSettings: { mode: mode === "adapter_managed" ? "agent_default" : mode },
+ });
+ act(() => root.unmount());
+ });
+
+ it.each(["isolated_workspace", "shared_workspace"])("restores the project checkout and clears reuse when choosing %s", async (mode) => {
+ enableWorktrees();
+ mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([{
+ id: "worktree-1", name: "Sign-in fix", mode: "isolated_workspace", status: "idle",
+ branchName: "fix/sign-in", cwd: "/tmp/worktree-1", projectWorkspaceId: "source-2", lastUsedAt: new Date(),
+ }]);
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[cmdk-item][data-value="reuse:worktree-1"]')).not.toBeNull());
+ selectWorktree("reuse:worktree-1");
+ selectWorktree(mode);
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ const payload = mockIssuesApi.create.mock.calls[0][1];
+ expect(payload).toMatchObject({ projectWorkspaceId: "source-1", executionWorkspacePreference: mode, executionWorkspaceSettings: { mode } });
+ expect(payload).not.toHaveProperty("executionWorkspaceId");
+ act(() => root.unmount());
+ });
+ it.each([false, true])("carries the source checkout when reusing another worktree in the same project (inherited: %s)", async (inherited) => {
+ enableWorktrees();
+ if (inherited) dialogState.newIssueDefaults.executionWorkspaceId = "worktree-secondary";
+ mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([{
+ id: "worktree-secondary", name: "Secondary checkout fix", mode: "isolated_workspace", status: "active",
+ branchName: "fix/secondary", cwd: "/tmp/worktree-secondary", projectWorkspaceId: "source-2", lastUsedAt: new Date(),
+ }]);
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[cmdk-item][data-value="reuse:worktree-secondary"]')).not.toBeNull());
+ expect(mockExecutionWorkspacesApi.listSummaries).toHaveBeenCalledWith("company-1", { projectId: "project-1", reuseEligible: true });
+ if (!inherited) selectWorktree("reuse:worktree-secondary");
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ expect(mockIssuesApi.create.mock.calls[0][1]).toMatchObject({ projectWorkspaceId: "source-2", executionWorkspaceId: "worktree-secondary" });
+ act(() => root.unmount());
+ });
+
+ it("clears a reused worktree when switching to a project without isolation", async () => {
+ enableWorktrees();
+ dialogState.newIssueDefaults.executionWorkspaceId = "worktree-1";
const { root } = renderDialog(container);
await flush();
+ act(() => container.querySelector<HTMLButtonElement>('[data-slot="new-issue-compact-control"]')!.click());
+ await flush();
+ expect(container.querySelector('[aria-label="Worktrees"]')).toBeNull();
+ act(() => container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ const payload = mockIssuesApi.create.mock.calls[0][1];
+ expect(payload.projectId).toBe("project-2");
+ expect(payload).not.toHaveProperty("executionWorkspaceId");
+ expect(payload).not.toHaveProperty("executionWorkspacePreference");
+ expect(payload).not.toHaveProperty("executionWorkspaceSettings");
+ act(() => root.unmount());
+ });
- await waitForAssertion(() => {
- const workspaceInput = container.querySelector('input[placeholder="Search workspaces..."]');
- expect(workspaceInput?.closest("[data-disable-portal]")?.getAttribute("data-disable-portal")).toBe("true");
- });
+ it.each([false, true])("hides worktrees and skips reuse queries when the project has isolation disabled (instance: %s)", async (instanceEnabled) => {
+ mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: instanceEnabled });
+ dialogState.newIssueDefaults = { projectId: "project-1" };
+ const { root } = renderDialog(container);
+ await flush();
+ expect(container.querySelector('[aria-label="Worktrees"]')).toBeNull();
+ expect(mockExecutionWorkspacesApi.listSummaries).not.toHaveBeenCalled();
+ act(() => root.unmount());
+ });
+ it.each(["loading", "error", "missing"])("blocks an unchecked reused worktree but still permits a new one (%s)", async (state) => {
+ enableWorktrees();
+ dialogState.newIssueDefaults.executionWorkspaceId = "stale-worktree";
+ if (state === "loading") mockExecutionWorkspacesApi.listSummaries.mockImplementation(() => new Promise(() => {}));
+ if (state === "error") mockExecutionWorkspacesApi.listSummaries.mockRejectedValue(new Error("Unavailable"));
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.querySelector('[aria-label="Worktrees"]')).not.toBeNull());
+ await flush();
+ const submit = container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!;
+ expect(submit.disabled).toBe(true);
+ act(() => { container.querySelector('textarea')!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true })); });
+ expect(mockIssuesApi.create).not.toHaveBeenCalled();
+ selectWorktree("isolated_workspace");
+ await flush();
+ expect(submit.disabled).toBe(false);
+ act(() => submit.click());
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalled());
+ expect(mockIssuesApi.create.mock.calls[0][1]).toMatchObject({ executionWorkspacePreference: "isolated_workspace" });
act(() => root.unmount());
});
+
it("restores a description-only draft", async () => {
localStorage.setItem("paperclip:issue-draft", JSON.stringify({
title: "", description: "Keep the request without a title", status: "todo", priority: "medium",
@@ -909,9 +1118,9 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
await waitForAssertion(() => {
- expect((container.querySelector('textarea[aria-label="Add description..."]') as HTMLTextAreaElement).value).toBe("Keep the request without a title");
+ expect((container.querySelector('textarea[aria-label="Describe a task…"]') as HTMLTextAreaElement).value).toBe("Keep the request without a title");
});
- const submit = Array.from(container.querySelectorAll("button")).find(button => button.textContent?.includes("Create Task"))!;
+ const submit = Array.from(container.querySelectorAll("button")).find(button => button.getAttribute("aria-label") === "Create task")!;
expect(submit.hasAttribute("disabled")).toBe(false);
await act(async () => root.unmount());
});
@@ -919,9 +1128,9 @@ describe("NewIssueDialog", () => {
it("creates a task from its description without requiring a title", async () => {
const { root } = renderDialog(container);
await flush();
- const submit = Array.from(container.querySelectorAll("button")).find(button => button.textContent?.includes("Create Task"))!;
+ const submit = Array.from(container.querySelectorAll("button")).find(button => button.getAttribute("aria-label") === "Create task")!;
expect(submit.hasAttribute("disabled")).toBe(true);
- await typeTextareaValue(container.querySelector('textarea[aria-label="Add description..."]')!, "Investigate the sign-in redirect and fix it");
+ await typeTextareaValue(container.querySelector('textarea[aria-label="Describe a task…"]')!, "Investigate the sign-in redirect and fix it");
await vi.waitFor(() => expect(submit.hasAttribute("disabled")).toBe(false));
await act(async () => { submit.dispatchEvent(new MouseEvent("click", { bubbles: true })); });
await flush();
@@ -930,7 +1139,25 @@ describe("NewIssueDialog", () => {
await act(async () => root.unmount());
});
- it("submits the latest locally typed title and description", async () => {
+ it.each(["Corrected task title", ""])("lets users edit or clear an inherited title (%s)", async (nextTitle) => {
+ dialogState.newIssueDefaults = { title: "Suggested title", description: "Investigate the redirect" };
+ const { root } = renderDialog(container);
+ await flush();
+ const titleInput = container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')!;
+ expect(titleInput.value).toBe("Suggested title");
+ await typeTextareaValue(titleInput, nextTitle);
+ expect(container.querySelector('input[aria-label="Task title"]')).toBe(titleInput);
+ const submit = container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!;
+ await act(async () => submit.click());
+ await flush();
+ const payload = mockIssuesApi.create.mock.calls[0][1];
+ expect(payload.description).toBe("Investigate the redirect");
+ if (nextTitle) expect(payload.title).toBe(nextTitle);
+ else expect(payload).not.toHaveProperty("title");
+ await act(async () => root.unmount());
+ });
+
+ it("keeps a typed request when project data arrives after editing starts", async () => {
let resolveProjects: (projects: Array<{
id: string;
name: string;
@@ -942,15 +1169,13 @@ describe("NewIssueDialog", () => {
resolveProjects = resolve;
}));
+ dialogState.newIssueDefaults = { title: "Typed issue" };
const { root } = renderDialog(container);
await flush();
- const titleInput = container.querySelector('textarea[placeholder="Task title (optional)"]') as HTMLTextAreaElement | null;
- const descriptionInput = container.querySelector('textarea[aria-label="Add description..."]') as HTMLTextAreaElement | null;
- expect(titleInput).not.toBeNull();
+ const descriptionInput = container.querySelector('textarea[aria-label="Describe a task…"]') as HTMLTextAreaElement | null;
expect(descriptionInput).not.toBeNull();
- await typeTextareaValue(titleInput!, "Typed issue");
await typeTextareaValue(descriptionInput!, "Typed description");
await act(async () => {
@@ -968,7 +1193,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -999,7 +1224,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await act(async () => {
@@ -1007,7 +1232,7 @@ describe("NewIssueDialog", () => {
});
await flush();
- expect(submitButton?.textContent).toContain("Creating...");
+ expect(submitButton?.querySelector(".animate-spin")).not.toBeNull();
expect(submitButton?.getAttribute("aria-busy")).toBe("true");
expect(container.textContent).not.toContain("Creating issue");
@@ -1019,7 +1244,7 @@ describe("NewIssueDialog", () => {
const { root, queryClient } = renderDialog(container);
await flush();
const submit = () => Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"))!;
+ .find((button) => button.getAttribute("aria-label") === "Create task")!;
act(() => submit().click());
await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1));
@@ -1057,7 +1282,7 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
act(() => Array.from(container.querySelectorAll("button"))
- .find(button => button.textContent?.includes("Create Task"))!.click());
+ .find(button => button.getAttribute("aria-label") === "Create task")!.click());
await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1));
expect(mockIssuesApi.create.mock.calls[0][1].idempotencyKey)
.toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
@@ -1072,7 +1297,7 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
const submit = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"))!;
+ .find((button) => button.getAttribute("aria-label") === "Create task")!;
act(() => submit.click());
await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledTimes(1));
expect(mockIssuesApi.create.mock.calls[0][1]).not.toHaveProperty("navigateOnCreate");
@@ -1091,7 +1316,7 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
act(() => Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"))!.click());
+ .find((button) => button.getAttribute("aria-label") === "Create task")!.click());
await waitForAssertion(() => expect(navigateMock).toHaveBeenCalledExactlyOnceWith("/PAP/issues/created-task"));
act(() => root.unmount());
});
@@ -1102,7 +1327,7 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
const submit = () => Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"))!;
+ .find((button) => button.getAttribute("aria-label") === "Create task")!;
act(() => submit().click());
await waitForAssertion(() => expect(container.textContent).toContain("Request failed"));
@@ -1116,7 +1341,7 @@ describe("NewIssueDialog", () => {
await flush();
expect(mockIssuesApi.create.mock.calls[1][1].idempotencyKey).toBe(firstPayload.idempotencyKey);
- await typeTextareaValue(container.querySelector('textarea[placeholder="Task title (optional)"]')!, "Connect another app");
+ await typeTextareaValue(container.querySelector<HTMLInputElement>('input[aria-label="Task title"]')!, "Connect another app");
act(() => submit().click());
await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledTimes(3));
expect(mockIssuesApi.create.mock.calls[2][1].idempotencyKey).not.toBe(firstPayload.idempotencyKey);
@@ -1131,19 +1356,17 @@ describe("NewIssueDialog", () => {
"हिन्दी: कृपया स्थिति बताएं।",
].join("\n");
+ dialogState.newIssueDefaults = { title };
const { root } = renderDialog(container);
await flush();
- const titleInput = container.querySelector('textarea[placeholder="Task title (optional)"]') as HTMLTextAreaElement | null;
- const descriptionInput = container.querySelector('textarea[aria-label="Add description..."]') as HTMLTextAreaElement | null;
- expect(titleInput).not.toBeNull();
+ const descriptionInput = container.querySelector('textarea[aria-label="Describe a task…"]') as HTMLTextAreaElement | null;
expect(descriptionInput).not.toBeNull();
- await typeTextareaValue(titleInput!, title);
await typeTextareaValue(descriptionInput!, description);
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -1170,11 +1393,11 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const titleInput = container.querySelector('textarea[placeholder="Task title (optional)"]') as HTMLTextAreaElement | null;
+ const titleInput = container.querySelector('textarea[aria-label="Describe a task…"]') as HTMLTextAreaElement | null;
expect(titleInput).not.toBeNull();
await typeTextareaValue(titleInput!, "Plan this first");
- const planningButton = container.querySelector('[data-issue-work-mode="planning"]');
+ const planningButton = container.querySelector('[data-testid="composer-add-plan"]');
expect(planningButton).not.toBeNull();
await act(async () => {
planningButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
@@ -1182,7 +1405,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -1196,7 +1419,7 @@ describe("NewIssueDialog", () => {
expect(mockIssuesApi.create).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
- title: "Plan this first",
+ description: "Plan this first",
workMode: "planning",
}),
);
@@ -1208,11 +1431,11 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const titleInput = container.querySelector('textarea[placeholder="Task title (optional)"]') as HTMLTextAreaElement | null;
+ const titleInput = container.querySelector('textarea[aria-label="Describe a task…"]') as HTMLTextAreaElement | null;
expect(titleInput).not.toBeNull();
await typeTextareaValue(titleInput!, "Answer this first");
- const askButton = container.querySelector('[data-issue-work-mode="ask"]');
+ const askButton = container.querySelector('[data-testid="composer-add-ask"]');
expect(askButton).not.toBeNull();
await act(async () => {
askButton!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
@@ -1220,7 +1443,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -1234,7 +1457,7 @@ describe("NewIssueDialog", () => {
expect(mockIssuesApi.create).toHaveBeenCalledWith(
"company-1",
expect.objectContaining({
- title: "Answer this first",
+ description: "Answer this first",
workMode: "ask",
}),
);
@@ -1246,41 +1469,40 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const modeChip = () => container.querySelector("[data-issue-work-mode-chip]");
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("standard");
- expect(modeChip()?.textContent).toContain("Auto mode");
+ const modeChip = () => container.querySelector("[data-testid=task-chat-composer-mode]");
+ expect(modeChip()).toBeNull();
await act(async () => {
- modeChip()?.dispatchEvent(new KeyboardEvent("keydown", {
+ container.querySelector(".paperclip-task-chat-composer")?.dispatchEvent(new KeyboardEvent("keydown", {
bubbles: true,
code: "",
key: ".",
metaKey: true,
}));
});
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("planning");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("planning");
expect(modeChip()?.textContent).toContain("Plan mode");
await act(async () => {
- modeChip()?.dispatchEvent(new KeyboardEvent("keydown", {
+ container.querySelector(".paperclip-task-chat-composer")?.dispatchEvent(new KeyboardEvent("keydown", {
bubbles: true,
code: "Period",
key: ".",
metaKey: true,
}));
});
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("ask");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("ask");
expect(modeChip()?.textContent).toContain("Ask mode");
await act(async () => {
- modeChip()?.dispatchEvent(new KeyboardEvent("keydown", {
+ container.querySelector(".paperclip-task-chat-composer")?.dispatchEvent(new KeyboardEvent("keydown", {
bubbles: true,
code: "Period",
key: ".",
metaKey: true,
}));
});
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("standard");
+ expect(modeChip()).toBeNull();
act(() => root.unmount());
});
@@ -1289,8 +1511,8 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const modeChip = () => container.querySelector("[data-issue-work-mode-chip]");
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("standard");
+ const modeChip = () => container.querySelector("[data-testid=task-chat-composer-mode]");
+ expect(modeChip()).toBeNull();
expect(dialogContentState.onEscapeKeyDown).not.toBeNull();
const commandPeriodAsEscape = new KeyboardEvent("keydown", {
@@ -1304,7 +1526,7 @@ describe("NewIssueDialog", () => {
});
expect(commandPeriodAsEscape.defaultPrevented).toBe(true);
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("planning");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("planning");
expect(dialogState.closeNewIssue).not.toHaveBeenCalled();
const plainEscape = new KeyboardEvent("keydown", {
@@ -1317,7 +1539,7 @@ describe("NewIssueDialog", () => {
});
expect(plainEscape.defaultPrevented).toBe(false);
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("planning");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("planning");
const controlEscape = new KeyboardEvent("keydown", {
bubbles: true,
@@ -1330,7 +1552,7 @@ describe("NewIssueDialog", () => {
});
expect(controlEscape.defaultPrevented).toBe(false);
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("planning");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("planning");
act(() => root.unmount());
});
@@ -1339,18 +1561,18 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- const modeChip = () => container.querySelector("[data-issue-work-mode-chip]");
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("standard");
+ const modeChip = () => container.querySelector("[data-testid=task-chat-composer-mode]");
+ expect(modeChip()).toBeNull();
await act(async () => {
- modeChip()?.dispatchEvent(new KeyboardEvent("keydown", {
+ container.querySelector(".paperclip-task-chat-composer")?.dispatchEvent(new KeyboardEvent("keydown", {
bubbles: true,
code: "Period",
key: ".",
ctrlKey: true,
}));
});
- expect(modeChip()?.getAttribute("data-issue-work-mode-chip")).toBe("planning");
+ expect(modeChip()?.getAttribute("data-pending-work-mode")).toBe("planning");
act(() => root.unmount());
});
@@ -1370,7 +1592,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Sub-Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create sub-task");
expect(submitButton).not.toBeUndefined();
await act(async () => {
@@ -1402,14 +1624,12 @@ describe("NewIssueDialog", () => {
expect(dialogContent?.className).toContain("h-(--new-issue-dialog-height)");
expect(dialogContent?.className).toContain("overflow-hidden");
- const titleInput = container.querySelector('textarea[placeholder="Task title (optional)"]');
- const descriptionInput = container.querySelector('textarea[aria-label="Add description..."]');
+ const descriptionInput = container.querySelector('textarea[aria-label="Describe a task…"]');
const bodyScrollRegion = Array.from(container.querySelectorAll("div")).find((element) =>
typeof element.className === "string" && element.className.includes("overscroll-contain"),
);
- expect(bodyScrollRegion?.className).toContain("flex-1");
+ expect(bodyScrollRegion?.className).toContain("min-h-0");
expect(bodyScrollRegion?.className).toContain("overflow-y-auto");
- expect(bodyScrollRegion?.contains(titleInput ?? null)).toBe(true);
expect(bodyScrollRegion?.contains(descriptionInput ?? null)).toBe(true);
act(() => root.unmount());
@@ -1438,7 +1658,7 @@ describe("NewIssueDialog", () => {
element.className.includes("max-h-(--new-issue-dialog-height)"),
);
const descriptionInput = container.querySelector<HTMLTextAreaElement>(
- 'textarea[aria-label="Add description..."]',
+ 'textarea[aria-label="Describe a task…"]',
);
const scrollIntoView = vi.fn();
Object.defineProperty(descriptionInput!, "scrollIntoView", {
@@ -1448,7 +1668,7 @@ describe("NewIssueDialog", () => {
descriptionInput?.focus();
expect(dialogContent?.style.top).toBe("");
- expect(dialogContent?.style.height).toBe("");
+ expect(dialogContent?.style.maxHeight).toBe("");
expect(dialogContent?.style.translate).toBe("");
visualViewport.height = 420;
@@ -1466,7 +1686,7 @@ describe("NewIssueDialog", () => {
"calc(var(--new-issue-visual-viewport-height) - var(--new-issue-dialog-top-gap) - var(--new-issue-dialog-bottom-gap))",
);
expect(dialogContent?.style.top).toBe("var(--new-issue-dialog-top)");
- expect(dialogContent?.style.height).toBe("var(--new-issue-dialog-height)");
+ expect(dialogContent?.style.maxHeight).toBe("var(--new-issue-dialog-height)");
expect(dialogContent?.style.translate).toBe("var(--pct-neg-50)");
expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
@@ -1497,7 +1717,7 @@ describe("NewIssueDialog", () => {
);
expect(dialogContent?.style.getPropertyValue("--new-issue-visual-viewport-height")).toBe("");
expect(dialogContent?.style.top).toBe("");
- expect(dialogContent?.style.height).toBe("");
+ expect(dialogContent?.style.maxHeight).toBe("");
expect(dialogContent?.style.translate).toBe("");
visualViewport.height = 420;
@@ -1508,7 +1728,7 @@ describe("NewIssueDialog", () => {
expect(dialogContent?.style.getPropertyValue("--new-issue-visual-viewport-height")).toBe("420px");
expect(dialogContent?.style.top).toBe("var(--new-issue-dialog-top)");
- expect(dialogContent?.style.height).toBe("var(--new-issue-dialog-height)");
+ expect(dialogContent?.style.maxHeight).toBe("var(--new-issue-dialog-height)");
visualViewport.height = 0;
visualViewport.offsetTop = Number.NaN;
@@ -1518,7 +1738,7 @@ describe("NewIssueDialog", () => {
expect(dialogContent?.style.getPropertyValue("--new-issue-visual-viewport-height")).toBe("420px");
expect(dialogContent?.style.top).toBe("var(--new-issue-dialog-top)");
- expect(dialogContent?.style.height).toBe("var(--new-issue-dialog-height)");
+ expect(dialogContent?.style.maxHeight).toBe("var(--new-issue-dialog-height)");
act(() => root.unmount());
});
@@ -1547,7 +1767,7 @@ describe("NewIssueDialog", () => {
await flush();
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -1591,101 +1811,7 @@ describe("NewIssueDialog", () => {
act(() => root.unmount());
});
- it("warns when a sub-issue stops matching the parent workspace", async () => {
- mockProjectsApi.list.mockResolvedValue([
- {
- id: "project-1",
- name: "Alpha",
- description: null,
- archivedAt: null,
- color: "#445566",
- executionWorkspacePolicy: {
- enabled: true,
- defaultMode: "shared_workspace",
- },
- },
- ]);
- mockExecutionWorkspacesApi.listSummaries.mockResolvedValue([
- {
- id: "workspace-1",
- name: "Parent workspace",
- mode: "isolated_workspace",
- status: "active",
- branchName: "feature/pap-1",
- cwd: "/tmp/workspace-1",
- projectWorkspaceId: null,
- lastUsedAt: new Date("2026-04-06T16:00:00.000Z"),
- },
- {
- id: "workspace-2",
- name: "Other workspace",
- mode: "isolated_workspace",
- status: "active",
- branchName: "feature/pap-2",
- cwd: "/tmp/workspace-2",
- projectWorkspaceId: null,
- lastUsedAt: new Date("2026-04-06T16:01:00.000Z"),
- },
- ]);
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({ enableIsolatedWorkspaces: true });
- dialogState.newIssueDefaults = {
- parentId: "issue-1",
- parentIdentifier: "PAP-1",
- parentTitle: "Parent issue",
- title: "Child issue",
- projectId: "project-1",
- executionWorkspaceId: "workspace-1",
- parentExecutionWorkspaceLabel: "Parent workspace",
- goalId: "goal-1",
- };
-
- const { root } = renderDialog(container);
- await flush();
- await flush();
-
- expect(container.textContent).not.toContain("will no longer use the parent task workspace");
-
- const selects = Array.from(container.querySelectorAll("select"));
- const modeSelect = selects[0] as HTMLSelectElement | undefined;
- expect(modeSelect).not.toBeUndefined();
-
- await act(async () => {
- modeSelect!.value = "shared_workspace";
- modeSelect!.dispatchEvent(new Event("change", { bubbles: true }));
- });
- await flush();
-
- expect(container.textContent).toContain("will no longer use the parent task workspace");
- expect(container.textContent).toContain("Parent workspace");
-
- act(() => root.unmount());
- });
-
- it("reveals the watchdog editor from the overflow menu", async () => {
- mockInstanceSettingsApi.getExperimental.mockResolvedValue({
- enableIsolatedWorkspaces: false,
- });
-
- const { root } = renderDialog(container);
- await flush();
- // The watchdog row is hidden until the menu item is toggled on.
- expect(container.querySelector('textarea[placeholder^="What should the watchdog"]')).toBeNull();
-
- const watchdogMenuItem = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.trim() === "Watchdog");
- expect(watchdogMenuItem).not.toBeUndefined();
-
- await act(async () => {
- watchdogMenuItem!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- });
- await flush();
-
- expect(container.textContent).toContain("Set watchdog");
- expect(container.querySelector('textarea[placeholder^="What should the watchdog"]')).not.toBeNull();
-
- act(() => root.unmount());
- });
it("submits the configured watchdog from a restored draft", async () => {
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
@@ -1714,10 +1840,9 @@ describe("NewIssueDialog", () => {
const { root } = renderDialog(container);
await flush();
- expect(container.textContent).toContain("Keep it moving");
const submitButton = Array.from(container.querySelectorAll("button"))
- .find((button) => button.textContent?.includes("Create Task"));
+ .find((button) => button.getAttribute("aria-label") === "Create task");
expect(submitButton).not.toBeUndefined();
await vi.waitFor(() => {
expect(submitButton?.hasAttribute("disabled")).toBe(false);
@@ -1739,66 +1864,57 @@ describe("NewIssueDialog", () => {
act(() => root.unmount());
});
- describe("graduated work-mode labels and status hues", () => {
- function workModeOption(value: string) {
- return container.querySelector(`[data-issue-work-mode="${value}"]`);
- }
+ it("retains a failed creation draft and allows retry through the composer", async () => {
+ mockIssuesApi.create.mockRejectedValueOnce(new Error("Service unavailable"));
+ dialogState.newIssueDefaults = { description: "Keep this request for retry" };
+ const { root } = renderDialog(container);
+ await flush();
+ const send = container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!;
+ await act(async () => { send.click(); });
+ await waitForAssertion(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Service unavailable"));
+ expect(container.querySelector<HTMLTextAreaElement>('textarea[aria-label="Describe a task…"]')?.value).toBe("Keep this request for retry");
+ expect(dialogState.closeNewIssue).not.toHaveBeenCalled();
+ await act(async () => { send.click(); });
+ await waitForAssertion(() => expect(dialogState.closeNewIssue).toHaveBeenCalledOnce());
+ expect(mockIssuesApi.create).toHaveBeenCalledTimes(2);
+ act(() => root.unmount());
+ });
- function statusOptionIconClass(label: string, description?: string) {
- const button = Array.from(container.querySelectorAll("button")).find((candidate) => {
- const text = candidate.textContent ?? "";
- return (
- candidate.querySelector("svg") !== null &&
- text.includes(label) &&
- (description === undefined || text.includes(description))
- );
- });
- return button?.querySelector("svg")?.getAttribute("class") ?? "";
+ it("restores shared model, effort, and fast settings into the created task", async () => {
+ mockAgentsApi.list.mockResolvedValue([{ id: "agent-1", name: "Coder", status: "active", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {} }]);
+ localStorage.setItem("paperclip:issue-draft", JSON.stringify({
+ title: "", description: "Use the saved run settings", status: "todo", priority: "medium",
+ assigneeValue: "agent:agent-1", projectId: "", workMode: "planning",
+ composerSettings: { model: "gpt-6-astra", effort: "ultra", fast: true },
+ }));
+ const { root } = renderDialog(container);
+ await waitForAssertion(() => expect(container.textContent).toContain("Coder"));
+ await act(async () => { container.querySelector<HTMLButtonElement>('[aria-label="Create task"]')!.click(); });
+ await waitForAssertion(() => expect(mockIssuesApi.create).toHaveBeenCalledWith("company-1", expect.objectContaining({
+ assigneeAgentId: "agent-1", workMode: "planning",
+ assigneeAdapterOverrides: { adapterConfig: { model: "gpt-6-astra", modelReasoningEffort: "ultra", fastMode: true } },
+ })));
+ act(() => root.unmount());
+ });
+
+ describe("work-mode labels", () => {
+ function workModeOption(value: string) {
+ return container.querySelector(`[data-testid="composer-add-${value === "planning" ? "plan" : value}"]`);
}
- it("uses auto-mode labels and brand status hues by default", async () => {
+ it("uses the shared composer mode labels", async () => {
const { root } = renderDialog(container);
await waitForAssertion(() => {
- expect(workModeOption("standard")?.textContent).toContain("Auto mode");
+ expect(container.querySelector("[data-testid=task-chat-composer-add]")).not.toBeNull();
});
- expect(workModeOption("standard")?.textContent).toContain("Auto mode");
+ expect(container.querySelector("[data-testid=task-chat-composer-add]")).not.toBeNull();
expect(workModeOption("ask")?.textContent).toContain("Ask mode");
expect(workModeOption("planning")?.textContent).toContain("Plan mode");
- expect(statusOptionIconClass("Todo", "Executable - assignee will be woken")).toContain("text-amber-600");
- expect(statusOptionIconClass("In Progress")).toContain("text-blue-600");
act(() => root.unmount());
});
});
- describe("PAP-8501: company badge shows issuePrefix", () => {
- it("displays issuePrefix instead of name-derived prefix", async () => {
- // Override company data to have mismatched name/prefix
- companyState.companies = [
- {
- id: "company-1",
- name: "Acme Labs",
- status: "active",
- issuePrefix: "OPS",
- },
- ];
- companyState.selectedCompany = {
- id: "company-1",
- name: "Acme Labs",
- status: "active",
- issuePrefix: "OPS",
- };
-
- const { root } = renderDialog(container);
- await waitForAssertion(() => {
- const text = container.textContent ?? "";
- // Should show OPS (issuePrefix), not ACM (name.slice(0,3))
- expect(text).toContain("OPS");
- });
-
- act(() => root.unmount());
- });
- });
});
diff --git a/ui/src/components/NewIssueDialog.tsx b/ui/src/components/NewIssueDialog.tsx
index 36ef947261..73be4ff291 100644
--- a/ui/src/components/NewIssueDialog.tsx
+++ b/ui/src/components/NewIssueDialog.tsx
@@ -1,7 +1,5 @@
import { useWorkspaceIsolationControls } from "@/hooks/useWorkspaceIsolationControls";
-import { AgentAvatar } from "@/components/AgentAvatar";
-import { normalizeLegacyRunnerProvider } from "@paperclipai/adapter-utils";
-import { memo, useState, useEffect, useRef, useCallback, useMemo, type ChangeEvent, type CSSProperties, type DragEvent, type RefObject } from "react";
+import { useState, useEffect, useRef, useCallback, useMemo, type CSSProperties, type DragEvent } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import type { AgentEnvConfig, EnvBinding, IssueWorkMode } from "@paperclipai/shared";
import { useDialog } from "../context/DialogContext";
@@ -18,7 +16,6 @@ import { assetsApi } from "../api/assets";
import { buildCompanyUserInlineOptions, buildMarkdownMentionOptions, isAgentTaskTarget } from "../lib/company-members";
import { queryKeys } from "../lib/queryKeys";
import { useNavigate } from "../lib/router";
-import { orderReusableExecutionWorkspaces } from "../lib/reusable-execution-workspaces";
import {
defaultExecutionWorkspaceModeForProject,
defaultProjectWorkspaceIdForProject,
@@ -26,66 +23,27 @@ import {
} from "../lib/project-workspace-defaults";
import { useProjectOrder } from "../hooks/useProjectOrder";
import { useStreamlinedUiEnabled } from "../hooks/useStreamlinedUiEnabled";
-import { getRecentAssigneeIds, sortAgentsByRecency, trackRecentAssignee } from "../lib/recent-assignees";
-import { getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
+import { getRecentAssigneeIds, getRecentAssigneeSelectionIds, sortAgentsByRecency, trackRecentAssignee, trackRecentAssigneeUser } from "../lib/recent-assignees";
+import { getLastProjectId, getRecentProjectIds, trackRecentProject } from "../lib/recent-projects";
import { recordRecentTask } from "../lib/recent-tasks";
import { buildExecutionPolicy } from "../lib/issue-execution-policy";
import { createUuid } from "../lib/uuid";
-import { isIssueWorkMode, nextWorkMode, workModeMetaFor, workModeMetaList } from "../lib/work-mode-meta";
+import { isIssueWorkMode, nextWorkMode } from "../lib/work-mode-meta";
import { useToastActions } from "../context/ToastContext";
-import {
- assigneeValueFromSelection,
- currentUserAssigneeOption,
- parseAssigneeValue,
-} from "../lib/assignees";
-import {
- Dialog,
- DialogContent,
-} from "@/components/ui/dialog";
+import { assigneeValueFromSelection, currentUserAssigneeOption, parseAssigneeValue } from "../lib/assignees";
+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
-import { ToggleSwitch } from "@/components/ui/toggle-switch";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/components/ui/popover";
-import {
- Maximize2,
- Minimize2,
- MoreHorizontal,
- ChevronRight,
- ChevronDown,
- Check,
- CircleDot,
- Minus,
- ArrowUp,
- ArrowDown,
- AlertTriangle,
- Tag,
- Calendar,
- Paperclip,
- FileText,
- Flag,
- PauseCircle,
- Loader2,
- ListTree,
- X,
- Eye,
- ShieldAlert,
- ShieldCheck,
- ScanEye,
-} from "lucide-react";
-import { Textarea } from "@/components/ui/textarea";
+import { Paperclip, FileText, Flag, PauseCircle, ListTree, X, ShieldAlert, Folder, ChevronDown } from "lucide-react";
import { cn } from "../lib/utils";
-import { extractProviderIdWithFallback } from "../lib/model-utils";
-import { issueStatusText, issueStatusTextDefault, priorityColor, priorityColorDefault } from "../lib/status-colors";
-import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
-import { MarkdownEditor, type MarkdownEditorRef, type MentionOption } from "./MarkdownEditor";
+import type { MentionOption } from "./MarkdownEditor";
+import { TaskChatComposer } from "./task-chat/TaskChatComposer";
+import { ComposerWorktreePicker } from "./task-chat/ComposerWorktreePicker";
+import { TaskChatPresentationProvider } from "./task-chat/presentation-mode";
+import { mergeComposerRunSettings, type ComposerRunSettings } from "./task-chat/composer-run-settings";
+import { useSidebar } from "../context/SidebarContext";
import { InlineBanner } from "./InlineBanner";
import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
import { getTrustPreset } from "../lib/trust-policy-ui";
-import { ReusableExecutionWorkspaceSelect } from "./ReusableExecutionWorkspaceSelect";
-import { codexReasoningEffortOptions } from "../lib/codex-reasoning-effort";
const DRAFT_KEY = "paperclip:issue-draft";
const DEBOUNCE_MS = 800;
@@ -111,12 +69,7 @@ function readVisualViewportLayout(): VisualViewportLayout | null {
const { height, offsetTop } = window.visualViewport;
// Mobile browsers can briefly report unusable geometry while the visual
// viewport initializes or animates. Applying it collapses the dialog.
- if (
- !Number.isFinite(height)
- || height <= 0
- || !Number.isFinite(offsetTop)
- || offsetTop < 0
- ) {
+ if (!Number.isFinite(height) || height <= 0 || !Number.isFinite(offsetTop) || offsetTop < 0) {
return null;
}
return {
@@ -180,6 +133,7 @@ interface IssueDraft {
selectedExecutionWorkspaceId?: string;
useIsolatedExecutionWorkspace?: boolean;
workMode?: IssueWorkMode;
+ composerSettings?: ComposerRunSettings | null;
}
type StagedIssueFile = {
@@ -191,31 +145,7 @@ type StagedIssueFile = {
};
import { Badge } from "@/components/ui/badge";
-import {
- buildAssigneeAdapterOverrides,
- ISSUE_OVERRIDE_ADAPTER_TYPES,
- type IssueModelLane,
-} from "../lib/issue-assignee-overrides";
-
-const STAGED_FILE_ACCEPT = "image/*,application/pdf,text/plain,text/markdown,application/json,text/csv,text/html,.md,.markdown";
-
-const ISSUE_THINKING_EFFORT_OPTIONS = {
- claude_local: [
- { value: "", label: "Default" },
- { value: "low", label: "Low" },
- { value: "medium", label: "Medium" },
- { value: "high", label: "High" },
- ],
- opencode_local: [
- { value: "", label: "Default" },
- { value: "minimal", label: "Minimal" },
- { value: "low", label: "Low" },
- { value: "medium", label: "Medium" },
- { value: "high", label: "High" },
- { value: "xhigh", label: "X-High" },
- { value: "max", label: "Max" },
- ],
-} as const;
+import { buildAssigneeAdapterOverrides, type IssueModelLane } from "../lib/issue-assignee-overrides";
function loadDraft(): IssueDraft | null {
try {
@@ -288,48 +218,31 @@ function formatFileSize(file: File) {
return `${(file.size / (1024 * 1024)).toFixed(1)} MB`;
}
-function buildStatusOptions(): ReadonlyArray<{ value: string; label: string; color: string; description?: string }> {
- const palette = issueStatusText;
- return [
- {
- value: "backlog",
- label: "Backlog",
- color: palette.backlog ?? issueStatusTextDefault,
- description: "Parked - assignee will not be woken",
- },
- {
- value: "todo",
- label: "Todo",
- color: palette.todo ?? issueStatusTextDefault,
- description: "Executable - assignee will be woken",
- },
- { value: "in_progress", label: "In Progress", color: palette.in_progress ?? issueStatusTextDefault },
- { value: "in_review", label: "In Review", color: palette.in_review ?? issueStatusTextDefault },
- { value: "done", label: "Done", color: palette.done ?? issueStatusTextDefault },
- ];
-}
-
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function isRequiredUserSecretBinding(value: unknown): value is Extract<EnvBinding, { type: "user_secret_ref" }> {
- return isRecord(value)
- && value.type === "user_secret_ref"
- && typeof value.key === "string"
- && value.key.trim().length > 0
- && value.required !== false
- && value.allowMissingOverride !== true;
+ return (
+ isRecord(value) &&
+ value.type === "user_secret_ref" &&
+ typeof value.key === "string" &&
+ value.key.trim().length > 0 &&
+ value.required !== false &&
+ value.allowMissingOverride !== true
+ );
}
-function collectRequiredUserSecretKeysFromEnv(env: AgentEnvConfig | Record<string, unknown> | null | undefined): string[] {
+function collectRequiredUserSecretKeysFromEnv(
+ env: AgentEnvConfig | Record<string, unknown> | null | undefined,
+): string[] {
if (!isRecord(env)) return [];
- return Object.values(env).flatMap((binding) =>
- isRequiredUserSecretBinding(binding) ? [binding.key.trim()] : [],
- );
+ return Object.values(env).flatMap((binding) => (isRequiredUserSecretBinding(binding) ? [binding.key.trim()] : []));
}
-function uniqueRequiredUserSecretKeys(inputs: Array<AgentEnvConfig | Record<string, unknown> | null | undefined>): string[] {
+function uniqueRequiredUserSecretKeys(
+ inputs: Array<AgentEnvConfig | Record<string, unknown> | null | undefined>,
+): string[] {
return [...new Set(inputs.flatMap(collectRequiredUserSecretKeysFromEnv))];
}
@@ -337,19 +250,6 @@ function shouldWarnAboutRunUserSecrets(status: string, assigneeAgentId: string |
return Boolean(assigneeAgentId) && (status === "todo" || status === "in_progress");
}
-const priorities = [
- { value: "critical", label: "Critical", icon: AlertTriangle, color: priorityColor.critical ?? priorityColorDefault },
- { value: "high", label: "High", icon: ArrowUp, color: priorityColor.high ?? priorityColorDefault },
- { value: "medium", label: "Medium", icon: Minus, color: priorityColor.medium ?? priorityColorDefault },
- { value: "low", label: "Low", icon: ArrowDown, color: priorityColor.low ?? priorityColorDefault },
-];
-
-const EXECUTION_WORKSPACE_MODES = [
- { value: "shared_workspace", label: "Project default" },
- { value: "isolated_workspace", label: "New isolated workspace" },
- { value: "reuse_existing", label: "Reuse existing workspace" },
-] as const;
-
function defaultExecutionWorkspaceModeForIssueDefaults(
defaults: {
executionWorkspaceId?: unknown;
@@ -374,143 +274,30 @@ function isWorkModeEscapeShortcut(e: Pick<KeyboardEvent, "key" | "metaKey">) {
return e.metaKey && e.key === "Escape";
}
-const IssueTitleTextarea = memo(function IssueTitleTextarea({
- value,
- pending,
- assigneeValue,
- projectId,
- descriptionEditorRef,
- assigneeSelectorRef,
- projectSelectorRef,
- onChange,
-}: {
- value: string;
- pending: boolean;
- assigneeValue: string;
- projectId: string;
- descriptionEditorRef: RefObject<MarkdownEditorRef | null>;
- assigneeSelectorRef: RefObject<HTMLButtonElement | null>;
- projectSelectorRef: RefObject<HTMLButtonElement | null>;
- onChange: (value: string) => void;
-}) {
- const [draftValue, setDraftValue] = useState(value);
-
- useEffect(() => {
- setDraftValue(value);
- }, [value]);
-
- return (
- <textarea
- className="w-full text-lg font-semibold bg-transparent outline-none resize-none overflow-hidden placeholder:text-muted-foreground/50"
- placeholder="Task title (optional)"
- rows={1}
- value={draftValue}
- onChange={(e) => {
- const nextValue = e.target.value;
- setDraftValue(nextValue);
- onChange(nextValue);
- e.target.style.height = "auto";
- e.target.style.height = `${e.target.scrollHeight}px`;
- }}
- readOnly={pending}
- onKeyDown={(e) => {
- if (
- e.key === "Enter" &&
- !e.metaKey &&
- !e.ctrlKey &&
- !e.nativeEvent.isComposing
- ) {
- e.preventDefault();
- descriptionEditorRef.current?.focus();
- }
- if (e.key === "Tab" && !e.shiftKey) {
- e.preventDefault();
- if (assigneeValue) {
- if (projectId) {
- descriptionEditorRef.current?.focus();
- } else {
- projectSelectorRef.current?.focus();
- }
- } else {
- assigneeSelectorRef.current?.focus();
- }
- }
- }}
- autoFocus
- />
- );
-});
-
-const IssueDescriptionEditor = memo(function IssueDescriptionEditor({
- value,
- expanded,
- mentions,
- descriptionEditorRef,
- imageUploadHandler,
- onChange,
-}: {
- value: string;
- expanded: boolean;
- mentions: MentionOption[];
- descriptionEditorRef: RefObject<MarkdownEditorRef | null>;
- imageUploadHandler: (file: File) => Promise<string>;
- onChange: (value: string) => void;
-}) {
- const [draftValue, setDraftValue] = useState(value);
-
- useEffect(() => {
- setDraftValue(value);
- }, [value]);
-
- return (
- <MarkdownEditor
- ref={descriptionEditorRef}
- value={draftValue}
- onChange={(nextValue) => {
- setDraftValue(nextValue);
- onChange(nextValue);
- }}
- placeholder="Add description..."
- bordered={false}
- mentions={mentions}
- contentClassName={cn("text-sm text-muted-foreground pb-12", expanded ? "min-h-(--sz-220px)" : "min-h-(--sz-120px)")}
- imageUploadHandler={imageUploadHandler}
- />
- );
-});
-
export function NewIssueDialog() {
const { visible: workspaceIsolationControlsVisible } = useWorkspaceIsolationControls();
const { newIssueOpen, newIssueDefaults, closeNewIssue } = useDialog();
const visualViewportLayout = useVisualViewportLayout(newIssueOpen);
const dialogBodyRef = useRef<HTMLDivElement>(null);
- const { companies, selectedCompanyId, selectedCompany } = useCompany();
- const workModeOptions = useMemo(() => workModeMetaList(), []);
- const statuses = useMemo(() => buildStatusOptions(), []);
+ const { companies, selectedCompanyId: effectiveCompanyId } = useCompany();
const queryClient = useQueryClient();
const navigate = useNavigate();
const { pushToast } = useToastActions();
const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled();
const [title, setTitle] = useState("");
+ const [hasTitle, setHasTitle] = useState(false);
const [description, setDescription] = useState("");
const titleRef = useRef("");
const descriptionRef = useRef("");
- const [draftHasText, setDraftHasText] = useState(false);
const [status, setStatus] = useState("todo");
const [priority, setPriority] = useState("");
const [assigneeValue, setAssigneeValue] = useState("");
const [reviewerValue, setReviewerValue] = useState("");
const [approverValue, setApproverValue] = useState("");
- const [showReviewerRow, setShowReviewerRow] = useState(false);
- const [showApproverRow, setShowApproverRow] = useState(false);
const [watchdogAgentId, setWatchdogAgentId] = useState("");
const [watchdogInstructions, setWatchdogInstructions] = useState("");
- const [showWatchdogRow, setShowWatchdogRow] = useState(false);
- const [watchdogEditorOpen, setWatchdogEditorOpen] = useState(false);
- const [participantMenuOpen, setParticipantMenuOpen] = useState(false);
const [projectId, setProjectId] = useState("");
const [projectWorkspaceId, setProjectWorkspaceId] = useState("");
- const [assigneeOptionsOpen, setAssigneeOptionsOpen] = useState(false);
const [assigneeModelLane, setAssigneeModelLane] = useState<IssueModelLane>("primary");
const [assigneeModelOverride, setAssigneeModelOverride] = useState("");
const [assigneeThinkingEffort, setAssigneeThinkingEffort] = useState("");
@@ -518,34 +305,23 @@ export function NewIssueDialog() {
const [executionWorkspaceMode, setExecutionWorkspaceMode] = useState<string>("shared_workspace");
const [selectedExecutionWorkspaceId, setSelectedExecutionWorkspaceId] = useState("");
const [workMode, setWorkMode] = useState<IssueWorkMode>("standard");
- const [expanded, setExpanded] = useState(false);
- const [dialogCompanyId, setDialogCompanyId] = useState<string | null>(null);
+ const { isMobile } = useSidebar();
+ const [composerSettings, setComposerSettings] = useState<ComposerRunSettings | null>(null);
const [stagedFiles, setStagedFiles] = useState<StagedIssueFile[]>([]);
const [isFileDragOver, setIsFileDragOver] = useState(false);
const draftTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const executionWorkspaceDefaultProjectId = useRef<string | null>(null);
const initializationKeyRef = useRef<string | null>(null);
+ const defaultAssigneePendingRef = useRef(false);
+ const defaultProjectPendingRef = useRef(false);
const createRequestRef = useRef<{ fingerprint: string; idempotencyKey: string } | null>(null);
- const effectiveCompanyId = dialogCompanyId ?? selectedCompanyId;
- const dialogCompany = companies.find((c) => c.id === effectiveCompanyId) ?? selectedCompany;
const isSubIssueMode = Boolean(newIssueDefaults.parentId);
- const parentIssueLabel = newIssueDefaults.parentIdentifier
- ?? (newIssueDefaults.parentId ? newIssueDefaults.parentId.slice(0, 8) : "");
+ const parentIssueLabel =
+ newIssueDefaults.parentIdentifier ?? (newIssueDefaults.parentId ? newIssueDefaults.parentId.slice(0, 8) : "");
const parentExecutionWorkspaceId = newIssueDefaults.executionWorkspaceId ?? "";
const parentExecutionWorkspaceLabel = newIssueDefaults.parentExecutionWorkspaceLabel ?? parentExecutionWorkspaceId;
- // Popover states
- const [statusOpen, setStatusOpen] = useState(false);
- const [priorityOpen, setPriorityOpen] = useState(false);
- const [workModeOpen, setWorkModeOpen] = useState(false);
- const [moreOpen, setMoreOpen] = useState(false);
- const [companyOpen, setCompanyOpen] = useState(false);
- const descriptionEditorRef = useRef<MarkdownEditorRef>(null);
- const stageFileInputRef = useRef<HTMLInputElement | null>(null);
- const assigneeSelectorRef = useRef<HTMLButtonElement | null>(null);
- const projectSelectorRef = useRef<HTMLButtonElement | null>(null);
-
const { data: agents } = useQuery({
queryKey: queryKeys.agents.list(effectiveCompanyId!),
queryFn: () => agentsApi.list(effectiveCompanyId!),
@@ -557,29 +333,21 @@ export function NewIssueDialog() {
queryFn: () => projectsApi.list(effectiveCompanyId!),
enabled: !!effectiveCompanyId && newIssueOpen,
});
- const {
- data: reusableExecutionWorkspaces,
- isLoading: reusableExecutionWorkspacesLoading,
- isError: reusableExecutionWorkspacesError,
- } = useQuery({
- queryKey: queryKeys.executionWorkspaces.summaryList(effectiveCompanyId!, {
- projectId,
- projectWorkspaceId: projectWorkspaceId || undefined,
- reuseEligible: true,
+ const { data: mentionIssues } = useQuery({
+ queryKey: queryKeys.issues.mentionPool(effectiveCompanyId!),
+ queryFn: () => issuesApi.list(effectiveCompanyId!, {
+ limit: 100,
+ sortField: "updated",
+ sortDir: "desc",
}),
- queryFn: () =>
- executionWorkspacesApi.listSummaries(effectiveCompanyId!, {
- projectId,
- projectWorkspaceId: projectWorkspaceId || undefined,
- reuseEligible: true,
- }),
- enabled: Boolean(effectiveCompanyId) && newIssueOpen && Boolean(projectId) && workspaceIsolationControlsVisible,
+ enabled: Boolean(effectiveCompanyId) && newIssueOpen,
+ staleTime: 60_000,
});
- const { data: session } = useQuery({
+ const { data: session, isFetched: sessionFetched } = useQuery({
queryKey: queryKeys.auth.session,
queryFn: () => authApi.getSession(),
});
- const { data: companyMembers } = useQuery({
+ const { data: companyMembers, isFetched: membersFetched } = useQuery({
queryKey: queryKeys.access.companyUserDirectory(effectiveCompanyId!),
queryFn: () => accessApi.listUserDirectory(effectiveCompanyId!),
enabled: Boolean(effectiveCompanyId) && newIssueOpen,
@@ -591,15 +359,34 @@ export function NewIssueDialog() {
retry: false,
});
const currentUserId = session?.user?.id ?? session?.session?.userId ?? null;
- const activeProjects = useMemo(
- () => projects ?? [],
- [projects],
- );
+ const activeProjects = useMemo(() => projects ?? [], [projects]);
const { orderedProjects } = useProjectOrder({
projects: activeProjects,
companyId: effectiveCompanyId,
userId: currentUserId,
});
+ const currentProject = orderedProjects.find((project) => project.id === projectId);
+ const currentProjectExecutionWorkspacePolicy =
+ experimentalSettings?.enableIsolatedWorkspaces === true ? (currentProject?.executionWorkspacePolicy ?? null) : null;
+ const currentProjectSupportsExecutionWorkspace = Boolean(currentProjectExecutionWorkspacePolicy?.enabled);
+ const canChooseWorktrees = workspaceIsolationControlsVisible && currentProjectSupportsExecutionWorkspace;
+ const {
+ data: reusableExecutionWorkspaces,
+ isPending: worktreesLoading,
+ isError: worktreesError,
+ refetch: refetchWorktrees,
+ } = useQuery({
+ queryKey: queryKeys.executionWorkspaces.summaryList(effectiveCompanyId!, {
+ projectId,
+ reuseEligible: true,
+ }),
+ queryFn: () => executionWorkspacesApi.listSummaries(effectiveCompanyId!, {
+ projectId,
+ reuseEligible: true,
+ }),
+ enabled: Boolean(effectiveCompanyId) && newIssueOpen && canChooseWorktrees,
+ retry: false,
+ });
const selectedAssignee = useMemo(() => parseAssigneeValue(assigneeValue), [assigneeValue]);
const selectedAssigneeAgentId = selectedAssignee.assigneeAgentId;
@@ -610,31 +397,14 @@ export function NewIssueDialog() {
[agents, selectedAssigneeAgentId],
);
const assigneeAdapterType = selectedAssigneeAgent?.adapterType ?? null;
- const assigneePrimaryModel = isRecord(selectedAssigneeAgent?.adapterConfig)
- && typeof selectedAssigneeAgent.adapterConfig.model === "string"
- ? selectedAssigneeAgent.adapterConfig.model
- : "";
- const effectiveAssigneeModel = assigneeModelOverride || assigneePrimaryModel;
- const supportsAssigneeOverrides = Boolean(
- assigneeAdapterType && ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType),
- );
const mentionOptions = useMemo<MentionOption[]>(() => {
return buildMarkdownMentionOptions({
agents,
projects: orderedProjects,
members: companyMembers?.users,
+ issues: mentionIssues,
});
- }, [agents, companyMembers?.users, orderedProjects]);
-
- const catalogProvider = assigneeAdapterType === "paperclip_runner" ? String(normalizeLegacyRunnerProvider(selectedAssigneeAgent?.adapterConfig ?? {}).provider ?? "codex") : undefined;
- const { data: assigneeAdapterModels } = useQuery({
- queryKey:
- effectiveCompanyId && assigneeAdapterType
- ? queryKeys.agents.adapterModels(effectiveCompanyId, assigneeAdapterType, null, catalogProvider)
- : ["agents", "none", "adapter-models", assigneeAdapterType ?? "none"],
- queryFn: () => agentsApi.adapterModels(effectiveCompanyId!, assigneeAdapterType!, { provider: catalogProvider }),
- enabled: Boolean(effectiveCompanyId) && newIssueOpen && supportsAssigneeOverrides,
- });
+ }, [agents, companyMembers?.users, orderedProjects, mentionIssues]);
const createIssue = useMutation({
mutationFn: async ({
@@ -651,7 +421,7 @@ export function NewIssueDialog() {
if (stagedFile.kind === "document") {
const body = await stagedFile.file.text();
await issuesApi.upsertDocument(issue.id, stagedFile.documentKey ?? "document", {
- title: stagedFile.documentKey === "plan" ? null : stagedFile.title ?? null,
+ title: stagedFile.documentKey === "plan" ? null : (stagedFile.title ?? null),
format: "markdown",
body,
baseRevisionId: null,
@@ -667,6 +437,9 @@ export function NewIssueDialog() {
return { issue, companyId, failures, navigateOnCreate };
},
onSuccess: ({ issue, companyId, failures, navigateOnCreate }) => {
+ trackRecentProject(issue.projectId ?? "", companyId);
+ if (issue.assigneeAgentId) trackRecentAssignee(issue.assigneeAgentId, companyId);
+ if (issue.assigneeUserId) trackRecentAssigneeUser(issue.assigneeUserId, companyId);
if (streamlinedUiEnabled) recordRecentTask(issue, currentUserId);
queryClient.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) });
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listMineByMe(companyId) });
@@ -700,43 +473,52 @@ export function NewIssueDialog() {
},
});
- const uploadDescriptionImage = useMutation({
- mutationFn: async (file: File) => {
- if (!effectiveCompanyId) throw new Error("No organization selected");
- return assetsApi.uploadImage(effectiveCompanyId, file, "issues/drafts");
- },
- });
- const uploadDescriptionImageHandler = useCallback(async (file: File) => {
- const asset = await uploadDescriptionImage.mutateAsync(file);
- return asset.contentPath;
- }, [uploadDescriptionImage.mutateAsync]);
-
// Debounced draft saving
- const scheduleSave = useCallback(
- (draft: IssueDraft) => {
- if (draftTimer.current) clearTimeout(draftTimer.current);
- draftTimer.current = setTimeout(() => {
- if (draft.title.trim() || draft.description.trim()) saveDraft(draft);
- }, DEBOUNCE_MS);
- },
- [],
- );
+ const scheduleSave = useCallback((draft: IssueDraft) => {
+ if (draftTimer.current) clearTimeout(draftTimer.current);
+ draftTimer.current = setTimeout(() => {
+ if (draft.title.trim() || draft.description.trim()) saveDraft(draft);
+ }, DEBOUNCE_MS);
+ }, []);
const setIssueText = useCallback((nextTitle: string, nextDescription: string) => {
+ setHasTitle(Boolean(nextTitle));
titleRef.current = nextTitle;
descriptionRef.current = nextDescription;
setTitle(nextTitle);
setDescription(nextDescription);
- setDraftHasText(nextTitle.trim().length > 0 || nextDescription.trim().length > 0);
}, []);
- const queueDraftSave = useCallback((overrides: { title?: string; description?: string } = {}) => {
- if (!newIssueOpen) return;
- const nextTitle = overrides.title ?? titleRef.current;
- const nextDescription = overrides.description ?? descriptionRef.current;
- scheduleSave({
- title: nextTitle,
- description: nextDescription,
+ const queueDraftSave = useCallback(
+ (overrides: { title?: string; description?: string } = {}) => {
+ if (!newIssueOpen) return;
+ const nextTitle = overrides.title ?? titleRef.current;
+ const nextDescription = overrides.description ?? descriptionRef.current;
+ scheduleSave({
+ title: nextTitle,
+ description: nextDescription,
+ status,
+ priority,
+ assigneeValue,
+ reviewerValue,
+ approverValue,
+ watchdogAgentId,
+ watchdogInstructions,
+ projectId,
+ projectWorkspaceId,
+ assigneeModelLane,
+ assigneeModelOverride,
+ assigneeThinkingEffort,
+ assigneeChrome,
+ executionWorkspaceMode,
+ selectedExecutionWorkspaceId,
+ workMode,
+ composerSettings,
+ });
+ },
+ [
+ newIssueOpen,
+ scheduleSave,
status,
priority,
assigneeValue,
@@ -746,48 +528,25 @@ export function NewIssueDialog() {
watchdogInstructions,
projectId,
projectWorkspaceId,
- assigneeModelLane,
assigneeModelOverride,
assigneeThinkingEffort,
assigneeChrome,
executionWorkspaceMode,
selectedExecutionWorkspaceId,
workMode,
- });
- }, [
- newIssueOpen,
- scheduleSave,
- status,
- priority,
- assigneeValue,
- reviewerValue,
- approverValue,
- watchdogAgentId,
- watchdogInstructions,
- projectId,
- projectWorkspaceId,
- assigneeModelOverride,
- assigneeThinkingEffort,
- assigneeChrome,
- executionWorkspaceMode,
- selectedExecutionWorkspaceId,
- workMode,
- ]);
+ composerSettings,
+ ],
+ );
- const handleTitleChange = useCallback((nextTitle: string) => {
- titleRef.current = nextTitle;
- const nextTitleHasText = nextTitle.trim().length > 0;
- const nextDraftHasText = nextTitleHasText || descriptionRef.current.trim().length > 0;
- setDraftHasText((current) => current === nextDraftHasText ? current : nextDraftHasText);
- queueDraftSave({ title: nextTitle });
- }, [queueDraftSave]);
+ const handleDescriptionChange = useCallback(
+ (nextDescription: string) => {
+ descriptionRef.current = nextDescription;
+ setDescription(nextDescription);
- const handleDescriptionChange = useCallback((nextDescription: string) => {
- descriptionRef.current = nextDescription;
- const nextDraftHasText = titleRef.current.trim().length > 0 || nextDescription.trim().length > 0;
- setDraftHasText((current) => current === nextDraftHasText ? current : nextDraftHasText);
- queueDraftSave({ description: nextDescription });
- }, [queueDraftSave]);
+ queueDraftSave({ description: nextDescription });
+ },
+ [queueDraftSave],
+ );
// Save draft on meaningful changes
useEffect(() => {
@@ -818,23 +577,32 @@ export function NewIssueDialog() {
useEffect(() => {
if (!newIssueOpen) {
initializationKeyRef.current = null;
+ defaultAssigneePendingRef.current = false;
+ defaultProjectPendingRef.current = false;
return;
}
- const initializationKey = `${selectedCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}`;
+ const initializationKey = `${effectiveCompanyId ?? ""}:${JSON.stringify(newIssueDefaults)}`;
if (initializationKeyRef.current === initializationKey) return;
initializationKeyRef.current = initializationKey;
- setDialogCompanyId(selectedCompanyId);
+
executionWorkspaceDefaultProjectId.current = null;
const draft = loadDraft();
+ defaultProjectPendingRef.current = newIssueDefaults.projectId === undefined && !newIssueDefaults.parentId;
+ defaultAssigneePendingRef.current = !newIssueDefaults.assigneeAgentId && !newIssueDefaults.assigneeUserId;
+ setComposerSettings(null);
+ createIssue.reset();
if (newIssueDefaults.parentId) {
const nextWorkMode = isIssueWorkMode(newIssueDefaults.workMode) ? newIssueDefaults.workMode : "standard";
const defaultProjectId = newIssueDefaults.projectId ?? "";
const defaultProject = orderedProjects.find((project) => project.id === defaultProjectId);
const hasExplicitProjectWorkspaceId = newIssueDefaults.projectWorkspaceId !== undefined;
- const defaultProjectWorkspaceId = newIssueDefaults.projectWorkspaceId
- ?? defaultProjectWorkspaceIdForProject(defaultProject);
- const defaultExecutionWorkspaceMode = defaultExecutionWorkspaceModeForIssueDefaults(newIssueDefaults, defaultProject);
+ const defaultProjectWorkspaceId =
+ newIssueDefaults.projectWorkspaceId ?? defaultProjectWorkspaceIdForProject(defaultProject);
+ const defaultExecutionWorkspaceMode = defaultExecutionWorkspaceModeForIssueDefaults(
+ newIssueDefaults,
+ defaultProject,
+ );
setIssueText(newIssueDefaults.title ?? "", newIssueDefaults.description ?? "");
setStatus(newIssueDefaults.status ?? "todo");
setPriority(newIssueDefaults.priority ?? "");
@@ -848,9 +616,8 @@ export function NewIssueDialog() {
setExecutionWorkspaceMode(defaultExecutionWorkspaceMode);
setWorkMode(nextWorkMode);
setSelectedExecutionWorkspaceId(newIssueDefaults.executionWorkspaceId ?? "");
- executionWorkspaceDefaultProjectId.current = hasExplicitProjectWorkspaceId || defaultProject
- ? defaultProjectId || null
- : null;
+ executionWorkspaceDefaultProjectId.current =
+ hasExplicitProjectWorkspaceId || defaultProject ? defaultProjectId || null : null;
} else if (newIssueDefaults.title || newIssueDefaults.description) {
const nextWorkMode = isIssueWorkMode(newIssueDefaults.workMode) ? newIssueDefaults.workMode : "standard";
setIssueText(newIssueDefaults.title ?? "", newIssueDefaults.description ?? "");
@@ -864,21 +631,23 @@ export function NewIssueDialog() {
setAssigneeValue(assigneeValueFromSelection(newIssueDefaults));
setReviewerValue("");
setApproverValue("");
- setShowReviewerRow(false);
- setShowApproverRow(false);
+
setWatchdogAgentId("");
setWatchdogInstructions("");
- setShowWatchdogRow(false);
+
setAssigneeModelOverride("");
setAssigneeThinkingEffort("");
setAssigneeChrome(false);
setExecutionWorkspaceMode(defaultExecutionWorkspaceModeForIssueDefaults(newIssueDefaults, defaultProject));
setWorkMode(nextWorkMode);
setSelectedExecutionWorkspaceId(newIssueDefaults.executionWorkspaceId ?? "");
- executionWorkspaceDefaultProjectId.current = hasExplicitProjectWorkspaceId || newIssueDefaults.executionWorkspaceId || defaultProject
- ? defaultProjectId || null
- : null;
+ executionWorkspaceDefaultProjectId.current =
+ hasExplicitProjectWorkspaceId || newIssueDefaults.executionWorkspaceId || defaultProject
+ ? defaultProjectId || null
+ : null;
} else if (draft && (draft.title.trim() || draft.description.trim())) {
+ defaultAssigneePendingRef.current = false;
+ defaultProjectPendingRef.current = false;
const nextWorkMode = isIssueWorkMode(draft.workMode) ? draft.workMode : "standard";
const restoredProjectId = newIssueDefaults.projectId ?? draft.projectId;
const restoredProject = orderedProjects.find((project) => project.id === restoredProjectId);
@@ -886,6 +655,7 @@ export function NewIssueDialog() {
const hasExplicitExecutionWorkspaceId = newIssueDefaults.executionWorkspaceId !== undefined;
const hasExplicitExecutionWorkspaceMode = newIssueDefaults.executionWorkspaceMode !== undefined;
setIssueText(draft.title, draft.description);
+ setComposerSettings(draft.composerSettings ?? null);
setStatus(draft.status || "todo");
setPriority(draft.priority);
setAssigneeValue(
@@ -895,11 +665,10 @@ export function NewIssueDialog() {
);
setReviewerValue(draft.reviewerValue ?? "");
setApproverValue(draft.approverValue ?? "");
- setShowReviewerRow(!!(draft.reviewerValue));
- setShowApproverRow(!!(draft.approverValue));
+
setWatchdogAgentId(draft.watchdogAgentId ?? "");
setWatchdogInstructions(draft.watchdogInstructions ?? "");
- setShowWatchdogRow(!!(draft.watchdogAgentId));
+
setProjectId(restoredProjectId);
setProjectWorkspaceId(
hasExplicitProjectWorkspaceId
@@ -913,10 +682,10 @@ export function NewIssueDialog() {
setExecutionWorkspaceMode(
hasExplicitExecutionWorkspaceId || hasExplicitExecutionWorkspaceMode
? defaultExecutionWorkspaceModeForIssueDefaults(newIssueDefaults, restoredProject)
- : (
- draft.executionWorkspaceMode
- ?? (draft.useIsolatedExecutionWorkspace ? "isolated_workspace" : defaultExecutionWorkspaceModeForProject(restoredProject))
- ),
+ : (draft.executionWorkspaceMode ??
+ (draft.useIsolatedExecutionWorkspace
+ ? "isolated_workspace"
+ : defaultExecutionWorkspaceModeForProject(restoredProject))),
);
setWorkMode(nextWorkMode);
setSelectedExecutionWorkspaceId(
@@ -924,11 +693,12 @@ export function NewIssueDialog() {
? (newIssueDefaults.executionWorkspaceId ?? "")
: (draft.selectedExecutionWorkspaceId ?? ""),
);
- executionWorkspaceDefaultProjectId.current = hasExplicitProjectWorkspaceId || hasExplicitExecutionWorkspaceId || draft.projectWorkspaceId || restoredProject
- ? restoredProjectId || null
- : null;
+ executionWorkspaceDefaultProjectId.current =
+ hasExplicitProjectWorkspaceId || hasExplicitExecutionWorkspaceId || draft.projectWorkspaceId || restoredProject
+ ? restoredProjectId || null
+ : null;
} else {
- setWorkMode("standard");
+ setWorkMode(isIssueWorkMode(newIssueDefaults.workMode) ? newIssueDefaults.workMode : "standard");
const defaultProjectId = newIssueDefaults.projectId ?? "";
const defaultProject = orderedProjects.find((project) => project.id === defaultProjectId);
const hasExplicitProjectWorkspaceId = newIssueDefaults.projectWorkspaceId !== undefined;
@@ -940,46 +710,21 @@ export function NewIssueDialog() {
setAssigneeValue(assigneeValueFromSelection(newIssueDefaults));
setReviewerValue("");
setApproverValue("");
- setShowReviewerRow(false);
- setShowApproverRow(false);
+
setWatchdogAgentId("");
setWatchdogInstructions("");
- setShowWatchdogRow(false);
+
setAssigneeModelOverride("");
setAssigneeThinkingEffort("");
setAssigneeChrome(false);
setExecutionWorkspaceMode(defaultExecutionWorkspaceModeForIssueDefaults(newIssueDefaults, defaultProject));
setSelectedExecutionWorkspaceId(newIssueDefaults.executionWorkspaceId ?? "");
- executionWorkspaceDefaultProjectId.current = hasExplicitProjectWorkspaceId || newIssueDefaults.executionWorkspaceId || defaultProject
- ? defaultProjectId || null
- : null;
- }
- }, [newIssueOpen, newIssueDefaults, orderedProjects, selectedCompanyId, setIssueText]);
-
- useEffect(() => {
- if (!supportsAssigneeOverrides) {
- setAssigneeOptionsOpen(false);
- setAssigneeModelLane("primary");
- setAssigneeModelOverride("");
- setAssigneeThinkingEffort("");
- setAssigneeChrome(false);
- return;
- }
- const validThinkingValues =
- assigneeAdapterType === "codex_local"
- ? codexReasoningEffortOptions(effectiveAssigneeModel)
- : assigneeAdapterType === "opencode_local"
- ? ISSUE_THINKING_EFFORT_OPTIONS.opencode_local
- : ISSUE_THINKING_EFFORT_OPTIONS.claude_local;
- if (!validThinkingValues.some((option) => option.value === assigneeThinkingEffort)) {
- setAssigneeThinkingEffort("");
+ executionWorkspaceDefaultProjectId.current =
+ hasExplicitProjectWorkspaceId || newIssueDefaults.executionWorkspaceId || defaultProject
+ ? defaultProjectId || null
+ : null;
}
- }, [
- supportsAssigneeOverrides,
- assigneeAdapterType,
- effectiveAssigneeModel,
- assigneeThinkingEffort,
- ]);
+ }, [newIssueOpen, newIssueDefaults, orderedProjects, effectiveCompanyId, setIssueText]);
// Cleanup timer on unmount
useEffect(() => {
@@ -996,14 +741,12 @@ export function NewIssueDialog() {
setAssigneeValue("");
setReviewerValue("");
setApproverValue("");
- setShowReviewerRow(false);
- setShowApproverRow(false);
+
setWatchdogAgentId("");
setWatchdogInstructions("");
- setShowWatchdogRow(false);
+
setProjectId("");
setProjectWorkspaceId("");
- setAssigneeOptionsOpen(false);
setAssigneeModelLane("primary");
setAssigneeModelOverride("");
setAssigneeThinkingEffort("");
@@ -1011,51 +754,23 @@ export function NewIssueDialog() {
setExecutionWorkspaceMode("shared_workspace");
setSelectedExecutionWorkspaceId("");
setWorkMode("standard");
- setExpanded(false);
- setDialogCompanyId(null);
+
+ setComposerSettings(null);
+
setStagedFiles([]);
setIsFileDragOver(false);
- setCompanyOpen(false);
+
executionWorkspaceDefaultProjectId.current = null;
initializationKeyRef.current = null;
}
- function handleCompanyChange(companyId: string) {
- if (isSubIssueMode) return;
- if (companyId === effectiveCompanyId) return;
- setDialogCompanyId(companyId);
- setAssigneeValue("");
- setReviewerValue("");
- setApproverValue("");
- setShowReviewerRow(false);
- setShowApproverRow(false);
- setWatchdogAgentId("");
- setWatchdogInstructions("");
- setShowWatchdogRow(false);
- setProjectId("");
- setProjectWorkspaceId("");
- setAssigneeModelLane("primary");
- setAssigneeModelOverride("");
- setAssigneeThinkingEffort("");
- setAssigneeChrome(false);
- setExecutionWorkspaceMode("shared_workspace");
- setSelectedExecutionWorkspaceId("");
- setWorkMode("standard");
- }
-
- function discardDraft() {
- clearDraft();
- reset();
- closeNewIssue();
- }
-
- function handleSubmit() {
+ async function handleSubmit(body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) {
const currentTitle = titleRef.current.trim();
- const currentDescription = descriptionRef.current.trim();
- if (!effectiveCompanyId || (!currentTitle && !currentDescription) || createIssue.isPending) return;
- const assigneeAdapterOverrides = buildAssigneeAdapterOverrides({
+ const currentDescription = body.trim();
+ if (!effectiveCompanyId || (!currentTitle && !currentDescription) || createIssue.isPending || worktreeSelectionIncomplete) return;
+ const inheritedOverrides = buildAssigneeAdapterOverrides({
adapterType: assigneeAdapterType,
- lane: assigneeModelLane,
+ lane: assigneeChrome ? "custom" : assigneeModelLane,
modelOverride: assigneeModelOverride,
thinkingEffortOverride: assigneeThinkingEffort,
chrome: assigneeChrome,
@@ -1064,7 +779,7 @@ export function NewIssueDialog() {
// Hidden selectors must not submit a restored draft over the managed default.
const executionWorkspacePolicy =
workspaceIsolationControlsVisible && experimentalSettings?.enableIsolatedWorkspaces === true
- ? selectedProject?.executionWorkspacePolicy ?? null
+ ? (selectedProject?.executionWorkspacePolicy ?? null)
: null;
const selectedReusableExecutionWorkspace = selectableReusableWorkspaces.find(
(workspace) => workspace.id === selectedExecutionWorkspaceId,
@@ -1076,16 +791,22 @@ export function NewIssueDialog() {
const executionWorkspaceSettings = executionWorkspacePolicy?.enabled
? { mode: requestedExecutionWorkspaceMode }
: null;
+ const requestedProjectWorkspaceId = canChooseWorktrees && executionWorkspaceMode === "reuse_existing" && selectedReusableExecutionWorkspace
+ ? selectedReusableExecutionWorkspace.projectWorkspaceId
+ : projectWorkspaceId;
// A task launched from a workspace (or its parent task) keeps that explicit
// context. Draft-only choices are ignored while the selector is hidden.
- const contextualWorkspaceId = !workspaceIsolationControlsVisible
- && newIssueDefaults.projectId === projectId
- ? newIssueDefaults.executionWorkspaceId
- : undefined;
+ const contextualWorkspaceId =
+ !workspaceIsolationControlsVisible && newIssueDefaults.projectId === projectId
+ ? newIssueDefaults.executionWorkspaceId
+ : undefined;
const executionPolicy = buildExecutionPolicy({
reviewerValues: reviewerValue ? [reviewerValue] : [],
approverValues: approverValue ? [approverValue] : [],
});
+ const assigneeAdapterOverrides = settings
+ ? mergeComposerRunSettings(inheritedOverrides, assigneeAdapterType ?? undefined, settings)
+ : inheritedOverrides;
const createData = {
companyId: effectiveCompanyId,
stagedFiles,
@@ -1093,20 +814,24 @@ export function NewIssueDialog() {
description: currentDescription || undefined,
status,
priority: priority || "medium",
- workMode,
+ workMode: mode,
...(selectedAssigneeAgentId ? { assigneeAgentId: selectedAssigneeAgentId } : {}),
...(selectedAssigneeUserId ? { assigneeUserId: selectedAssigneeUserId } : {}),
...(newIssueDefaults.parentId ? { parentId: newIssueDefaults.parentId } : {}),
...(newIssueDefaults.goalId ? { goalId: newIssueDefaults.goalId } : {}),
...(projectId ? { projectId } : {}),
- ...(projectWorkspaceId ? { projectWorkspaceId } : {}),
+ ...(requestedProjectWorkspaceId ? { projectWorkspaceId: requestedProjectWorkspaceId } : {}),
...(assigneeAdapterOverrides ? { assigneeAdapterOverrides } : {}),
...(executionWorkspacePolicy?.enabled ? { executionWorkspacePreference: executionWorkspaceMode } : {}),
- ...(workspaceIsolationControlsVisible && executionWorkspaceMode === "reuse_existing" && selectedExecutionWorkspaceId
+ ...(canChooseWorktrees &&
+ executionWorkspaceMode === "reuse_existing" &&
+ selectedExecutionWorkspaceId
? { executionWorkspaceId: selectedExecutionWorkspaceId }
: {}),
...(executionWorkspaceSettings ? { executionWorkspaceSettings } : {}),
- ...(contextualWorkspaceId ? { executionWorkspaceId: contextualWorkspaceId, executionWorkspacePreference: "reuse_existing" } : {}),
+ ...(contextualWorkspaceId
+ ? { executionWorkspaceId: contextualWorkspaceId, executionWorkspacePreference: "reuse_existing" }
+ : {}),
...(executionPolicy ? { executionPolicy } : {}),
...(watchdogAgentId
? { watchdog: { agentId: watchdogAgentId, instructions: watchdogInstructions.trim() || null } }
@@ -1118,7 +843,7 @@ export function NewIssueDialog() {
if (createRequestRef.current?.fingerprint !== fingerprint) {
createRequestRef.current = { fingerprint, idempotencyKey: createUuid() };
}
- createIssue.mutate({
+ await createIssue.mutateAsync({
...createData,
allowDuplicate: true,
idempotencyKey: createRequestRef.current.idempotencyKey,
@@ -1132,14 +857,10 @@ export function NewIssueDialog() {
setWorkMode((current) => nextWorkMode(current));
return;
}
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- handleSubmit();
- }
}
function stageFiles(files: File[]) {
- if (files.length === 0) return;
+ if (files.length === 0 || createIssue.isPending) return;
setStagedFiles((current) => {
const next = [...current];
for (const file of files) {
@@ -1165,13 +886,6 @@ export function NewIssueDialog() {
});
}
- function handleStageFilesPicked(evt: ChangeEvent<HTMLInputElement>) {
- stageFiles(Array.from(evt.target.files ?? []));
- if (stageFileInputRef.current) {
- stageFileInputRef.current.value = "";
- }
- }
-
function handleFileDragEnter(evt: DragEvent<HTMLDivElement>) {
if (!evt.dataTransfer.types.includes("Files")) return;
evt.preventDefault();
@@ -1201,68 +915,35 @@ export function NewIssueDialog() {
setStagedFiles((current) => current.filter((file) => file.id !== id));
}
- const hasDraft = draftHasText || stagedFiles.length > 0;
- const currentStatus = statuses.find((s) => s.value === status) ?? statuses[1]!;
- const currentPriority = priorities.find((p) => p.value === priority);
- const currentAssignee = selectedAssigneeAgentId
- ? (agents ?? []).find((a) => a.id === selectedAssigneeAgentId)
- : null;
+ const currentAssignee = selectedAssigneeAgentId ? (agents ?? []).find((a) => a.id === selectedAssigneeAgentId) : null;
const currentAssigneeLowTrust = getTrustPreset(currentAssignee?.permissions) === "low_trust_review";
- const currentProject = orderedProjects.find((project) => project.id === projectId);
- const neededUserSecretKeys = useMemo(
- () => {
- if (!shouldWarnAboutRunUserSecrets(status, selectedAssigneeAgentId)) return [];
- return uniqueRequiredUserSecretKeys([
- isRecord(currentAssignee?.adapterConfig) ? currentAssignee.adapterConfig.env as Record<string, unknown> : null,
- currentProject?.env ?? null,
- ]);
- },
- [currentAssignee?.adapterConfig, currentProject?.env, selectedAssigneeAgentId, status],
- );
- const currentProjectExecutionWorkspacePolicy =
- experimentalSettings?.enableIsolatedWorkspaces === true
- ? currentProject?.executionWorkspacePolicy ?? null
- : null;
- const currentProjectSupportsExecutionWorkspace = Boolean(currentProjectExecutionWorkspacePolicy?.enabled);
+ const neededUserSecretKeys = useMemo(() => {
+ if (!shouldWarnAboutRunUserSecrets(status, selectedAssigneeAgentId)) return [];
+ return uniqueRequiredUserSecretKeys([
+ isRecord(currentAssignee?.adapterConfig) ? (currentAssignee.adapterConfig.env as Record<string, unknown>) : null,
+ currentProject?.env ?? null,
+ ]);
+ }, [currentAssignee?.adapterConfig, currentProject?.env, selectedAssigneeAgentId, status]);
const selectableReusableWorkspaces = reusableExecutionWorkspaces ?? [];
- const selectedReusableExecutionWorkspace = selectableReusableWorkspaces.find(
- (workspace) => workspace.id === selectedExecutionWorkspaceId,
- );
- const isUsingParentExecutionWorkspace = isSubIssueMode && parentExecutionWorkspaceId
- ? executionWorkspaceMode === "reuse_existing" && selectedExecutionWorkspaceId === parentExecutionWorkspaceId
- : false;
- const showParentWorkspaceWarning = isSubIssueMode
- && currentProjectSupportsExecutionWorkspace
- && Boolean(parentExecutionWorkspaceId)
- && !isUsingParentExecutionWorkspace;
- const assigneeOptionsTitle =
- assigneeAdapterType === "claude_local"
- ? "Claude options"
- : assigneeAdapterType === "codex_local"
- ? "Codex options"
- : assigneeAdapterType === "opencode_local"
- ? "OpenCode options"
- : "Agent options";
- const thinkingEffortOptions =
- assigneeAdapterType === "codex_local"
- ? codexReasoningEffortOptions(effectiveAssigneeModel)
- : assigneeAdapterType === "opencode_local"
- ? ISSUE_THINKING_EFFORT_OPTIONS.opencode_local
- : ISSUE_THINKING_EFFORT_OPTIONS.claude_local;
+ const selectedReusableWorktree = selectableReusableWorkspaces.find((workspace) => workspace.id === selectedExecutionWorkspaceId);
+ const worktreeSelectionIncomplete = canChooseWorktrees && executionWorkspaceMode === "reuse_existing"
+ && (worktreesLoading || worktreesError || !selectedReusableWorktree);
+ const isUsingParentExecutionWorkspace =
+ isSubIssueMode && parentExecutionWorkspaceId
+ ? executionWorkspaceMode === "reuse_existing" && selectedExecutionWorkspaceId === parentExecutionWorkspaceId
+ : false;
+ const showParentWorkspaceWarning =
+ isSubIssueMode &&
+ currentProjectSupportsExecutionWorkspace &&
+ Boolean(parentExecutionWorkspaceId) &&
+ !isUsingParentExecutionWorkspace;
const recentAssigneeIds = useMemo(() => getRecentAssigneeIds(), [newIssueOpen]);
- const recentAssigneeOptionIds = useMemo(
- () => recentAssigneeIds.map((id) => assigneeValueFromSelection({ assigneeAgentId: id })),
- [recentAssigneeIds],
- );
const recentProjectIds = useMemo(() => getRecentProjectIds(), [newIssueOpen]);
const assigneeOptions = useMemo<InlineEntityOption[]>(
() => [
...currentUserAssigneeOption(currentUserId),
...buildCompanyUserInlineOptions(companyMembers?.users, { excludeUserIds: [currentUserId] }),
- ...sortAgentsByRecency(
- (agents ?? []).filter(isAgentTaskTarget),
- recentAssigneeIds,
- ).map((agent) => ({
+ ...sortAgentsByRecency((agents ?? []).filter(isAgentTaskTarget), recentAssigneeIds).map((agent) => ({
id: assigneeValueFromSelection({ assigneeAgentId: agent.id }),
label: agent.name,
searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`,
@@ -1270,19 +951,33 @@ export function NewIssueDialog() {
],
[agents, companyMembers?.users, currentUserId, recentAssigneeIds],
);
- const watchdogAgentOptions = useMemo<InlineEntityOption[]>(
- () =>
- sortAgentsByRecency((agents ?? []).filter(isAgentTaskTarget), recentAssigneeIds).map((agent) => ({
- id: agent.id,
- label: agent.name,
- searchText: `${agent.name} ${agent.role} ${agent.title ?? ""}`,
- })),
- [agents, recentAssigneeIds],
- );
- const selectedWatchdogAgent = useMemo(
- () => (watchdogAgentId ? (agents ?? []).find((agent) => agent.id === watchdogAgentId) ?? null : null),
- [agents, watchdogAgentId],
- );
+ // Resolve once after the directory loads, without resetting text typed while
+ // the queries were in flight or replacing an explicit/restored assignee.
+ useEffect(() => {
+ if (!newIssueOpen || !effectiveCompanyId || !defaultAssigneePendingRef.current
+ || !agents || !sessionFetched || !membersFetched) return;
+ defaultAssigneePendingRef.current = false;
+ const available = new Set(assigneeOptions.map((option) => option.id));
+ const scopedRecents = getRecentAssigneeSelectionIds(effectiveCompanyId);
+ // Older history has no company key. Agent IDs identify their company;
+ // human IDs can belong to several companies and cannot be migrated safely.
+ const recents = scopedRecents.length ? scopedRecents
+ : getRecentAssigneeSelectionIds().filter((value) => value.startsWith("agent:"));
+ const recent = recents.find((value) => available.has(value));
+ const targets = agents.filter(isAgentTaskTarget);
+ const fallback = targets.find((agent) => agent.role === "ceo") ?? targets[0];
+ setAssigneeValue(recent ?? (fallback ? assigneeValueFromSelection({ assigneeAgentId: fallback.id }) : ""));
+ }, [newIssueOpen, effectiveCompanyId, agents, assigneeOptions, sessionFetched, membersFetched]);
+ useEffect(() => {
+ if (!newIssueOpen || !effectiveCompanyId || !defaultProjectPendingRef.current || !projects) return;
+ defaultProjectPendingRef.current = false;
+ const available = new Set(orderedProjects.filter((project) => !project.archivedAt).map((project) => project.id));
+ const last = getLastProjectId(effectiveCompanyId);
+ const remembered = last !== undefined
+ ? (available.has(last) ? last : "")
+ : (getRecentProjectIds().find((id) => available.has(id)) ?? "");
+ setProjectId(remembered);
+ }, [newIssueOpen, effectiveCompanyId, projects, orderedProjects]);
const projectOptions = useMemo<InlineEntityOption[]>(
() =>
orderedProjects.map((project) => ({
@@ -1292,23 +987,22 @@ export function NewIssueDialog() {
})),
[orderedProjects],
);
- const savedDraft = useMemo(() => newIssueOpen ? loadDraft() : null, [newIssueOpen]);
- const hasSavedDraft = Boolean(savedDraft?.title.trim() || savedDraft?.description.trim());
- const canDiscardDraft = hasDraft || hasSavedDraft;
- const createIssueErrorMessage =
- createIssue.error instanceof Error ? createIssue.error.message : "Failed to create task. Try again.";
const stagedDocuments = stagedFiles.filter((file) => file.kind === "document");
const stagedAttachments = stagedFiles.filter((file) => file.kind === "attachment");
- const handleProjectChange = useCallback((nextProjectId: string) => {
- if (nextProjectId) trackRecentProject(nextProjectId);
- setProjectId(nextProjectId);
- const nextProject = orderedProjects.find((project) => project.id === nextProjectId);
- executionWorkspaceDefaultProjectId.current = nextProjectId || null;
- setProjectWorkspaceId(defaultProjectWorkspaceIdForProject(nextProject));
- setExecutionWorkspaceMode(defaultExecutionWorkspaceModeForProject(nextProject));
- setSelectedExecutionWorkspaceId("");
- }, [orderedProjects]);
+ const handleProjectChange = useCallback(
+ (nextProjectId: string) => {
+ defaultProjectPendingRef.current = false;
+ trackRecentProject(nextProjectId, effectiveCompanyId ?? undefined);
+ setProjectId(nextProjectId);
+ const nextProject = orderedProjects.find((project) => project.id === nextProjectId);
+ executionWorkspaceDefaultProjectId.current = nextProjectId || null;
+ setProjectWorkspaceId(defaultProjectWorkspaceIdForProject(nextProject));
+ setExecutionWorkspaceMode(defaultExecutionWorkspaceModeForProject(nextProject));
+ setSelectedExecutionWorkspaceId("");
+ },
+ [orderedProjects, effectiveCompanyId],
+ );
useEffect(() => {
if (
@@ -1326,26 +1020,6 @@ export function NewIssueDialog() {
setExecutionWorkspaceMode(defaultExecutionWorkspaceModeForProject(project));
setSelectedExecutionWorkspaceId("");
}, [newIssueOpen, orderedProjects, projectId, selectedExecutionWorkspaceId]);
- const modelOverrideOptions = useMemo<InlineEntityOption[]>(
- () => {
- return [...(assigneeAdapterModels ?? [])]
- .sort((a, b) => {
- const providerA = extractProviderIdWithFallback(a.id);
- const providerB = extractProviderIdWithFallback(b.id);
- const byProvider = providerA.localeCompare(providerB);
- if (byProvider !== 0) return byProvider;
- return a.id.localeCompare(b.id);
- })
- .map((model) => ({
- id: model.id,
- label: model.label,
- searchText: `${model.id} ${extractProviderIdWithFallback(model.id)}`,
- }));
- },
- [assigneeAdapterModels],
- );
- const currentWorkMode = workModeMetaFor(workMode);
- const CurrentWorkModeIcon = currentWorkMode.icon;
const dialogViewportStyle = useMemo<NewIssueDialogViewportStyle>(() => {
const dialogGeometry = {
// Fixed-position coordinates are relative to Safari's visual viewport.
@@ -1362,7 +1036,7 @@ export function NewIssueDialog() {
...(visualViewportLayout.constrained
? {
top: "var(--new-issue-dialog-top)",
- height: "var(--new-issue-dialog-height)",
+ maxHeight: "var(--new-issue-dialog-height)",
translate: "var(--pct-neg-50)",
}
: {}),
@@ -1379,9 +1053,9 @@ export function NewIssueDialog() {
if (!visualViewportLayout?.constrained) return;
const focusedElement = document.activeElement;
if (
- !(focusedElement instanceof HTMLElement)
- || !dialogBodyRef.current?.contains(focusedElement)
- || typeof focusedElement.scrollIntoView !== "function"
+ !(focusedElement instanceof HTMLElement) ||
+ !dialogBodyRef.current?.contains(focusedElement) ||
+ typeof focusedElement.scrollIntoView !== "function"
) {
return;
}
@@ -1392,6 +1066,15 @@ export function NewIssueDialog() {
return () => window.cancelAnimationFrame(frame);
}, [visualViewportLayout]);
+ const modelAgents = useMemo(() => new Map((agents ?? []).map((agent) => [agent.id, agent])), [agents]);
+ const inheritedOverrides = buildAssigneeAdapterOverrides({
+ adapterType: assigneeAdapterType,
+ lane: assigneeChrome ? "custom" : assigneeModelLane,
+ modelOverride: assigneeModelOverride,
+ thinkingEffortOverride: assigneeThinkingEffort,
+ chrome: assigneeChrome,
+ });
+
return (
<Dialog
open={newIssueOpen}
@@ -1403,998 +1086,327 @@ export function NewIssueDialog() {
showCloseButton={false}
aria-describedby={undefined}
style={dialogViewportStyle}
- className={cn(
- "flex h-(--new-issue-dialog-height) max-h-(--new-issue-dialog-height) flex-col gap-0 overflow-hidden p-0 sm:h-auto",
- expanded
- ? "sm:max-w-2xl sm:h-(--new-issue-dialog-height)"
- : "sm:max-w-lg"
- )}
+ className="flex max-h-(--new-issue-dialog-height) flex-col gap-0 overflow-hidden rounded-(--radius-task-composer) border-0 bg-transparent p-0 shadow-none sm:max-w-2xl"
onKeyDown={handleKeyDown}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ dialogBodyRef.current?.querySelector<HTMLElement>('[contenteditable="true"]')?.focus();
+ }}
onEscapeKeyDown={(event) => {
if (event.defaultPrevented) return;
- // iOS Safari maps command-period to Escape for hardware keyboards.
- // Treat modifier-Escape as the same mode-cycle shortcut so the
- // dialog does not dismiss before the shortcut can run.
if (isWorkModeEscapeShortcut(event)) {
event.preventDefault();
setWorkMode((current) => nextWorkMode(current));
- return;
- }
- if (createIssue.isPending) {
- event.preventDefault();
- }
+ } else if (createIssue.isPending) event.preventDefault();
}}
onPointerDownOutside={(event) => {
- if (createIssue.isPending) {
- event.preventDefault();
- return;
- }
- // Radix Dialog's modal DismissableLayer calls preventDefault() on
- // pointerdown events that originate outside the Dialog DOM tree.
- // Popover and editor autocomplete portals render at the body level
- // (outside the Dialog), so touch/click events on their content get
- // their default prevented. Telling Radix "this event is handled" skips
- // that preventDefault, restoring popover scroll and autocomplete taps.
const target = event.detail.originalEvent.target as HTMLElement | null;
- if (target?.closest("[data-radix-popper-content-wrapper], [data-paperclip-floating-ui]")) {
+ if (
+ createIssue.isPending ||
+ target?.closest("[data-radix-popper-content-wrapper], [data-paperclip-floating-ui]")
+ ) {
event.preventDefault();
}
}}
>
- {/* Header bar */}
- <div className="flex items-center justify-between px-4 py-2.5 border-b border-border shrink-0">
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Popover open={companyOpen} onOpenChange={setCompanyOpen}>
- <PopoverTrigger asChild>
- <button
- data-slot="new-issue-compact-control"
- className="rounded bg-muted p-1.5 text-xs font-semibold cursor-pointer hover:opacity-80 transition-opacity sm:px-1.5 sm:py-0.5"
- disabled={isSubIssueMode}
- >
- {dialogCompany?.issuePrefix ?? ""}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-48 p-1" align="start">
- {companies.filter((c) => c.status !== "archived").map((c) => (
- <button
- key={c.id}
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- c.id === effectiveCompanyId && "bg-accent",
- )}
- onClick={() => {
- handleCompanyChange(c.id);
- setCompanyOpen(false);
- }}
- >
- <span className="px-1 py-0.5 rounded bg-muted text-(length:--text-nano) font-semibold leading-none">
- {c.issuePrefix}
- </span>
- <span className="truncate">{c.name}</span>
- </button>
- ))}
- </PopoverContent>
- </Popover>
- <span className="text-muted-foreground/60">&rsaquo;</span>
- <span>{isSubIssueMode ? "New sub-task" : "New task"}</span>
- </div>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon-xs"
- className="text-muted-foreground"
- onClick={() => setExpanded(!expanded)}
- disabled={createIssue.isPending}
- >
- {expanded ? <Minimize2 className="h-3.5 w-3.5" /> : <Maximize2 className="h-3.5 w-3.5" />}
- </Button>
- <Button
- variant="ghost"
- size="icon-xs"
- className="text-muted-foreground"
- onClick={() => closeNewIssue()}
- disabled={createIssue.isPending}
- >
- <span className="text-lg leading-none">&times;</span>
- </Button>
- </div>
- </div>
-
- <div ref={dialogBodyRef} className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
- {/* Title */}
- <div className="px-4 pt-4 pb-2">
- <IssueTitleTextarea
- value={title}
- pending={createIssue.isPending}
- assigneeValue={assigneeValue}
- projectId={projectId}
- descriptionEditorRef={descriptionEditorRef}
- assigneeSelectorRef={assigneeSelectorRef}
- projectSelectorRef={projectSelectorRef}
- onChange={handleTitleChange}
- />
- </div>
-
- {effectiveCompanyId ? (
- <div className="px-4 pb-2">
- {neededUserSecretKeys.length > 0 ? (
- <MissingUserSecretsBanner
- companyId={effectiveCompanyId}
- definitionKeys={neededUserSecretKeys}
- />
- ) : null}
- </div>
- ) : null}
-
- <div className="px-4 pb-2">
- <div className="overflow-x-auto overscroll-x-contain">
- <div className="inline-flex items-center gap-2 text-sm text-muted-foreground flex-wrap sm:flex-nowrap sm:min-w-max">
- <span className="w-6 shrink-0 text-center">For</span>
- <InlineEntitySelector
- ref={assigneeSelectorRef}
- value={assigneeValue}
- options={assigneeOptions}
- recentOptionIds={recentAssigneeOptionIds}
- placeholder="Assignee"
- mobileTitle="Select assignee"
- className="h-8 px-2.5 py-0 sm:h-auto sm:px-2 sm:py-1"
- triggerDataSlot="new-issue-compact-control"
- contentStyle={entityPickerViewportStyle}
- noneLabel="No assignee"
- searchPlaceholder="Search assignees..."
- emptyMessage="No assignees found."
- onChange={(value) => {
- const nextAssignee = parseAssigneeValue(value);
- if (nextAssignee.assigneeAgentId) {
- trackRecentAssignee(nextAssignee.assigneeAgentId);
- }
- setAssigneeValue(value);
- const hasAssignee = Boolean(nextAssignee.assigneeAgentId || nextAssignee.assigneeUserId);
- if (hasAssignee && status === "backlog") {
- setStatus("todo");
- }
- }}
- onConfirm={() => {
- if (projectId) {
- descriptionEditorRef.current?.focus();
- } else {
- projectSelectorRef.current?.focus();
- }
- }}
- renderTriggerValue={(option) =>
- option ? (
- currentAssignee ? (
- <>
- <AgentAvatar agent={currentAssignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
- <span className="truncate">{option.label}</span>
- </>
- ) : (
- <span className="truncate">{option.label}</span>
- )
- ) : (
- <span className="text-muted-foreground">Assignee</span>
- )
- }
- renderOption={(option) => {
- if (!option.id) return <span className="truncate">{option.label}</span>;
- const assignee = parseAssigneeValue(option.id).assigneeAgentId
- ? (agents ?? []).find((agent) => agent.id === parseAssigneeValue(option.id).assigneeAgentId)
- : null;
- return (
- <>
- {assignee ? <AgentAvatar agent={assignee} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null}
- <span className="truncate">{option.label}</span>
- {assignee && getTrustPreset(assignee.permissions) === "low_trust_review" ? (
- <ShieldAlert className="ml-auto h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-300" aria-label="Low-trust review agent" />
+ <DialogTitle className="sr-only">{isSubIssueMode ? "New sub-task" : "New task"}</DialogTitle>
+ <div
+ ref={dialogBodyRef}
+ className={cn("min-h-0 overflow-y-auto overscroll-contain", isFileDragOver && "bg-accent/20")}
+ onDragEnter={handleFileDragEnter}
+ onDragOver={handleFileDragOver}
+ onDragLeave={handleFileDragLeave}
+ onDrop={handleFileDrop}
+ >
+ <TaskChatPresentationProvider mode={streamlinedUiEnabled ? "streamlined" : "production"}>
+ <TaskChatComposer
+ workMode={workMode}
+ onWorkModeChange={setWorkMode}
+ disabled={createIssue.isPending || !effectiveCompanyId}
+ placeholder="Describe a task…"
+ mobile={isMobile}
+ mentions={mentionOptions}
+ onImageUpload={async (file) => {
+ if (!effectiveCompanyId) throw new Error("No organization selected");
+ const asset = await assetsApi.uploadImage(effectiveCompanyId, file, "issues/drafts");
+ return asset.contentPath;
+ }}
+ companyId={effectiveCompanyId}
+ enableReassign
+ reassignOptions={assigneeOptions}
+ modelAgents={modelAgents}
+ agentMap={modelAgents}
+ currentAssigneeValue={assigneeValue}
+ assigneeAdapterOverrides={inheritedOverrides}
+ onPendingAssigneeChange={(value) => {
+ if (value === null) return;
+ defaultAssigneePendingRef.current = false;
+ const next = parseAssigneeValue(value);
+ if (next.assigneeAgentId) trackRecentAssignee(next.assigneeAgentId, effectiveCompanyId ?? undefined);
+ if (next.assigneeUserId) trackRecentAssigneeUser(next.assigneeUserId, effectiveCompanyId ?? undefined);
+ setAssigneeValue(value);
+ setComposerSettings(null);
+ setAssigneeModelLane("primary");
+ setAssigneeModelOverride("");
+ setAssigneeThinkingEffort("");
+ setAssigneeChrome(false);
+ if (value && status === "backlog") setStatus("todo");
+ }}
+ creation={{
+ value: description,
+ onChange: handleDescriptionChange,
+ onSubmit: handleSubmit,
+ submitLabel: isSubIssueMode ? "Create sub-task" : "Create task",
+ canSubmitWithoutBody: Boolean(title.trim()),
+ onSelectFiles: stageFiles,
+ runSettings: composerSettings,
+ onRunSettingsChange: setComposerSettings,
+ header:
+ hasTitle || isSubIssueMode ? (
+ <div className="mb-3 flex flex-col gap-2 text-xs">
+ {hasTitle ? (
+ <input
+ aria-label="Task title"
+ value={title}
+ disabled={createIssue.isPending}
+ className="w-full bg-transparent text-sm text-foreground outline-none"
+ onChange={(event) => {
+ titleRef.current = event.target.value;
+ setTitle(event.target.value);
+ queueDraftSave({ title: event.target.value });
+ }}
+ />
) : null}
- </>
- );
- }}
- />
- <span>in</span>
- <InlineEntitySelector
- ref={projectSelectorRef}
- value={projectId}
- options={projectOptions}
- recentOptionIds={recentProjectIds}
- placeholder="Project"
- mobileTitle="Select project"
- className="h-8 px-2.5 py-0 sm:h-auto sm:px-2 sm:py-1"
- triggerDataSlot="new-issue-compact-control"
- contentStyle={entityPickerViewportStyle}
- noneLabel="No project"
- searchPlaceholder="Search projects..."
- emptyMessage="No projects found."
- onChange={handleProjectChange}
- onConfirm={() => {
- descriptionEditorRef.current?.focus();
- }}
- renderTriggerValue={(option) =>
- option && currentProject ? (
- <>
- <span
- className="h-3.5 w-3.5 shrink-0 rounded-sm"
- style={{ backgroundColor: currentProject.color ?? "var(--project-seed)" }}
- />
- <span className="truncate">{option.label}</span>
- </>
- ) : (
- <span className="text-muted-foreground">Project</span>
- )
- }
- renderOption={(option) => {
- if (!option.id) return <span className="truncate">{option.label}</span>;
- const project = orderedProjects.find((item) => item.id === option.id);
- return (
- <>
- <span
- className="h-3.5 w-3.5 shrink-0 rounded-sm"
- style={{ backgroundColor: project?.color ?? "var(--project-seed)" }}
- />
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- />
-
- {/* Three-dot menu to add Reviewer / Approver rows */}
- <Popover open={participantMenuOpen} onOpenChange={setParticipantMenuOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- className="inline-flex items-center justify-center rounded-md p-1 text-muted-foreground hover:bg-accent/50 transition-colors"
- title="Add reviewer, approver, or watchdog"
- >
- <MoreHorizontal className="h-4 w-4" />
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-44 p-1" align="start">
- <button
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- showReviewerRow && "bg-accent",
- )}
- onClick={() => {
- setShowReviewerRow((v) => !v);
- if (showReviewerRow) setReviewerValue("");
- setParticipantMenuOpen(false);
- }}
- >
- <Eye className="h-3 w-3" />
- Reviewer
- </button>
- <button
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- showApproverRow && "bg-accent",
- )}
- onClick={() => {
- setShowApproverRow((v) => !v);
- if (showApproverRow) setApproverValue("");
- setParticipantMenuOpen(false);
- }}
- >
- <ShieldCheck className="h-3 w-3" />
- Approver
- </button>
- <button
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- showWatchdogRow && "bg-accent",
- )}
- onClick={() => {
- if (showWatchdogRow) {
- setShowWatchdogRow(false);
- setWatchdogAgentId("");
- setWatchdogInstructions("");
- setWatchdogEditorOpen(false);
- } else {
- setShowWatchdogRow(true);
- setWatchdogEditorOpen(true);
- }
- setParticipantMenuOpen(false);
- }}
- >
- <ScanEye className="h-3 w-3" />
- Watchdog
- </button>
- </PopoverContent>
- </Popover>
- </div>
- </div>
-
- {/* Reviewer row */}
- {showReviewerRow && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground mt-1">
- <span className="w-6 shrink-0 flex items-center justify-center"><Eye className="h-3.5 w-3.5" /></span>
- <InlineEntitySelector
- value={reviewerValue}
- options={assigneeOptions}
- recentOptionIds={recentAssigneeOptionIds}
- placeholder="Reviewer"
- contentStyle={entityPickerViewportStyle}
- noneLabel="No reviewer"
- searchPlaceholder="Search reviewers..."
- emptyMessage="No reviewers found."
- onChange={setReviewerValue}
- renderTriggerValue={(option) =>
- option ? (
- <>
- {(() => {
- const reviewer = parseAssigneeValue(option.id).assigneeAgentId
- ? (agents ?? []).find((a) => a.id === parseAssigneeValue(option.id).assigneeAgentId)
- : null;
- return reviewer ? <AgentAvatar agent={reviewer} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null;
- })()}
- <span className="truncate">{option.label}</span>
- </>
- ) : (
- <span className="text-muted-foreground">Reviewer</span>
- )
- }
- renderOption={(option) => {
- if (!option.id) return <span className="truncate">{option.label}</span>;
- const reviewer = parseAssigneeValue(option.id).assigneeAgentId
- ? (agents ?? []).find((agent) => agent.id === parseAssigneeValue(option.id).assigneeAgentId)
- : null;
- return (
- <>
- {reviewer ? <AgentAvatar agent={reviewer} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null}
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- />
- </div>
- )}
-
- {/* Approver row */}
- {showApproverRow && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground mt-1">
- <span className="w-6 shrink-0 flex items-center justify-center"><ShieldCheck className="h-3.5 w-3.5" /></span>
- <InlineEntitySelector
- value={approverValue}
- options={assigneeOptions}
- recentOptionIds={recentAssigneeOptionIds}
- placeholder="Approver"
- contentStyle={entityPickerViewportStyle}
- noneLabel="No approver"
- searchPlaceholder="Search approvers..."
- emptyMessage="No approvers found."
- onChange={setApproverValue}
- renderTriggerValue={(option) =>
- option ? (
- <>
- {(() => {
- const approver = parseAssigneeValue(option.id).assigneeAgentId
- ? (agents ?? []).find((a) => a.id === parseAssigneeValue(option.id).assigneeAgentId)
- : null;
- return approver ? <AgentAvatar agent={approver} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null;
- })()}
- <span className="truncate">{option.label}</span>
- </>
- ) : (
- <span className="text-muted-foreground">Approver</span>
- )
- }
- renderOption={(option) => {
- if (!option.id) return <span className="truncate">{option.label}</span>;
- const approver = parseAssigneeValue(option.id).assigneeAgentId
- ? (agents ?? []).find((agent) => agent.id === parseAssigneeValue(option.id).assigneeAgentId)
- : null;
- return (
- <>
- {approver ? <AgentAvatar agent={approver} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null}
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- />
- </div>
- )}
-
- {/* Watchdog row */}
- {showWatchdogRow && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground mt-1">
- <span className="w-6 shrink-0 flex items-center justify-center"><ScanEye className="h-3.5 w-3.5" /></span>
- <Popover open={watchdogEditorOpen} onOpenChange={setWatchdogEditorOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- className="inline-flex max-w-full items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors min-w-0"
- title="Configure watchdog"
- >
- {selectedWatchdogAgent ? (
- <>
- <AgentAvatar agent={selectedWatchdogAgent} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
- <span className="truncate text-foreground">{selectedWatchdogAgent.name}</span>
- {watchdogInstructions.trim() ? (
- <span className="truncate text-muted-foreground">· {watchdogInstructions.trim()}</span>
- ) : null}
- </>
- ) : (
- <span className="text-muted-foreground">Set watchdog</span>
- )}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-80 p-3 space-y-3" align="start">
- <div className="space-y-1.5">
- <div className="text-xs font-medium text-foreground">Watchdog agent</div>
- <InlineEntitySelector
- value={watchdogAgentId}
- options={watchdogAgentOptions}
- placeholder="Select agent"
- noneLabel="No watchdog agent"
- searchPlaceholder="Search agents..."
- emptyMessage="No agents found."
- onChange={setWatchdogAgentId}
- renderTriggerValue={(option) =>
- option ? (
- <>
- {selectedWatchdogAgent ? (
- <AgentAvatar agent={selectedWatchdogAgent} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/>
- ) : null}
- <span className="truncate">{option.label}</span>
- </>
- ) : (
- <span className="text-muted-foreground">Select agent</span>
- )
- }
- renderOption={(option) => {
- const agent = (agents ?? []).find((a) => a.id === option.id);
- return (
- <>
- {agent ? <AgentAvatar agent={agent} size={16} className="h-3.5 w-3.5 shrink-0 text-muted-foreground"/> : null}
- <span className="truncate">{option.label}</span>
- </>
- );
- }}
- />
- </div>
- <div className="space-y-1.5">
- <div className="text-xs font-medium text-foreground">Instructions <span className="font-normal text-muted-foreground">(optional)</span></div>
- <Textarea
- value={watchdogInstructions}
- onChange={(event) => setWatchdogInstructions(event.target.value)}
- placeholder="What should the watchdog watch for and how should it keep work moving?"
- rows={4}
- className="text-xs"
- />
- </div>
- <div className="flex items-center justify-between">
- <button
- type="button"
- className="text-xs text-muted-foreground hover:text-destructive transition-colors"
- onClick={() => {
- setWatchdogAgentId("");
- setWatchdogInstructions("");
- setShowWatchdogRow(false);
- setWatchdogEditorOpen(false);
- }}
- >
- Remove
- </button>
- <Button type="button" size="sm" className="h-7 text-xs" onClick={() => setWatchdogEditorOpen(false)}>
- Done
- </Button>
- </div>
- </PopoverContent>
- </Popover>
- </div>
- )}
- </div>
-
- {isSubIssueMode ? (
- <div className="px-4 pb-2">
- <div className="max-w-full rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs text-muted-foreground">
- <div className="flex items-center gap-1.5">
- <ListTree className="h-3.5 w-3.5 shrink-0" />
- <span className="shrink-0">Sub-task of</span>
- <span className="font-medium text-foreground">{parentIssueLabel}</span>
- </div>
- {newIssueDefaults.parentTitle ? (
- <div className="pl-5 text-foreground/80 truncate">
- {newIssueDefaults.parentTitle}
- </div>
- ) : null}
- </div>
- </div>
- ) : null}
-
- {workspaceIsolationControlsVisible && currentProject && currentProjectSupportsExecutionWorkspace && (
- <div className="px-4 py-3 space-y-2">
- <div className="space-y-1.5">
- <div className="text-xs font-medium">Execution workspace</div>
- <div className="text-(length:--text-micro) text-muted-foreground">
- Control whether this task runs in the shared workspace, a new isolated workspace, or an existing one.
- </div>
- <select
- className="w-full rounded border border-border bg-transparent px-2 py-1.5 text-xs outline-none"
- value={executionWorkspaceMode}
- onChange={(e) => {
- setExecutionWorkspaceMode(e.target.value);
- if (e.target.value !== "reuse_existing") {
- setSelectedExecutionWorkspaceId("");
- }
- }}
- >
- {EXECUTION_WORKSPACE_MODES.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- {executionWorkspaceMode === "reuse_existing" && (
- <ReusableExecutionWorkspaceSelect
- value={selectedExecutionWorkspaceId}
- workspaces={selectableReusableWorkspaces}
- onValueChange={(workspaceId) => setSelectedExecutionWorkspaceId(workspaceId)}
- loading={reusableExecutionWorkspacesLoading}
- error={reusableExecutionWorkspacesError}
- disablePortal
- />
- )}
- {/*
- The label used to fall back to the workspace working directory,
- a path on the execution host. It now falls back to a neutral
- phrase, so the dialog never renders a host path.
- */}
- {executionWorkspaceMode === "reuse_existing" && selectedReusableExecutionWorkspace && (
- <div className="text-(length:--text-micro) text-muted-foreground">
- Reusing {selectedReusableExecutionWorkspace.name} from {selectedReusableExecutionWorkspace.branchName ?? "existing execution workspace"}.
- </div>
- )}
- {showParentWorkspaceWarning ? (
- <div className="rounded-md border border-amber-300/60 bg-amber-50 px-2 py-1.5 text-(length:--text-micro) text-amber-900 dark:border-amber-800/70 dark:bg-amber-950/30 dark:text-amber-100">
- Warning: this sub-task will no longer use the parent task workspace{parentExecutionWorkspaceLabel ? ` (${parentExecutionWorkspaceLabel})` : ""}.
- </div>
- ) : null}
- </div>
- </div>
- )}
-
- {supportsAssigneeOverrides && (
- <div className="px-4 pb-2">
- <button
- className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
- onClick={() => setAssigneeOptionsOpen((open) => !open)}
- >
- {assigneeOptionsOpen ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
- {assigneeOptionsTitle}
- </button>
- {assigneeOptionsOpen && (
- <div className="mt-2 rounded-md border border-border p-3 bg-muted/20 space-y-3">
- <div className="space-y-1.5">
- <div className="text-xs text-muted-foreground">Model lane</div>
- <div
- className="flex w-full overflow-hidden rounded-md border border-border"
- role="radiogroup"
- aria-label="Model lane"
- >
- {(["primary", "custom"] as const).map((lane) => (
- <button
- key={lane}
- type="button"
- role="radio"
- aria-checked={assigneeModelLane === lane}
- className={cn(
- "flex-1 px-2 py-1 text-xs capitalize transition-colors hover:bg-accent/40",
- assigneeModelLane === lane && "bg-accent text-foreground",
- )}
- onClick={() => setAssigneeModelLane(lane)}
- >
- {lane === "primary" ? "Primary" : "Custom"}
- </button>
- ))}
- </div>
- {assigneeModelLane === "primary" && (
- <p className="text-(length:--text-micro) text-muted-foreground">Runs on the agent's primary model.</p>
- )}
- {assigneeModelLane === "custom" && (
- <p className="text-(length:--text-micro) text-muted-foreground">Override the model and effort for this task only.</p>
- )}
- </div>
- {assigneeModelLane === "custom" && (
- <div className="space-y-1.5">
- <div className="text-xs text-muted-foreground">Model</div>
- <InlineEntitySelector
- value={assigneeModelOverride}
- options={modelOverrideOptions}
- placeholder="Default model"
- contentStyle={entityPickerViewportStyle}
- noneLabel="Default model"
- searchPlaceholder="Search models..."
- emptyMessage="No models found."
- onChange={setAssigneeModelOverride}
- />
- </div>
- )}
- {assigneeModelLane === "custom" && (
- <div className="space-y-1.5">
- <div className="text-xs text-muted-foreground">Thinking effort</div>
- <div className="flex items-center gap-1.5 flex-wrap">
- {thinkingEffortOptions.map((option) => (
- <button
- key={option.value || "default"}
- className={cn(
- "px-2 py-1 rounded-md text-xs border border-border hover:bg-accent/50 transition-colors",
- assigneeThinkingEffort === option.value && "bg-accent"
- )}
- onClick={() => setAssigneeThinkingEffort(option.value)}
- >
- {option.label}
- </button>
- ))}
- </div>
- </div>
- )}
- {assigneeAdapterType === "claude_local" && assigneeModelLane === "custom" && (
- <div className="flex items-center justify-between rounded-md border border-border px-2 py-1.5">
- <div className="text-xs text-muted-foreground">Enable Chrome (--chrome)</div>
- <ToggleSwitch
- checked={assigneeChrome}
- onCheckedChange={() => setAssigneeChrome((value) => !value)}
- />
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {/* Description */}
- <div
- className="border-t border-border/60 px-4 pb-2 pt-3"
- onDragEnter={handleFileDragEnter}
- onDragOver={handleFileDragOver}
- onDragLeave={handleFileDragLeave}
- onDrop={handleFileDrop}
- >
- <div
- className={cn(
- "rounded-md transition-colors",
- isFileDragOver && "bg-accent/20",
- )}
- >
- <IssueDescriptionEditor
- value={description}
- expanded={expanded}
- mentions={mentionOptions}
- descriptionEditorRef={descriptionEditorRef}
- imageUploadHandler={uploadDescriptionImageHandler}
- onChange={handleDescriptionChange}
- />
- </div>
- {stagedFiles.length > 0 ? (
- <div className="mt-4 space-y-3 rounded-lg border border-border/70 p-3">
- {stagedDocuments.length > 0 ? (
- <div className="space-y-2">
- <div className="text-xs font-medium text-muted-foreground">Documents</div>
- <div className="space-y-2">
- {stagedDocuments.map((file) => (
- <div key={file.id} className="flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2">
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <Badge variant="outline" className="border-border font-mono text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow) text-muted-foreground">
- {file.documentKey}
- </Badge>
- <span className="truncate text-sm">{file.file.name}</span>
- </div>
- <div className="mt-1 flex items-center gap-2 text-(length:--text-micro) text-muted-foreground">
- <FileText className="h-3.5 w-3.5" />
- <span>{file.title || file.file.name}</span>
- <span>•</span>
- <span>{formatFileSize(file.file)}</span>
+ {isSubIssueMode ? (
+ <div className="px-4 pb-2">
+ <div className="max-w-full rounded-md border border-border bg-muted/30 px-2.5 py-1.5 text-xs text-muted-foreground">
+ <div className="flex items-center gap-1.5">
+ <ListTree className="h-3.5 w-3.5 shrink-0" />
+ <span className="shrink-0">Sub-task of</span>
+ <span className="font-medium text-foreground">{parentIssueLabel}</span>
+ </div>
+ {newIssueDefaults.parentTitle ? (
+ <div className="pl-5 text-foreground/80 truncate">{newIssueDefaults.parentTitle}</div>
+ ) : null}
</div>
</div>
- <Button
- variant="ghost"
- size="icon-xs"
- className="shrink-0 text-muted-foreground"
- onClick={() => removeStagedFile(file.id)}
- disabled={createIssue.isPending}
- title="Remove document"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- </div>
- ))}
- </div>
- </div>
- ) : null}
-
- {stagedAttachments.length > 0 ? (
- <div className="space-y-2">
- <div className="text-xs font-medium text-muted-foreground">Attachments</div>
- <div className="space-y-2">
- {stagedAttachments.map((file) => (
- <div key={file.id} className="flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2">
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <Paperclip className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate text-sm">{file.file.name}</span>
+ ) : null}
+ </div>
+ ) : undefined,
+ details: (
+ <>
+ {worktreeSelectionIncomplete && !worktreesLoading ? (
+ <p role="alert" className="mb-2 text-xs text-destructive">
+ {worktreesError ? "Couldn't check the selected worktree. Retry in Worktrees or choose New worktree."
+ : "The selected worktree is no longer available. Choose another worktree or start a new one."}
+ </p>
+ ) : null}
+ {stagedFiles.length > 0 ? (
+ <div className="mt-4 space-y-3 rounded-lg border border-border/70 p-3">
+ {stagedDocuments.length > 0 ? (
+ <div className="space-y-2">
+ <div className="text-xs font-medium text-muted-foreground">Documents</div>
+ <div className="space-y-2">
+ {stagedDocuments.map((file) => (
+ <div
+ key={file.id}
+ className="flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2"
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <Badge
+ variant="outline"
+ className="border-border font-mono text-(length:--text-nano) uppercase tracking-(--tracking-eyebrow) text-muted-foreground"
+ >
+ {file.documentKey}
+ </Badge>
+ <span className="truncate text-sm">{file.file.name}</span>
+ </div>
+ <div className="mt-1 flex items-center gap-2 text-(length:--text-micro) text-muted-foreground">
+ <FileText className="h-3.5 w-3.5" />
+ <span>{file.title || file.file.name}</span>
+ <span>•</span>
+ <span>{formatFileSize(file.file)}</span>
+ </div>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground"
+ onClick={() => removeStagedFile(file.id)}
+ disabled={createIssue.isPending}
+ title="Remove document"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
</div>
- <div className="mt-1 text-(length:--text-micro) text-muted-foreground">
- {file.file.type || "application/octet-stream"} • {formatFileSize(file.file)}
+ ) : null}
+
+ {stagedAttachments.length > 0 ? (
+ <div className="space-y-2">
+ <div className="text-xs font-medium text-muted-foreground">Attachments</div>
+ <div className="space-y-2">
+ {stagedAttachments.map((file) => (
+ <div
+ key={file.id}
+ className="flex items-start justify-between gap-3 rounded-md border border-border/70 px-3 py-2"
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <Paperclip className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate text-sm">{file.file.name}</span>
+ </div>
+ <div className="mt-1 text-(length:--text-micro) text-muted-foreground">
+ {file.file.type || "application/octet-stream"} • {formatFileSize(file.file)}
+ </div>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 text-muted-foreground"
+ onClick={() => removeStagedFile(file.id)}
+ disabled={createIssue.isPending}
+ title="Remove attachment"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
</div>
- </div>
- <Button
- variant="ghost"
- size="icon-xs"
- className="shrink-0 text-muted-foreground"
- onClick={() => removeStagedFile(file.id)}
- disabled={createIssue.isPending}
- title="Remove attachment"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
+ ) : null}
</div>
- ))}
- </div>
- </div>
- ) : null}
- </div>
- ) : null}
- </div>
- </div>
+ ) : null}
+ {assigneeValue && status === "backlog" ? (
+ <div
+ data-testid="new-issue-assigned-backlog-note"
+ className="mx-4 mb-2 flex items-start gap-2 rounded-md border border-amber-300/70 bg-amber-50/90 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100"
+ >
+ <Flag className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-300" />
+ <span className="leading-snug">
+ Assigning implies executable intent - leave status as{" "}
+ <span className="font-medium">Backlog</span> only to deliberately park this. The assignee will
+ not be woken until status moves to <span className="font-medium">Todo</span> or{" "}
+ <span className="font-medium">In Progress</span>.
+ </span>
+ </div>
+ ) : null}
- {/* Property chips bar */}
- <div className="flex items-center gap-1.5 px-4 py-2 border-t border-border flex-wrap shrink-0">
- {/* Status chip */}
- <Popover open={statusOpen} onOpenChange={setStatusOpen}>
- <PopoverTrigger asChild>
- <button
- data-slot="new-issue-compact-control"
- className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 py-0 text-xs hover:bg-accent/50 transition-colors sm:h-auto sm:px-2 sm:py-1"
- >
- <CircleDot className={cn("h-3 w-3", currentStatus.color)} />
- {currentStatus.label}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-56 p-1" align="start">
- {statuses.map((s) => (
- <button
- key={s.value}
- className={cn(
- "flex w-full items-start gap-2 px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- s.value === status && "bg-accent"
- )}
- onClick={() => { setStatus(s.value); setStatusOpen(false); }}
- >
- <CircleDot className={cn("h-3 w-3 mt-0.5 shrink-0", s.color)} />
- <span className="flex flex-col text-left leading-tight">
- <span>{s.label}</span>
- {s.description ? (
- <span className="text-(length:--text-nano) text-muted-foreground">{s.description}</span>
+ {selectedAssigneeAgent?.status === "paused" ? (
+ <div data-testid="new-issue-paused-assignee-note" className="mx-4 mb-2">
+ <InlineBanner tone="warning" icon={PauseCircle} compact>
+ <span className="font-medium">{selectedAssigneeAgent.name}</span> is paused and will not start
+ work on this task until it is resumed
+ {selectedAssigneeAgent.pauseReason === "import"
+ ? " — it arrived paused from an organization import"
+ : ""}
+ . You can resume it from the task page after creating the task.
+ </InlineBanner>
+ </div>
+ ) : null}
+
+ {currentAssigneeLowTrust ? (
+ <div
+ data-testid="new-issue-low-trust-assignee-note"
+ className="mx-4 mb-2 flex items-start gap-2 rounded-md border border-amber-300/70 bg-amber-50/90 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100"
+ >
+ <ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-300" />
+ <span className="leading-snug">
+ Low-trust review agent. It can only act inside its assigned review boundary; task, project, or
+ run policy defines the concrete scope.
+ </span>
+ </div>
+ ) : null}
+
+ {showParentWorkspaceWarning ? (
+ <div className="mb-2">
+ <InlineBanner tone="warning" compact>
+ This sub-task will no longer use the parent task workspace
+ {parentExecutionWorkspaceLabel ? ` (${parentExecutionWorkspaceLabel})` : ""}.
+ </InlineBanner>
+ </div>
+ ) : null}
+ {effectiveCompanyId && neededUserSecretKeys.length > 0 ? (
+ <MissingUserSecretsBanner companyId={effectiveCompanyId} definitionKeys={neededUserSecretKeys} />
) : null}
- </span>
- </button>
- ))}
- </PopoverContent>
- </Popover>
-
- {/* Priority chip — PAP-411: hidden behind SHOW_TASK_PRIORITY_UI. */}
- {SHOW_TASK_PRIORITY_UI && (
- <Popover open={priorityOpen} onOpenChange={setPriorityOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- data-testid="new-issue-priority-chip"
- className="hidden items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs transition-colors hover:bg-accent/50 sm:inline-flex"
- >
- {currentPriority ? (
- <>
- <currentPriority.icon className={cn("h-3 w-3", currentPriority.color)} />
- {currentPriority.label}
</>
- ) : (
+ ),
+ submitDisabled: worktreeSelectionIncomplete,
+ contextBar: (
<>
- <Minus className="h-3 w-3 text-muted-foreground" />
- Priority
+ <InlineEntitySelector
+ value={projectId}
+ options={projectOptions}
+ recentOptionIds={recentProjectIds}
+ placeholder="Project"
+ mobileTitle="Select project"
+ className="h-8 min-w-0 flex-1 gap-1.5 border-0 bg-transparent px-2 text-xs shadow-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0 sm:max-w-64 sm:flex-none"
+ disabled={createIssue.isPending}
+ triggerDataSlot="new-issue-compact-control"
+ contentStyle={entityPickerViewportStyle}
+ noneLabel="No project"
+ noneAtEnd
+ searchPlaceholder="Search projects..."
+ emptyMessage="No projects found."
+ onChange={handleProjectChange}
+ renderTriggerValue={(option) =>
+ option && currentProject ? (
+ <>
+ <Folder className="size-3.5 shrink-0" style={{ color: currentProject.color ?? "var(--project-seed)" }} aria-hidden />
+ <span className="truncate">{option.label}</span>
+ <ChevronDown className="size-3 shrink-0 text-muted-foreground" aria-hidden />
+ </>
+ ) : (
+ <>
+ <Folder className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="truncate text-muted-foreground">Project</span>
+ <ChevronDown className="size-3 shrink-0 text-muted-foreground" aria-hidden />
+ </>
+ )
+ }
+ renderOption={(option) => {
+ if (!option.id) return <><Folder className="size-4 shrink-0 text-muted-foreground" aria-hidden /><span className="truncate">{option.label}</span></>;
+ const project = orderedProjects.find((item) => item.id === option.id);
+ return (
+ <>
+ <Folder className="size-4 shrink-0" style={{ color: project?.color ?? "var(--project-seed)" }} aria-hidden />
+ <span className="truncate">{option.label}</span>
+ </>
+ );
+ }}
+ />
+ {canChooseWorktrees ? (
+ <ComposerWorktreePicker
+ mode={executionWorkspaceMode}
+ workspaceId={selectedExecutionWorkspaceId}
+ selectedWorkspaceLabel={selectedReusableWorktree?.name ?? (selectedExecutionWorkspaceId === parentExecutionWorkspaceId ? newIssueDefaults.parentExecutionWorkspaceLabel : undefined)}
+ workspaces={selectableReusableWorkspaces}
+ onChange={(mode, workspaceId) => {
+ setExecutionWorkspaceMode(mode);
+ setSelectedExecutionWorkspaceId(workspaceId);
+ if (workspaceId) {
+ const workspace = selectableReusableWorkspaces.find((entry) => entry.id === workspaceId);
+ if (workspace) setProjectWorkspaceId(workspace.projectWorkspaceId ?? "");
+ } else {
+ setProjectWorkspaceId(defaultProjectWorkspaceIdForProject(currentProject));
+ }
+ }}
+ loading={worktreesLoading}
+ error={worktreesError}
+ onRetry={() => void refetchWorktrees()}
+ disabled={createIssue.isPending}
+ mobile={isMobile}
+ contentStyle={entityPickerViewportStyle}
+ />
+ ) : null}
</>
- )}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-36 p-1" align="start">
- {priorities.map((p) => (
- <button
- key={p.value}
- className={cn(
- "flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50",
- p.value === priority && "bg-accent"
- )}
- onClick={() => { setPriority(p.value); setPriorityOpen(false); }}
- >
- <p.icon className={cn("h-3 w-3", p.color)} />
- {p.label}
- </button>
- ))}
- </PopoverContent>
- </Popover>
- )}
-
- {/* Labels chip — disabled, not wired up yet */}
- {/* <button className="inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-xs hover:bg-accent/50 transition-colors text-muted-foreground">
- <Tag className="h-3 w-3" />
- Labels
- </button> */}
-
- <input
- ref={stageFileInputRef}
- type="file"
- accept={STAGED_FILE_ACCEPT}
- className="hidden"
- onChange={handleStageFilesPicked}
- multiple
- />
- <button
- data-slot="new-issue-compact-control"
- className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border px-2.5 py-0 text-xs hover:bg-accent/50 transition-colors text-muted-foreground sm:h-auto sm:px-2 sm:py-1"
- onClick={() => stageFileInputRef.current?.click()}
- disabled={createIssue.isPending}
- >
- <Paperclip className="h-3 w-3" />
- Upload
- </button>
-
- {/* Work mode chip */}
- <Popover open={workModeOpen} onOpenChange={setWorkModeOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- data-issue-work-mode-chip={workMode}
- data-slot="new-issue-compact-control"
- aria-keyshortcuts="Meta+Period Control+Period"
- className={cn(
- "inline-flex h-8 items-center gap-1.5 rounded-md border px-2.5 py-0 text-xs transition-colors sm:h-auto sm:px-2 sm:py-1",
- currentWorkMode.classes.chip,
- )}
- >
- <CurrentWorkModeIcon className="h-3 w-3" />
- {currentWorkMode.label}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-36 p-1" align="start">
- {workModeOptions.map((option) => {
- const Icon = option.icon;
- return (
- <button
- key={option.value}
- data-issue-work-mode={option.value}
- className={cn(
- "flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/50",
- option.value === workMode && "bg-accent",
- option.classes.menuItem,
- )}
- onClick={() => {
- setWorkMode(option.value);
- setWorkModeOpen(false);
- }}
- >
- <Icon className="h-3 w-3" />
- {option.label}
- {option.value === workMode ? <Check className="ml-auto h-3 w-3" aria-hidden /> : null}
- </button>
- );
- })}
- </PopoverContent>
- </Popover>
-
- {/* More */}
- <Popover open={moreOpen} onOpenChange={setMoreOpen}>
- <PopoverTrigger asChild>
- <button
- type="button"
- data-testid="new-issue-more-menu-trigger"
- data-slot="new-issue-compact-control"
- className="inline-flex size-8 items-center justify-center rounded-md border border-border p-0 text-xs text-muted-foreground transition-colors hover:bg-accent/50 sm:size-auto sm:p-1"
- >
- <MoreHorizontal className="h-3 w-3" />
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-44 p-1" align="start" data-testid="new-issue-more-menu">
- {/* PAP-411: mobile priority section hidden behind SHOW_TASK_PRIORITY_UI. */}
- {SHOW_TASK_PRIORITY_UI && (
- <div className="sm:hidden">
- <div className="px-2 py-1 text-(length:--text-nano) font-medium uppercase text-muted-foreground">
- Priority
- </div>
- {priorities.map((p) => (
- <button
- type="button"
- key={p.value}
- data-testid={`new-issue-more-priority-${p.value}`}
- className={cn(
- "flex w-full items-center gap-2 rounded px-2 py-1.5 text-xs hover:bg-accent/50",
- p.value === priority && "bg-accent",
- )}
- onClick={() => {
- setPriority(p.value);
- setMoreOpen(false);
- }}
- >
- <p.icon className={cn("h-3 w-3", p.color)} />
- {p.label}
- </button>
- ))}
- <div className="my-1 border-t border-border" />
- </div>
- )}
- <button className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground">
- <Calendar className="h-3 w-3" />
- Start date
- </button>
- <button className="flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-muted-foreground">
- <Calendar className="h-3 w-3" />
- Due date
- </button>
- </PopoverContent>
- </Popover>
- </div>
-
- {assigneeValue && status === "backlog" ? (
- <div
- data-testid="new-issue-assigned-backlog-note"
- className="mx-4 mb-2 flex items-start gap-2 rounded-md border border-amber-300/70 bg-amber-50/90 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100"
- >
- <Flag className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-300" />
- <span className="leading-snug">
- Assigning implies executable intent - leave status as <span className="font-medium">Backlog</span> only to deliberately park this. The assignee will not be woken until status moves to <span className="font-medium">Todo</span> or <span className="font-medium">In Progress</span>.
- </span>
- </div>
- ) : null}
-
- {selectedAssigneeAgent?.status === "paused" ? (
- <div data-testid="new-issue-paused-assignee-note" className="mx-4 mb-2">
- <InlineBanner tone="warning" icon={PauseCircle} compact>
- <span className="font-medium">{selectedAssigneeAgent.name}</span> is paused and will not start work on this task until it is resumed
- {selectedAssigneeAgent.pauseReason === "import" ? " — it arrived paused from an organization import" : ""}. You can resume it from the task page after creating the task.
- </InlineBanner>
- </div>
- ) : null}
-
- {currentAssigneeLowTrust ? (
- <div
- data-testid="new-issue-low-trust-assignee-note"
- className="mx-4 mb-2 flex items-start gap-2 rounded-md border border-amber-300/70 bg-amber-50/90 px-3 py-2 text-xs text-amber-900 dark:border-amber-500/40 dark:bg-amber-500/10 dark:text-amber-100"
- >
- <ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-300" />
- <span className="leading-snug">
- Low-trust review agent. It can only act inside its assigned review boundary; task, project, or run policy defines the concrete scope.
- </span>
- </div>
- ) : null}
-
- {/* Footer */}
- <div className="flex items-center justify-between px-4 py-2.5 border-t border-border shrink-0">
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground"
- onClick={discardDraft}
- disabled={createIssue.isPending || !canDiscardDraft}
- >
- Discard Draft
- </Button>
- <div className="flex items-center gap-3">
- {createIssue.isError ? (
- <div className="min-h-5 text-right">
- <span className="text-xs text-destructive">{createIssueErrorMessage}</span>
- </div>
- ) : null}
- <Button
- size="sm"
- className="min-w-(--sz-8_5rem) disabled:opacity-100"
- disabled={!draftHasText || createIssue.isPending}
- onClick={handleSubmit}
- aria-busy={createIssue.isPending}
- >
- <span className="inline-flex items-center justify-center gap-1.5">
- {createIssue.isPending ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : null}
- <span>{createIssue.isPending ? "Creating..." : isSubIssueMode ? "Create Sub-Task" : "Create Task"}</span>
- </span>
- </Button>
- </div>
+ ),
+ }}
+ />
+ </TaskChatPresentationProvider>
</div>
</DialogContent>
</Dialog>
diff --git a/ui/src/components/NewProjectDialog.test.tsx b/ui/src/components/NewProjectDialog.test.tsx
new file mode 100644
index 0000000000..f7dc764db1
--- /dev/null
+++ b/ui/src/components/NewProjectDialog.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+
+import { act, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { PROJECT_COLORS } from "@paperclipai/shared";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { projectsApi } from "../api/projects";
+import { getLastProjectId } from "../lib/recent-projects";
+import { NewProjectForm } from "./NewProjectDialog";
+
+vi.mock("../api/projects", () => ({ projectsApi: { create: vi.fn() } }));
+vi.mock("./ProjectRepositoryInput", () => ({
+ ProjectRepositoryInput: () => null,
+ repositoryOptionsKey: (companyId: string) => ["repositories", companyId],
+}));
+vi.mock("@/features/connections/ConnectionSetupFlow", () => ({ ConnectionSetupFlow: () => null }));
+vi.mock("./ui/dialog", () => ({
+ Dialog: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
+}));
+
+let root: ReturnType<typeof createRoot>;
+let container: HTMLDivElement;
+beforeEach(() => {
+ localStorage.clear();
+ vi.mocked(projectsApi.create).mockReset();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.restoreAllMocks();
+});
+
+async function settle() {
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); });
+}
+
+describe("new project colors", () => {
+ it("previews a palette color, keeps it through a retry, and remembers the created project", async () => {
+ vi.mocked(projectsApi.create)
+ .mockRejectedValueOnce(new Error("Try again"))
+ .mockResolvedValueOnce({ id: "project-created" } as Awaited<ReturnType<typeof projectsApi.create>>);
+ const onClose = vi.fn();
+ act(() => root.render(<QueryClientProvider client={new QueryClient({ defaultOptions: { mutations: { retry: false } } })}>
+ <NewProjectForm companyId="company-1" onClose={onClose} />
+ </QueryClientProvider>));
+ const previewColor = container.querySelector<HTMLElement>('span[style]')!.style.backgroundColor;
+ const input = container.querySelector<HTMLInputElement>('input[aria-label="Project name"]')!;
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "Colorful project");
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ act(() => container.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
+ await settle();
+ expect(container.querySelector('[role="alert"]')?.textContent).toBe("Try again");
+ const firstColor = vi.mocked(projectsApi.create).mock.calls[0][1].color;
+ expect(PROJECT_COLORS).toContain(firstColor);
+ const expected = document.createElement("span");
+ expected.style.backgroundColor = String(firstColor);
+ expect(previewColor).toBe(expected.style.backgroundColor);
+ act(() => container.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
+ await settle();
+ expect(vi.mocked(projectsApi.create).mock.calls[1][1]).toEqual({ name: "Colorful project", color: firstColor, status: "planned", repositoryIds: [] });
+ expect(getLastProjectId("company-1")).toBe("project-created");
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+});
diff --git a/ui/src/components/NewProjectDialog.tsx b/ui/src/components/NewProjectDialog.tsx
index 80813664b4..f0c922546b 100644
--- a/ui/src/components/NewProjectDialog.tsx
+++ b/ui/src/components/NewProjectDialog.tsx
@@ -1,11 +1,13 @@
import { useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import type { ProjectRepository } from "@paperclipai/shared";
-import { Folder, X } from "lucide-react";
+import { PROJECT_COLORS, type ProjectRepository } from "@paperclipai/shared";
+import { X } from "lucide-react";
import { useDialog } from "../context/DialogContext";
import { useCompany } from "../context/CompanyContext";
import { projectsApi } from "../api/projects";
import { queryKeys } from "../lib/queryKeys";
+import { trackRecentProject } from "../lib/recent-projects";
+import { ProjectTile } from "./ProjectTile";
import { Dialog, DialogContent, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { ProjectRepositoryInput, repositoryOptionsKey } from "./ProjectRepositoryInput";
@@ -21,12 +23,14 @@ export function NewProjectDialog() {
export function NewProjectForm({ companyId, onClose }: { companyId: string; onClose: () => void }) {
const client = useQueryClient();
const [name, setName] = useState("");
+ const [color] = useState(() => PROJECT_COLORS[Math.floor(Math.random() * PROJECT_COLORS.length)]!);
const [repos, setRepos] = useState<ProjectRepository[]>([]);
const [connecting, setConnecting] = useState(false);
const input = useRef<HTMLInputElement>(null);
const create = useMutation({
- mutationFn: () => projectsApi.create(companyId, { name: name.trim(), status: "planned", repositoryIds: repos.map((repo) => repo.id) }),
- onSuccess: () => {
+ mutationFn: () => projectsApi.create(companyId, { name: name.trim(), color, status: "planned", repositoryIds: repos.map((repo) => repo.id) }),
+ onSuccess: (project) => {
+ trackRecentProject(project.id, companyId);
void client.invalidateQueries({ queryKey: queryKeys.projects.all(companyId) });
onClose();
},
@@ -48,7 +52,7 @@ export function NewProjectForm({ companyId, onClose }: { companyId: string; onCl
<Button type="button" variant="ghost" size="icon-sm" disabled={create.isPending} aria-label="Close new project" onClick={onClose}><X className="size-4" /></Button>
</div>
<div className="flex items-center gap-3 rounded-lg border border-input px-3 focus-within:border-ring focus-within:ring-1 focus-within:ring-ring">
- <Folder className="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <ProjectTile color={color} size="sm" />
<input ref={input} aria-label="Project name" value={name} disabled={create.isPending} onChange={(event) => setName(event.target.value)} placeholder="Project name" required
className="h-10 w-full min-w-0 border-0 bg-transparent text-base outline-none placeholder:text-muted-foreground md:text-sm" />
</div>
diff --git a/ui/src/components/SearchableSelect.test.tsx b/ui/src/components/SearchableSelect.test.tsx
index ab6a2aef71..4b3d4c5ffb 100644
--- a/ui/src/components/SearchableSelect.test.tsx
+++ b/ui/src/components/SearchableSelect.test.tsx
@@ -5,6 +5,7 @@ import { createRoot, type Root } from "react-dom/client";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SearchableSelect, type SearchableSelectGroup, type SearchableSelectOption } from "./SearchableSelect";
+import { Dialog, DialogContent, DialogTitle } from "./ui/dialog";
import {
buildReusableExecutionWorkspaceOptionGroups,
reusableWorkspaceOptionMatches,
@@ -393,6 +394,55 @@ describe("SearchableSelect", () => {
expect(trigger?.getAttribute("aria-expanded")).toBe("false");
});
+ it.each([false, true])("dismisses outside a nested worktree picker (modal=%s) without reopening or closing the task", async (modal) => {
+ const onValueChange = vi.fn();
+ root = render(
+ <Dialog defaultOpen>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle>New task</DialogTitle>
+ <button type="button" data-testid="outside-worktree">Task draft</button>
+ <SearchableSelect
+ value="new"
+ groups={[{ id: "all", options: [{ key: "new", value: "new", label: "New worktree" }] }]}
+ onValueChange={onValueChange}
+ placeholder="Worktrees"
+ searchPlaceholder="Search worktrees..."
+ modal={modal}
+ />
+ </DialogContent>
+ </Dialog>,
+ container,
+ );
+ await flush();
+ const trigger = document.querySelector<HTMLButtonElement>('button[role="combobox"]')!;
+ const outside = document.querySelector<HTMLButtonElement>('[data-testid="outside-worktree"]')!;
+ act(() => trigger.click());
+ // Radix installs its outside pointer listener after the opening event.
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ const picker = document.querySelector<HTMLElement>("[data-mobile-entity-picker]")!;
+ const outsideTarget = modal ? picker.parentElement! : outside;
+ act(() => {
+ const pointerDown = new MouseEvent("pointerdown", { bubbles: true, cancelable: true });
+ Object.defineProperty(pointerDown, "pointerType", { value: modal ? "touch" : "mouse" });
+ outsideTarget.dispatchEvent(pointerDown);
+ if (!modal) outside.focus();
+ outsideTarget.click();
+ });
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
+ expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull();
+ expect(document.querySelector("[data-slot=dialog-content]")).not.toBeNull();
+ expect(trigger.getAttribute("aria-expanded")).toBe("false");
+ expect(trigger.textContent).toContain("New worktree");
+ expect(onValueChange).not.toHaveBeenCalled();
+ if (modal) expect(document.activeElement).toBe(trigger);
+ act(() => {
+ outside.focus();
+ trigger.focus();
+ });
+ await flush();
+ expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull();
+ });
+
it("filters workspace options, moves with arrows, and selects the workspace id with Enter", async () => {
const onValueChange = vi.fn();
const groups = buildWorkspaceSelectGroups([
diff --git a/ui/src/components/SearchableSelect.tsx b/ui/src/components/SearchableSelect.tsx
index bf69dfacb6..cab584a61e 100644
--- a/ui/src/components/SearchableSelect.tsx
+++ b/ui/src/components/SearchableSelect.tsx
@@ -1,5 +1,5 @@
import { Check, ChevronsUpDown, X } from "lucide-react";
-import { useMemo, useRef, useState, type ReactNode } from "react";
+import { useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { Button } from "@/components/ui/button";
import {
Command,
@@ -62,6 +62,10 @@ export interface SearchableSelectProps<
disablePortal?: boolean;
/** Heading for the large mobile selector modal. Defaults to the placeholder. */
mobileTitle?: string;
+ triggerAriaLabel?: string;
+ modal?: boolean;
+ contentStyle?: CSSProperties;
+ listFooter?: ReactNode;
/**
* Optional pinned "creatable" item rendered at the bottom of the list,
* regardless of the query (used e.g. by the secret picker's
@@ -111,6 +115,10 @@ export function SearchableSelect<
scoreOption,
disablePortal,
mobileTitle,
+ triggerAriaLabel,
+ modal,
+ contentStyle,
+ listFooter,
createItem,
}: SearchableSelectProps<TValue, TOption>) {
const [open, setOpen] = useState(false);
@@ -190,6 +198,7 @@ export function SearchableSelect<
return (
<Popover
+ modal={modal}
open={open}
onOpenChange={(next) => {
setOpen(next);
@@ -220,6 +229,7 @@ export function SearchableSelect<
}
}}
aria-expanded={open}
+ aria-label={triggerAriaLabel}
role="combobox"
className={cn("w-full justify-between overflow-hidden", className, triggerClassName)}
>
@@ -232,7 +242,7 @@ export function SearchableSelect<
<PopoverContent
data-mobile-entity-picker=""
aria-label={mobileTitle ?? placeholder}
- style={mobileViewportStyle}
+ style={{ ...mobileViewportStyle, ...contentStyle }}
align={align}
collisionPadding={16}
disablePortal={disablePortal}
@@ -250,6 +260,12 @@ export function SearchableSelect<
closePopover({ suppressTriggerFocus: true });
}
}}
+ onCloseAutoFocus={() => {
+ // Modal outside dismissal restores focus to the trigger. Keep that
+ // restore from reopening the picker, without swallowing a later Tab.
+ suppressNextTriggerFocusRef.current = true;
+ queueMicrotask(() => { suppressNextTriggerFocusRef.current = false; });
+ }}
>
<div data-mobile-entity-picker-header="" className="hidden items-center justify-between border-b border-border px-4 py-3">
<span className="text-base font-semibold text-foreground">{mobileTitle ?? placeholder}</span>
@@ -325,6 +341,7 @@ export function SearchableSelect<
</CommandItem>
</CommandGroup>
) : null}
+ {listFooter}
</>
)}
</CommandList>
diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx
index 510a3ad0d3..640ae943bb 100644
--- a/ui/src/components/issue-properties/IssueProperties.tsx
+++ b/ui/src/components/issue-properties/IssueProperties.tsx
@@ -39,7 +39,7 @@ import {
trackRecentAssignee,
trackRecentAssigneeUser,
} from "../../lib/recent-assignees";
-import { getRecentProjectIds, trackRecentProject } from "../../lib/recent-projects";
+import { getRecentProjectIds } from "../../lib/recent-projects";
import { orderItemsBySelectedAndRecent } from "../../lib/recent-selections";
import { formatAssigneeUserLabel, formatUserLabel } from "../../lib/assignees";
import { buildExecutionPolicy, stageParticipantValues } from "../../lib/issue-execution-policy";
@@ -1762,11 +1762,11 @@ export function IssueProperties({
onClick={() => {
if (option.kind === "agent") {
selectAssignee({ assigneeAgentId: option.agent.id, assigneeUserId: null }, option.label, () =>
- trackRecentAssignee(option.agent.id),
+ trackRecentAssignee(option.agent.id, companyId ?? undefined),
);
} else if (option.kind === "user") {
selectAssignee({ assigneeAgentId: null, assigneeUserId: option.userId }, option.label, () =>
- trackRecentAssigneeUser(option.userId),
+ trackRecentAssigneeUser(option.userId, companyId ?? undefined),
);
} else {
selectAssignee({ assigneeAgentId: null, assigneeUserId: null }, option.label);
@@ -1995,7 +1995,6 @@ export function IssueProperties({
onClick={() => {
if (option.kind === "project") {
const defaultMode = defaultExecutionWorkspaceModeForProject(option.project);
- trackRecentProject(option.project.id);
onUpdate({
projectId: option.project.id,
projectWorkspaceId: defaultProjectWorkspaceIdForProject(option.project),
diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx
index 3185f1d905..23efce4e86 100644
--- a/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx
+++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx
@@ -1,13 +1,14 @@
// @vitest-environment jsdom
-import { act } from "react";
+import { act, type ComponentProps } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent } from "@paperclipai/shared";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { agentsApi } from "@/api/agents";
import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker";
+import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort";
const agent = {
id: "a1", companyId: "company-1", name: "Clippy",
@@ -33,7 +34,7 @@ async function click(label: string) {
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
}
-function render(onAssigneeChange: (value: string) => void, onSettingsChange: () => void, useCatalog = false) {
+function render(onAssigneeChange: (value: string) => void, onSettingsChange: () => void, useCatalog = false, props: Partial<ComponentProps<typeof ComposerRunSettingsPicker>> = {}) {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -42,10 +43,11 @@ function render(onAssigneeChange: (value: string) => void, onSettingsChange: ()
<ComposerRunSettingsPicker companyId="company-1" assigneeValue="agent:a1" currentAssigneeValue="agent:a1"
options={options} agents={agents} settings={{ model: "gpt-6-sol", effort: "high", fast: true }}
onAssigneeChange={onAssigneeChange} onSettingsChange={onSettingsChange}
- modelOptionsOverride={useCatalog ? undefined : []} />
+ modelOptionsOverride={useCatalog ? undefined : []} {...props} />
</QueryClientProvider>));
}
+beforeEach(() => localStorage.clear());
afterEach(() => {
vi.restoreAllMocks();
flushSync(() => root?.unmount());
@@ -55,11 +57,61 @@ afterEach(() => {
});
describe("composer assignee picker", () => {
+ it.each([
+ { adapterType: "claude_local", config: {}, label: "Default" },
+ { adapterType: "claude_local", config: { model: "claude-opus-5" }, label: "Claude Opus 5" },
+ { adapterType: "claude_local", config: { env: { ANTHROPIC_MODEL: "claude-opus-5" } }, label: "Claude Opus 5" },
+ { adapterType: "codex_local", config: {}, label: "Default" },
+ ])("labels the $adapterType default honestly", ({ adapterType, config, label }) => {
+ const defaultAgent = { ...agent, adapterType, adapterConfig: config } as Agent;
+ render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]),
+ modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] });
+ expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')?.textContent).toBe(label);
+ });
+
+ it("does not offer effort levels for an unknown Claude default", async () => {
+ const defaultAgent = { ...agent, adapterType: "claude_local", adapterConfig: {} } as Agent;
+ render(vi.fn(), vi.fn(), false, { settings: null, agents: new Map([[agent.id, defaultAgent]]),
+ modelOptionsOverride: [{ id: "claude-opus-5", label: "Claude Opus 5" }] });
+ await click("Select model and effort");
+ expect(document.querySelector('[aria-label="Effort"]')).toBeNull();
+ });
+
+ it.each([
+ { remembered: "high", settings: null, overrides: null, restored: "high" },
+ { remembered: "off", settings: null, overrides: null, restored: null },
+ { remembered: "high", settings: { model: null, effort: "low", fast: false }, overrides: null, restored: null },
+ { remembered: "high", settings: null, overrides: { adapterConfig: { modelReasoningEffort: "low" } }, restored: null },
+ ])("restores compatible history ($remembered) without replacing explicit settings", ({ remembered, settings, overrides, restored }) => {
+ rememberComposerEffort("company-1", remembered);
+ const onSettingsChange = vi.fn();
+ render(vi.fn(), onSettingsChange, false, { settings, overrides });
+ if (restored) expect(onSettingsChange).toHaveBeenCalledWith({ model: null, effort: restored, fast: false });
+ else expect(onSettingsChange).not.toHaveBeenCalled();
+ });
+
+ it("records effort changes and preserves effort when changing to a compatible model", async () => {
+ const onSettingsChange = vi.fn();
+ render(vi.fn(), onSettingsChange, false, { modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] });
+ await click("Select model and effort");
+ const range = document.querySelector<HTMLInputElement>('input[aria-label="Effort"]')!;
+ flushSync(() => {
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1");
+ range.dispatchEvent(new Event("change", { bubbles: true }));
+ range.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ expect(getLastComposerEffort("company-1")).toBe("low");
+ await click("Choose exact model");
+ await click("GPT-6 Astra");
+ expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false });
+ await click("Reset to agent default");
+ expect(getLastComposerEffort("company-1")).toBeNull();
+ });
it("lets the assignee and model use the available composer width", () => {
render(vi.fn(), vi.fn());
const trigger = container!.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-assignee"]');
const assignee = trigger!.querySelector('[data-testid="task-chat-composer-assignee-label"]');
- const model = trigger!.querySelector('[data-testid="task-chat-composer-model-label"]');
+ const model = container!.querySelector('[data-testid="task-chat-composer-model-label"]');
expect(trigger?.className).toContain("max-w-full");
expect(trigger?.className).not.toContain("max-w-64");
@@ -72,8 +124,7 @@ describe("composer assignee picker", () => {
it("finds assignees by their displayed role and harness", async () => {
render(vi.fn(), vi.fn());
- await click("Select assignee, model and effort");
- await click("Choose assignee");
+ await click("Select assignee");
const input = document.querySelector<HTMLInputElement>('input[aria-label="Search assignees"]');
expect(input).not.toBeNull();
const setValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!;
@@ -94,7 +145,7 @@ describe("composer assignee picker", () => {
]);
render(vi.fn(), vi.fn(), true);
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
- await click("Select assignee, model and effort");
+ await click("Select model and effort");
await click("Choose exact model");
const options = [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')]
.map((item) => item.textContent ?? "");
@@ -115,7 +166,7 @@ describe("composer assignee picker", () => {
environmentId: null,
provider: undefined,
});
- await click("Select assignee, model and effort");
+ await click("Select model and effort");
await click("Choose exact model");
const choices = [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')]
.map((item) => item.textContent ?? "");
@@ -127,21 +178,48 @@ describe("composer assignee picker", () => {
const onAssigneeChange = vi.fn();
const onSettingsChange = vi.fn();
render(onAssigneeChange, onSettingsChange);
- await click("Select assignee, model and effort");
- await click("Choose assignee");
+ await click("Select assignee");
await click("Clippy");
expect(onAssigneeChange).not.toHaveBeenCalled();
expect(onSettingsChange).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="listbox"]')).toBeNull();
});
it("offers No assignee and clears settings when selected", async () => {
const onAssigneeChange = vi.fn();
const onSettingsChange = vi.fn();
render(onAssigneeChange, onSettingsChange);
- await click("Select assignee, model and effort");
- await click("Choose assignee");
+ await click("Select assignee");
await click("No assignee");
expect(onAssigneeChange).toHaveBeenCalledWith("");
- expect(onSettingsChange).toHaveBeenCalledWith({ model: null, effort: null, fast: false });
+ expect(onSettingsChange).toHaveBeenCalledWith(null);
+ expect(document.querySelector('[role="listbox"]')).toBeNull();
+ });
+
+ it.each(["", "user:me"])("hides model and effort for %s and opens assignees in one click", async (assigneeValue) => {
+ const loadModels = vi.spyOn(agentsApi, "adapterModels");
+ render(vi.fn(), vi.fn(), true, {
+ assigneeValue,
+ currentAssigneeValue: assigneeValue,
+ options: [...options, { id: "user:me", label: "Me" }],
+ });
+ expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull();
+ expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull();
+ expect(container!.textContent).not.toContain("Harness default");
+ expect(container!.textContent).not.toContain("High");
+ await click("Select assignee");
+ expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Effort"]')).toBeNull();
+ expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull();
+ expect(document.body.textContent).not.toContain("Choose an agent");
+ expect(loadModels).not.toHaveBeenCalled();
+ });
+
+ it("opens the assignee list directly on mobile", async () => {
+ render(vi.fn(), vi.fn(), false, { mobile: true });
+ await click("Select assignee");
+ expect(document.querySelector('[data-testid="composer-mobile-dialog"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull();
+ expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull();
});
});
diff --git a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
index 63f42235d2..dd88b4c0f4 100644
--- a/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
+++ b/ui/src/components/task-chat/ComposerRunSettingsPicker.tsx
@@ -5,11 +5,12 @@ import type { Agent, IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
import { agentsApi, type AdapterModel } from "@/api/agents";
import { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
+import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort";
import type { InlineEntityOption } from "@/components/InlineEntitySelector";
import { Dialog, DialogClose, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
- composerCatalogProvider, composerEfforts, composerFastAvailable, DEFAULT_COMPOSER_RUN_SETTINGS,
+ composerCatalogProvider, composerDefaultModel, composerEfforts, composerFastAvailable, DEFAULT_COMPOSER_RUN_SETTINGS,
EFFORT_LABELS, readComposerRunSettings, supportsComposerModel,
type ComposerRunSettings,
} from "./composer-run-settings";
@@ -23,7 +24,7 @@ interface Props {
agents: ReadonlyMap<string, Agent>;
overrides?: IssueAssigneeAdapterOverrides | null;
settings: ComposerRunSettings | null;
- onSettingsChange: (settings: ComposerRunSettings) => void;
+ onSettingsChange: (settings: ComposerRunSettings | null) => void;
onAssigneeChange: (value: string) => void;
disabled?: boolean;
mobile?: boolean;
@@ -117,7 +118,7 @@ export function ComposerRunSettingsPicker({
? readComposerRunSettings(overrides, agent?.adapterType)
: DEFAULT_COMPOSER_RUN_SETTINGS;
const selected = settings ?? base;
- const configuredModel = typeof agent?.adapterConfig.model === "string" ? agent.adapterConfig.model : "";
+ const configuredModel = composerDefaultModel(agent);
const model = selected.model ?? configuredModel;
const modelName = models.find((item) => item.id === model)?.label ?? model ?? "";
const choices = composerEfforts(agent, model, models.map((item) => item.id));
@@ -125,6 +126,15 @@ export function ComposerRunSettingsPicker({
const effortIndex = effort ? choices.indexOf(effort) + 1 : 0;
const effortLabel = effort ? EFFORT_LABELS[effort] ?? effort : "Default";
const fastAvailable = composerFastAvailable(agent, model);
+ const effortChoicesKey = choices.join(",");
+ useEffect(() => {
+ // Explicit drafts and task overrides take precedence over remembered effort.
+ if (settings !== null || base.effort || !modelSupported) return;
+ const remembered = getLastComposerEffort(companyId);
+ if (remembered && effortChoicesKey.split(",").includes(remembered)) {
+ onSettingsChange({ ...base, effort: remembered });
+ }
+ }, [companyId, agentId, model, modelSupported, settings, base.model, base.effort, base.fast, effortChoicesKey, onSettingsChange]);
const changed = Boolean(selected.model || selected.effort || selected.fast);
const assigneeOptions = [{ id: "", label: "No assignee", searchText: "Unassigned" }, ...options.filter((item) => item.id !== "")];
const filteredAgents = assigneeOptions.filter((item) => {
@@ -146,34 +156,50 @@ export function ComposerRunSettingsPicker({
useEffect(() => {
if (previousAgentId.current === agentId) return;
previousAgentId.current = agentId;
- setView("settings");
+ setView((current) => current === "agents" ? "agents" : "settings");
setModelSearch("");
- setAssigneeSearch("");
}, [agentId]);
const chooseAssignee = (value: string) => {
if (value !== assigneeValue) {
onAssigneeChange(value);
- onSettingsChange(DEFAULT_COMPOSER_RUN_SETTINGS);
+ onSettingsChange(null);
}
+ setOpen(false);
setView("settings");
setAssigneeSearch("");
};
const chooseModel = (value: string | null) => {
- onSettingsChange({ model: value, effort: null, fast: false });
+ const nextChoices = composerEfforts(agent, value ?? configuredModel, models.map((item) => item.id));
+ const preferred = selected.effort ?? getLastComposerEffort(companyId);
+ onSettingsChange({ model: value, effort: preferred && nextChoices.includes(preferred) ? preferred : null, fast: false });
setView("settings");
setModelSearch("");
};
- const reset = () => onSettingsChange(DEFAULT_COMPOSER_RUN_SETTINGS);
+ const reset = () => {
+ rememberComposerEffort(companyId, null);
+ onSettingsChange(DEFAULT_COMPOSER_RUN_SETTINGS);
+ };
const closeButton = mobile ? <DialogClose asChild><button type="button" aria-label="Close picker" className="grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent"><X className="size-4" /></button></DialogClose> : null;
- const trigger = <button ref={triggerRef} type="button" disabled={disabled} aria-label="Select assignee, model and effort" data-testid="task-chat-composer-assignee"
- className="flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full bg-muted px-2.5 text-xs font-medium hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">
- {renderAssigneeIdentity?.(assigneeValue, agent?.name ?? "Unassigned", "trigger")}
- <span data-testid="task-chat-composer-assignee-label" className="min-w-0 truncate">{assigneeOptions.find((item) => item.id === assigneeValue)?.label ?? "Unassigned"}</span>
- <span className="text-muted-foreground" aria-hidden>·</span><span data-testid="task-chat-composer-model-label" className="min-w-0 truncate text-muted-foreground">{modelSupported ? modelName || "Harness default" : "Harness default"}</span>
- {effort ? <span className="hidden shrink-0 text-muted-foreground sm:inline">{effortLabel}</span> : null}
- <ChevronDown className="size-3 shrink-0 text-muted-foreground" aria-hidden />
- </button>;
+ const Trigger = mobile ? DialogTrigger : PopoverTrigger;
+ const triggers = <div data-testid="task-chat-composer-selection" className="flex min-w-0 max-w-full items-center rounded-full bg-muted text-xs font-medium">
+ <Trigger asChild><button ref={triggerRef} type="button" disabled={disabled} aria-label="Select assignee" data-testid="task-chat-composer-assignee"
+ onClick={() => { setView("agents"); setHighlightedAssignee(0); }}
+ className="flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full px-2.5 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">
+ {renderAssigneeIdentity?.(assigneeValue, agent?.name ?? "Unassigned", "trigger")}
+ <span data-testid="task-chat-composer-assignee-label" className="min-w-0 truncate">{assigneeOptions.find((item) => item.id === assigneeValue)?.label ?? "Unassigned"}</span>
+ {!modelSupported ? <ChevronDown className="size-3 shrink-0 text-muted-foreground" aria-hidden /> : null}
+ </button></Trigger>
+ {modelSupported ? <>
+ <span className="text-muted-foreground" aria-hidden>·</span>
+ <button type="button" disabled={disabled} aria-label="Select model and effort" aria-haspopup="dialog" aria-expanded={open && view !== "agents"} onClick={() => { setView("settings"); setOpen(true); }}
+ className="flex h-8 min-w-0 max-w-full items-center gap-1.5 rounded-full px-2.5 text-muted-foreground hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">
+ <span data-testid="task-chat-composer-model-label" className="min-w-0 truncate">{modelName || "Default"}</span>
+ {effort ? <span className="hidden shrink-0 sm:inline">{effortLabel}</span> : null}
+ <ChevronDown className="size-3 shrink-0" aria-hidden />
+ </button>
+ </> : null}
+ </div>;
const body = view === "settings" ? <div className="p-3">
<div className="flex items-center gap-2">
@@ -188,7 +214,7 @@ export function ComposerRunSettingsPicker({
</div>
{modelSupported ? <>
<button type="button" aria-label="Choose exact model" onClick={() => setView("models")} className="mt-3 flex w-full items-center gap-2 rounded-md px-1 py-1 text-left hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <span className="min-w-0 flex-1"><span className="block text-xs text-muted-foreground">Model</span><span className="block truncate text-sm font-medium">{modelName || "Harness default"}</span></span><ChevronDown className="size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 flex-1"><span className="block text-xs text-muted-foreground">Model</span><span className="block truncate text-sm font-medium">{modelName || "Default"}</span></span><ChevronDown className="size-4 shrink-0 text-muted-foreground" aria-hidden />
</button>
{choices.length ? <div className="mt-3">
<div className="flex items-center gap-2">
@@ -197,22 +223,29 @@ export function ComposerRunSettingsPicker({
<button type="button" aria-label="Reset to agent default" title="Reset to agent default" disabled={!changed} onClick={reset} className="grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent disabled:opacity-40"><RotateCcw className="size-4" /></button>
</div>
<input id="composer-run-effort" type="range" min={0} max={choices.length} step={1} value={effortIndex} aria-label={agent?.adapterType === "pi_local" ? "Thinking" : "Effort"} aria-valuetext={effortLabel}
- onChange={(event) => onSettingsChange({ ...selected, effort: Number(event.target.value) === 0 ? null : choices[Number(event.target.value) - 1] })}
+ onChange={(event) => {
+ const nextEffort = Number(event.target.value) === 0 ? null : choices[Number(event.target.value) - 1]!;
+ rememberComposerEffort(companyId, nextEffort);
+ onSettingsChange({ ...selected, effort: nextEffort });
+ }}
className="composer-run-effort-range mt-3 w-full" style={{ "--fill": `${effortIndex / choices.length * 100}%` } as CSSProperties} />
</div> : null}
- </> : <div className="mt-3 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground" data-testid="model-unavailable">{unavailableModelReason(agent)}</div>}
+ </> : agent ? <div className="mt-3 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground" data-testid="model-unavailable">{unavailableModelReason(agent)}</div> : null}
</div> : view === "agents" ? <div className="p-2">
- <div className="flex items-center gap-2 px-1 py-1.5"><button type="button" aria-label="Back to selection" onClick={() => setView("settings")} className="grid size-7 place-items-center rounded-md hover:bg-accent"><ArrowLeft className="size-4" /></button><span className="min-w-0 flex-1"><span className="block text-xs font-semibold">Choose assignee</span><span className="block truncate text-xs text-muted-foreground">Each agent keeps its configured harness.</span></span>{closeButton}</div>
+ <div className="flex items-center gap-2 px-1 py-1.5"><span className="min-w-0 flex-1 text-xs font-semibold">Choose assignee</span>{closeButton}</div>
<div className="relative mt-2"><Search className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground" aria-hidden /><input autoFocus type="search" aria-label="Search assignees" placeholder="Search assignees…" value={assigneeSearch} onChange={(event) => { setAssigneeSearch(event.target.value); setHighlightedAssignee(0); }} onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); setHighlightedAssignee((current) => filteredAgents.length ? (current + (event.key === "ArrowDown" ? 1 : -1) + filteredAgents.length) % filteredAgents.length : 0); }
if (event.key === "Enter" && filteredAgents.length) { event.preventDefault(); chooseAssignee(filteredAgents[Math.min(highlightedAssignee, filteredAgents.length - 1)]!.id); }
}} className="h-9 w-full rounded-md border border-border bg-background pl-8 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring" /></div>
- <div className="mt-2 max-h-60 overflow-y-auto" role="listbox" aria-label="Assignees">{filteredAgents.map((item, index) => <button key={item.id} type="button" role="option" aria-selected={item.id === assigneeValue} onMouseEnter={() => setHighlightedAssignee(index)} onClick={() => chooseAssignee(item.id)} className={cn("flex w-full items-center gap-2 rounded-md px-2 py-2 text-left focus-visible:outline-none", highlightedAssignee === index ? "bg-accent" : "hover:bg-accent")}>{renderAssigneeIdentity?.(item.id, item.label, "option")}<span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium">{item.label}</span><span className="block truncate text-xs text-muted-foreground">{agents.get(item.id.startsWith("agent:") ? item.id.slice(6) : "")?.role ?? ""}</span></span><span className="truncate text-xs text-muted-foreground">{harnessLabel(agents.get(item.id.startsWith("agent:") ? item.id.slice(6) : ""))}</span>{item.id === assigneeValue ? <Check className="composer-run-settings-accent size-4" /> : null}</button>)}{!filteredAgents.length ? <p className="px-2 py-2 text-xs text-muted-foreground">No matches.</p> : null}</div>
+ <div className="mt-2 max-h-60 overflow-y-auto" role="listbox" aria-label="Assignees">{filteredAgents.map((item, index) => {
+ const optionAgent = agents.get(item.id.startsWith("agent:") ? item.id.slice(6) : "");
+ return <button key={item.id} type="button" role="option" aria-selected={item.id === assigneeValue} onMouseEnter={() => setHighlightedAssignee(index)} onClick={() => chooseAssignee(item.id)} className={cn("flex w-full items-center gap-2 rounded-md px-2 py-2 text-left focus-visible:outline-none", highlightedAssignee === index ? "bg-accent" : "hover:bg-accent")}>{renderAssigneeIdentity?.(item.id, item.label, "option")}<span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium">{item.label}</span>{optionAgent ? <span className="block truncate text-xs text-muted-foreground">{optionAgent.role}</span> : null}</span>{optionAgent ? <span className="truncate text-xs text-muted-foreground">{harnessLabel(optionAgent)}</span> : null}{item.id === assigneeValue ? <Check className="composer-run-settings-accent size-4" /> : null}</button>;
+ })}{!filteredAgents.length ? <p className="px-2 py-2 text-xs text-muted-foreground">No matches.</p> : null}</div>
</div> : <div className="p-2">
<div className="flex items-center gap-2 px-1 py-1.5"><button type="button" aria-label="Back to selection" onClick={() => setView("settings")} className="grid size-7 place-items-center rounded-md hover:bg-accent"><ArrowLeft className="size-4" /></button><span className="min-w-0 flex-1"><span className="block text-xs font-semibold">Choose model</span><span className="block truncate text-xs text-muted-foreground">{harnessLabel(agent)}</span></span>{closeButton}</div>
<div className="relative mt-2"><Search className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-muted-foreground" aria-hidden /><input autoFocus type="search" aria-label="Search or paste a model ID" placeholder="Search or paste a model ID" value={modelSearch} onChange={(event) => setModelSearch(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && manualValid && !exactMatch) chooseModel(query); }} className="h-9 w-full rounded-md border border-border bg-background pl-8 pr-2 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring" /></div>
<div className="mt-2 max-h-60 overflow-y-auto" role="listbox" aria-label="Models">
- {!query ? <button type="button" role="option" aria-selected={selected.model === null} onClick={() => chooseModel(null)} className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left hover:bg-accent"><span className="min-w-0 flex-1"><span className="block text-sm font-medium">Use agent default</span><span className="block truncate text-xs text-muted-foreground">{models.find((item) => item.id === configuredModel)?.label || configuredModel || "Harness default"}</span></span>{selected.model === null ? <Check className="composer-run-settings-accent size-4" /> : null}</button> : null}
+ {!query ? <button type="button" role="option" aria-selected={selected.model === null} onClick={() => chooseModel(null)} className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left hover:bg-accent"><span className="min-w-0 flex-1"><span className="block text-sm font-medium">Use agent default</span><span className="block truncate text-xs text-muted-foreground">{models.find((item) => item.id === configuredModel)?.label || configuredModel || "Default"}</span></span>{selected.model === null ? <Check className="composer-run-settings-accent size-4" /> : null}</button> : null}
{filteredModels.map((item) => <button type="button" role="option" aria-selected={selected.model === item.id} key={item.id} onClick={() => chooseModel(item.id)} className="flex w-full items-center gap-3 rounded-md px-2.5 py-2 text-left text-sm transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"><span className="min-w-0 flex-1"><span className="block truncate font-medium">{item.label}</span><span className="block truncate font-mono text-xs text-muted-foreground">{item.id}</span></span>{item.detail || item.id === configuredModel ? <span className="shrink-0 text-xs text-muted-foreground">{item.detail ?? "Agent default"}</span> : null}{selected.model === item.id ? <Check className="composer-run-settings-accent size-4 shrink-0" /> : null}</button>)}
{catalogPending ? <p className="px-2.5 py-2 text-xs text-muted-foreground">Loading models…</p> : null}
{!catalogPending && !filteredModels.length && query ? <p className="px-2.5 py-2 text-xs text-muted-foreground">No catalog match.</p> : null}
@@ -222,6 +255,6 @@ export function ComposerRunSettingsPicker({
</div>;
const onOpenChange = (next: boolean) => { setOpen(next); if (!next) { setView("settings"); setModelSearch(""); setAssigneeSearch(""); } };
- return mobile ? <Dialog open={open} onOpenChange={onOpenChange}><DialogTrigger asChild>{trigger}</DialogTrigger><DialogContent aria-describedby={undefined} showCloseButton={false} className="composer-mobile-dialog top-(--pct-50) -translate-y-(--pct-50) gap-0 overflow-y-auto p-0" data-testid="composer-mobile-dialog"><DialogTitle className="sr-only">Select assignee, model and effort</DialogTitle><AnimatedBody>{body}</AnimatedBody></DialogContent></Dialog>
- : <Popover open={open} onOpenChange={onOpenChange}><PopoverTrigger asChild>{trigger}</PopoverTrigger><PopoverContent side="top" align="end" sideOffset={8} className="w-80 max-w-full p-0 shadow-sm" data-testid="composer-model-popover"><AnimatedBody>{body}</AnimatedBody></PopoverContent></Popover>;
+ return mobile ? <Dialog open={open} onOpenChange={onOpenChange}>{triggers}<DialogContent aria-describedby={undefined} showCloseButton={false} className="composer-mobile-dialog top-(--pct-50) -translate-y-(--pct-50) gap-0 overflow-y-auto p-0" data-testid="composer-mobile-dialog"><DialogTitle className="sr-only">{view === "agents" ? "Select assignee" : "Select model and effort"}</DialogTitle><AnimatedBody>{body}</AnimatedBody></DialogContent></Dialog>
+ : <Popover open={open} onOpenChange={onOpenChange}><PopoverAnchor asChild>{triggers}</PopoverAnchor><PopoverContent side="top" align="end" sideOffset={8} className="w-80 max-w-full p-0 shadow-sm" data-testid="composer-model-popover"><AnimatedBody>{body}</AnimatedBody></PopoverContent></Popover>;
}
diff --git a/ui/src/components/task-chat/ComposerWorktreePicker.tsx b/ui/src/components/task-chat/ComposerWorktreePicker.tsx
new file mode 100644
index 0000000000..52b714693a
--- /dev/null
+++ b/ui/src/components/task-chat/ComposerWorktreePicker.tsx
@@ -0,0 +1,109 @@
+import { useMemo, type CSSProperties } from "react";
+import { Folder, GitBranch, GitBranchPlus, Monitor } from "lucide-react";
+import type { ExecutionWorkspaceSummary } from "@paperclipai/shared";
+import { SearchableSelect, type SearchableSelectOption } from "@/components/SearchableSelect";
+import { orderReusableExecutionWorkspaces } from "@/lib/reusable-execution-workspaces";
+
+interface WorktreeOption extends SearchableSelectOption {
+ mode: string;
+ workspaceId?: string;
+ description: string;
+}
+
+interface ComposerWorktreePickerProps {
+ mode: string;
+ workspaceId: string;
+ workspaces: readonly ExecutionWorkspaceSummary[];
+ onChange: (mode: string, workspaceId: string) => void;
+ loading: boolean;
+ error: boolean;
+ onRetry: () => void;
+ disabled?: boolean;
+ mobile?: boolean;
+ contentStyle?: CSSProperties;
+ selectedWorkspaceLabel?: string;
+}
+
+const MODE_OPTIONS: WorktreeOption[] = [
+ { key: "isolated_workspace", value: "isolated_workspace", mode: "isolated_workspace", label: "New worktree", description: "Start in an isolated checkout." },
+ { key: "shared_workspace", value: "shared_workspace", mode: "shared_workspace", label: "Project workspace", description: "Use the project's shared checkout." },
+ { key: "operator_branch", value: "operator_branch", mode: "operator_branch", label: "New branch", description: "Create a branch in the project workspace." },
+ { key: "agent_default", value: "agent_default", mode: "agent_default", label: "Agent default", description: "Let the agent choose its workspace." },
+ { key: "inherit", value: "inherit", mode: "inherit", label: "Project default", description: "Use the project's worktree settings." },
+];
+
+/** Reuses the searchable selector and the existing workspace recency ordering. */
+export function ComposerWorktreePicker({
+ mode, workspaceId, workspaces, onChange, loading, error, onRetry,
+ disabled, mobile, contentStyle, selectedWorkspaceLabel,
+}: ComposerWorktreePickerProps) {
+ const groups = useMemo(() => [
+ { id: "new", options: [MODE_OPTIONS[0]!] },
+ {
+ id: "reuse", label: "Reuse a worktree",
+ options: orderReusableExecutionWorkspaces(workspaces).map((workspace): WorktreeOption => ({
+ key: `reuse:${workspace.id}`, value: `reuse:${workspace.id}`,
+ workspaceId: workspace.id, mode: "reuse_existing", label: workspace.name,
+ description: workspace.branchName ?? "Existing workspace",
+ searchText: `${workspace.branchName ?? ""} ${workspace.id}`,
+ })),
+ },
+ {
+ id: "other", label: "Other options",
+ options: MODE_OPTIONS.filter((option) => option.mode === "shared_workspace"
+ || (option.mode !== "isolated_workspace" && option.mode === mode)),
+ },
+ ], [mode, workspaces]);
+
+ const value = mode === "reuse_existing" ? `reuse:${workspaceId}` : mode;
+ return (
+ <SearchableSelect<string, WorktreeOption>
+ value={value}
+ groups={groups}
+ onValueChange={(_, option) => onChange(option.mode, option.workspaceId ?? "")}
+ placeholder="Worktrees"
+ triggerAriaLabel="Worktrees"
+ mobileTitle="Worktrees"
+ searchPlaceholder="Search worktrees..."
+ emptyMessage="No matching worktrees."
+ disabled={disabled}
+ modal={mobile}
+ contentStyle={contentStyle}
+ contentWidth="auto"
+ className="min-w-0 flex-1 sm:flex-none sm:max-w-72"
+ triggerClassName="h-8 gap-1.5 border-0 bg-transparent px-2 text-xs font-medium shadow-none hover:bg-accent focus-visible:bg-accent focus-visible:ring-0"
+ renderValue={(option) => (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <GitBranch className="size-3.5 shrink-0" aria-hidden />
+ <span className="truncate">
+ <span className="hidden text-muted-foreground sm:inline">Worktrees · </span>
+ {option?.label ?? selectedWorkspaceLabel ?? "Select worktree"}
+ </span>
+ </span>
+ )}
+ renderOption={(option) => {
+ const Icon = option.workspaceId ? GitBranch : option.mode === "isolated_workspace" ? GitBranchPlus
+ : option.mode === "agent_default" ? Monitor : option.mode === "operator_branch" ? GitBranch : Folder;
+ return (
+ <>
+ <Icon className="size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate">{option.label}</span>
+ <span className="truncate text-xs text-muted-foreground">{option.description}</span>
+ </span>
+ </>
+ );
+ }}
+ listFooter={loading || error || workspaces.length === 0 ? (
+ <div className="border-t border-border px-3 py-2 text-xs text-muted-foreground" role="status">
+ {loading ? "Loading existing worktrees…" : error ? (
+ <span className="flex items-center justify-between gap-2">
+ Couldn't load worktrees.
+ <button type="button" className="rounded px-2 py-1 text-foreground hover:bg-accent" onClick={onRetry}>Retry</button>
+ </span>
+ ) : "No existing worktrees yet. Choose New worktree to start one."}
+ </div>
+ ) : undefined}
+ />
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx
index 05a2a1d074..769a4d4c50 100644
--- a/ui/src/components/task-chat/TaskChatComposer.test.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx
@@ -297,6 +297,54 @@ function autocompleteOption(matchText: string) {
}
describe("TaskChatComposer", () => {
+ it("keeps creation images inline and prevents submission during their upload", async () => {
+ let resolveUpload!: (url: string) => void;
+ const onImageUpload = vi.fn().mockReturnValue(new Promise<string>((resolve) => { resolveUpload = resolve; }));
+ const creation = {
+ value: "Before the screenshot",
+ onChange: vi.fn(),
+ onSubmit: vi.fn().mockResolvedValue(undefined),
+ submitLabel: "Create task",
+ onSelectFiles: vi.fn(),
+ runSettings: null,
+ onRunSettingsChange: vi.fn(),
+ };
+ render(<TaskChatComposer creation={creation} workMode="standard" onImageUpload={onImageUpload} />);
+ const image = new File(["png"], "screen.png", { type: "image/png" });
+ expect(pasteFiles([image]).defaultPrevented).toBe(false);
+ expect(creation.onSelectFiles).not.toHaveBeenCalled();
+ const handler = mdxEditorMockState.imagePluginOptions!.imageUploadHandler!;
+ const upload = handler(image);
+ await flushAsync();
+ expect(sendButton().disabled).toBe(true);
+ pressKey("Enter", { metaKey: true });
+ expect(creation.onSubmit).not.toHaveBeenCalled();
+ resolveUpload("/api/assets/screen/content");
+ const url = await upload;
+ const value = `Before the screenshot\n\n![screen](${url})\n\nAfter the screenshot`;
+ render(<TaskChatComposer creation={{ ...creation, value }} workMode="standard" onImageUpload={onImageUpload} />);
+ await flushAsync();
+ flushSync(() => sendButton().click());
+ await flushAsync();
+ expect(creation.onSubmit).toHaveBeenCalledWith(value, "standard", null);
+ expect(onImageUpload).toHaveBeenCalledWith(image);
+ });
+
+ it("stages non-image creation paste files while images reach the editor", () => {
+ const creation = {
+ value: "Inspect these files",
+ onChange: vi.fn(), onSubmit: vi.fn().mockResolvedValue(undefined),
+ submitLabel: "Create task", onSelectFiles: vi.fn(),
+ runSettings: null, onRunSettingsChange: vi.fn(),
+ };
+ render(<TaskChatComposer creation={creation} workMode="standard" onImageUpload={vi.fn()} />);
+ const image = new File(["png"], "screen.png", { type: "image/png" });
+ const document = new File(["notes"], "notes.txt", { type: "text/plain" });
+ expect(pasteFiles([image, document]).defaultPrevented).toBe(false);
+ expect(creation.onSelectFiles).toHaveBeenCalledWith([document]);
+ expect(pasteFiles([document]).defaultPrevented).toBe(true);
+ });
+
it("settles an acknowledged submission after navigating away", async () => {
const key = "navigate-before-save";
let resolveSend!: () => void;
diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx
index 36e2f7a7b0..19ed3daf86 100644
--- a/ui/src/components/task-chat/TaskChatComposer.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.tsx
@@ -49,6 +49,7 @@ import {
type MarkdownEditorRef,
} from "@/components/MarkdownEditor";
import { nextWorkMode } from "@/lib/work-mode-meta";
+import { trackRecentAssignee, trackRecentAssigneeUser } from "@/lib/recent-assignees";
import {
InlineEntitySelector,
type InlineEntityOption,
@@ -62,6 +63,7 @@ import { TaskChatComposerTakeoverActionsContext } from "./TaskChatComposerTakeov
import { TaskChatPausedTakeover, type TaskComposerPause } from "./TaskChatPausedTakeover";
import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker";
+import { TaskChatComposerBar } from "./TaskChatComposerBar";
import { ComposerAddMenu, ComposerModeChip } from "./ComposerAddMenu";
import type { ComposerRunSettings } from "./composer-run-settings";
import type { Agent, IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
@@ -89,7 +91,7 @@ export interface TaskChatComposerTakeover {
}
interface TaskChatComposerProps {
- onAdd: (
+ onAdd?: (
body: string,
reopen?: boolean,
reassignment?: CommentReassignment,
@@ -97,6 +99,21 @@ interface TaskChatComposerProps {
clientRequestId?: string,
runSettings?: ComposerRunSettings,
) => Promise<void> | void;
+ /** New tasks share the editor and controls, but retain their draft until creation succeeds. */
+ creation?: {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: (body: string, mode: IssueWorkMode, settings: ComposerRunSettings | null) => Promise<void>;
+ submitLabel: string;
+ canSubmitWithoutBody?: boolean;
+ header?: ReactNode;
+ details?: ReactNode;
+ contextBar?: ReactNode;
+ submitDisabled?: boolean;
+ onSelectFiles: (files: File[]) => void;
+ runSettings: ComposerRunSettings | null;
+ onRunSettingsChange: (settings: ComposerRunSettings | null) => void;
+ };
confirmedSubmissionIds?: ReadonlySet<string>;
onStop?: () => Promise<void>;
stopPending?: boolean;
@@ -358,6 +375,7 @@ function escapeMarkdownLabel(name: string): string {
*/
export function TaskChatComposer({
onAdd,
+ creation,
confirmedSubmissionIds,
onStop,
stopPending = false,
@@ -395,7 +413,8 @@ export function TaskChatComposer({
}: TaskChatComposerProps) {
const streamlined = useStreamlinedTaskChatPresentation();
const stopControl = useComposerStop(onStop, stopPending);
- const [body, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));
+ const [localBody, setBody] = useState(() => (draftKey ? loadDraft(draftKey) : ""));
+ const body = creation ? creation.value : localBody;
const [submitting, setSubmitting] = useState(false);
const [reviewError, setReviewError] = useState(false);
const [uncertainSubmission, setUncertainSubmission] =
@@ -417,10 +436,13 @@ export function TaskChatComposer({
useState<HTMLElement | null>(null);
const [takeoverControlsSlot, setTakeoverControlsSlot] =
useState<HTMLElement | null>(null);
- const [pendingMode, setPendingMode] = useState<IssueWorkMode>(workMode);
+ const [localPendingMode, setPendingMode] = useState<IssueWorkMode>(workMode);
+ const pendingMode = creation ? workMode : localPendingMode;
const [pendingAssignee, setPendingAssignee] = useState<string | null>(null);
- const [runSettings, setRunSettings] = useState<ComposerRunSettings | null>(null);
- useEffect(() => setRunSettings(null), [draftKey, currentAssigneeValue]);
+ const [localRunSettings, setLocalRunSettings] = useState<ComposerRunSettings | null>(null);
+ const runSettings = creation ? creation.runSettings : localRunSettings;
+ const setRunSettings = creation ? creation.onRunSettingsChange : setLocalRunSettings;
+ useEffect(() => setLocalRunSettings(null), [draftKey, currentAssigneeValue]);
const [actionError, setActionError] = useState<string | null>(null);
const [attachments, setAttachmentState] = useState<ComposerAttachment[]>(
() =>
@@ -465,6 +487,10 @@ export function TaskChatComposer({
} | null>(null);
function changeBody(value: string) {
bodyRef.current = value;
+ if (creation) {
+ creation.onChange(value);
+ return;
+ }
setBody(value);
const pending = pendingDraftRef.current;
if (!pending || pending.draftKey !== draftKey ||
@@ -607,11 +633,11 @@ export function TaskChatComposer({
!pause &&
!queuedEdit &&
!uncertainSubmission &&
- Boolean(onAttachImage || onImageUpload);
+ Boolean(creation || onAttachImage || onImageUpload);
const showAssignee = Boolean(
enableReassign && reassignOptions && reassignOptions.length > 0,
);
- const assigneeValue = pendingAssignee ?? currentAssigneeValue;
+ const assigneeValue = creation ? currentAssigneeValue : pendingAssignee ?? currentAssigneeValue;
const assigneeLabel =
reassignOptions?.find((o) => o.id === assigneeValue)?.label ?? "Unassigned";
const assigneeName =
@@ -637,10 +663,20 @@ export function TaskChatComposer({
};
function updatePendingAssignee(value: string | null) {
+ if (!creation && value && companyId) {
+ const selection = parseAssigneeValue(value);
+ if (selection?.assigneeAgentId) trackRecentAssignee(selection.assigneeAgentId, companyId);
+ if (selection?.assigneeUserId) trackRecentAssigneeUser(selection.assigneeUserId, companyId);
+ }
setPendingAssignee(value);
onPendingAssigneeChange?.(value);
}
+ function changeMode(mode: IssueWorkMode) {
+ setPendingMode(mode);
+ if (creation) void onWorkModeChange?.(mode);
+ }
+
/** Upload an image and return its URL for inline `![](src)` markdown. */
async function uploadInlineImage(file: File): Promise<string> {
const id = crypto.randomUUID();
@@ -764,6 +800,11 @@ export function TaskChatComposer({
function handleFileInputChange(evt: ChangeEvent<HTMLInputElement>) {
const files = evt.target.files;
if (files && files.length > 0) {
+ if (creation) {
+ creation.onSelectFiles(Array.from(files));
+ evt.target.value = "";
+ return;
+ }
void (async () => {
for (const file of Array.from(files)) await attachPickedFile(file);
})();
@@ -787,6 +828,19 @@ export function TaskChatComposer({
if (pause || !canAcceptFiles) return;
const files = Array.from(evt.clipboardData?.files ?? []);
if (files.length === 0) return;
+ if (creation) {
+ if (onImageUpload) {
+ const nonImages = files.filter((file) => !file.type.startsWith("image/"));
+ if (nonImages.length === 0) return;
+ creation.onSelectFiles(nonImages);
+ if (nonImages.length !== files.length) return;
+ } else {
+ creation.onSelectFiles(files);
+ }
+ evt.preventDefault();
+ evt.stopPropagation();
+ return;
+ }
const nonImages = files.filter((file) => !file.type.startsWith("image/"));
if (nonImages.length === 0) return;
if (nonImages.length === files.length) {
@@ -830,6 +884,22 @@ export function TaskChatComposer({
async function submit() {
if (disabled || (pause && !canResetPausedConversation)) return;
+ if (creation) {
+ if (submittingRef.current || uploadPending || uploadFailed || creation.submitDisabled || (!bodyRef.current.trim() && !creation.canSubmitWithoutBody)) return;
+ submittingRef.current = true;
+ setSubmitting(true);
+ setActionError(null);
+ try {
+ await creation.onSubmit(bodyRef.current, pendingMode, runSettings);
+ } catch (error) {
+ setActionError(error instanceof Error ? error.message : "Failed to create task. Try again.");
+ } finally {
+ submittingRef.current = false;
+ setSubmitting(false);
+ }
+ return;
+ }
+ if (!onAdd) return;
const retained =
draftKey && !queuedEdit ? loadDraftSubmission(draftKey) : null;
if (retained && !submitting) {
@@ -1116,7 +1186,7 @@ export function TaskChatComposer({
}
return (
- <div className="flex min-w-0 flex-col gap-2">
+ <div className={cn("flex min-w-0 flex-col", creation?.contextBar ? "gap-0" : "gap-2")}>
{takeoverVisible && takeover ? (
<section
className={cn(
@@ -1180,6 +1250,16 @@ export function TaskChatComposer({
) : null}
</section>
) : null}
+ {creation?.contextBar ? (
+ <TaskChatComposerBar
+ className="flex h-11 min-w-0 items-center gap-2 px-2.5"
+ data-testid="task-chat-composer-context"
+ role="group"
+ aria-label="Task project and worktrees"
+ >
+ {creation.contextBar}
+ </TaskChatComposerBar>
+ ) : null}
<div
className={cn(
streamlined
@@ -1200,11 +1280,12 @@ export function TaskChatComposer({
if (isModeShortcut) {
e.preventDefault();
e.stopPropagation();
- setPendingMode((mode) => nextWorkMode(mode));
+ changeMode(nextWorkMode(pendingMode));
}
}}
onPasteCapture={handlePasteCapture}
>
+ {creation?.header}
{uncertainSubmission ? (
<div
role="alert"
@@ -1275,18 +1356,18 @@ export function TaskChatComposer({
? (disabledReason ?? "Composer disabled")
: effectivePlaceholder
}
- readOnly={disabled || !!uncertainSubmission}
+ readOnly={disabled || !!uncertainSubmission || Boolean(creation && submitting)}
mentions={mentions}
- actionCommands={conversationMode ? [{
+ actionCommands={creation ? [] : conversationMode ? [{
id: "action:new", kind: "action", command: "new", name: "New session",
description: "Start fresh context here, preserving conversation history.", aliases: ["new"],
disabled,
}] : [goalCommandOption]}
onSubmit={() => void submit()}
imageUploadHandler={
- canAcceptFiles ? uploadInlineImage : undefined
+ canAcceptFiles && (!creation || onImageUpload) ? uploadInlineImage : undefined
}
- onDropFile={canAcceptFiles ? attachNonImageFile : undefined}
+ onDropFile={canAcceptFiles && !creation ? attachNonImageFile : undefined}
bordered={false}
className={cn(disabled && "opacity-60")}
contentClassName={
@@ -1301,7 +1382,7 @@ export function TaskChatComposer({
<p
className="px-1 text-xs text-destructive"
role="alert"
- data-testid="task-chat-goal-error"
+ data-testid={creation ? "task-chat-create-error" : "task-chat-goal-error"}
>
{actionError}
</p>
@@ -1368,17 +1449,19 @@ export function TaskChatComposer({
</AttachmentGroup>
) : null}
+ {creation?.details}
+
<div
className={cn("mt-2 flex items-center gap-x-2 gap-y-3", mobile && !queuedEdit ? "flex-nowrap" : "flex-wrap")}
data-testid="task-chat-composer-actions"
>
<div className="flex min-w-0 max-w-full items-center gap-2">
{canAcceptFiles ? (
- <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileInputChange} />
+ <input ref={fileInputRef} type="file" className="hidden" multiple={Boolean(creation)} onChange={handleFileInputChange} />
) : null}
<ComposerAddMenu
mode={pendingMode}
- onModeChange={!queuedEdit && onWorkModeChange ? setPendingMode : undefined}
+ onModeChange={!queuedEdit && onWorkModeChange ? changeMode : undefined}
onAttachFile={canAcceptFiles ? () => fileInputRef.current?.click() : undefined}
onGoal={!queuedEdit && !conversationMode && attachments.length === 0 &&
runnerGoalCapability?.availability === "available" && onRunnerGoalCommand
@@ -1395,7 +1478,7 @@ export function TaskChatComposer({
: "Editing queued message"}
</span>
) : (
- <ComposerModeChip mode={pendingMode} onRemove={onWorkModeChange ? () => setPendingMode("standard") : undefined}
+ <ComposerModeChip mode={pendingMode} onRemove={onWorkModeChange ? () => changeMode("standard") : undefined}
disabled={disabled || !!uncertainSubmission} testId="task-chat-composer-mode" mobile={mobile} />
)}
</div>
@@ -1495,7 +1578,8 @@ export function TaskChatComposer({
!!uncertainSubmission ||
uploadPending ||
uploadFailed ||
- (body.trim().length === 0 && attachedRefs.length === 0)
+ Boolean(creation?.submitDisabled) ||
+ (body.trim().length === 0 && attachedRefs.length === 0 && !creation?.canSubmitWithoutBody)
}
title={
showStop
@@ -1510,7 +1594,7 @@ export function TaskChatComposer({
? "Waiting for upload to finish"
: uploadFailed
? "Remove the failed attachment to send"
- : "Send (⌘+Enter)"
+ : creation ? `${creation.submitLabel} (⌘+Enter)` : "Send (⌘+Enter)"
}
aria-label={
showStop
@@ -1521,8 +1605,9 @@ export function TaskChatComposer({
? queuedEdit.stale
? "Queue as new message"
: "Save queued message"
- : "Send"
+ : creation?.submitLabel ?? "Send"
}
+ aria-busy={submitting}
className={cn(
"flex size-8 min-h-8 min-w-8 shrink-0 aspect-square items-center justify-center rounded-full transition-transform hover:scale-105 disabled:scale-100",
streamlined
diff --git a/ui/src/components/task-chat/TaskChatComposerBar.tsx b/ui/src/components/task-chat/TaskChatComposerBar.tsx
new file mode 100644
index 0000000000..84aeb00b53
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatComposerBar.tsx
@@ -0,0 +1,15 @@
+import type { ComponentProps } from "react";
+import { cn } from "@/lib/utils";
+
+/** The inset strip shared by queued messages and new-task context. */
+export function TaskChatComposerBar({ className, ...props }: ComponentProps<"div">) {
+ return (
+ <div
+ className={cn(
+ "relative z-0 mx-3 -mb-px overflow-hidden rounded-t-xl rounded-b-none border border-b-0 border-border/75 bg-card shadow-sm",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx
index a365a56067..baf0bbf799 100644
--- a/ui/src/components/task-chat/TaskChatQueuedMessages.tsx
+++ b/ui/src/components/task-chat/TaskChatQueuedMessages.tsx
@@ -29,6 +29,7 @@ import type {
IssueQueuedCommentQueue,
} from "@paperclipai/shared";
import { cn } from "@/lib/utils";
+import { TaskChatComposerBar } from "./TaskChatComposerBar";
import {
DropdownMenu,
DropdownMenuContent,
@@ -377,8 +378,7 @@ export function TaskChatQueuedMessages({
if (entries.length === 0 && !visibleError) return null;
return (
- <div
- className="relative z-0 mx-3 -mb-px overflow-hidden rounded-t-xl rounded-b-none border border-b-0 border-border/75 bg-card shadow-sm"
+ <TaskChatComposerBar
data-testid="task-chat-queued-messages"
aria-label="Queued messages"
>
@@ -433,6 +433,6 @@ export function TaskChatQueuedMessages({
<div className="sr-only" aria-live="polite" aria-atomic="true">
{announcement}
</div>
- </div>
+ </TaskChatComposerBar>
);
}
diff --git a/ui/src/components/task-chat/composer-run-settings.test.ts b/ui/src/components/task-chat/composer-run-settings.test.ts
index 7ad7563e5f..9df5c74917 100644
--- a/ui/src/components/task-chat/composer-run-settings.test.ts
+++ b/ui/src/components/task-chat/composer-run-settings.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { Agent } from "@paperclipai/shared";
import {
- composerCatalogProvider, composerEfforts, composerFastAvailable, mergeComposerRunSettings,
+ composerCatalogProvider, composerDefaultModel, composerEfforts, composerFastAvailable, mergeComposerRunSettings,
readComposerRunSettings, supportsComposerModel,
} from "./composer-run-settings";
@@ -10,6 +10,19 @@ const agent = (adapterType: Agent["adapterType"], provider?: string) => ({
}) as Agent;
describe("composer run settings", () => {
+ it("resolves known adapter defaults without guessing local CLI settings", () => {
+ expect(composerDefaultModel(agent("claude_local"))).toBe("");
+ expect(composerDefaultModel({ ...agent("claude_local"), adapterConfig: { model: "claude-opus-5" } })).toBe("claude-opus-5");
+ expect(composerDefaultModel({ ...agent("claude_local"), adapterConfig: { env: { ANTHROPIC_MODEL: "claude-sonnet-5" } } })).toBe("claude-sonnet-5");
+ expect(composerDefaultModel({ ...agent("claude_local"), adapterConfig: { env: { CLAUDE_CODE_USE_BEDROCK: "1" } } })).toBe("");
+ expect(composerDefaultModel({ ...agent("claude_local"), adapterConfig: { env: { CLAUDE_CODE_USE_VERTEX: "1" } } })).toBe("");
+ expect(composerDefaultModel({ ...agent("claude_local"), adapterConfig: { env: { ANTHROPIC_MODEL: { type: "secret_ref", secretId: "model-secret" } } } })).toBe("");
+ expect(composerDefaultModel({ ...agent("codex_local"), adapterConfig: { model: " private-codex " } })).toBe("private-codex");
+ expect(composerDefaultModel(agent("codex_local"))).toBe("");
+ expect(composerDefaultModel(agent("paperclip_runner", "codex"))).toBe("gpt-5.6-sol");
+ expect(composerDefaultModel(agent("grok_local"))).toBe("grok-build");
+ expect(composerDefaultModel(undefined)).toBe("");
+ });
it("shows only effort levels known for the selected harness and model", () => {
expect(composerEfforts(agent("codex_local"), "gpt-6-astra", [])).toContain("ultra");
expect(composerEfforts(agent("paperclip_runner", "codex"), "gpt-6-astra", [])).toContain("ultra");
diff --git a/ui/src/components/task-chat/composer-run-settings.ts b/ui/src/components/task-chat/composer-run-settings.ts
index 8b5ad5cc91..5df778ba79 100644
--- a/ui/src/components/task-chat/composer-run-settings.ts
+++ b/ui/src/components/task-chat/composer-run-settings.ts
@@ -1,5 +1,6 @@
import { codexLocalReasoningEffortsForModel, isCodexLocalFastModeSupported, isCodexLocalKnownModel } from "@paperclipai/adapter-codex-local";
import { claudeLocalReasoningEffortsForModel } from "@paperclipai/adapter-claude-local";
+import { resolvePaperclipRunnerModel } from "@paperclipai/adapter-utils";
import { DEFAULT_GROK_LOCAL_MODEL, grokLocalReasoningEffortsForModel } from "@paperclipai/adapter-grok-local";
import { DEFAULT_KIMI_LOCAL_MODEL, modelSupportsEffort, KIMI_SUPPORTED_EFFORTS } from "@paperclipai/adapter-kimi-local";
import { aiConnectionBindingSchema, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
@@ -25,6 +26,29 @@ export function supportsComposerModel(agent: Agent | undefined): boolean {
return Boolean(agent && MODEL_ADAPTERS.has(agent.adapterType));
}
+/** Resolve visible defaults; host environment and a local CLI's own config are unknown. */
+export function composerDefaultModel(agent: Agent | undefined): string {
+ if (!agent) return "";
+ const config = agent.adapterConfig;
+ const configured = typeof config.model === "string" ? config.model.trim() : "";
+ if (configured) return configured;
+ if (agent.adapterType === "claude_local") {
+ const env = config.env && typeof config.env === "object" && !Array.isArray(config.env)
+ ? config.env as Record<string, unknown> : {};
+ // The server merges host env too, which may select a different model or
+ // Bedrock/Vertex. Without an explicit agent setting, the default is unknown.
+ return typeof env.ANTHROPIC_MODEL === "string" ? env.ANTHROPIC_MODEL.trim() : "";
+ }
+ if (agent.adapterType === "grok_local") return DEFAULT_GROK_LOCAL_MODEL;
+ if (agent.adapterType === "kimi_local") return DEFAULT_KIMI_LOCAL_MODEL;
+ if (agent.adapterType === "paperclip_runner") {
+ const provider = composerCatalogProvider(agent);
+ if (provider === "codex" || provider === "opencode") return resolvePaperclipRunnerModel(provider, config.model);
+ if (provider === "acpx" && config.acpxAgent !== "grok") return resolvePaperclipRunnerModel(provider, config.model);
+ }
+ return "";
+}
+
export function composerCatalogProvider(agent: Agent | undefined): string | undefined {
if (!agent) return undefined;
if (agent.adapterType === "paperclip_runner") return String(agent.adapterConfig.provider ?? "codex");
diff --git a/ui/src/index.css b/ui/src/index.css
index fda1064a1d..60b7d89d19 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -1808,7 +1808,7 @@ select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="
align-items: center;
gap: 0.25rem;
margin: 0 0.1rem;
- padding: 0 0.625rem;
+ padding: 2px 0.625rem;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.75rem;
@@ -1847,17 +1847,12 @@ a.paperclip-mention-chip[data-mention-kind="project"]::before {
.paperclip-mdxeditor-content a.paperclip-mention-chip[data-mention-kind="agent"]::before,
a.paperclip-mention-chip[data-mention-kind="agent"]::before {
- width: 0.75rem;
- height: 0.75rem;
- background-color: currentColor;
- -webkit-mask-image: var(--paperclip-mention-icon-mask);
- mask-image: var(--paperclip-mention-icon-mask);
- -webkit-mask-position: center;
- mask-position: center;
- -webkit-mask-repeat: no-repeat;
- mask-repeat: no-repeat;
- -webkit-mask-size: contain;
- mask-size: contain;
+ width: 1rem;
+ height: 1rem;
+ background-image: var(--paperclip-mention-avatar-image);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: contain;
}
.paperclip-mdxeditor-content ul,
@@ -2404,7 +2399,7 @@ span.paperclip-project-mention-chip {
align-items: center;
gap: 0.25rem;
margin: 0 0.1rem;
- padding: 0 0.625rem;
+ padding: 2px 0.625rem;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.75rem;
@@ -3163,7 +3158,9 @@ span.paperclip-mention-chip[data-mention-kind="external-object"] {
position: absolute;
inset: 0;
background: var(--mobile-entity-picker-backdrop);
- pointer-events: none;
+ /* Hit the popper wrapper so Radix dismisses this sheet, while the parent
+ task dialog recognizes the tap as belonging to its nested picker. */
+ pointer-events: auto;
}
[data-mobile-entity-picker] {
diff --git a/ui/src/lib/mention-aware-link-node.test.ts b/ui/src/lib/mention-aware-link-node.test.ts
index 314b59eb29..40e25548cd 100644
--- a/ui/src/lib/mention-aware-link-node.test.ts
+++ b/ui/src/lib/mention-aware-link-node.test.ts
@@ -47,4 +47,29 @@ describe("getMentionAwareLinkNodeInit", () => {
expect(created).toBeInstanceOf(MentionAwareLinkNode);
});
+
+ it.each([
+ "agent://agent-123?i=code",
+ "project://project-123?c=0f766e",
+ "user://user-123",
+ "skill://skill-123?s=test-it-for-real",
+ "routine://routine-123",
+ "/issues/PAP-123",
+ ])("preserves the rich-chip destination %s", (href) => {
+ const editor = createTestEditor();
+ let renderedUrl: string | undefined;
+ editor.update(() => {
+ renderedUrl = $createLinkNode(href).sanitizeUrl(href);
+ });
+ expect(renderedUrl).toBe(href);
+ });
+
+ it("still blocks executable link destinations", () => {
+ const editor = createTestEditor();
+ let renderedUrl: string | undefined;
+ editor.update(() => {
+ renderedUrl = $createLinkNode("javascript:alert(1)").sanitizeUrl("javascript:alert(1)");
+ });
+ expect(renderedUrl).toBe("about:blank");
+ });
});
diff --git a/ui/src/lib/mention-aware-link-node.ts b/ui/src/lib/mention-aware-link-node.ts
index 8706f0bdbb..d1eb832a30 100644
--- a/ui/src/lib/mention-aware-link-node.ts
+++ b/ui/src/lib/mention-aware-link-node.ts
@@ -4,7 +4,7 @@ import {
type SerializedLinkNode,
} from "@lexical/link";
-const CUSTOM_MENTION_URL_RE = /^(agent|project|skill):\/\//;
+const CUSTOM_MENTION_URL_RE = /^(agent|project|user|skill|routine):\/\//;
export class MentionAwareLinkNode extends LinkNode {
static getType(): string {
diff --git a/ui/src/lib/mention-chips.test.ts b/ui/src/lib/mention-chips.test.ts
index 7d138f5b27..cdb565779e 100644
--- a/ui/src/lib/mention-chips.test.ts
+++ b/ui/src/lib/mention-chips.test.ts
@@ -1,20 +1,31 @@
-import { describe, expect, it, vi } from "vitest";
-import { mentionChipInlineStyle } from "./mention-chips";
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { appearanceForPalette, agentAvatarUrl, legacyAgentAppearance } from "@paperclipai/shared";
+import { applyMentionChipDecoration, clearMentionChipDecoration, mentionChipInlineStyle, parseMentionChipHref } from "./mention-chips";
-const getAgentIcon = vi.hoisted(() => vi.fn());
-vi.mock("./agent-icons", () => ({ getAgentIcon }));
+describe("agent mention avatars", () => {
+ it("uses the agent's selected appearance instead of the saved legacy icon", () => {
+ const appearance = appearanceForPalette("electric-grove");
+ const style = mentionChipInlineStyle({ kind: "agent", agentId: "agent", icon: "code", appearance });
+ expect(style).toEqual({ "--paperclip-mention-avatar-image": `url("${agentAvatarUrl(appearance, 16, 2)}")` });
+ });
-describe("agent mention icon compatibility", () => {
- const node = [["path", { d: "m16 18 6-6-6-6", key: "code" }]];
+ it("keeps old icon-bearing mentions readable with the agent's stable default avatar", () => {
+ const parsed = parseMentionChipHref("agent://agent-old?icon=crown");
+ expect(parsed?.kind).toBe("agent");
+ expect(mentionChipInlineStyle(parsed!)).toEqual({
+ "--paperclip-mention-avatar-image": `url("${agentAvatarUrl(legacyAgentAppearance("agent-old"), 16, 2)}")`,
+ });
+ });
- it.each([
- ["static", { iconNode: node }],
- ["legacy", { render: () => ({ props: { iconNode: node } }) }],
- ["icon-data", { render: () => ({ props: { icon: { name: "code", size: 24, node } } }) }],
- ])("renders an agent mention mask from Lucide's %s format", (name, icon) => {
- getAgentIcon.mockReturnValue(icon);
- const style = mentionChipInlineStyle({ kind: "agent", agentId: "agent", icon: name });
- const mask = (style as Record<string, string>)["--paperclip-mention-icon-mask"];
- expect(decodeURIComponent(mask)).toContain('<path d="m16 18 6-6-6-6"></path>');
+ it("clears the avatar and any old icon decoration when an anchor stops being a mention", () => {
+ const anchor = document.createElement("a");
+ anchor.style.setProperty("--paperclip-mention-icon-mask", "old-icon");
+ applyMentionChipDecoration(anchor, { kind: "agent", agentId: "agent", icon: "code" });
+ expect(anchor.style.getPropertyValue("--paperclip-mention-icon-mask")).toBe("");
+ expect(anchor.style.getPropertyValue("--paperclip-mention-avatar-image")).toContain("/api/agent-avatars/");
+ clearMentionChipDecoration(anchor);
+ expect(anchor.hasAttribute("data-mention-kind")).toBe(false);
+ expect(anchor.style.getPropertyValue("--paperclip-mention-avatar-image")).toBe("");
});
});
diff --git a/ui/src/lib/mention-chips.ts b/ui/src/lib/mention-chips.ts
index 48b8303889..02f292857a 100644
--- a/ui/src/lib/mention-chips.ts
+++ b/ui/src/lib/mention-chips.ts
@@ -6,8 +6,10 @@ import {
parseRoutineMentionHref,
parseSkillMentionHref,
parseUserMentionHref,
+ resolveAgentAppearance,
+ type AgentAppearance,
} from "@paperclipai/shared";
-import { getAgentIcon } from "./agent-icons";
+import { agentAvatarUrl } from "@/lib/agent-avatar-url";
import { hexToRgb, pickTextColorForPillBg } from "./color-contrast";
export type ParsedMentionChip =
@@ -15,6 +17,7 @@ export type ParsedMentionChip =
kind: "agent";
agentId: string;
icon: string | null;
+ appearance?: AgentAppearance | null;
}
| {
kind: "issue";
@@ -39,8 +42,6 @@ export type ParsedMentionChip =
routineId: string;
};
-const iconMaskCache = new Map<string, string>();
-
export function parseMentionChipHref(href: string): ParsedMentionChip | null {
if (/^https?:\/\//i.test(href.trim())) {
return null;
@@ -110,10 +111,8 @@ export function mentionChipInlineStyle(mention: ParsedMentionChip): CSSPropertie
}
if (mention.kind === "agent") {
- const iconMask = buildAgentIconMask(mention.icon);
- if (iconMask) {
- style["--paperclip-mention-icon-mask"] = iconMask;
- }
+ const appearance = resolveAgentAppearance(mention.appearance, mention.agentId);
+ style["--paperclip-mention-avatar-image"] = `url("${agentAvatarUrl(appearance, 16, 2)}")`;
}
return Object.keys(style).length > 0 ? (style as CSSProperties) : undefined;
@@ -159,6 +158,7 @@ export function clearMentionChipDecoration(element: HTMLElement) {
element.style.removeProperty("color");
element.style.removeProperty("--paperclip-mention-project-color");
element.style.removeProperty("--paperclip-mention-icon-mask");
+ element.style.removeProperty("--paperclip-mention-avatar-image");
}
function projectMentionColors(color: string): Pick<CSSProperties, "borderColor" | "backgroundColor" | "color"> {
@@ -170,70 +170,3 @@ function projectMentionColors(color: string): Pick<CSSProperties, "borderColor"
color: pickTextColorForPillBg(color),
};
}
-
-function buildAgentIconMask(iconName: string | null): string | null {
- const cacheKey = iconName ?? "__default__";
- const cached = iconMaskCache.get(cacheKey);
- if (cached) return cached;
-
- const Icon = getAgentIcon(iconName);
- // Lucide's component internals differ between browser and server builds.
- // Keep the agent marker visible when its private iconNode is unavailable.
- const iconNode = resolveLucideIconNode(Icon) ?? [
- ["rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }],
- ["path", { d: "M8 10h.01M16 10h.01M8 15h8" }],
- ];
-
- const body = iconNode.map(([tag, attrs]) => {
- const attrString = Object.entries(attrs)
- .filter(([key]) => key !== "key")
- .map(([key, value]) => `${key}="${escapeAttribute(String(value))}"`)
- .join(" ");
- return `<${tag}${attrString ? ` ${attrString}` : ""}></${tag}>`;
- }).join("");
-
- const svg =
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" ` +
- `fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" ` +
- `stroke-linejoin="round">${body}</svg>`;
- const url = `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;
- iconMaskCache.set(cacheKey, url);
- return url;
-}
-
-function resolveLucideIconNode(
- icon: unknown,
-): Array<[string, Record<string, string>]> | null {
- const staticIconNode = (
- icon as {
- iconNode?: Array<[string, Record<string, string>]>;
- }
- ).iconNode;
- if (Array.isArray(staticIconNode) && staticIconNode.length > 0) {
- return staticIconNode;
- }
-
- const render = (
- icon as {
- render?: (props: Record<string, unknown>, ref: unknown) => {
- props?: {
- iconNode?: Array<[string, Record<string, string>]>;
- icon?: { node?: Array<[string, Record<string, string>]> };
- };
- } | null;
- }
- ).render;
- const rendered = typeof render === "function" ? render({}, null) : null;
- const renderedIconNode = rendered?.props?.icon?.node ?? rendered?.props?.iconNode;
- return Array.isArray(renderedIconNode) && renderedIconNode.length > 0
- ? renderedIconNode
- : null;
-}
-
-function escapeAttribute(value: string): string {
- return value
- .replaceAll("&", "&amp;")
- .replaceAll('"', "&quot;")
- .replaceAll("<", "&lt;")
- .replaceAll(">", "&gt;");
-}
diff --git a/ui/src/lib/recent-assignees.ts b/ui/src/lib/recent-assignees.ts
index 9b4937a30d..d8a57a07c6 100644
--- a/ui/src/lib/recent-assignees.ts
+++ b/ui/src/lib/recent-assignees.ts
@@ -26,19 +26,21 @@ export function getRecentAssigneeIds(): string[] {
.filter((id): id is string => Boolean(id));
}
-export function getRecentAssigneeSelectionIds(): string[] {
- return readRecentSelectionIds(STORAGE_KEY).map((id) => {
+export function getRecentAssigneeSelectionIds(companyId?: string): string[] {
+ return readRecentSelectionIds(companyId ? `${STORAGE_KEY}:${companyId}` : STORAGE_KEY).map((id) => {
if (id.includes(":")) return id;
return agentSelectionId(id);
});
}
-export function trackRecentAssignee(agentId: string): void {
+export function trackRecentAssignee(agentId: string, companyId?: string): void {
trackRecentSelectionId(STORAGE_KEY, agentSelectionId(agentId));
+ if (companyId) trackRecentSelectionId(`${STORAGE_KEY}:${companyId}`, agentSelectionId(agentId));
}
-export function trackRecentAssigneeUser(userId: string): void {
+export function trackRecentAssigneeUser(userId: string, companyId?: string): void {
trackRecentSelectionId(STORAGE_KEY, userSelectionId(userId));
+ if (companyId) trackRecentSelectionId(`${STORAGE_KEY}:${companyId}`, userSelectionId(userId));
}
export function sortAgentsByRecency<T extends { id: string; name: string }>(
diff --git a/ui/src/lib/recent-composer-effort.ts b/ui/src/lib/recent-composer-effort.ts
new file mode 100644
index 0000000000..ce45aeb58d
--- /dev/null
+++ b/ui/src/lib/recent-composer-effort.ts
@@ -0,0 +1,21 @@
+const STORAGE_KEY = "paperclip:composer-effort";
+
+/** Undefined means no preference; null is the user's explicit Default choice. */
+export function getLastComposerEffort(companyId: string): string | null | undefined {
+ try {
+ const raw = localStorage.getItem(`${STORAGE_KEY}:${companyId}`);
+ if (raw === null) return undefined;
+ const value: unknown = JSON.parse(raw);
+ return value === null || typeof value === "string" ? value : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function rememberComposerEffort(companyId: string, effort: string | null): void {
+ try {
+ localStorage.setItem(`${STORAGE_KEY}:${companyId}`, JSON.stringify(effort));
+ } catch {
+ // The current run setting still works without persistent storage.
+ }
+}
diff --git a/ui/src/lib/recent-projects.ts b/ui/src/lib/recent-projects.ts
index d9da262176..ab712a2d51 100644
--- a/ui/src/lib/recent-projects.ts
+++ b/ui/src/lib/recent-projects.ts
@@ -9,6 +9,22 @@ export function getRecentProjectIds(): string[] {
return readRecentSelectionIds(STORAGE_KEY);
}
-export function trackRecentProject(projectId: string): void {
+/** Undefined means no history; an empty string remembers an explicit No project. */
+export function getLastProjectId(companyId: string): string | undefined {
+ try {
+ return localStorage.getItem(`${STORAGE_KEY}:${companyId}`) ?? undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function trackRecentProject(projectId: string, companyId?: string): void {
trackRecentSelectionId(STORAGE_KEY, projectId);
+ if (companyId) {
+ try {
+ localStorage.setItem(`${STORAGE_KEY}:${companyId}`, projectId);
+ } catch {
+ // Selection remains usable when browser storage is unavailable.
+ }
+ }
}
diff --git a/ui/src/lib/recent-selections.test.ts b/ui/src/lib/recent-selections.test.ts
index 6f50e9980a..197698cbc4 100644
--- a/ui/src/lib/recent-selections.test.ts
+++ b/ui/src/lib/recent-selections.test.ts
@@ -8,7 +8,8 @@ import {
trackRecentAssignee,
trackRecentAssigneeUser,
} from "./recent-assignees";
-import { getRecentProjectIds, trackRecentProject } from "./recent-projects";
+import { getLastProjectId, getRecentProjectIds, trackRecentProject } from "./recent-projects";
+import { getLastComposerEffort, rememberComposerEffort } from "./recent-composer-effort";
import { orderItemsBySelectedAndRecent } from "./recent-selections";
describe("recent selection ordering", () => {
@@ -69,6 +70,30 @@ describe("recent selection ordering", () => {
expect(getRecentProjectIds()).toEqual(["project-1", "project-2"]);
});
+ it("remembers projects and explicit No project separately for each company", () => {
+ expect(getLastProjectId("company-1")).toBeUndefined();
+ trackRecentProject("project-1", "company-1");
+ trackRecentProject("project-2", "company-2");
+ expect(getLastProjectId("company-1")).toBe("project-1");
+ expect(getLastProjectId("company-2")).toBe("project-2");
+ trackRecentProject("", "company-1");
+ expect(getLastProjectId("company-1")).toBe("");
+ expect(getLastProjectId("company-2")).toBe("project-2");
+ expect(getRecentProjectIds()).toEqual(["project-2", "project-1"]);
+ });
+
+ it("remembers effort and an explicit Default choice within the company", () => {
+ expect(getLastComposerEffort("company-1")).toBeUndefined();
+ rememberComposerEffort("company-1", "high");
+ rememberComposerEffort("company-2", "ultra");
+ expect(getLastComposerEffort("company-1")).toBe("high");
+ rememberComposerEffort("company-1", null);
+ expect(getLastComposerEffort("company-1")).toBeNull();
+ expect(getLastComposerEffort("company-2")).toBe("ultra");
+ localStorage.setItem("paperclip:composer-effort:company-1", "broken json");
+ expect(getLastComposerEffort("company-1")).toBeUndefined();
+ });
+
it("tracks recent user and agent assignee selections with prefixed ids", () => {
trackRecentAssignee("agent-1");
trackRecentAssigneeUser("user-1");
@@ -76,4 +101,14 @@ describe("recent selection ordering", () => {
expect(getRecentAssigneeSelectionIds()).toEqual(["user:user-1", "agent:agent-1"]);
expect(getRecentAssigneeIds()).toEqual(["agent-1"]);
});
+
+ it("remembers assignees separately in each company", () => {
+ trackRecentAssignee("agent-1", "company-1");
+ trackRecentAssigneeUser("user-1", "company-2");
+ trackRecentAssigneeUser("user-2", "company-1");
+
+ expect(getRecentAssigneeSelectionIds("company-1")).toEqual(["user:user-2", "agent:agent-1"]);
+ expect(getRecentAssigneeSelectionIds("company-2")).toEqual(["user:user-1"]);
+ expect(getRecentAssigneeSelectionIds("company-3")).toEqual([]);
+ });
});
diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx
index 4945013540..1055e4be7c 100644
--- a/ui/src/pages/IssueDetail.test.tsx
+++ b/ui/src/pages/IssueDetail.test.tsx
@@ -42,6 +42,7 @@ import {
createIssueDetailLocationState,
} from "../lib/issueDetailBreadcrumb";
import { getRecentTasksStorageKey, readRecentTasks } from "../lib/recent-tasks";
+import { getLastProjectId, trackRecentProject } from "../lib/recent-projects";
import { ApiError } from "../api/client";
import type { issuesApi } from "../api/issues";
@@ -1431,6 +1432,34 @@ describe("IssueDetail", () => {
vi.restoreAllMocks();
});
+ it.each(["new-project", null])("remembers project %s only after its task update succeeds", async (projectId) => {
+ const issue = createIssue({ projectId: "original-project" });
+ trackRecentProject("original-project", issue.companyId);
+ const failedUpdate = createDeferred<Issue>();
+ const successfulUpdate = createDeferred<Issue>();
+ mockIssuesApi.get.mockResolvedValue(issue);
+ mockIssuesApi.update.mockClear();
+ mockIssuesApi.update.mockReturnValueOnce(failedUpdate.promise).mockReturnValueOnce(successfulUpdate.promise);
+ await act(async () => root.render(<QueryClientProvider client={queryClient}><IssueDetail /></QueryClientProvider>));
+ let properties!: { onUpdate: (data: Record<string, unknown>) => void };
+ await waitForAssertion(() => {
+ properties = mockOpenPanel.mock.calls.at(-1)?.[0]?.props.children?.props;
+ expect(properties?.onUpdate).toBeTypeOf("function");
+ });
+ await act(async () => properties.onUpdate({ projectId }));
+ await waitForAssertion(() => expect(mockIssuesApi.update).toHaveBeenCalledTimes(1));
+ expect(getLastProjectId(issue.companyId)).toBe("original-project");
+ await act(async () => failedUpdate.reject(new Error("Project save failed")));
+ await waitForAssertion(() => expect(mockPushToast).toHaveBeenCalledWith(expect.objectContaining({ title: "Task update failed" })));
+ expect(getLastProjectId(issue.companyId)).toBe("original-project");
+ await act(async () => properties.onUpdate({ projectId }));
+ await waitForAssertion(() => expect(mockIssuesApi.update).toHaveBeenCalledTimes(2));
+ expect(getLastProjectId(issue.companyId)).toBe("original-project");
+ await act(async () => successfulUpdate.resolve({ ...issue, projectId }));
+ await waitForAssertion(() => expect(getLastProjectId(issue.companyId)).toBe(projectId ?? ""));
+ expect(getLastProjectId("company-2")).toBeUndefined();
+ });
+
it("keeps an existing conversation on its agent-addressed route", async () => {
const agent = createAgent();
const canonical = createIssue({ conversationAgentId: agent.id, conversationUserId: "user-1", conversationState: "waiting", status: "in_review" });
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index 3d4b3685a0..07b3c07216 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -7,6 +7,7 @@ import { mergeComposerRunSettings, type ComposerRunSettings } from "@/components
import { AgentIdentity } from "@/components/AgentIdentity";
import { clearLegacyChatMessageRequests } from "@/lib/chat-message-request";
import { agentChatDraft } from "@/lib/agent-chat-draft";
+import { trackRecentProject } from "@/lib/recent-projects";
import { Settings as ChatSettings } from "lucide-react";
import { agentDetailHref } from "./agent-detail-navigation";
import { ExecutionBlockerNotice } from "../components/ExecutionBlockerNotice";
@@ -4161,7 +4162,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
changes: _changes,
blockedByIssueIds: _blockedByIssueIds,
...nextIssue
- }) => {
+ }, data) => {
+ if (Object.prototype.hasOwnProperty.call(data, "projectId")) {
+ trackRecentProject(nextIssue.projectId ?? "", nextIssue.companyId);
+ }
const issueRefs = new Set<string>([issueId!, nextIssue.id]);
if (nextIssue.identifier) issueRefs.add(nextIssue.identifier);
mergeIssueResponseIntoCaches(issueRefs, nextIssue);
diff --git a/ui/storybook/fixtures/agent-avatar-url.ts b/ui/storybook/fixtures/agent-avatar-url.ts
index efbe5c3ce5..f2276955e7 100644
--- a/ui/storybook/fixtures/agent-avatar-url.ts
+++ b/ui/storybook/fixtures/agent-avatar-url.ts
@@ -1,8 +1,11 @@
import { agentAvatarUrl as apiAvatarUrl } from "@paperclipai/shared";
-/** Relative to iframe.html, including when a preview is hosted under a branch prefix. */
+/** Resolve against iframe.html so CSS backgrounds also work under hosted branch prefixes. */
export const agentAvatarUrl: typeof apiAvatarUrl = (...args) => {
const url = new URL(apiAvatarUrl(...args), "https://storybook.invalid");
const preset = url.pathname.slice("/api/agent-avatars/".length).replace(/\.png$/, "");
- return `./agent-avatar-images/${preset}-${url.searchParams.get("size")}-${url.searchParams.get("scale")}.png`;
+ const path = `./agent-avatar-images/${preset}-${url.searchParams.get("size")}-${url.searchParams.get("scale")}.png`;
+ // The build-time asset packer needs relative file names. Browser consumers
+ // need absolute URLs because CSS custom properties use the stylesheet base.
+ return typeof document === "undefined" ? path : new URL(path, document.baseURI).href;
};
diff --git a/ui/storybook/prototypes/composer-model-picker/ComposerModelPickerPreview.tsx b/ui/storybook/prototypes/composer-model-picker/ComposerModelPickerPreview.tsx
index aac6e2955e..e2137c1013 100644
--- a/ui/storybook/prototypes/composer-model-picker/ComposerModelPickerPreview.tsx
+++ b/ui/storybook/prototypes/composer-model-picker/ComposerModelPickerPreview.tsx
@@ -156,7 +156,7 @@ export function ComposerModelPickerPreview({
<AgentMark agent={agent} size={16} />
<span className="max-w-20 shrink-0 truncate">{agent.name}</span>
<span className="text-muted-foreground" aria-hidden>·</span>
- <span className="min-w-0 truncate text-muted-foreground">{modelAvailable ? modelLabel(agent, model) : "Harness default"}</span>
+ <span className="min-w-0 truncate text-muted-foreground">{modelAvailable ? modelLabel(agent, model) : "Default"}</span>
{effectiveEffort ? <span className="hidden shrink-0 text-muted-foreground sm:inline">{effortLabel}</span> : null}
<ChevronDown className="size-3 shrink-0 text-muted-foreground" aria-hidden />
</button>
diff --git a/ui/storybook/prototypes/composer-model-picker/fixtures.ts b/ui/storybook/prototypes/composer-model-picker/fixtures.ts
index 2ea83b9771..711d81b7ef 100644
--- a/ui/storybook/prototypes/composer-model-picker/fixtures.ts
+++ b/ui/storybook/prototypes/composer-model-picker/fixtures.ts
@@ -122,6 +122,6 @@ export function fastModeAvailable(agent: ComposerAgent, model: string): boolean
}
export function modelLabel(agent: ComposerAgent, model: string): string {
- if (!model) return agent.defaultLabel ?? "Harness default";
+ if (!model) return agent.defaultLabel ?? "Default";
return agent.models.find((option) => option.id === model)?.label ?? model;
}
diff --git a/ui/storybook/stories/composer-model-picker.stories.tsx b/ui/storybook/stories/composer-model-picker.stories.tsx
index 391eddb75c..b99938b62f 100644
--- a/ui/storybook/stories/composer-model-picker.stories.tsx
+++ b/ui/storybook/stories/composer-model-picker.stories.tsx
@@ -406,7 +406,7 @@ export const ProductionIntermediateWidthPlan: Story = {
play: async ({ canvasElement }) => {
const screen = within(canvasElement.ownerDocument.body);
const chip = screen.getByRole("button", { name: "Remove Plan mode" }).getBoundingClientRect();
- const capsule = screen.getByTestId("task-chat-composer-assignee").getBoundingClientRect();
+ const capsule = screen.getByTestId("task-chat-composer-selection").getBoundingClientRect();
const send = screen.getByRole("button", { name: "Send message" }).getBoundingClientRect();
await expect(chip.height).toBe(capsule.height);
await expect(Math.abs(send.top - capsule.top)).toBeLessThanOrEqual(1);
diff --git a/ui/storybook/stories/dialogs-modals.stories.tsx b/ui/storybook/stories/dialogs-modals.stories.tsx
index 4e04fad60c..60d7ba8063 100644
--- a/ui/storybook/stories/dialogs-modals.stories.tsx
+++ b/ui/storybook/stories/dialogs-modals.stories.tsx
@@ -522,7 +522,7 @@ function IssueDialogOpener({
useEffect(() => {
if (variant !== "validation") return undefined;
const timer = window.setTimeout(() => {
- clickButtonByText("Create Issue");
+ document.querySelector<HTMLButtonElement>('[aria-label="Create task"]')?.click();
}, 500);
return () => window.clearTimeout(timer);
}, [variant]);
@@ -728,9 +728,8 @@ export const NewIssuePrefilled: Story = {
export const NewIssueMobileAssigneePicker: Story = {
name: "New Issue - Mobile Assignee Picker",
- parameters: {
- viewport: { defaultViewport: "mobile" },
- },
+ globals: { viewport: { value: "mobile", isRotated: false } },
+ parameters: { waitForViewport: true },
render: () => (
<DialogStory
eyebrow="NewIssueDialog"
@@ -743,17 +742,8 @@ export const NewIssueMobileAssigneePicker: Story = {
),
play: async () => {
const page = within(document.body);
- await userEvent.click(await page.findByRole("button", { name: "Assignee" }));
- const search = await page.findByPlaceholderText("Search assignees...");
- await userEvent.click(search);
- const viewport = constrainVisualViewportForPickerStory();
- await new Promise((resolve) => requestAnimationFrame(resolve));
- const bounds = search.closest<HTMLElement>("[data-mobile-entity-picker]")?.getBoundingClientRect();
- const offsetTop = viewport?.offsetTop ?? 0;
- await expect((bounds?.top ?? -1) + offsetTop).toBeGreaterThanOrEqual(offsetTop);
- await expect((bounds?.bottom ?? Number.POSITIVE_INFINITY) + offsetTop).toBeLessThanOrEqual(
- offsetTop + (viewport?.height ?? window.innerHeight),
- );
+ await userEvent.click(await page.findByRole("button", { name: "Select assignee" }));
+ await expect(await page.findByRole("listbox", { name: "Assignees" })).toBeVisible();
},
};
diff --git a/ui/storybook/stories/new-task-composer.stories.tsx b/ui/storybook/stories/new-task-composer.stories.tsx
new file mode 100644
index 0000000000..73fd9a8275
--- /dev/null
+++ b/ui/storybook/stories/new-task-composer.stories.tsx
@@ -0,0 +1,534 @@
+import { useLayoutEffect, useRef, useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, waitFor, within } from "storybook/test";
+import { useQueryClient } from "@tanstack/react-query";
+import {
+ appearanceForPalette,
+ buildAgentMentionHref,
+ buildIssueReferenceHref,
+ buildProjectMentionHref,
+ buildRoutineMentionHref,
+ buildSkillMentionHref,
+ buildUserMentionHref,
+} from "@paperclipai/shared";
+import { MarkdownBody } from "@/components/MarkdownBody";
+import { NewIssueDialog } from "@/components/NewIssueDialog";
+import { useCompany } from "@/context/CompanyContext";
+import { useDialog } from "@/context/DialogContext";
+import { queryKeys } from "@/lib/queryKeys";
+import { trackRecentAssignee, trackRecentAssigneeUser } from "@/lib/recent-assignees";
+import { trackRecentProject } from "@/lib/recent-projects";
+import { rememberComposerEffort } from "@/lib/recent-composer-effort";
+import {
+ storybookAgents,
+ storybookAuthSession,
+ storybookExecutionWorkspaces,
+ storybookProjects,
+ storybookIssues,
+} from "../fixtures/paperclipData";
+
+const COMPANY_ID = "company-storybook";
+const NEW_TASK_AGENTS = [...storybookAgents, { ...storybookAgents[2]!, id: "agent-ceo", name: "CEO", role: "ceo" }].map((agent) =>
+ agent.id === "agent-codex"
+ ? { ...agent, adapterConfig: { ...agent.adapterConfig, model: "gpt-6-sol" }, appearance: appearanceForPalette("electric-grove") }
+ : { ...agent, appearance: appearanceForPalette("pink-lemonade") },
+);
+const REQUEST = "Review the sign-in flow and fix the redirect after a session expires.";
+const SKILLS = [{ id: "skill-test-drive", key: "test-it-for-real", slug: "test-it-for-real", name: "Test it for real", description: "Walk through the feature in the browser." }];
+const ROUTINES = [{ id: "routine-daily-check", title: "Daily check-in", status: "active" }];
+const RICH_REQUEST = [
+ `Ask [@CodexCoder](${buildAgentMentionHref("agent-codex", "code")}) and [@QAChecker](${buildAgentMentionHref("agent-qa", "shield")}) to review [@Board UI](${buildProjectMentionHref("project-board-ui", storybookProjects[0]!.color)}).`,
+ `Check [PAP-1602](${buildIssueReferenceHref("PAP-1602")}) with [@Product Lead](${buildUserMentionHref("user-product")}) using [/test-it-for-real](${buildSkillMentionHref(SKILLS[0]!.id, SKILLS[0]!.slug)}).`,
+ `Use [/routine:Daily check-in](${buildRoutineMentionHref(ROUTINES[0]!.id)}) as the checklist.`,
+].join("\n\n");
+const WORKTREES = [
+ { ...storybookExecutionWorkspaces[0]!, name: "Sign-in redirect", branchName: "codex/sign-in-redirect" },
+ { ...storybookExecutionWorkspaces[0]!, id: "worktree-settings", name: "Settings polish", branchName: "codex/settings-polish", projectWorkspaceId: "workspace-release-local", cwd: `${storybookExecutionWorkspaces[0]!.cwd}-settings` },
+];
+
+function NewTaskStory({
+ scenario = "empty",
+ worktrees = "ready",
+ isolation = true,
+ rememberedAssignee = "none",
+ rememberedProject = false,
+ rememberedEffort = false,
+}: {
+ scenario?: "empty" | "prefilled" | "title" | "subtask" | "planning" | "error" | "saving" | "rich";
+ worktrees?: "ready" | "reuse" | "empty" | "loading" | "error";
+ isolation?: boolean;
+ rememberedAssignee?: "none" | "agent" | "human";
+ rememberedProject?: boolean;
+ rememberedEffort?: boolean;
+}) {
+ const client = useQueryClient();
+ const { selectedCompanyId, setSelectedCompanyId } = useCompany();
+ const { openNewIssue } = useDialog();
+ const opened = useRef(false);
+ const [submitted, setSubmitted] = useState<Record<string, unknown> | null>(null);
+
+ useLayoutEffect(() => {
+ const originalFetch = window.fetch;
+ const imageUrls: string[] = [];
+ window.fetch = async (input, init) => {
+ const url = new URL(
+ typeof input === "string" ? input : input instanceof URL ? input.href : input.url,
+ location.origin,
+ );
+ if (url.pathname === `/api/companies/${COMPANY_ID}/skills`) return Response.json(SKILLS);
+ if (url.pathname === `/api/companies/${COMPANY_ID}/agents`) return Response.json(NEW_TASK_AGENTS);
+ if (url.pathname === `/api/companies/${COMPANY_ID}/routines`) return Response.json(ROUTINES);
+ if (url.pathname === `/api/companies/${COMPANY_ID}/execution-workspaces`) {
+ if (worktrees === "loading") return new Promise<Response>(() => {});
+ if (worktrees === "error") return Response.json({ error: "Worktrees unavailable" }, { status: 503 });
+ return Response.json(worktrees === "empty" || url.searchParams.get("projectId") !== "project-board-ui" ? [] : WORKTREES);
+ }
+ if (url.pathname === `/api/companies/${COMPANY_ID}/assets/images` && init?.method === "POST") {
+ const file = init.body instanceof FormData ? init.body.get("file") : null;
+ if (!(file instanceof File)) return Response.json({ error: "Select an image" }, { status: 400 });
+ const contentPath = URL.createObjectURL(file);
+ imageUrls.push(contentPath);
+ return Response.json({ contentPath });
+ }
+ if (url.pathname === `/api/companies/${COMPANY_ID}/issues` && init?.method === "POST") {
+ if (scenario === "saving") return new Promise<Response>(() => {});
+ if (scenario === "error")
+ return Response.json(
+ {
+ error: "Could not create the task. Your draft is saved; try again.",
+ },
+ { status: 503 },
+ );
+ const data = JSON.parse(String(init.body)) as Record<string, unknown>;
+ setSubmitted(data);
+ return Response.json({
+ ...data,
+ id: "storybook-created-task",
+ identifier: "PAP-204",
+ companyId: COMPANY_ID,
+ });
+ }
+ return originalFetch(input, init);
+ };
+ return () => {
+ window.fetch = originalFetch;
+ imageUrls.forEach((url) => URL.revokeObjectURL(url));
+ };
+ }, [scenario, worktrees]);
+
+ useLayoutEffect(() => {
+ if (selectedCompanyId !== COMPANY_ID) {
+ setSelectedCompanyId(COMPANY_ID);
+ return;
+ }
+ if (opened.current) return;
+ opened.current = true;
+ localStorage.removeItem("paperclip:issue-draft");
+ localStorage.removeItem("paperclip:recent-assignees");
+ localStorage.removeItem(`paperclip:recent-assignees:${COMPANY_ID}`);
+ localStorage.removeItem("paperclip:recent-projects");
+ localStorage.removeItem(`paperclip:recent-projects:${COMPANY_ID}`);
+ localStorage.removeItem(`paperclip:composer-effort:${COMPANY_ID}`);
+ if (rememberedAssignee === "agent") trackRecentAssignee("agent-codex", COMPANY_ID);
+ if (rememberedAssignee === "human") trackRecentAssigneeUser(storybookAuthSession.user.id, COMPANY_ID);
+ if (rememberedProject) trackRecentProject("project-board-ui", COMPANY_ID);
+ if (rememberedEffort) rememberComposerEffort(COMPANY_ID, "high");
+ client.setQueryData(queryKeys.health, { hiddenSettings: [] });
+ client.setQueryData(queryKeys.auth.session, storybookAuthSession);
+ client.setQueryData(
+ queryKeys.agents.list(COMPANY_ID),
+ NEW_TASK_AGENTS,
+ );
+ client.setQueryData(queryKeys.agents.adapterModels(COMPANY_ID, "codex_local"), [
+ { id: "gpt-6-sol", label: "GPT-6 Sol" },
+ { id: "gpt-6-astra", label: "GPT-6 Astra" },
+ ]);
+ client.setQueryData(queryKeys.projects.list(COMPANY_ID), isolation ? storybookProjects : storybookProjects.map((project) => ({
+ ...project, executionWorkspacePolicy: { ...project.executionWorkspacePolicy, enabled: false },
+ })));
+ client.setQueryData(queryKeys.issues.mentionPool(COMPANY_ID), storybookIssues);
+ client.setQueryData(queryKeys.companySkills.list(COMPANY_ID), SKILLS);
+ client.setQueryData(queryKeys.routines.list(COMPANY_ID), ROUTINES);
+ client.setQueryData(queryKeys.instance.experimentalSettings, {
+ enableIsolatedWorkspaces: true,
+ });
+ const worktreeQueryKey = queryKeys.executionWorkspaces.summaryList(COMPANY_ID, {
+ projectId: "project-board-ui",
+ reuseEligible: true,
+ });
+ client.removeQueries({ queryKey: worktreeQueryKey, exact: true });
+ if (worktrees !== "loading" && worktrees !== "error") client.setQueryData(
+ worktreeQueryKey,
+ worktrees === "empty" ? [] : WORKTREES,
+ );
+ openNewIssue(
+ scenario === "empty"
+ ? {}
+ : {
+ description: scenario === "rich" ? RICH_REQUEST : REQUEST,
+ ...(scenario === "title" ? { title: "Fix the sign-in redirect" } : {}),
+ assigneeAgentId: "agent-codex",
+ projectId: "project-board-ui",
+ projectWorkspaceId: "workspace-board-ui",
+ workMode: scenario === "planning" ? "planning" : "standard",
+ ...(worktrees === "reuse" ? { executionWorkspaceId: WORKTREES[0]!.id } : {}),
+ ...(scenario === "subtask"
+ ? {
+ parentId: "issue-storybook-1",
+ parentIdentifier: "PAP-203",
+ parentTitle: "Improve sign-in reliability",
+ executionWorkspaceId: WORKTREES[0]!.id,
+ parentExecutionWorkspaceLabel: WORKTREES[0]!.name,
+ }
+ : {}),
+ },
+ );
+ }, [client, isolation, openNewIssue, rememberedAssignee, rememberedProject, rememberedEffort, scenario, selectedCompanyId, setSelectedCompanyId, worktrees]);
+
+ return (
+ <div className="min-h-screen bg-background p-8 text-foreground">
+ {submitted ? (
+ <div role="status" className="mt-4 space-y-2">
+ <p>Task created</p>
+ <MarkdownBody>{String(submitted.description ?? submitted.title)}</MarkdownBody>
+ <p>Mode: {String(submitted.workMode)}</p>
+ <p>Worktrees: {String(submitted.executionWorkspacePreference ?? "Project default")}</p>
+ <p>Checkout: {String(submitted.projectWorkspaceId ?? "None")}</p>
+ {submitted.executionWorkspaceId ? <p>Reused: {String(submitted.executionWorkspaceId)}</p> : null}
+ </div>
+ ) : null}
+ <NewIssueDialog />
+ </div>
+ );
+}
+
+const meta = {
+ title: "Composer/New task",
+ component: NewTaskStory,
+ parameters: {
+ layout: "fullscreen",
+ controls: { disable: true },
+ options: { showPanel: false },
+ waitForViewport: true,
+ docs: {
+ description: {
+ component:
+ "The production new-task dialog renders TaskChatComposer. An inset bar shared with queued messages holds the colored project picker and, for projects with isolation enabled, Worktrees. Choose a new worktree or reuse a project worktree. The shared editor supports agent, person, project, and task mentions plus skill and routine slash-command chips. Agent mentions show the agent's current avatar. The editor, add menu, work modes, assignee/model/effort picker, and send button are shared with task chat. Creation is mocked locally; no agents run.",
+ },
+ },
+ },
+ args: { scenario: "empty" },
+} satisfies Meta<typeof NewTaskStory>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Empty: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await expect(await page.findByRole("button", { name: "Create task" })).toBeDisabled();
+ await expect(page.getByTestId("task-chat-composer-input")).toBeVisible();
+ await waitFor(() => expect(page.getByTestId("task-chat-composer-assignee-label")).toHaveTextContent("CEO"));
+ await expect(page.getByRole("textbox", { name: "editable markdown" })).toHaveTextContent("");
+ await expect(page.getByRole("textbox", { name: "editable markdown" }).querySelector('[data-mention-kind]')).toBeNull();
+ },
+};
+export const LastAssignee: Story = {
+ args: { rememberedAssignee: "agent" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await waitFor(() => expect(page.getByTestId("task-chat-composer-assignee-label")).toHaveTextContent("CodexCoder"));
+ await expect(page.getByRole("textbox", { name: "editable markdown" })).toHaveTextContent("");
+ },
+};
+export const ReturningPreferences: Story = {
+ args: { rememberedAssignee: "agent", rememberedProject: true, rememberedEffort: true },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await waitFor(() => expect(page.getByTestId("task-chat-composer-assignee-label")).toHaveTextContent("CodexCoder"));
+ await expect(page.getByTestId("task-chat-composer-context")).toHaveTextContent("Board UI");
+ await userEvent.click(page.getByRole("button", { name: "Select model and effort" }));
+ await waitFor(() => expect(page.getByTestId("selected-effort")).toHaveTextContent("High"));
+ },
+};
+export const MobileReturningPreferences: Story = {
+ ...ReturningPreferences,
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+export const HumanAssignee: Story = {
+ args: { rememberedAssignee: "human" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await waitFor(() => expect(page.getByTestId("task-chat-composer-assignee-label")).toHaveTextContent("Me"));
+ await expect(page.queryByRole("button", { name: "Select model and effort" })).not.toBeInTheDocument();
+ await expect(page.queryByTestId("task-chat-composer-model-label")).not.toBeInTheDocument();
+ },
+};
+export const AssigneePicker: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Select assignee" }));
+ await expect(page.getByRole("searchbox", { name: "Search assignees" })).toBeVisible();
+ await expect(page.getByRole("listbox", { name: "Assignees" })).toBeVisible();
+ },
+};
+export const NoAssignee: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Select assignee" }));
+ await userEvent.click(page.getByRole("option", { name: "No assignee" }));
+ await expect(page.queryByRole("listbox", { name: "Assignees" })).not.toBeInTheDocument();
+ await expect(page.getByTestId("task-chat-composer-assignee-label")).toHaveTextContent("No assignee");
+ await expect(page.queryByTestId("task-chat-composer-model-label")).not.toBeInTheDocument();
+ },
+};
+export const MobileAssigneePicker: Story = {
+ ...AssigneePicker,
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+export const Prefilled: Story = { args: { scenario: "prefilled" } };
+export const InheritedTitle: Story = { args: { scenario: "title" } };
+export const Planning: Story = { args: { scenario: "planning" } };
+export const SubTask: Story = { args: { scenario: "subtask" } };
+export const ProjectPicker: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Board UI" }));
+ await expect(page.getByPlaceholderText("Search projects...")).toBeVisible();
+ },
+};
+export const ModelPicker: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ await page.findByRole("button", {
+ name: "Select model and effort",
+ }),
+ );
+ await expect(page.getByRole("button", { name: "Choose exact model" })).toBeVisible();
+ },
+};
+export const Files: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await page.findByTestId("task-chat-composer-input");
+ const input = canvasElement.ownerDocument.querySelector<HTMLInputElement>('input[type="file"]')!;
+ await userEvent.upload(input, [
+ new File(["# Sign-in plan\n\nReproduce the redirect."], "plan.md", {
+ type: "text/markdown",
+ }),
+ new File(["fixture"], "redirect.png", { type: "image/png" }),
+ ]);
+ await expect(page.getByText("plan.md")).toBeVisible();
+ await expect(page.getByText("redirect.png")).toBeVisible();
+ },
+};
+export const Saving: Story = {
+ args: { scenario: "saving" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const send = await page.findByRole("button", { name: "Create task" });
+ await userEvent.click(send);
+ await expect(send).toHaveAttribute("aria-busy", "true");
+ await expect(page.getByTestId("task-chat-composer-input")).toHaveTextContent(REQUEST);
+ },
+};
+export const SaveError: Story = {
+ args: { scenario: "error" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Create task" }));
+ await expect(await page.findByRole("alert")).toHaveTextContent("Your draft is saved");
+ await expect(page.getByTestId("task-chat-composer-input")).toHaveTextContent(REQUEST);
+ },
+};
+export const CreateFromComposer: Story = {
+ args: { scenario: "planning" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Create task" }));
+ await expect(await page.findByRole("status")).toHaveTextContent("Task created");
+ await expect(page.getByRole("status")).toHaveTextContent("Mode: planning");
+ },
+};
+export const Light: Story = {
+ args: { scenario: "prefilled" },
+ globals: { theme: "light" },
+};
+export const Mobile: Story = {
+ args: { scenario: "prefilled" },
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+export const MobileProjectPicker: Story = {
+ ...ProjectPicker,
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+export const MobileModelPicker: Story = {
+ ...ModelPicker,
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+
+export const WorktreePicker: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await expect(page.getByPlaceholderText("Search worktrees...")).toBeVisible();
+ await expect(page.getByRole("option", { name: /New worktree/ })).toBeVisible();
+ await expect(page.getByRole("option", { name: /Sign-in redirect/ })).toBeVisible();
+ },
+};
+export const ReuseWorktree: Story = {
+ args: { scenario: "prefilled", worktrees: "reuse" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await expect(await page.findByRole("combobox", { name: "Worktrees" })).toHaveTextContent("Sign-in redirect");
+ },
+};
+export const CreateWithReusedWorktree: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await userEvent.type(page.getByPlaceholderText("Search worktrees..."), "settings");
+ await userEvent.click(await page.findByRole("option", { name: /Settings polish/ }));
+ await expect(page.getByRole("combobox", { name: "Worktrees" })).toHaveTextContent("Settings polish");
+ await userEvent.click(page.getByRole("button", { name: "Create task" }));
+ await expect(await page.findByRole("status")).toHaveTextContent("Worktrees: reuse_existing");
+ await expect(page.getByRole("status")).toHaveTextContent("Reused: worktree-settings");
+ await expect(page.getByRole("status")).toHaveTextContent("Checkout: workspace-release-local");
+ },
+};
+export const NewWorktreeAfterReuse: Story = {
+ args: { scenario: "prefilled" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await userEvent.click(await page.findByRole("option", { name: /Settings polish/ }));
+ await userEvent.click(page.getByRole("combobox", { name: "Worktrees" }));
+ await userEvent.click(page.getByRole("option", { name: /New worktree/ }));
+ await userEvent.click(page.getByRole("button", { name: "Create task" }));
+ await expect(await page.findByRole("status")).toHaveTextContent("Worktrees: isolated_workspace");
+ await expect(page.getByRole("status")).toHaveTextContent("Checkout: workspace-board-ui");
+ await expect(page.getByRole("status")).not.toHaveTextContent("Reused:");
+ },
+};
+export const EmptyWorktrees: Story = { ...WorktreePicker, args: { scenario: "prefilled", worktrees: "empty" }, play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await expect(page.getByText(/No existing worktrees yet/)).toBeVisible();
+ await expect(page.getByRole("option", { name: /New worktree/ })).toBeVisible();
+} };
+export const LoadingWorktrees: Story = { ...EmptyWorktrees, args: { scenario: "prefilled", worktrees: "loading" }, play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await expect(page.getByText("Loading existing worktrees…")).toBeVisible();
+ await expect(page.getByRole("option", { name: /New worktree/ })).toBeVisible();
+} };
+export const WorktreeError: Story = { ...EmptyWorktrees, args: { scenario: "prefilled", worktrees: "error" }, play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("combobox", { name: "Worktrees" }));
+ await expect(await page.findByRole("button", { name: "Retry" })).toBeVisible();
+ await expect(page.getByRole("option", { name: /New worktree/ })).toBeVisible();
+} };
+export const IsolationDisabled: Story = { args: { scenario: "prefilled", isolation: false }, play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await expect(await page.findByRole("button", { name: "Board UI" })).toBeVisible();
+ await expect(page.queryByRole("combobox", { name: "Worktrees" })).not.toBeInTheDocument();
+} };
+export const MobileWorktreePicker: Story = {
+ ...WorktreePicker,
+ globals: { viewport: { value: "mobile", isRotated: false } },
+};
+
+export const MentionPicker: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const editor = await page.findByRole("textbox", { name: "editable markdown" });
+ await userEvent.type(editor, "@");
+ const menu = await page.findByTestId("mention-autocomplete-menu");
+ await expect(within(menu).getByText("CodexCoder")).toBeVisible();
+ await expect(menu.querySelector('[data-slot="agent-avatar"] img')).toBeVisible();
+ await expect(within(menu).getByText("Product Lead")).toBeVisible();
+ await expect(within(menu).getByText("Board UI")).toBeVisible();
+ await expect(within(menu).getByText("PAP-1602")).toBeVisible();
+ await expect(menu.getBoundingClientRect().right).toBeLessThanOrEqual(canvasElement.ownerDocument.defaultView!.innerWidth);
+ },
+};
+
+export const SlashCommands: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.type(await page.findByRole("textbox", { name: "editable markdown" }), "/");
+ const menuElement = await page.findByTestId("mention-autocomplete-menu");
+ const menu = within(menuElement);
+ await expect(menu.getByText("/test-it-for-real")).toBeVisible();
+ await expect(menu.getByText("/routine:Daily check-in")).toBeVisible();
+ await expect(menuElement.getBoundingClientRect().right).toBeLessThanOrEqual(canvasElement.ownerDocument.defaultView!.innerWidth);
+ },
+};
+
+export const RichChips: Story = {
+ args: { scenario: "rich" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const composer = await page.findByTestId("task-chat-composer-input");
+ for (const kind of ["agent", "user", "project", "issue", "skill", "routine"]) {
+ await waitFor(() => expect(composer.querySelector(`[data-mention-kind="${kind}"]`)).toBeVisible());
+ }
+ const agentChip = composer.querySelector('[data-mention-kind="agent"]')!;
+ await expect(agentChip).toHaveAttribute("style", expect.stringContaining("--paperclip-mention-avatar-image"));
+ await expect(canvasElement.ownerDocument.defaultView!.getComputedStyle(agentChip, "::before").backgroundImage)
+ .toContain(new URL("./agent-avatar-images/", canvasElement.ownerDocument.baseURI).href);
+ },
+};
+
+export const CreateWithRichChips: Story = {
+ args: { scenario: "rich" },
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ await userEvent.click(await page.findByRole("button", { name: "Create task" }));
+ const receipt = await page.findByRole("status");
+ await expect(receipt).toHaveTextContent("Task created");
+ await expect(receipt).toHaveTextContent("/test-it-for-real");
+ await expect(receipt).toHaveTextContent("/routine:Daily check-in");
+ await expect(receipt.querySelector('[data-mention-kind="agent"]')).toHaveAttribute("style", expect.stringContaining("electric-grove"));
+ },
+};
+
+export const InsertRichChips: Story = {
+ play: async ({ canvasElement }) => {
+ const page = within(canvasElement.ownerDocument.body);
+ const editor = await page.findByRole("textbox", { name: "editable markdown" });
+ await userEvent.click(editor);
+ for (const [query, option] of [
+ ["@Codex", /CodexCoder/],
+ [" @Product", /Product Lead/],
+ [" @Board UI", /Board UI/],
+ [" @PAP-1602", /PAP-1602/],
+ [" /test-it", /test-it-for-real/],
+ [" /routine:Daily", /routine:Daily check-in/],
+ ] as const) {
+ await waitFor(() => expect(editor).toHaveFocus());
+ await userEvent.keyboard(query);
+ const menu = within(await page.findByTestId("mention-autocomplete-menu"));
+ await userEvent.click(await menu.findByRole("button", { name: option }));
+ }
+ await waitFor(() => expect(editor).toHaveFocus());
+ await userEvent.keyboard(" Please review these together.");
+ await userEvent.click(page.getByRole("button", { name: "Create task" }));
+ const receipt = await page.findByRole("status");
+ await expect(receipt).toHaveTextContent("Please review these together.");
+ for (const kind of ["agent", "user", "project", "skill", "routine"]) {
+ await expect(receipt.querySelector(`[data-mention-kind="${kind}"]`)).toBeVisible();
+ }
+ await expect(within(receipt).getByRole("link", { name: "Issue PAP-1602" })).toBeVisible();
+ },
+};
+
+export const MobileMentionPicker: Story = { ...MentionPicker, globals: { viewport: { value: "mobile", isRotated: false } } };
+export const MobileSlashCommands: Story = { ...SlashCommands, globals: { viewport: { value: "mobile", isRotated: false } } };
+export const MobileRichChips: Story = { ...RichChips, globals: { viewport: { value: "mobile", isRotated: false } } };
+export const MobileInsertRichChips: Story = { ...InsertRichChips, globals: { viewport: { value: "mobile", isRotated: false } } };