Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
56.7 KB
Raw Blame
import {
  cloneElement,
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
  type ReactElement,
  type ReactNode,
} from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

const mockQuickCreateIssue = vi.hoisted(() => vi.fn());
type VoiceOptions = { insert: (text: string) => boolean; submit?: () => void };
const voiceOptions = vi.hoisted(() => ({ last: null as VoiceOptions | null }));

// Voice input has its own tests; here only its wiring to the editor matters.
vi.mock("../voice", () => ({
  useComposerVoice: (options: VoiceOptions) => {
    voiceOptions.last = options;
    return { rootRef: () => {}, onFocusCapture: () => {} };
  },
  VoiceDialogFooter: ({ children }: { children: ReactNode }) => children,
  VoiceMicButton: () => null,
}));
const mockCreateCommentSubIssue = vi.hoisted(() => vi.fn());
const mockSetLastActor = vi.hoisted(() => vi.fn());
const mockCountActorCreate = vi.hoisted(() => vi.fn());
const mockSetQuickCreateFieldVisible = vi.hoisted(() => vi.fn());
const mockSetKeepOpen = vi.hoisted(() => vi.fn());
const mockSetLastMode = vi.hoisted(() => vi.fn());
const mockToastSuccess = vi.hoisted(() => vi.fn());
// Uploads flow through the module-level coordinator, which calls
// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2).
const mockApiUploadFile = vi.hoisted(() => vi.fn());
const mockNavigationPush = vi.hoisted(() => vi.fn());
const mockSetShared = vi.hoisted(() => vi.fn());
const mockSetManual = vi.hoisted(() => vi.fn());
const mockSetAgent = vi.hoisted(() => vi.fn());
const mockSetActiveMode = vi.hoisted(() => vi.fn());
const mockClearDraft = vi.hoisted(() => vi.fn());

const sourceContextPanelData = {
  anchor_comment_id: "comment-source",
  source_context_preview: {
    source_issue: {
      id: "issue-source",
      identifier: "MUL-9",
      number: 9,
      title: "Source",
      description: "Historical body",
      created_at: "2026-08-20T00:00:00Z",
      updated_at: "2026-08-21T00:00:00Z",
      revision: 1,
      attachments: [],
    },
    comment_thread: [{
      id: "comment-source",
      parent_id: null,
      type: "comment",
      content: "Historical comment",
      author: { type: "member", id: "user-1", name: "Alice" },
      created_at: "2026-08-21T00:00:00Z",
      updated_at: "2026-08-21T00:00:00Z",
      revision: 1,
      attachments: [],
    }],
    anchor_comment_id: "comment-source",
    capture_token: "sha256:preview-token",
    limits: { comment_count: 1, text_bytes: 100, attachment_count: 0, attachment_bytes: 0 },
  },
};

const emptyIssueDraft = () => ({
  shared: {
    projectId: undefined as string | undefined,
    priority: "none" as "none" | "low" | "medium" | "high" | "urgent",
    dueDate: null as string | null,
    attachments: [] as Array<{ id: string }>,
  },
  manual: {
    title: "",
    description: "",
    status: "todo" as const,
    startDate: null as string | null,
    assigneeType: undefined as "agent" | "squad" | "member" | undefined,
    assigneeId: undefined as string | undefined,
    labelIds: [] as string[],
    propertyValues: {} as Record<string, string | number | boolean | string[]>,
  },
  agent: {
    prompt: "",
    actorType: undefined as "agent" | "squad" | undefined,
    actorId: undefined as string | undefined,
  },
  activeMode: "agent" as "agent" | "manual",
});

const mockIssueDraftStore = {
  draft: emptyIssueDraft(),
  setShared: mockSetShared,
  setManual: mockSetManual,
  setAgent: mockSetAgent,
  setActiveMode: mockSetActiveMode,
  clearDraft: mockClearDraft,
};

const mockQuickCreateStore = {
  lastActorType: null as "agent" | "squad" | null,
  lastActorId: null as string | null,
  setLastActor: mockSetLastActor,
  actorCreateCounts: {} as Record<string, number>,
  countActorCreate: mockCountActorCreate,
  keepOpen: false,
  setKeepOpen: mockSetKeepOpen,
  // Not part of the store's interface any more (MUL-5862), but an older
  // build persisted it and localStorage still hands it back on rehydrate.
  // Kept here so the tests can prove the panel ignores it.
  lastProjectId: null as string | null,
};

const mockCreateSettingsStore = {
  quickCreateFields: ["project"] as Array<"project" | "priority" | "due_date">,
  setQuickCreateFieldVisible: mockSetQuickCreateFieldVisible,
};

// Per-test override for the projects query, so tests can swap between
// "loaded as empty" (the deleted-project case) and "still loading" without
// re-mocking the whole module.
const mockProjectsQuery = vi.hoisted(() => ({
  data: [] as Array<{ id: string; title: string; icon: string | null }>,
  isSuccess: true,
}));

// Per-test override for the squads list so we can flip between "squads
// exist and one's leader is reachable" and "no squads" cases without
// re-mocking the whole module.
const mockSquadsData = vi.hoisted(
  () => ({ list: [] as Array<{ id: string; name: string; leader_id: string; archived_at: string | null }> }),
);

const mockAgentsData = vi.hoisted(
  () => ({ list: [] as Array<{ id: string; name: string; archived_at: string | null; runtime_id: string }> }),
);

// Per-test override for the runtimes list. Non-admin members receive a
// filtered list (ListVisibleAgentRuntimes) that omits other members' private
// machines, so a selected agent can point at a runtime_id that is simply not
// present here — the case that used to be misreported as "daemon has no CLI
// version" (#7633). Tests flip this to drop the row and prove the panel no
// longer blocks on it.
const mockRuntimesData = vi.hoisted(
  () => ({ list: [{ id: "runtime-1", metadata: { cli_version: "1.2.3" } }] as Array<{ id: string; provider?: string; metadata: Record<string, unknown> }> }),
);

// The real handle mints an id when it inserts the placeholder and hands it to
// the uploader, which adopts it as the draft `clientUploadId`. Mocks must do
// the same or the two records drift apart only in tests.
let mockUploadIdSeq = 0;

vi.mock("@tanstack/react-query", () => ({
  useQuery: ({ queryKey }: { queryKey: string[] }) => {
    // Workspace-scoped query keys carry the wsId as `queryKey[1]`; the
    // discriminator is at `queryKey[2]` (e.g. ["workspaces", wsId, "squads"]).
    if (queryKey[0] === "workspaces" && queryKey[2] === "squads") {
      return { data: mockSquadsData.list };
    }
    switch (queryKey[0]) {
      case "members":
        return { data: [{ user_id: "user-1", role: "admin" }] };
      case "agents":
        return { data: mockAgentsData.list };
      case "runtimes":
        return { data: mockRuntimesData.list };
      case "projects":
        return mockProjectsQuery;
      default:
        return { data: [] };
    }
  },
}));

const { ApiError } = vi.hoisted(() => {
  class ApiErrorImpl extends Error {
    readonly status: number;
    readonly statusText: string;
    readonly body?: unknown;
    constructor(message: string, status: number, statusText: string, body?: unknown) {
      super(message);
      this.name = "ApiError";
      this.status = status;
      this.statusText = statusText;
      this.body = body;
    }
  }
  return { ApiError: ApiErrorImpl };
});

vi.mock("@multica/core/api", () => ({
  api: {
    createCommentSubIssue: mockCreateCommentSubIssue,
    quickCreateIssue: mockQuickCreateIssue,
    uploadFile: mockApiUploadFile,
  },
  ApiError,
}));

vi.mock("@multica/core/hooks", () => ({
  useWorkspaceId: () => "ws-test",
}));

vi.mock("@multica/core/paths", () => ({
  useCurrentWorkspace: () => ({ name: "Test Workspace" }),
  useWorkspacePaths: () => ({
    settings: () => "/ws-test/settings",
  }),
}));

// Mocked at the context module rather than the barrel so <AppLink> stays the
// real component and its click contract is what the test exercises.
vi.mock("../navigation/context", () => ({
  useNavigation: () => ({ push: mockNavigationPush }),
}));

vi.mock("@multica/core/workspace/queries", () => ({
  agentListOptions: () => ({ queryKey: ["agents"] }),
  memberListOptions: () => ({ queryKey: ["members"] }),
  squadListOptions: (wsId: string) => ({
    queryKey: ["workspaces", wsId, "squads"],
  }),
}));

vi.mock("@multica/core/projects/queries", () => ({
  projectListOptions: () => ({ queryKey: ["projects"] }),
}));

vi.mock("@multica/core/issues/stores/quick-create-store", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/core/issues/stores/quick-create-store")>()),
  useQuickCreateStore: (selector?: (state: typeof mockQuickCreateStore) => unknown) =>
    (selector ? selector(mockQuickCreateStore) : mockQuickCreateStore),
}));

vi.mock("@multica/core/issues/stores/draft-store", () => ({
  useIssueDraftStore: Object.assign(
    (selector?: (state: typeof mockIssueDraftStore) => unknown) =>
      (selector ? selector(mockIssueDraftStore) : mockIssueDraftStore),
    { getState: () => mockIssueDraftStore },
  ),
}));

vi.mock("@multica/core/issues/stores/issue-create-settings-store", () => ({
  useIssueCreateSettingsStore: (
    selector?: (state: typeof mockCreateSettingsStore) => unknown,
  ) => (selector ? selector(mockCreateSettingsStore) : mockCreateSettingsStore),
}));

vi.mock("@multica/core/issues/stores/create-mode-store", () => ({
  useCreateModeStore: (selector?: (state: { setLastMode: typeof mockSetLastMode }) => unknown) =>
    (selector ? selector({ setLastMode: mockSetLastMode }) : { setLastMode: mockSetLastMode }),
}));

vi.mock("@multica/core/auth", () => ({
  useAuthStore: (selector?: (state: { user: { id: string } }) => unknown) =>
    (selector ? selector({ user: { id: "user-1" } }) : { user: { id: "user-1" } }),
}));

// Use the REAL version-check helpers (not stubs): the fix hinges on how the
// panel reacts when the selected runtime is absent vs. present-but-old, and a
// constant-"ok" stub would mask exactly that. Only runtimeListOptions is
// overridden so the query key routes to our mocked useQuery above.
vi.mock("@multica/core/runtimes", async (importOriginal) => ({
  ...(await importOriginal<typeof import("@multica/core/runtimes")>()),
  runtimeListOptions: () => ({ queryKey: ["runtimes"] }),
}));


vi.mock("../issues/components/pickers/assignee-picker", () => ({
  canAssignAgent: () => true,
}));

vi.mock("../common/actor-avatar", () => ({
  ActorAvatar: () => <span data-testid="actor-avatar" />,
}));

vi.mock("../issues/components", () => ({
  PriorityIcon: ({ priority }: { priority: string }) => <span>{priority}</span>,
  PriorityPicker: ({ priority, onUpdate }: any) => (
    <button type="button" data-testid="priority-picker" onClick={() => onUpdate({ priority: "high" })}>
      Priority {priority}
    </button>
  ),
  DueDatePicker: ({ dueDate, onUpdate }: any) => (
    <button type="button" data-testid="due-date-picker" onClick={() => onUpdate({ due_date: "2026-08-01" })}>
      Due date {dueDate ?? "none"}
    </button>
  ),
}));

vi.mock("../projects/components/project-picker", () => ({
  ProjectPicker: ({ projectId, onUpdate, triggerRender }: any) => (
    <>
      <button type="button" data-testid="project-picker" onClick={() => onUpdate({ project_id: "proj-1" })}>
        Project {projectId ?? "none"}
      </button>
      {/* The caller's own trigger renders too — the pill carries the
          quick-clear ×, which belongs to this panel, not to the picker. */}
      {triggerRender}
    </>
  ),
}));

vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
  DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
  DropdownMenuTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,
  DropdownMenuContent: ({ children }: { children: ReactNode }) => <>{children}</>,
  // `render` mirrors Base UI: an item can BE another element (an <AppLink>).
  // The real Item gives that element role="button", which the queries match.
  DropdownMenuItem: ({
    children,
    onClick,
    render,
  }: {
    children: ReactNode;
    onClick?: () => void;
    render?: ReactElement<{ role?: string; children?: ReactNode }>;
  }) =>
    render ? (
      cloneElement(render, { role: "button" }, children)
    ) : (
      <button type="button" onClick={onClick}>{children}</button>
    ),
  DropdownMenuSeparator: () => null,
}));

vi.mock("@multica/ui/lib/utils", () => ({
  cn: (...values: Array<string | false | null | undefined>) => values.filter(Boolean).join(" "),
}));

vi.mock("../editor", async () => {
  // Real submit gate (pure React) driven by the mock editor's
  // `hasActiveUploads` / `onUploadingChange`.
  const uploadGate = await vi.importActual<typeof import("../editor/use-upload-gate")>(
    "../editor/use-upload-gate",
  );
  // Real composer submit contract — pure React, no network. Drives the
  // single-flight + upload-gate semantics against the mocked editor/api.
  const composer = await vi.importActual<typeof import("../editor/use-composer-submit")>(
    "../editor/use-composer-submit",
  );
  const ContentEditor = forwardRef(({ defaultValue, onUpdate, onSubmit, onUploadFile, onUploadingChange, placeholder }: any, ref: any) => {
    const valueRef = useRef(defaultValue || "");
    const [value, setValue] = useState(defaultValue || "");
    // Mirrors the real editor's `uploading` node attrs: the placeholder sits
    // in the doc from before the await until the upload settles, which is what
    // `hasActiveUploads` reports and `onUploadingChange` publishes.
    const inFlightRef = useRef(0);
    const runUpload = async (file: File) => {
      inFlightRef.current += 1;
      if (inFlightRef.current === 1) onUploadingChange?.(true);
      try {
        return await onUploadFile?.(file, `mock-upload-${++mockUploadIdSeq}`);
      } finally {
        inFlightRef.current -= 1;
        if (inFlightRef.current === 0) onUploadingChange?.(false);
      }
    };

    useImperativeHandle(ref, () => ({
      getMarkdown: () => valueRef.current,
      clearContent: () => {
        valueRef.current = "";
        setValue("");
      },
      uploadFile: runUpload,
      focus: vi.fn(),
      insertText: (text: string) => {
        valueRef.current += text;
        setValue(valueRef.current);
        onUpdate?.(valueRef.current);
        return true;
      },
      hasActiveUploads: () => inFlightRef.current > 0,
      // Placeholder rebuild contract: the real handle draws a card for an
      // upload the document is not showing and reports whether it landed.
      // Mocks track ids only — no document to draw into.
      insertUploadPlaceholder: () => true,
      settleUploadPlaceholder: () => false,
    }));

    return (
      <>
        <textarea
          value={value}
          placeholder={placeholder}
          onChange={(e) => {
            valueRef.current = e.target.value;
            setValue(e.target.value);
            onUpdate?.(e.target.value);
          }}
          onKeyDown={(e) => {
            if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
              onSubmit?.();
            }
          }}
        />
        <button
          type="button"
          onClick={() => runUpload(new File(["image"], "shot.png", { type: "image/png" }))}
        >
          Mock editor upload
        </button>
      </>
    );
  });
  ContentEditor.displayName = "ContentEditor";

  return {
    ...uploadGate,
    ...composer,
    ContentEditor,
    useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),
    FileDropOverlay: () => null,
  };
});

vi.mock("@multica/ui/components/ui/dialog", () => ({
  DialogTitle: ({ children, className }: { children: ReactNode; className?: string }) => (
    <div className={className}>{children}</div>
  ),
}));

vi.mock("../issues/components/pickers/property-picker", () => ({
  PropertyPicker: ({
    trigger,
    children,
    searchPlaceholder,
    onSearchChange,
  }: {
    trigger: ReactNode;
    children: ReactNode;
    searchPlaceholder?: string;
    onSearchChange?: (v: string) => void;
  }) => (
    <>
      {trigger}
      <input
        aria-label="actor-search"
        placeholder={searchPlaceholder}
        onChange={(e) => onSearchChange?.(e.target.value)}
      />
      {children}
    </>
  ),
  PickerItem: ({
    children,
    onClick,
    selected,
  }: {
    children: ReactNode;
    onClick: () => void;
    selected?: boolean;
  }) => (
    <button type="button" onClick={onClick} data-selected={selected ? "true" : "false"}>
      {children}
    </button>
  ),
  PickerSection: ({ label, children }: { label: string; children: ReactNode }) => (
    <div>
      <div data-testid="picker-section-label">{label}</div>
      {children}
    </div>
  ),
  PickerEmpty: () => <div data-testid="picker-empty" />,
}));

vi.mock("@multica/ui/components/ui/switch", () => ({
  Switch: ({ checked, onCheckedChange }: { checked: boolean; onCheckedChange: (v: boolean) => void }) => (
    <input
      type="checkbox"
      checked={checked}
      onChange={(e) => onCheckedChange(e.target.checked)}
    />
  ),
}));

vi.mock("@multica/ui/components/common/file-upload-button", () => ({
  // `disabled` is forwarded so the "can still queue another file mid-upload"
  // guarantee is actually assertable here (MUL-4808).
  FileUploadButton: ({ disabled, size }: { disabled?: boolean; size?: string }) => (
    <button type="button" disabled={disabled} data-size={size}>Upload file</button>
  ),
}));

vi.mock("sonner", () => ({
  toast: {
    success: mockToastSuccess,
  },
}));

import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../locales/en/common.json";
import enModals from "../locales/en/modals.json";
import enEditor from "../locales/en/editor.json";
import enProjects from "../locales/en/projects.json";
import enIssues from "../locales/en/issues.json";
import { AgentCreatePanel } from "./quick-create-issue";

const TEST_RESOURCES = {
  en: { common: enCommon, modals: enModals, editor: enEditor, projects: enProjects, issues: enIssues },
};

// A row of the actor popover, as opposed to the quick-switch chip that can
// carry the same name.
function pickerRow(name: RegExp) {
  const rows = screen
    .getAllByRole("button", { name })
    .filter((el) => el.hasAttribute("data-selected"));
  expect(rows).toHaveLength(1);
  return rows[0]!;
}

function renderPanel(props: React.ComponentProps<typeof AgentCreatePanel>) {
  return render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <AgentCreatePanel {...props} />
    </I18nProvider>,
  );
}

describe("AgentCreatePanel", () => {
  it("does not replace an explicitly cleared manual assignee with the filing agent", async () => {
    const user = userEvent.setup();
    renderPanel({ onClose: vi.fn(), onSwitchMode: vi.fn(), isExpanded: false, setIsExpanded: vi.fn(), data: { manual_assignee_cleared: true } });
    await user.click(screen.getByRole("button", { name: /Switch to Manual/i }));
    expect(mockIssueDraftStore.draft.manual.assigneeId).toBeUndefined();
    expect(mockSetManual.mock.calls.some(([patch]) => "assigneeId" in patch)).toBe(false);
  });

  it("selects Qoder agents without the daemon CLI version gate", () => {
    mockRuntimesData.list = [{ id: "runtime-1", provider: "qoder_cloud", metadata: {} }];
    mockQuickCreateStore.lastActorType = "agent";
    mockQuickCreateStore.lastActorId = "agent-1";
    mockSquadsData.list = [{ id: "squad-1", name: "Cloud Squad", leader_id: "agent-1", archived_at: null }];
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    expect(screen.getByRole("button", { name: /^Create$/i })).toBeEnabled();
    expect(screen.queryByText(/daemon.*version/i)).not.toBeInTheDocument();
    expect(screen.getAllByText("Bohan").length).toBeGreaterThan(0);
    expect(pickerRow(/Cloud Squad/)).toBeInTheDocument();
  });

  it("blocks Qoder agents when the prompt references an attachment", () => {
    mockRuntimesData.list = [{ id: "runtime-1", provider: "qoder_cloud", metadata: {} }];
    mockQuickCreateStore.lastActorType = "agent";
    mockQuickCreateStore.lastActorId = "agent-1";
    const attachmentId = "019ec09d-6222-722b-bdfa-427b105d80be";
    mockIssueDraftStore.draft.agent.prompt = `See ![shot](/api/attachments/${attachmentId}/download)`;
    mockIssueDraftStore.draft.shared.attachments = [{
      clientUploadId: attachmentId,
      status: "uploaded",
      filename: "shot.png",
      attachment: { id: attachmentId, url: "https://cdn.example/shot.png", filename: "shot.png" },
    } as never];
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    expect(screen.getByRole("button", { name: /^Create$/i })).toBeDisabled();
    expect(screen.getByText(/can't read attachments/i)).toBeInTheDocument();
  });

  beforeEach(() => {
    vi.clearAllMocks();
    mockQuickCreateStore.lastActorType = null;
    mockQuickCreateStore.lastActorId = null;
    mockQuickCreateStore.lastProjectId = null;
    mockQuickCreateStore.actorCreateCounts = {};
    mockAgentsData.list = [{ id: "agent-1", name: "Bohan", archived_at: null, runtime_id: "runtime-1" }];
    mockCreateSettingsStore.quickCreateFields = ["project"];
    mockQuickCreateStore.keepOpen = false;
    mockIssueDraftStore.draft = emptyIssueDraft();
    // The prompt now lives in the unified draft's agent slot.
    mockIssueDraftStore.draft.agent.prompt = "Persisted draft prompt";
    mockSetShared.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.shared>) => {
      mockIssueDraftStore.draft.shared = { ...mockIssueDraftStore.draft.shared, ...patch };
    });
    mockSetManual.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.manual>) => {
      mockIssueDraftStore.draft.manual = { ...mockIssueDraftStore.draft.manual, ...patch };
    });
    mockSetAgent.mockImplementation((patch: Partial<typeof mockIssueDraftStore.draft.agent>) => {
      mockIssueDraftStore.draft.agent = { ...mockIssueDraftStore.draft.agent, ...patch };
    });
    mockClearDraft.mockImplementation(() => {
      mockIssueDraftStore.draft = emptyIssueDraft();
    });
    mockProjectsQuery.data = [];
    mockProjectsQuery.isSuccess = true;
    mockSquadsData.list = [];
    mockRuntimesData.list = [{ id: "runtime-1", metadata: { cli_version: "1.2.3" } }];
    mockQuickCreateIssue.mockResolvedValue(undefined);
    mockCreateCommentSubIssue.mockResolvedValue({ task_id: "task-source-child" });
    mockApiUploadFile.mockResolvedValue({
      id: "019ec09d-6222-722b-bdfa-427b105d80be",
      workspace_id: "ws-test",
      issue_id: null,
      comment_id: null,
      chat_session_id: null,
      chat_message_id: null,
      uploader_type: "member",
      uploader_id: "user-1",
      filename: "shot.png",
      url: "/uploads/shot.png",
      download_url: "/api/attachments/019ec09d-6222-722b-bdfa-427b105d80be/download",
      markdown_url: "/api/attachments/019ec09d-6222-722b-bdfa-427b105d80be/download",
      content_type: "image/png",
      size_bytes: 5,
      created_at: "2026-06-12T00:00:00Z",
    });
    mockSetKeepOpen.mockImplementation((value: boolean) => {
      mockQuickCreateStore.keepOpen = value;
    });
  });

  it("loads the persisted prompt draft when no transient prompt is provided", () => {
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(
      screen.getByPlaceholderText(
        'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
      ),
    ).toHaveValue("Persisted draft prompt");
  });

  it("prefers a prompt handed in by the opener over the draft and saves it to the draft", () => {
    renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
      data: { prompt: "fix the Safari login callback 500" },
    });

    expect(
      screen.getByPlaceholderText(
        'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
      ),
    ).toHaveValue("fix the Safari login callback 500");
    expect(mockIssueDraftStore.draft.agent.prompt).toBe("fix the Safari login callback 500");
  });

  it("restores unfinished actor, project, priority, and due-date selections after remount", async () => {
    mockSquadsData.list = [
      { id: "squad-1", name: "Frontend Squad", leader_id: "agent-1", archived_at: null },
    ];
    mockProjectsQuery.data = [{ id: "proj-1", title: "Web", icon: null }];
    mockCreateSettingsStore.quickCreateFields = ["project", "priority", "due_date"];
    const user = userEvent.setup();

    const firstOpen = renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
    });

    await user.click(pickerRow(/Frontend Squad/));
    await user.click(screen.getByTestId("project-picker"));
    await user.click(screen.getByTestId("priority-picker"));
    await user.click(screen.getByTestId("due-date-picker"));

    expect(mockIssueDraftStore.draft.agent).toEqual(
      expect.objectContaining({ actorType: "squad", actorId: "squad-1" }),
    );
    expect(mockIssueDraftStore.draft.shared).toEqual(
      expect.objectContaining({
        projectId: "proj-1",
        priority: "high",
        dueDate: "2026-08-01",
      }),
    );

    firstOpen.unmount();
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(pickerRow(/Frontend Squad/)).toHaveAttribute(
      "data-selected",
      "true",
    );
    expect(screen.getByTestId("project-picker")).toHaveTextContent("Project proj-1");
    expect(screen.getByTestId("priority-picker")).toHaveTextContent("Priority high");
    expect(screen.getByTestId("due-date-picker")).toHaveTextContent("Due date 2026-08-01");
  });

  it("writes prompt changes back to the draft store and clears them after submit", async () => {
    const user = userEvent.setup();
    const onClose = vi.fn();

    renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );

    await user.clear(editor);
    await user.type(editor, "New agent prompt");
    expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: "New agent prompt" });

    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith({
        agent_id: "agent-1",
        prompt: "New agent prompt",
        project_id: undefined,
      });
    });

    expect(mockSetLastActor).toHaveBeenCalledWith("agent", "agent-1");
    // A successful create ends the whole unified draft.
    expect(mockClearDraft).toHaveBeenCalled();
    expect(mockSetLastMode).toHaveBeenCalledWith("agent");
    expect(onClose).toHaveBeenCalled();
  });

  it("dictates into the prompt and lets voice send it to the agent", async () => {
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    act(() => {
      expect(voiceOptions.last?.insert("fix the inbox")).toBe(true);
    });
    expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: expect.stringContaining("fix the inbox") });
    act(() => voiceOptions.last?.submit?.());
    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith(
        expect.objectContaining({ agent_id: "agent-1", prompt: expect.stringContaining("fix the inbox") }),
      );
    });
  });

  it("reveals optional fields from the overflow and submits their values", async () => {
    const user = userEvent.setup();

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(screen.queryByTestId("priority-picker")).not.toBeInTheDocument();
    await user.click(screen.getByText("Set priority..."));
    await user.click(screen.getByTestId("priority-picker"));
    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith(
        expect.objectContaining({
          agent_id: "agent-1",
          priority: "high",
        }),
      );
    });
  });

  it("routes Customize fields to Settings → Preferences → Issue creation, keeping the typed prompt", async () => {
    const user = userEvent.setup();
    const onClose = vi.fn();

    renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    fireEvent.change(editor, { target: { value: "Half-typed request" } });
    await user.click(screen.getByRole("button", { name: "Customize fields..." }));

    expect(mockSetAgent).toHaveBeenLastCalledWith({ prompt: "Half-typed request" });
    expect(onClose).toHaveBeenCalled();
    expect(mockNavigationPush).toHaveBeenCalledWith("/ws-test/settings?tab=preferences&section=issue");
  });

  it("respects fields enabled in Settings → Preferences → Issue creation by rendering them inline", () => {
    mockCreateSettingsStore.quickCreateFields = ["project", "priority", "due_date"];

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(screen.getByTestId("project-picker")).toBeInTheDocument();
    expect(screen.getByTestId("priority-picker")).toBeInTheDocument();
    expect(screen.getByTestId("due-date-picker")).toBeInTheDocument();
  });

  it("submits seeded priority and due date as authoritative quick-create fields", async () => {
    const user = userEvent.setup();

    renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
      data: { priority: "urgent", due_date: "2026-08-01" },
    });

    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith(
        expect.objectContaining({
          priority: "urgent",
          due_date: "2026-08-01",
        }),
      );
    });
  });

  // MUL-5181 P0: success may only consume the draft it submitted — the editor
  // stays interactive during the request, so mid-flight edits must survive.
  it("typing draft B while draft A's quick-create is pending survives the success (mounted)", async () => {
    let resolveCreate!: (v: unknown) => void;
    mockQuickCreateIssue.mockImplementationOnce(
      () => new Promise((resolve) => { resolveCreate = resolve; }),
    );
    const onClose = vi.fn();
    renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });
    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    fireEvent.change(editor, { target: { value: "Draft A prompt" } });
    fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));
    await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());

    // Mid-flight edit replaces the singleton draft's object identity.
    mockIssueDraftStore.draft = {
      ...emptyIssueDraft(),
      agent: { ...emptyIssueDraft().agent, prompt: "Draft B prompt" },
    };

    await act(async () => {
      resolveCreate(undefined);
      await Promise.resolve();
    });

    expect(mockClearDraft).not.toHaveBeenCalled();
    expect(onClose).not.toHaveBeenCalled();
    expect(mockIssueDraftStore.draft.agent.prompt).toBe("Draft B prompt");
  });

  // MUL-5181 P0: a submit that outlives its dialog may only consume the draft
  // it submitted — never one typed after closing and reopening.
  it("a late quick-create success does NOT clear a draft replaced after close", async () => {
    let resolveCreate!: (v: unknown) => void;
    mockQuickCreateIssue.mockImplementationOnce(
      () => new Promise((resolve) => { resolveCreate = resolve; }),
    );
    const view = renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    fireEvent.change(editor, { target: { value: "Draft A prompt" } });
    fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));
    await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());

    view.unmount();
    mockIssueDraftStore.draft = {
      ...emptyIssueDraft(),
      agent: { ...emptyIssueDraft().agent, prompt: "Draft B prompt" },
    };

    await act(async () => {
      resolveCreate(undefined);
      await Promise.resolve();
    });

    expect(mockClearDraft).not.toHaveBeenCalled();
    expect(mockIssueDraftStore.draft.agent.prompt).toBe("Draft B prompt");
  });

  it("a late quick-create success still clears an untouched draft", async () => {
    let resolveCreate!: (v: unknown) => void;
    mockQuickCreateIssue.mockImplementationOnce(
      () => new Promise((resolve) => { resolveCreate = resolve; }),
    );
    const view = renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    fireEvent.change(editor, { target: { value: "Draft A prompt" } });
    fireEvent.click(screen.getByRole("button", { name: /^Create$/i }));
    await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalled());

    view.unmount();
    await act(async () => {
      resolveCreate(undefined);
      await Promise.resolve();
    });

    expect(mockClearDraft).toHaveBeenCalled();
  });

  it("passes referenced upload attachment ids to quick-create", async () => {
    const user = userEvent.setup();
    const onClose = vi.fn();

    renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });

    await user.click(screen.getByRole("button", { name: "Mock editor upload" }));
    await waitFor(() => expect(mockApiUploadFile).toHaveBeenCalled());

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    await user.clear(editor);
    fireEvent.change(editor, {
      target: {
        value: "Create issue with ![image](/api/attachments/019ec09d-6222-722b-bdfa-427b105d80be/download)",
      },
    });

    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith({
        agent_id: "agent-1",
        prompt: "Create issue with ![image](/api/attachments/019ec09d-6222-722b-bdfa-427b105d80be/download)",
        project_id: undefined,
        parent_issue_id: undefined,
        attachment_ids: ["019ec09d-6222-722b-bdfa-427b105d80be"],
      });
    });
  });

  // Picking a squad routes the submission through `squad_id` (not
  // `agent_id`) so the backend can resolve the squad's leader agent and
  // inject the squad-leader briefing on dispatch. The persisted preference
  // remembers the actor type so the next open defaults back to the squad.
  it("submits squad_id when the user picks a squad in the actor picker", async () => {
    mockSquadsData.list = [
      { id: "squad-1", name: "Frontend Squad", leader_id: "agent-1", archived_at: null },
    ];
    const user = userEvent.setup();
    const onClose = vi.fn();

    renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });

    // The picker mock renders both sections inline as buttons; click the
    // squad row directly.
    await user.click(pickerRow(/Frontend Squad/));

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    await user.clear(editor);
    await user.type(editor, "Investigate the regression");

    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith({
        squad_id: "squad-1",
        prompt: "Investigate the regression",
        project_id: undefined,
      });
    });
    expect(mockSetLastActor).toHaveBeenCalledWith("squad", "squad-1");
  });

  // Squads whose leader agent isn't visible (archived, private, etc.) must
  // not appear in the picker — the backend would reject the pick on
  // validateAssigneePair, and showing them invites a confusing dead path.
  it("hides squads whose leader agent is not in the visible-agents list", () => {
    mockSquadsData.list = [
      { id: "squad-orphan", name: "Orphan Squad", leader_id: "agent-missing", archived_at: null },
    ];

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(screen.queryByRole("button", { name: /Orphan Squad/ })).toBeNull();
  });

  // A successful create used to persist its project, so the NEXT open
  // re-seeded the pill with it and quietly filed the following issue into the
  // same place. The target project belongs to the issue being filed, not to
  // the user as a standing preference — the actor is the only thing that
  // carries over now (MUL-5862).
  describe("project is not remembered across creates", () => {
    it("ignores a lastProjectId left behind by an older build", () => {
      mockQuickCreateStore.lastProjectId = "proj-1";
      mockProjectsQuery.data = [{ id: "proj-1", title: "Web", icon: null }];
      mockProjectsQuery.isSuccess = true;

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      // Seeding from it is exactly the removed behavior — the pill must be
      // empty, and with no value there is nothing to clear.
      expect(screen.getByTestId("project-picker")).toHaveTextContent("Project none");
      expect(screen.queryByRole("button", { name: "Clear project" })).not.toBeInTheDocument();
    });

    it("still submits the project picked in this session", async () => {
      // Guard against over-removal: dropping the memory must not drop the
      // field from the outgoing request.
      const user = userEvent.setup();
      mockProjectsQuery.data = [{ id: "proj-1", title: "Web", icon: null }];
      mockProjectsQuery.isSuccess = true;

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      await user.click(pickerRow(/Bohan/));
      await user.click(screen.getByTestId("project-picker"));
      await user.type(
        screen.getByPlaceholderText(
          'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
        ),
        "Ship it",
      );
      await user.click(screen.getByRole("button", { name: /^Create$/i }));

      await waitFor(() => {
        expect(mockQuickCreateIssue).toHaveBeenCalledWith(
          expect.objectContaining({ project_id: "proj-1" }),
        );
      });
      // The actor is still remembered — only the project memory is gone.
      expect(mockSetLastActor).toHaveBeenCalledWith("agent", "agent-1");
    });
  });

  // If the unfinished draft points at a project that has been deleted (or
  // moved to another workspace), the modal must not keep submitting that dead
  // UUID. Once the projects query resolves and the id is missing, we clear
  // BOTH local state and the draft; dropping only local state would leave the
  // next open re-seeding the same dead value and trigger the server's
  // `project not found` rejection. The draft is now the only persisted copy —
  // the last-create memory is gone (MUL-5862).
  it("clears a stale drafted project once the projects list resolves without it", async () => {
    mockIssueDraftStore.draft.shared.projectId = "deleted-proj";
    mockProjectsQuery.data = [];
    mockProjectsQuery.isSuccess = true;

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    await waitFor(() => {
      expect(mockSetShared).toHaveBeenCalledWith({ projectId: undefined });
    });
    expect(screen.getByTestId("project-picker")).toHaveTextContent("Project none");
  });

  // Dropping a project used to cost two clicks — open the popover, hit
  // "No project" — because the pill had no clear affordance of its own
  // (MUL-5862). The × is part of the pill, so it only exists once the field
  // has a value to drop.
  describe("project pill quick-clear", () => {
    it("has no × while no project is selected", () => {
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      expect(screen.getByTestId("project-picker")).toHaveTextContent("Project none");
      expect(screen.queryByRole("button", { name: "Clear project" })).not.toBeInTheDocument();
    });

    it("clears local state and the shared draft in one click", async () => {
      const user = userEvent.setup();
      mockIssueDraftStore.draft.shared.projectId = "proj-1";
      mockProjectsQuery.data = [{ id: "proj-1", title: "Web", icon: null }];
      mockProjectsQuery.isSuccess = true;

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
      expect(screen.getByTestId("project-picker")).toHaveTextContent("Project proj-1");

      await user.click(screen.getByRole("button", { name: "Clear project" }));

      expect(screen.getByTestId("project-picker")).toHaveTextContent("Project none");
      expect(mockSetShared).toHaveBeenCalledWith({ projectId: undefined });
      // The × retires with the value it cleared.
      expect(screen.queryByRole("button", { name: "Clear project" })).not.toBeInTheDocument();
    });
  });

  // Mirror case: while the query is still loading, we must NOT preemptively
  // clear the drafted project — that would wipe a perfectly valid selection
  // on every open before the list ever renders.
  it("keeps the drafted project while the projects list is still loading", () => {
    mockIssueDraftStore.draft.shared.projectId = "proj-1";
    mockProjectsQuery.data = [];
    mockProjectsQuery.isSuccess = false;

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

    expect(mockSetShared).not.toHaveBeenCalled();
    expect(screen.getByTestId("project-picker")).toHaveTextContent("Project proj-1");
  });

  it("opens without a project when asked for none, over an unfinished draft's project", () => {
    mockIssueDraftStore.draft.shared.projectId = "proj-1";

    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn(), data: { project_id: null } });

    expect(screen.queryByText("Project proj-1")).toBeNull();
  });

  // When the modal was opened from "Add sub issue" on an existing issue,
  // the manual panel transfers parent_issue_id through the `data` payload
  // on switch-to-agent. The agent panel must forward that UUID to the
  // quick-create API silently — without surfacing a parent picker — so the
  // new issue is filed as a sub-issue. Dropping parent_issue_id here was
  // the original bug; this locks the wiring in.
  it("forwards parent_issue_id from the carry payload to the quick-create API", async () => {
    const user = userEvent.setup();

    renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
      data: {
        parent_issue_id: "parent-uuid-1",
        parent_issue_identifier: "MUL-2534",
      },
    });

    // Sub-issue context chip is visible so the user knows the new issue
    // will be filed as a sub-issue.
    expect(screen.getByTestId("agent-sub-issue-chip")).toBeInTheDocument();

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
    );
    await user.clear(editor);
    await user.type(editor, "Investigate the regression");

    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => {
      expect(mockQuickCreateIssue).toHaveBeenCalledWith({
        agent_id: "agent-1",
        prompt: "Investigate the regression",
        project_id: undefined,
        parent_issue_id: "parent-uuid-1",
      });
    });
  });

  // The sub-issue chip is purely opt-in context — it only appears when the
  // modal was opened from an "Add sub issue" entry. A plain quick-create
  // (no parent in data) must NOT render the chip; otherwise users would see
  // a stray badge on every quick-create.
  it("does not render the sub-issue chip when no parent is seeded", () => {
    renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    expect(screen.queryByTestId("agent-sub-issue-chip")).toBeNull();
  });

  it("keeps captured context separate from the upstream prompt scroller", () => {
    renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
      data: sourceContextPanelData,
    });

    const prompt = screen.getByPlaceholderText(
      'Tell the agent what to do with this context, e.g. "continue investigating and fix the issue described here"',
    ).parentElement;
    const sourceContext = document.querySelector<HTMLElement>('[data-slot="source-context-preview"]');

    expect(prompt).toHaveClass("flex-1", "min-h-[140px]", "overflow-y-auto");
    expect(sourceContext).toHaveClass("shrink-0");
    expect(prompt?.parentElement).toBe(sourceContext?.parentElement);
    expect(prompt?.nextElementSibling).toBe(sourceContext);
    expect(prompt).not.toContainElement(sourceContext);
  });

  it("submits source-context agent create through the dedicated endpoint", async () => {
    const user = userEvent.setup();
    renderPanel({
      onClose: vi.fn(),
      isExpanded: false,
      setIsExpanded: vi.fn(),
      data: {
        ...sourceContextPanelData,
        parent_issue_id: "parent-uuid-1",
        parent_issue_identifier: "MUL-9",
      },
    });

    const editor = screen.getByPlaceholderText(
      'Tell the agent what to do with this context, e.g. "continue investigating and fix the issue described here"',
    );
    await user.clear(editor);
    await user.type(editor, "Investigate with captured context");
    await user.click(screen.getByRole("button", { name: /^Create$/i }));

    await waitFor(() => expect(mockCreateCommentSubIssue).toHaveBeenCalledWith(
      "comment-source",
      {
        mode: "agent",
        capture_token: "sha256:preview-token",
        quick_create: expect.objectContaining({
          agent_id: "agent-1",
          prompt: "Investigate with captured context",
        }),
      },
    ));
    expect(mockQuickCreateIssue).not.toHaveBeenCalled();
  });

  // MUL-4808 — Quick Create already gated Create; these pin the two gaps:
  // the mode switch (which re-serializes the prompt into the manual draft)
  // and the file button that used to lock during an upload for no reason.
  describe("upload submit gate", () => {
    function startPendingUpload() {
      let release!: (result: unknown) => void;
      mockApiUploadFile.mockImplementationOnce(
        () => new Promise((resolve) => { release = resolve; }),
      );
      fireEvent.click(screen.getByRole("button", { name: "Mock editor upload" }));
      return { release: (result: unknown) => release(result) };
    }

    it("blocks Switch to Manual while an upload is in flight", async () => {
      const onSwitchMode = vi.fn();
      renderPanel({ onClose: vi.fn(), onSwitchMode, isExpanded: false, setIsExpanded: vi.fn() });

      startPendingUpload();

      // The switch hands the serialized prompt to the manual panel — mid-upload
      // that prompt has already lost the pending image.
      const switchButton = screen.getByRole("button", { name: /Switch to Manual/i });
      await waitFor(() => expect(switchButton).toBeDisabled());
      fireEvent.click(switchButton);
      expect(onSwitchMode).not.toHaveBeenCalled();
    });

    it("keeps the attach-file button usable during an upload so files can queue", async () => {
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      startPendingUpload();

      // Each file is its own queue entry — making users wait for the first to
      // land before picking the second was a restriction with no race behind
      // it, and this issue explicitly removed it.
      const submit = await screen.findByRole("button", { name: "Uploading..." });
      expect(submit).toBeDisabled();
      expect(screen.getByRole("button", { name: "Upload file" })).not.toBeDisabled();
    });
  });

  // #7633 — a non-admin member's runtime list (ListVisibleAgentRuntimes) omits
  // other members' private machines, so a selected agent can point at a
  // runtime_id that is simply absent from the list the panel sees. That absence
  // used to collapse into "daemon reported no CLI version" and wall the member
  // off with a bogus upgrade prompt — even though the runtime is new enough and
  // the same create succeeds the instant the user is promoted to admin (which
  // only widens the list). The panel must NOT pre-block when it cannot see the
  // runtime at all; the server's version gate (which reads the row by id,
  // regardless of role) stays the trust boundary.
  describe("version pre-check with an unlisted runtime (#7633)", () => {
    it("does not block Create when the selected agent's runtime is not in the visible list", async () => {
      const user = userEvent.setup();
      // Member view: the agent's runtime-1 is a private machine they don't own,
      // so it never appears in their list.
      mockRuntimesData.list = [];

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      await user.click(pickerRow(/Bohan/));

      // No misleading "daemon has no CLI version" wall...
      expect(
        screen.queryByText(/doesn't report a CLI version/i),
      ).not.toBeInTheDocument();
      // ...and Create is reachable (gated only by prompt content, as usual).
      await user.type(
        screen.getByPlaceholderText(
          'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
        ),
        "Ship it",
      );
      const create = screen.getByRole("button", { name: /^Create$/i });
      expect(create).not.toBeDisabled();

      await user.click(create);
      await waitFor(() => expect(mockQuickCreateIssue).toHaveBeenCalledTimes(1));
    });

    it("still blocks a runtime that is visible but genuinely too old", async () => {
      const user = userEvent.setup();
      // The runtime IS in the list and reports a real, below-minimum version —
      // the case the gate exists for. We must keep failing closed here.
      mockRuntimesData.list = [{ id: "runtime-1", metadata: { cli_version: "0.0.1" } }];

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      await user.click(pickerRow(/Bohan/));

      expect(screen.getByText(/Create with agent needs ≥/i)).toBeInTheDocument();
      await user.type(
        screen.getByPlaceholderText(
          'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
        ),
        "Ship it",
      );
      // Blocked but still hoverable so its tooltip can explain why.
      const create = screen.getByRole("button", { name: /^Create$/i });
      expect(create).toHaveAttribute("aria-disabled", "true");
      await user.click(create);
      expect(mockQuickCreateIssue).not.toHaveBeenCalled();
    });
  });


  // ref can gate it. Mirrors the manual-create regression.
  describe("send shortcut single-flight", () => {
    it("creates once when the send chord fires twice in the same tick", async () => {
      // Hold the request open so both presses land inside the in-flight window.
      let release!: (v: unknown) => void;
      mockQuickCreateIssue.mockImplementationOnce(
        () => new Promise((resolve) => { release = resolve; }),
      );

      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      const editor = screen.getByPlaceholderText(
        'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"',
      );

      // Both presses inside ONE act: React cannot re-render between them, so
      // the second handler still closes over `submitting === false`. fireEvent
      // would flush in between and hide the race entirely.
      await act(async () => {
        const press = () =>
          editor.dispatchEvent(
            new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true }),
          );
        press();
        press();
      });

      await act(async () => { release(undefined); });

      expect(mockQuickCreateIssue).toHaveBeenCalledTimes(1);
    });
  });

  // MUL-6236 — the footer reflows to a 2x2 grid on phones. jsdom has no
  // layout, so these pin the two structural preconditions the grid depends
  // on rather than the rendered geometry.
  describe("phone footer layout", () => {
    beforeEach(() => {
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });
    });

    it("keeps every footer control a direct child of the grid container", () => {
      const switchToManual = screen.getByRole("button", { name: /Switch to Manual/i });
      const create = screen.getByRole("button", { name: /^Create$/i });
      const keepOpen = screen.getByRole("checkbox");
      const attach = screen.getByRole("button", { name: "Upload file" });

      const footer = switchToManual.parentElement;
      expect(footer?.className).toContain("grid-cols-[auto_1fr]");
      // From `sm` up the same children lay out as the original single row.
      expect(footer?.className).toContain("sm:flex");

      // Grid placement only sees direct children: re-wrapping any of these in
      // a <div> collapses the 2x2 back to the jammed single row the bug
      // report showed. The attach button keeps its own wrapper because it can
      // gain a "N sent" badge — that wrapper is itself the first grid cell.
      expect(create.parentElement).toBe(footer);
      expect(keepOpen.parentElement?.parentElement).toBe(footer);
      expect(attach.parentElement?.parentElement).toBe(footer);
      expect(attach).not.toHaveAttribute("data-size");
    });
  });

  // MUL-10012 — the three most used actors sit next to "Created by" as chips,
  // ranked by how many issues each has filed, and ⌥1–⌥3 pick them.
  describe("quick-switch chips", () => {
    const agent = (id: string, name: string) => ({ id, name, archived_at: null, runtime_id: "runtime-1" });
    const PROMPT_PLACEHOLDER =
      'Tell the agent what to do, e.g. "fix the slow inbox loading in the Web project"';

    beforeEach(() => {
      mockAgentsData.list = [
        agent("agent-1", "Bohan"),
        agent("agent-2", "Ada"),
        agent("agent-3", "Cyd"),
        agent("agent-4", "Dex"),
      ];
      mockQuickCreateStore.actorCreateCounts = { "agent:agent-3": 5, "agent:agent-4": 2 };
    });

    const chips = () =>
      within(screen.getByRole("group", { name: "Frequently used" })).getAllByRole("button");
    const chipNames = () => chips().map((el) => el.textContent);
    const pressedChip = () => chips().find((el) => el.getAttribute("aria-pressed") === "true");

    it("ranks the chips by create count and fills the rest in list order", () => {
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      expect(chipNames()).toEqual(["Cyd", "Dex", "Bohan"]);
      // With no draft or last pick, the default actor is the first agent.
      expect(pressedChip()).toHaveTextContent("Bohan");
    });

    it("submits with the chip the user clicked", async () => {
      const user = userEvent.setup();
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      await user.click(screen.getByRole("button", { name: "Dex", pressed: false }));
      expect(pressedChip()).toHaveTextContent("Dex");

      await user.type(screen.getByPlaceholderText(PROMPT_PLACEHOLDER), " now");
      await user.click(screen.getByRole("button", { name: /^Create$/i }));

      await waitFor(() => {
        expect(mockQuickCreateIssue).toHaveBeenCalledWith(
          expect.objectContaining({ agent_id: "agent-4" }),
        );
      });
      expect(mockCountActorCreate).toHaveBeenCalledWith("agent", "agent-4");
    });

    it("picks a chip with ⌥ + its position, even from inside the prompt", () => {
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      const notPrevented = fireEvent.keyDown(screen.getByPlaceholderText(PROMPT_PLACEHOLDER), {
        key: "2",
        code: "Digit2",
        altKey: true,
      });

      expect(notPrevented).toBe(false);
      expect(pressedChip()).toHaveTextContent("Dex");
      expect(mockIssueDraftStore.draft.agent).toEqual(
        expect.objectContaining({ actorType: "agent", actorId: "agent-4" }),
      );
    });

    it("leaves ⌥ + a digit past the chips to the editor", () => {
      mockAgentsData.list = [agent("agent-1", "Bohan")];
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      const notPrevented = fireEvent.keyDown(screen.getByPlaceholderText(PROMPT_PLACEHOLDER), {
        key: "2",
        code: "Digit2",
        altKey: true,
      });

      expect(notPrevented).toBe(true);
    });

    it("shows a pick from the full list as its own chip without moving the ranked ones", async () => {
      const user = userEvent.setup();
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      await user.click(pickerRow(/Ada/));

      expect(chipNames()).toEqual(["Cyd", "Dex", "Bohan", "Ada"]);
      expect(pressedChip()).toHaveTextContent("Ada");
    });

    it("keeps the chip order fixed while the dialog stays open", async () => {
      const user = userEvent.setup();
      renderPanel({ onClose: vi.fn(), isExpanded: false, setIsExpanded: vi.fn() });

      mockQuickCreateStore.actorCreateCounts = { "agent:agent-1": 50 };
      // Any re-render reads the store again; the ranking must not.
      await user.type(screen.getByPlaceholderText(PROMPT_PLACEHOLDER), "x");

      expect(chipNames()).toEqual(["Cyd", "Dex", "Bohan"]);
    });
  });
});