mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
Merge origin/master into feat/antigravity-swarm-command
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * origin/master: refactor(plugin-sdk): remove archivedState from the resume result (#22443) refactor(runner): let the provider decide whether a released Runner relaunches (#22442) fix(connections): drop MCP wording and the MCP guide link from Google Workspace setup (#22793) fix(ui): defer the Connectors announcement until a return visit (#22790) fix(connections): show only the privacy policy link in the Google Workspace picker (#22795) Add count, newest-first and lean run reads to customer-success inspection (#22781) fix(connections): keep a finished setup checklist on screen when the app refreshes queries (#22715) perf(ci): Phase 2 PR CI under 4 minutes (dynamic workers, fast E2E boot, typecheck overlap, test-budget gate) (#22729) fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
This commit is contained in:
commit
3cbfa500f4
142 files changed
+5552
-11636
No files matched your search
@@ -1,167 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { appearanceForPalette } from "@paperclipai/shared";
|
||||
import { AgentChatPicker, type AgentChatPickerProps } from "./AgentChatPicker";
|
||||
|
||||
const agents = [
|
||||
{ id: "first", name: "Alex", title: "Engineering Lead", role: "engineer", icon: "code", status: "idle" },
|
||||
{ id: "second", name: "Alex", title: "Product Designer", role: "designer", icon: "palette", status: "paused" },
|
||||
] as Agent[];
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
let props: AgentChatPickerProps;
|
||||
async function render(overrides: Partial<AgentChatPickerProps> = {}) {
|
||||
props = { ...props, ...overrides };
|
||||
await act(async () => { root.render(<AgentChatPicker {...props} />); });
|
||||
}
|
||||
async function search(value: string) {
|
||||
const input = document.querySelector<HTMLInputElement>("[role=combobox]")!;
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
}
|
||||
const options = () => [...document.querySelectorAll<HTMLElement>("[role=option]")];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
props = { agents, open: true, onOpenChange: vi.fn(), onSelect: vi.fn() };
|
||||
});
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("AgentChatPicker", () => {
|
||||
it("shows unread per agent through search and clears it when read state updates", async () => {
|
||||
await render({ existingChatAgentIds: ["first", "second"], unreadMessageCounts: new Map([["first", 0], ["second", 12]]) });
|
||||
expect(options()[0].querySelector('[aria-label*="unread message"]')).toBeNull();
|
||||
expect(options()[1].querySelector('[aria-label="12 unread messages from Alex"]')?.textContent).toBe("12");
|
||||
await search("designer");
|
||||
expect(options()).toHaveLength(1);
|
||||
expect(options()[0].textContent).toContain("12");
|
||||
await render({ unreadMessageCounts: new Map([["second", 0]]) });
|
||||
expect(options()[0].textContent).not.toContain("12");
|
||||
expect(options()[0].textContent).toContain("Open chat");
|
||||
});
|
||||
|
||||
it("uses indexed counts and memoized chat membership for a large team", async () => {
|
||||
const roster = Array.from({ length: 500 }, (_, index) => ({ ...agents[index % 2], id: `agent-${index}`, name: `Agent ${index}` }));
|
||||
let visits = 0;
|
||||
const ids = roster.map(agent => agent.id);
|
||||
const boundedIds = new Proxy(ids, { get(target, key, receiver) {
|
||||
if (typeof key === "string" && /^\d+$/.test(key) && ++visits > ids.length * 2) throw new Error("Repeated chat membership scan");
|
||||
return Reflect.get(target, key, receiver);
|
||||
} });
|
||||
const counts = new Map(ids.map(id => [id, 7]));
|
||||
const getCount = vi.spyOn(counts, "get");
|
||||
await render({ agents: roster, existingChatAgentIds: boundedIds, unreadMessageCounts: counts });
|
||||
expect(options()).toHaveLength(500);
|
||||
expect(document.querySelectorAll('[aria-label^="7 unread messages from"]')).toHaveLength(500);
|
||||
expect(visits).toBe(500);
|
||||
expect(getCount).toHaveBeenCalledTimes(500);
|
||||
await search("Agent 499");
|
||||
expect(options().length).toBeLessThan(500);
|
||||
expect(options().some(option => option.textContent?.includes("Agent 499"))).toBe(true);
|
||||
expect(visits).toBe(500);
|
||||
expect(getCount).toHaveBeenCalledTimes(1000);
|
||||
});
|
||||
|
||||
it("shows saved custom avatars and default avatars in agent choices", async () => {
|
||||
await render({ agents: [
|
||||
{ ...agents[0], appearance: { ...appearanceForPalette("deep-tide"), customAvatarAssetId: "22222222-2222-4222-8222-222222222222" } },
|
||||
agents[1],
|
||||
] });
|
||||
const customImage = options()[0].querySelector("img");
|
||||
expect(customImage?.getAttribute("src")).toBe("/api/assets/22222222-2222-4222-8222-222222222222/content");
|
||||
expect(customImage?.getAttribute("width")).toBe("32");
|
||||
expect(options()[1].querySelector("img")?.getAttribute("src")).toMatch(/^\/api\/agent-avatars\/cap-v1\//);
|
||||
});
|
||||
|
||||
it("lets a custom renderer replace the default avatar", async () => {
|
||||
await render({ renderAgentIcon: agent => <span>{agent.title} marker</span> });
|
||||
expect(options()[0].textContent).toContain("Engineering Lead marker");
|
||||
expect(options()[1].textContent).toContain("Product Designer marker");
|
||||
expect(options().flatMap(option => [...option.querySelectorAll("img")])).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not close a reopened picker when an earlier selection finishes", async () => {
|
||||
let finish!: () => void;
|
||||
await render({ onSelect: () => new Promise<void>(resolve => { finish = resolve; }) });
|
||||
await act(async () => options()[0].click());
|
||||
await render({ open: false });
|
||||
await render({ open: true });
|
||||
await search("designer");
|
||||
await act(async () => finish());
|
||||
expect(props.onOpenChange).not.toHaveBeenCalled();
|
||||
expect(document.querySelector<HTMLInputElement>("[role=combobox]")!.value).toBe("designer");
|
||||
expect(options()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("searches by role and selects the correct same-name agent with Enter", async () => {
|
||||
await render();
|
||||
expect(options()).toHaveLength(2);
|
||||
await search("designer");
|
||||
expect(options()).toHaveLength(1);
|
||||
expect(options()[0].textContent).toContain("Paused");
|
||||
await act(async () => {
|
||||
document.querySelector("[role=combobox]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
expect(props.onSelect).toHaveBeenCalledWith(agents[1], expect.any(AbortSignal));
|
||||
expect(props.onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("distinguishes existing conversations and selects the same agent when reopened", async () => {
|
||||
await render({ existingChatAgentIds: ["first"] });
|
||||
expect(options()[0].textContent).toContain("Open chat");
|
||||
expect(options()[1].textContent).toContain("New chat");
|
||||
await search("designer");
|
||||
await act(async () => options()[0].click());
|
||||
expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal));
|
||||
await render({ open: false });
|
||||
await render({ open: true, existingChatAgentIds: ["first", "second"] });
|
||||
await search("designer");
|
||||
expect(options()[0].textContent).toContain("Open chat");
|
||||
expect(options()[0].textContent).not.toContain("New chat");
|
||||
await act(async () => options()[0].click());
|
||||
expect(props.onSelect).toHaveBeenLastCalledWith(agents[1], expect.any(AbortSignal));
|
||||
});
|
||||
|
||||
it("recovers from no results and resets search when reopened", async () => {
|
||||
await render();
|
||||
await search("accountant");
|
||||
expect(options()).toHaveLength(0);
|
||||
expect(document.body.textContent).toContain("No agents match");
|
||||
const clear = [...document.querySelectorAll("button")].find((b) => b.textContent === "Clear search")!;
|
||||
await act(async () => clear.click());
|
||||
expect(options()).toHaveLength(2);
|
||||
await search("designer");
|
||||
await render({ open: false });
|
||||
await render({ open: true });
|
||||
expect(document.querySelector<HTMLInputElement>("[role=combobox]")!.value).toBe("");
|
||||
expect(options()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("shows loading, a retryable error, and an empty roster without stale choices", async () => {
|
||||
await render({ loading: true });
|
||||
expect(document.querySelector("[role=status]")?.textContent).toContain("Loading agents");
|
||||
expect(options()).toHaveLength(0);
|
||||
const retry = vi.fn();
|
||||
await render({ loading: false, error: new Error("Unavailable"), onRetry: retry });
|
||||
expect(document.querySelector("[role=alert]")?.textContent).toContain("Couldn’t load agents");
|
||||
expect(options()).toHaveLength(0);
|
||||
await act(async () => [...document.querySelectorAll("button")].find((b) => b.textContent === "Retry")!.click());
|
||||
expect(retry).toHaveBeenCalledOnce();
|
||||
await render({ error: null, agents: [] });
|
||||
expect(document.body.textContent).toContain("Create an agent from the Agents page");
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AgentMultiSelect, AgentSelect } from "./AgentMultiSelect";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> | undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
function setInputValue(input: HTMLInputElement, value: string) {
|
||||
act(() => {
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
|
||||
valueSetter?.call(input, value);
|
||||
input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" }));
|
||||
});
|
||||
}
|
||||
|
||||
describe("AgentMultiSelect", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root | null;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => {
|
||||
root?.unmount();
|
||||
});
|
||||
}
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("keeps agent lists compact and searchable", async () => {
|
||||
const onChange = vi.fn();
|
||||
const agents = Array.from({ length: 20 }, (_, index) => ({
|
||||
id: `agent-${index}`,
|
||||
name: index === 17 ? "Search Target" : `Agent ${index}`,
|
||||
title: `Role ${index}`,
|
||||
}));
|
||||
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<AgentMultiSelect agents={agents} selectedAgentIds={new Set()} onChange={onChange} />,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toBe("Select agents");
|
||||
expect(document.body.textContent).not.toContain("Agent 0");
|
||||
|
||||
act(() => {
|
||||
container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const filter = document.body.querySelector<HTMLInputElement>('input[placeholder="Filter agents"]');
|
||||
expect(filter).not.toBeNull();
|
||||
setInputValue(filter!, "search target");
|
||||
await flush();
|
||||
|
||||
expect(document.body.textContent).toContain("Search Target");
|
||||
expect(document.body.textContent).not.toContain("Agent 0");
|
||||
|
||||
act(() => {
|
||||
document.body
|
||||
.querySelector('[aria-label="Allow Search Target"]')
|
||||
?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1);
|
||||
expect(onChange.mock.calls[0]?.[0]).toEqual(new Set(["agent-17"]));
|
||||
});
|
||||
|
||||
it("filters and selects a single agent", async () => {
|
||||
const onChange = vi.fn();
|
||||
const agents = [
|
||||
{ id: "agent-1", name: "Alpha", title: "Engineer" },
|
||||
{ id: "agent-2", name: "Bravo", title: "Researcher" },
|
||||
];
|
||||
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(<AgentSelect agents={agents} value="" onChange={onChange} />);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const filter = document.body.querySelector<HTMLInputElement>('input[placeholder="Filter agents"]');
|
||||
expect(filter).not.toBeNull();
|
||||
setInputValue(filter!, "research");
|
||||
await flush();
|
||||
|
||||
expect(document.body.textContent).toContain("Bravo");
|
||||
expect(document.body.textContent).not.toContain("Alpha");
|
||||
|
||||
act(() => {
|
||||
document.body
|
||||
.querySelector('[aria-label="Select Bravo"]')
|
||||
?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith("agent-2");
|
||||
expect(document.body.querySelector('input[placeholder="Filter agents"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the same agent avatar in the selected value and every option", async () => {
|
||||
const agents = [{ id: "agent-1", name: "Ralph" }, { id: "agent-2", name: "Support" }];
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(<AgentSelect agents={agents} value="agent-1" onChange={vi.fn()} />));
|
||||
const selected = container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src");
|
||||
expect(selected).toBeTruthy();
|
||||
act(() => container.querySelector("button")?.click());
|
||||
await flush();
|
||||
expect(document.querySelector('[aria-label="Select Ralph"] [data-slot="agent-avatar"] img')?.getAttribute("src")).toBe(selected);
|
||||
expect(document.querySelector('[aria-label="Select Support"] [data-slot="agent-avatar"] img')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("previews selected agents and stages changes until save", async () => {
|
||||
const onSave = vi.fn();
|
||||
const agents = Array.from({ length: 6 }, (_, index) => ({
|
||||
id: `agent-${index}`,
|
||||
name: `Agent ${index}`,
|
||||
}));
|
||||
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<AgentMultiSelect
|
||||
agents={agents}
|
||||
selectedAgentIds={new Set(["agent-0", "agent-1", "agent-2", "agent-3", "agent-4"])}
|
||||
onSave={onSave}
|
||||
triggerLabel="Add to agent"
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Agent 0");
|
||||
expect(container.textContent).toContain("Agent 2");
|
||||
expect(container.textContent).toContain("and 2 more");
|
||||
expect(container.textContent).not.toContain("Agent 4");
|
||||
|
||||
act(() => {
|
||||
container.querySelector("button")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
act(() => {
|
||||
document.body
|
||||
.querySelector('[aria-label="Allow Agent 5"]')
|
||||
?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(onSave).not.toHaveBeenCalled();
|
||||
const save = Array.from(document.body.querySelectorAll("button")).find((button) => button.textContent === "Save");
|
||||
act(() => {
|
||||
save?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(new Set(agents.map((agent) => agent.id)));
|
||||
});
|
||||
});
|
||||
@@ -169,6 +169,44 @@ describe("agent setup progress", () => {
|
||||
const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
const token = () => container.querySelector('[data-testid="token"]')?.textContent;
|
||||
|
||||
it("keeps a finished checklist on screen when the app refreshes every query", async () => {
|
||||
const done: AgentSetupProgress = { ...WAITING, status: "done", summary: "Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1",
|
||||
items: [{ key: "create-role", title: "Create the role", status: "done", detail: null }] };
|
||||
const create = vi.fn().mockResolvedValue(HANDOFF);
|
||||
let status: "waiting" | "done" = "waiting";
|
||||
const client: AgentSetupProgressClient = { create, get: vi.fn(async () => status === "done" ? done : WAITING) };
|
||||
await act(async () => { root.render(<QueryClientProvider client={queryClient}><Full client={client} /></QueryClientProvider>); });
|
||||
await flush();
|
||||
status = "done";
|
||||
await act(async () => { await queryClient.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); });
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Your agent set up AWS"));
|
||||
// The live connection reconnects or the tab returns: the app refreshes every query on screen.
|
||||
await act(async () => { await queryClient.invalidateQueries({ type: "active" }); });
|
||||
await flush();
|
||||
expect(create).toHaveBeenCalledOnce();
|
||||
expect(token()).toBe("pcsp_token");
|
||||
expect(container.textContent).toContain("Your agent set up AWS");
|
||||
expect(container.textContent).toContain("Role ARN: arn:aws:iam::123456789012:role/paperclip-conn-1");
|
||||
});
|
||||
|
||||
it("still creates a fresh checklist when Start again's first create fails and its retry succeeds", async () => {
|
||||
const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission",
|
||||
items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] };
|
||||
const second: AgentSetupProgressHandoff = { ...HANDOFF, token: "pcsp_after_retry", progress: { ...WAITING, id: "88888888-8888-4888-8888-888888888888" } };
|
||||
const create = vi.fn().mockResolvedValueOnce(HANDOFF).mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(second);
|
||||
const client: AgentSetupProgressClient = { create, get: vi.fn(async (id: string) => id === ID ? failedAttempt : second.progress) };
|
||||
// The app's queries retry a failed request; this one retries once, at once.
|
||||
const retrying = new QueryClient({ defaultOptions: { queries: { retry: 1, retryDelay: 0 } } });
|
||||
await act(async () => { root.render(<QueryClientProvider client={retrying}><Full client={client} /></QueryClientProvider>); });
|
||||
await flush();
|
||||
await act(async () => { await retrying.invalidateQueries({ queryKey: queryKeys.agentSetupProgress(ID) }); });
|
||||
await vi.waitFor(() => expect(container.textContent).toContain("Your agent couldn’t finish setting up AWS"));
|
||||
const startAgain = [...container.querySelectorAll("button")].find((b) => b.textContent === "Start again")!;
|
||||
await act(async () => { startAgain.click(); });
|
||||
await vi.waitFor(() => expect(token()).toBe("pcsp_after_retry"));
|
||||
expect(create).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("offers a fresh checklist after a failed attempt, and opening the step again later starts fresh", async () => {
|
||||
const failedAttempt: AgentSetupProgress = { ...WAITING, status: "failed", summary: "Stopped: no permission",
|
||||
items: [{ key: "deploy", title: "Create the role", status: "failed", detail: "iam:CreateRole denied" }] };
|
||||
|
||||
@@ -73,12 +73,21 @@ export function useAgentSetupProgress({
|
||||
const accountFailed = !accountOverride && account.failed;
|
||||
const handoffKey = ["agent-setup-progress-handoff", accountId, companyId ?? null, purpose, subjectId ?? null] as const;
|
||||
const storageKey = agentSetupHandoffStorageKey(accountId, companyId, purpose, subjectId);
|
||||
// Set by renew and kept until a new checklist is created, so a retry of a failed create still
|
||||
// creates rather than returning the checklist being replaced.
|
||||
const replacing = useRef(false);
|
||||
const handoffQuery = useQuery({
|
||||
queryKey: handoffKey,
|
||||
queryFn: async () => {
|
||||
// Any other refetch (the app refreshes every query on screen when its live connection
|
||||
// reconnects or the tab returns) keeps the checklist on screen. A finished one is no longer
|
||||
// in storage, so falling through here would replace it with a blank checklist.
|
||||
const current = queryClient.getQueryData<{ handoff: AgentSetupProgressHandoff; fromEarlierVisit: boolean }>(handoffKey);
|
||||
if (current && !replacing.current) return current;
|
||||
// A handoff found in this tab's storage came from an earlier visit; a created one is new.
|
||||
const stored = storedAgentSetupHandoff(storageKey);
|
||||
const handoff = stored ?? await client.create(companyId!, { purpose, ...(subjectId ? { subjectId } : {}) });
|
||||
replacing.current = false;
|
||||
storeAgentSetupHandoff(storageKey, handoff);
|
||||
return { handoff, fromEarlierVisit: Boolean(stored) };
|
||||
},
|
||||
@@ -115,6 +124,7 @@ export function useAgentSetupProgress({
|
||||
return;
|
||||
}
|
||||
storeAgentSetupHandoff(storageKey, null);
|
||||
replacing.current = true;
|
||||
void handoffQuery.refetch();
|
||||
};
|
||||
|
||||
|
||||
@@ -29,11 +29,6 @@ export function useModalOpen(enabled: boolean, selector = MODAL_SELECTOR) {
|
||||
|
||||
const FINISHED_ONBOARDING_STATUSES = new Set(["done", "cancelled"]);
|
||||
|
||||
/**
|
||||
* A new user's first session is the onboarding first task. Announcements and
|
||||
* other optional prompts wait until that task is finished so they cannot cover
|
||||
* its questions. Unknown state (loading or a failed read) keeps them hidden.
|
||||
*/
|
||||
export function useOnboardingInProgress(companyId: string | null) {
|
||||
const query = useQuery({
|
||||
queryKey: queryKeys.issues.onboardingFirstTask(companyId ?? "__none__"),
|
||||
|
||||
@@ -1,254 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ChatComposer, type ChatComposerProps } from "./ChatComposer";
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
/** Stateful harness so the controlled textarea reflects typed input. */
|
||||
function Harness(props: Partial<ChatComposerProps> & { initial?: string }) {
|
||||
const { initial = "", onChange, ...rest } = props;
|
||||
const [value, setValue] = useState(initial);
|
||||
return (
|
||||
<ChatComposer
|
||||
value={value}
|
||||
onChange={(v) => {
|
||||
setValue(v);
|
||||
onChange?.(v);
|
||||
}}
|
||||
onSubmit={rest.onSubmit ?? (() => {})}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function typeInput(textarea: HTMLTextAreaElement, text: string) {
|
||||
const setter = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLTextAreaElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
setter?.call(textarea, text);
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
describe("ChatComposer", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function input() {
|
||||
return container.querySelector<HTMLTextAreaElement>('[data-testid="chat-composer-input"]')!;
|
||||
}
|
||||
function sendButton() {
|
||||
return container.querySelector<HTMLButtonElement>('button[aria-label="Send message"]')!;
|
||||
}
|
||||
function attachButton() {
|
||||
return container.querySelector<HTMLButtonElement>('button[aria-label="Attach files"]');
|
||||
}
|
||||
|
||||
it("renders a bare textarea + send and no attach button without a handler", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness placeholder="Ask anything…" />);
|
||||
});
|
||||
expect(input()).toBeTruthy();
|
||||
expect(input().placeholder).toBe("Ask anything…");
|
||||
expect(attachButton()).toBeNull();
|
||||
// No formatting toolbar — there is exactly one button (send) when bare.
|
||||
expect(container.querySelectorAll("button").length).toBe(1);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("shows the attach affordance when onAttachFiles is provided", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness onAttachFiles={() => {}} />);
|
||||
});
|
||||
expect(attachButton()).toBeTruthy();
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("disables send while empty and enables it once there is text", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
expect(sendButton().disabled).toBe(true);
|
||||
act(() => {
|
||||
typeInput(input(), "hello");
|
||||
});
|
||||
expect(sendButton().disabled).toBe(false);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("submits on click", () => {
|
||||
const onSubmit = vi.fn();
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness onSubmit={onSubmit} initial="hi" />);
|
||||
});
|
||||
act(() => {
|
||||
sendButton().dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('submitKey="enter": plain Enter submits, Shift+Enter does not', () => {
|
||||
const onSubmit = vi.fn();
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness onSubmit={onSubmit} initial="hi" submitKey="enter" />);
|
||||
});
|
||||
act(() => {
|
||||
input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, shiftKey: true }));
|
||||
});
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('submitKey="mod-enter": plain Enter does not submit, Cmd/Ctrl+Enter does', () => {
|
||||
const onSubmit = vi.fn();
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness onSubmit={onSubmit} initial="hi" submitKey="mod-enter" />);
|
||||
});
|
||||
act(() => {
|
||||
input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, metaKey: true }));
|
||||
});
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("singleLine strips newlines from input", () => {
|
||||
const onChange = vi.fn();
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness singleLine onChange={onChange} />);
|
||||
});
|
||||
act(() => {
|
||||
typeInput(input(), "one\ntwo");
|
||||
});
|
||||
expect(onChange).toHaveBeenLastCalledWith("one two");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("default (multiline) mode soft-wraps and auto-grows instead of clipping (PAP-116)", () => {
|
||||
// The conference room composer adopts this default mode. Text must wrap and
|
||||
// the box grow up to a cap — never clip horizontally or show an idle scrollbar.
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
const el = input();
|
||||
expect(el.getAttribute("wrap")).toBe("soft");
|
||||
expect(el.className).toContain("overflow-y-auto");
|
||||
expect(el.className).toContain("max-h-(--sz-200px)");
|
||||
expect(el.className).not.toContain("whitespace-nowrap");
|
||||
expect(el.className).not.toContain("overflow-x-auto");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("singleLine mode clips to one row (opt-in only)", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness singleLine />);
|
||||
});
|
||||
const el = input();
|
||||
expect(el.getAttribute("wrap")).toBe("off");
|
||||
expect(el.className).toContain("whitespace-nowrap");
|
||||
expect(el.className).toContain("max-h-(--sz-22px)");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('tone="planning" is reflected on the container', () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness tone="planning" />);
|
||||
});
|
||||
const box = container.querySelector('[data-testid="chat-composer"]');
|
||||
expect(box?.getAttribute("data-tone")).toBe("planning");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('tone="ask" is reflected on the container', () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness tone="ask" />);
|
||||
});
|
||||
const box = container.querySelector('[data-testid="chat-composer"]');
|
||||
expect(box?.getAttribute("data-tone")).toBe("ask");
|
||||
expect(box?.className).toContain("sky");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('defaults to the opaque "card" surface', () => {
|
||||
// PAP-131: surface is opt-in — existing adopters keep the bg-card box.
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness />);
|
||||
});
|
||||
const box = container.querySelector('[data-testid="chat-composer"]')!;
|
||||
expect(box.getAttribute("data-surface")).toBe("card");
|
||||
expect(box.className).toContain("bg-card");
|
||||
expect(box.className).not.toContain("backdrop-blur");
|
||||
// Rounded corners are shared chrome on both surfaces.
|
||||
expect(box.className).toContain("rounded-xl");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it('surface="translucent" applies the task glass recipe and keeps shared chrome (PAP-131)', () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness surface="translucent" />);
|
||||
});
|
||||
const box = container.querySelector('[data-testid="chat-composer"]')!;
|
||||
expect(box.getAttribute("data-surface")).toBe("translucent");
|
||||
// Glass recipe — mirrors the task-comments composer shell.
|
||||
expect(box.className).toContain("bg-background/95");
|
||||
expect(box.className).toContain("supports-[backdrop-filter]:bg-background/85");
|
||||
expect(box.className).toContain("backdrop-blur");
|
||||
expect(box.className).toContain("shadow-(--shadow-extract-4)");
|
||||
expect(box.className).toContain("dark:shadow-(--shadow-extract-5)");
|
||||
expect(box.className).not.toContain("bg-card");
|
||||
// Shared chrome survives: rounded-xl corners + neutral focus darkening.
|
||||
expect(box.className).toContain("rounded-xl");
|
||||
expect(box.className).toContain("focus-within:border-muted-foreground/40");
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("translucent surface keeps the drag-over attach layering", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness surface="translucent" onAttachFiles={() => {}} />);
|
||||
});
|
||||
const box = container.querySelector<HTMLDivElement>('[data-testid="chat-composer"]')!;
|
||||
act(() => {
|
||||
const dataTransfer = { types: ["Files"], dropEffect: "none" };
|
||||
const evt = new Event("dragenter", { bubbles: true }) as DragEvent & {
|
||||
dataTransfer: typeof dataTransfer;
|
||||
};
|
||||
Object.defineProperty(evt, "dataTransfer", { value: dataTransfer });
|
||||
box.dispatchEvent(evt);
|
||||
});
|
||||
expect(container.querySelector('[data-testid="chat-composer-drop-overlay"]')).toBeTruthy();
|
||||
act(() => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -1,302 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DocumentAnnotationLayer } from "./DocumentAnnotationLayer";
|
||||
|
||||
const mockBuildAnchorFromContainerSelection = vi.hoisted(() => vi.fn());
|
||||
const mockGetContainerTextOffset = vi.hoisted(() => vi.fn());
|
||||
const mockRangesForNormalizedSpan = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/lib/document-annotation-selection", () => ({
|
||||
buildAnchorFromContainerSelection: mockBuildAnchorFromContainerSelection,
|
||||
getContainerTextOffset: mockGetContainerTextOffset,
|
||||
rangesForNormalizedSpan: mockRangesForNormalizedSpan,
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
await callback();
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function makeRect(left: number, top: number, width: number, height: number): DOMRect {
|
||||
return {
|
||||
x: left,
|
||||
y: top,
|
||||
left,
|
||||
top,
|
||||
right: left + width,
|
||||
bottom: top + height,
|
||||
width,
|
||||
height,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect;
|
||||
}
|
||||
|
||||
function makeRange(rects: DOMRect[], commonAncestorContainer: Node = document.createTextNode("")): Range {
|
||||
return {
|
||||
commonAncestorContainer,
|
||||
getClientRects: () => rects,
|
||||
} as unknown as Range;
|
||||
}
|
||||
|
||||
describe("DocumentAnnotationLayer", () => {
|
||||
let container: HTMLDivElement;
|
||||
let rectSpy: ReturnType<typeof vi.spyOn>;
|
||||
let root: Root | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 12, 80, 18)])]);
|
||||
rectSpy = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(makeRect(0, 0, 400, 300));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await act(() => root?.unmount());
|
||||
root = null;
|
||||
}
|
||||
rectSpy.mockRestore();
|
||||
container.remove();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("uses borderless token-driven overlay boxes for annotation highlight states", async () => {
|
||||
const body = document.createElement("div");
|
||||
body.textContent = "Annotated body text.";
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<DocumentAnnotationLayer
|
||||
containerRef={{ current: body }}
|
||||
markdown="Annotated body text."
|
||||
threads={[
|
||||
{ id: "active", selectedText: "Annotated", status: "open", anchorState: "active" },
|
||||
{ id: "focused", selectedText: "body", status: "open", anchorState: "active" },
|
||||
{ id: "stale", selectedText: "text", status: "open", anchorState: "stale" },
|
||||
{ id: "resolved", selectedText: "body text", status: "resolved", anchorState: "active" },
|
||||
]}
|
||||
focusedThreadId="focused"
|
||||
onThreadFocus={vi.fn()}
|
||||
pendingAnchor={null}
|
||||
onPendingAnchorChange={vi.fn()}
|
||||
onRequestComment={vi.fn()}
|
||||
hideResolved={false}
|
||||
/>,
|
||||
);
|
||||
await new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
});
|
||||
|
||||
const highlights = Array.from(container.querySelectorAll(".paperclip-doc-annotation-highlight"));
|
||||
expect(highlights).toHaveLength(4);
|
||||
|
||||
for (const highlight of highlights) {
|
||||
expect(highlight.className).toBe("paperclip-doc-annotation-highlight absolute");
|
||||
expect(highlight.className).not.toContain("outline");
|
||||
expect(highlight.className).not.toContain("shadow");
|
||||
}
|
||||
expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "focused")
|
||||
?.getAttribute("data-focused")).toBe("true");
|
||||
expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "stale")
|
||||
?.getAttribute("data-anchor-state")).toBe("stale");
|
||||
expect(highlights.find((highlight) => highlight.getAttribute("data-thread-id") === "resolved")
|
||||
?.getAttribute("data-status")).toBe("resolved");
|
||||
});
|
||||
|
||||
it("does not render highlights for text clipped by folded document content", async () => {
|
||||
const body = document.createElement("div");
|
||||
const clippedContent = document.createElement("div");
|
||||
clippedContent.className = "fold-curtain__content";
|
||||
const hiddenText = document.createTextNode("Hidden folded text");
|
||||
clippedContent.appendChild(hiddenText);
|
||||
body.appendChild(clippedContent);
|
||||
mockRangesForNormalizedSpan.mockReturnValue([makeRange([makeRect(8, 60, 80, 18)], hiddenText)]);
|
||||
rectSpy.mockImplementation(function (this: HTMLElement) {
|
||||
if (this === clippedContent) return makeRect(0, 0, 400, 40);
|
||||
return makeRect(0, 0, 400, 120);
|
||||
});
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<DocumentAnnotationLayer
|
||||
containerRef={{ current: body }}
|
||||
markdown="Hidden folded text"
|
||||
threads={[
|
||||
{ id: "hidden", selectedText: "Hidden folded text", status: "open", anchorState: "active" },
|
||||
]}
|
||||
focusedThreadId={null}
|
||||
onThreadFocus={vi.fn()}
|
||||
pendingAnchor={null}
|
||||
onPendingAnchorChange={vi.fn()}
|
||||
onRequestComment={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
});
|
||||
|
||||
expect(container.querySelector(".paperclip-doc-annotation-highlight")).toBeNull();
|
||||
expect(container.querySelector(".paperclip-doc-annotation-hit-target")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not capture annotation comments from editable selections", async () => {
|
||||
const body = document.createElement("div");
|
||||
const editable = document.createElement("div");
|
||||
editable.setAttribute("contenteditable", "true");
|
||||
const text = document.createTextNode("Editing routine instructions");
|
||||
editable.appendChild(text);
|
||||
body.appendChild(editable);
|
||||
|
||||
const range = document.createRange();
|
||||
range.setStart(text, 0);
|
||||
range.setEnd(text, "Editing".length);
|
||||
const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({
|
||||
rangeCount: 1,
|
||||
isCollapsed: false,
|
||||
getRangeAt: () => range,
|
||||
} as unknown as Selection);
|
||||
const onPendingAnchorChange = vi.fn();
|
||||
root = createRoot(container);
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<DocumentAnnotationLayer
|
||||
containerRef={{ current: body }}
|
||||
markdown="Editing routine instructions"
|
||||
threads={[]}
|
||||
focusedThreadId={null}
|
||||
onThreadFocus={vi.fn()}
|
||||
pendingAnchor={null}
|
||||
onPendingAnchorChange={onPendingAnchorChange}
|
||||
onRequestComment={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
|
||||
expect(mockGetContainerTextOffset).not.toHaveBeenCalled();
|
||||
expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled();
|
||||
expect(onPendingAnchorChange).toHaveBeenCalledWith(null);
|
||||
expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull();
|
||||
} finally {
|
||||
getSelectionSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not capture annotation comments from bare contenteditable selections", async () => {
|
||||
const body = document.createElement("div");
|
||||
const editable = document.createElement("div");
|
||||
editable.setAttribute("contenteditable", "");
|
||||
const text = document.createTextNode("Editing routine instructions");
|
||||
editable.appendChild(text);
|
||||
body.appendChild(editable);
|
||||
|
||||
const range = document.createRange();
|
||||
range.setStart(text, 0);
|
||||
range.setEnd(text, "Editing".length);
|
||||
const getSelectionSpy = vi.spyOn(window, "getSelection").mockReturnValue({
|
||||
rangeCount: 1,
|
||||
isCollapsed: false,
|
||||
getRangeAt: () => range,
|
||||
} as unknown as Selection);
|
||||
const onPendingAnchorChange = vi.fn();
|
||||
root = createRoot(container);
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<DocumentAnnotationLayer
|
||||
containerRef={{ current: body }}
|
||||
markdown="Editing routine instructions"
|
||||
threads={[]}
|
||||
focusedThreadId={null}
|
||||
onThreadFocus={vi.fn()}
|
||||
pendingAnchor={null}
|
||||
onPendingAnchorChange={onPendingAnchorChange}
|
||||
onRequestComment={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
|
||||
expect(mockGetContainerTextOffset).not.toHaveBeenCalled();
|
||||
expect(mockBuildAnchorFromContainerSelection).not.toHaveBeenCalled();
|
||||
expect(onPendingAnchorChange).toHaveBeenCalledWith(null);
|
||||
expect(container.querySelector('[data-testid="document-annotation-selection-toolbar"]')).toBeNull();
|
||||
} finally {
|
||||
getSelectionSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps native CSS highlight ranges synchronized while using the overlay for visual paint", async () => {
|
||||
const originalCss = globalThis.CSS;
|
||||
const originalHighlight = (globalThis as { Highlight?: unknown }).Highlight;
|
||||
const setHighlight = vi.fn();
|
||||
const deleteHighlight = vi.fn();
|
||||
class MockHighlight {
|
||||
ranges: Range[];
|
||||
|
||||
constructor(...ranges: Range[]) {
|
||||
this.ranges = ranges;
|
||||
}
|
||||
}
|
||||
(globalThis as { CSS?: unknown }).CSS = {
|
||||
...(originalCss ?? {}),
|
||||
highlights: {
|
||||
set: setHighlight,
|
||||
delete: deleteHighlight,
|
||||
},
|
||||
};
|
||||
(globalThis as { Highlight?: unknown }).Highlight = MockHighlight;
|
||||
|
||||
const body = document.createElement("div");
|
||||
body.textContent = "Annotated body text.";
|
||||
root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root?.render(
|
||||
<DocumentAnnotationLayer
|
||||
containerRef={{ current: body }}
|
||||
markdown="Annotated body text."
|
||||
threads={[
|
||||
{ id: "active", selectedText: "Annotated", status: "open", anchorState: "active" },
|
||||
]}
|
||||
focusedThreadId={null}
|
||||
onThreadFocus={vi.fn()}
|
||||
pendingAnchor={null}
|
||||
onPendingAnchorChange={vi.fn()}
|
||||
onRequestComment={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
await new Promise((resolve) => window.requestAnimationFrame(resolve));
|
||||
});
|
||||
|
||||
expect(container.querySelector(".paperclip-doc-annotation-highlight")).not.toBeNull();
|
||||
expect(container.querySelector(".paperclip-doc-annotation-hit-target")).not.toBeNull();
|
||||
const openHighlightCall = setHighlight.mock.calls.find(([name]) => name === "paperclip-doc-annotation-open");
|
||||
expect(openHighlightCall).toBeTruthy();
|
||||
expect((openHighlightCall?.[1] as MockHighlight).ranges).toHaveLength(1);
|
||||
|
||||
await act(async () => root?.unmount());
|
||||
root = null;
|
||||
expect(deleteHighlight).toHaveBeenCalledWith("paperclip-doc-annotation-open");
|
||||
|
||||
(globalThis as { CSS?: unknown }).CSS = originalCss;
|
||||
(globalThis as { Highlight?: unknown }).Highlight = originalHighlight;
|
||||
});
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ThemeProvider } from "@/context/ThemeContext";
|
||||
import { DocumentMarkdownBody } from "./DocumentMarkdownBody";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
afterEach(async () => {
|
||||
await act(async () => root?.unmount());
|
||||
container?.remove();
|
||||
});
|
||||
|
||||
const body = "\n\n![Second][shot]\n\n\n\n[shot]: https://example.com/second.png";
|
||||
function LocationProbe() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
return <><output>{location.pathname}{location.search}{location.hash}</output><button onClick={() => navigate(-1)}>Back</button></>;
|
||||
}
|
||||
async function render(hash = "", markdown = body, revisionId?: string, documentIssueId?: string, currentIssueId?: string) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
await act(async () => {
|
||||
root.render(<MemoryRouter initialEntries={[`/PAP/issues/example?keep=1${hash}`]}>
|
||||
<QueryClientProvider client={client}><ThemeProvider>
|
||||
<DocumentMarkdownBody documentKey="report" revisionId={revisionId} documentIssueId={documentIssueId} currentIssueId={currentIssueId}>{markdown}</DocumentMarkdownBody>
|
||||
<LocationProbe />
|
||||
</ThemeProvider></QueryClientProvider>
|
||||
</MemoryRouter>);
|
||||
});
|
||||
}
|
||||
async function click(selector: string) {
|
||||
const element = document.querySelector<HTMLElement>(selector)!;
|
||||
expect(element).not.toBeNull();
|
||||
await act(async () => element.click());
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
}
|
||||
async function key(key: string) {
|
||||
await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })));
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
}
|
||||
function dialog() { return document.querySelector('[role="dialog"]'); }
|
||||
|
||||
describe("document image gallery", () => {
|
||||
it("keeps fragment links scoped to the saved document's task after the URL changes", async () => {
|
||||
await render("#document-local", "[Evidence](#document-evidence&thread=note)\n\n[Explicit](#document-brief&documentIssue=other)\n\n[Section](#section)", "old", "owner", "current");
|
||||
expect([...container.querySelectorAll(".paperclip-markdown a")].map(link => link.getAttribute("href"))).toEqual([
|
||||
"#document-evidence&thread=note&documentIssue=owner",
|
||||
"#document-brief&documentIssue=other",
|
||||
"#section",
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens a clicked occurrence, navigates all rendered images, and updates the URL", async () => {
|
||||
await render("#document-report&viewer=full&thread=thread-1");
|
||||
await click('[aria-label="Open image: Repeated"]');
|
||||
expect(dialog()?.textContent).toContain("3 / 3");
|
||||
expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("/first.png");
|
||||
expect(container.querySelector("output")?.textContent).toBe("/PAP/issues/example?keep=1#document-report&thread=thread-1&viewer=full&image=3");
|
||||
await key("ArrowRight");
|
||||
expect(dialog()?.textContent).toContain("1 / 3");
|
||||
await click('button[title="Next"]');
|
||||
expect(dialog()?.querySelector("img")?.getAttribute("src")).toBe("https://example.com/second.png");
|
||||
expect(container.querySelector("output")?.textContent).toContain("image=2");
|
||||
await key("ArrowLeft");
|
||||
expect(dialog()?.textContent).toContain("1 / 3");
|
||||
await click('button[title="Previous"]');
|
||||
expect(dialog()?.textContent).toContain("3 / 3");
|
||||
await key("Escape");
|
||||
expect(dialog()).toBeNull();
|
||||
expect(container.querySelector("output")?.textContent).not.toContain("image=");
|
||||
expect(container.querySelector("output")?.textContent).toContain("viewer=full");
|
||||
expect(document.activeElement?.getAttribute("aria-label")).toBe("Open image: Repeated");
|
||||
});
|
||||
|
||||
it("loads a shared image URL for the exact revision and retains it on close", async () => {
|
||||
await render("#document-report&revision=old&interaction=review&documentIssue=owner&image=2", body, "old", "owner");
|
||||
expect(dialog()?.textContent).toContain("2 / 3");
|
||||
expect(dialog()?.querySelector("a")?.getAttribute("href")).toBe("https://example.com/second.png");
|
||||
await click('button[title="Close"]');
|
||||
expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&interaction=review&documentIssue=owner");
|
||||
expect(dialog()).toBeNull();
|
||||
});
|
||||
|
||||
it("opens a saved owner after the URL has changed to another document", async () => {
|
||||
await render("#document-local&documentIssue=wrong-owner", body, "old", "owner");
|
||||
await click('[aria-label="Open image: First"]');
|
||||
expect(dialog()?.textContent).toContain("1 / 3");
|
||||
expect(container.querySelector("output")?.textContent).toContain("#document-report&revision=old&documentIssue=owner&image=1");
|
||||
await key("ArrowRight");
|
||||
expect(container.querySelector("output")?.textContent).toContain("documentIssue=owner&image=2");
|
||||
});
|
||||
|
||||
it("opens an explicit current-task link and keeps review parameters through navigation and reopening", async () => {
|
||||
await render("#document-report&revision=old&interaction=review&viewer=full&documentIssue=current-task&image=2", body, "old", undefined, "current-task");
|
||||
expect(dialog()?.textContent).toContain("2 / 3");
|
||||
await key("ArrowRight");
|
||||
expect(dialog()?.textContent).toContain("3 / 3");
|
||||
await click('button[title="Close"]');
|
||||
expect(dialog()).toBeNull();
|
||||
await click('[aria-label="Open image: First"]');
|
||||
expect(dialog()?.textContent).toContain("1 / 3");
|
||||
const url = container.querySelector("output")?.textContent;
|
||||
expect(url).toContain("revision=old");
|
||||
expect(url).toContain("interaction=review");
|
||||
expect(url).toContain("viewer=full");
|
||||
expect(url).toContain("documentIssue=current-task");
|
||||
});
|
||||
|
||||
it("does not match another task's saved tab to an implicit current-task link", async () => {
|
||||
await render("#document-report&revision=old&image=2", body, "old", "other-task", "current-task");
|
||||
expect(dialog()).toBeNull();
|
||||
await click('[aria-label="Open image: First"]');
|
||||
expect(dialog()?.textContent).toContain("1 / 3");
|
||||
expect(container.querySelector("output")?.textContent).toContain("documentIssue=other-task");
|
||||
});
|
||||
|
||||
it.each(["#document-other&image=1", "#document-report&image=100", "#document-report&image=0", "#document-report&revision=old&image=1"])("does not open an unavailable image target: %s", async (hash) => {
|
||||
await render(hash);
|
||||
expect(dialog()).toBeNull();
|
||||
});
|
||||
|
||||
it("opens a single image from the keyboard without navigation controls", async () => {
|
||||
await render("", "");
|
||||
const image = container.querySelector("img")!;
|
||||
await act(async () => {
|
||||
image.focus();
|
||||
image.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(dialog()?.textContent).toContain("1 / 1");
|
||||
expect(dialog()?.querySelector('button[title="Next"]')).toBeNull();
|
||||
await click('[role="dialog"]');
|
||||
expect(dialog()).toBeNull();
|
||||
expect(document.activeElement).toBe(image);
|
||||
});
|
||||
});
|
||||
@@ -1,127 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import type { CompanySecret, EnvBinding, UserSecretDefinition } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EnvironmentVariablesEditor } from "./environment-variables-editor";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const definition: UserSecretDefinition = {
|
||||
id: "def-1",
|
||||
companyId: "c1",
|
||||
key: "PERSONAL_GH_TOKEN",
|
||||
name: "Personal GitHub token",
|
||||
description: null,
|
||||
status: "active",
|
||||
provider: "local_encrypted",
|
||||
managedMode: "paperclip_managed",
|
||||
providerConfigId: null,
|
||||
providerMetadata: null,
|
||||
usageGuidance: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
updatedByAgentId: null,
|
||||
updatedByUserId: null,
|
||||
deletedAt: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function render(props: Partial<React.ComponentProps<typeof EnvironmentVariablesEditor>>) {
|
||||
root = createRoot(container);
|
||||
return act(() => {
|
||||
root.render(
|
||||
<EnvironmentVariablesEditor
|
||||
value={props.value ?? {}}
|
||||
secrets={props.secrets ?? []}
|
||||
userSecretDefinitions={props.userSecretDefinitions}
|
||||
onCreateSecret={props.onCreateSecret ?? (vi.fn() as never)}
|
||||
onChange={props.onChange ?? vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
describe("EnvironmentVariablesEditor user secret binding", () => {
|
||||
it("renders an existing user_secret_ref as a User secret row with the definition and requirement", async () => {
|
||||
const value: Record<string, EnvBinding> = {
|
||||
GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true },
|
||||
};
|
||||
await render({ value, userSecretDefinitions: [definition] });
|
||||
|
||||
const keyInput = container.querySelector<HTMLInputElement>('input[placeholder="KEY"]');
|
||||
expect(keyInput?.value).toBe("GH_TOKEN");
|
||||
// Radix Select triggers render the selected label as text.
|
||||
expect(container.textContent).toContain("User secret");
|
||||
expect(container.textContent).toContain("Personal GitHub token");
|
||||
expect(container.textContent).toContain("Required");
|
||||
});
|
||||
|
||||
it("explains user-secret bindings when a user secret row is present", async () => {
|
||||
await render({
|
||||
value: { GH_TOKEN: { type: "user_secret_ref", key: "PERSONAL_GH_TOKEN", required: true } },
|
||||
userSecretDefinitions: [definition],
|
||||
});
|
||||
expect(container.textContent).toContain("Personal GitHub token");
|
||||
expect(container.textContent).toContain("User secrets resolve from the user responsible for the run.");
|
||||
});
|
||||
|
||||
it("keeps working for company secrets when no user definitions are provided", async () => {
|
||||
const secret: CompanySecret = {
|
||||
id: "sec-1",
|
||||
companyId: "c1",
|
||||
scope: "company",
|
||||
ownerUserId: null,
|
||||
userSecretDefinitionId: null,
|
||||
key: "api_key",
|
||||
name: "API key",
|
||||
provider: "local_encrypted",
|
||||
status: "active",
|
||||
managedMode: "paperclip_managed",
|
||||
externalRef: null,
|
||||
providerConfigId: null,
|
||||
providerMetadata: null,
|
||||
latestVersion: 2,
|
||||
description: null,
|
||||
lastResolvedAt: null,
|
||||
lastRotatedAt: null,
|
||||
deletedAt: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
const value: Record<string, EnvBinding> = {
|
||||
API_KEY: { type: "secret_ref", secretId: "sec-1", version: "latest" },
|
||||
};
|
||||
await render({ value, secrets: [secret] });
|
||||
|
||||
const keyInput = container.querySelector<HTMLInputElement>('input[placeholder="KEY"]');
|
||||
expect(keyInput?.value).toBe("API_KEY");
|
||||
expect(container.textContent).toContain("API key");
|
||||
});
|
||||
});
|
||||
@@ -1,231 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { FileTree, buildFileTree } from "./FileTree";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
describe("FileTree", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function row(path: string) {
|
||||
return container.querySelector(`[data-file-tree-path="${path}"]`) as HTMLDivElement | null;
|
||||
}
|
||||
|
||||
it("preserves readable plugin error details and retry without exposing raw codes", () => {
|
||||
const retry = vi.fn();
|
||||
const renderError = (message: string) => act(() => root.render(
|
||||
<FileTree nodes={[]} selectedFile={null} expandedDirs={new Set()} onSelectFile={() => {}} onToggleDir={() => {}} error={{ message, retry }} />,
|
||||
));
|
||||
renderError("The wiki source was removed. Choose another source.");
|
||||
expect(container.textContent).toContain("The wiki source was removed. Choose another source.");
|
||||
act(() => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Retry")!.click());
|
||||
expect(retry).toHaveBeenCalledOnce();
|
||||
renderError("source_unavailable");
|
||||
expect(container.textContent).not.toContain("source_unavailable");
|
||||
});
|
||||
|
||||
it("selects file rows and expands directory rows", () => {
|
||||
const onSelectFile = vi.fn();
|
||||
const onToggleDir = vi.fn();
|
||||
const nodes = buildFileTree({
|
||||
"README.md": "",
|
||||
"docs/guide.md": "",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile="README.md"
|
||||
expandedDirs={new Set(["docs"])}
|
||||
onSelectFile={onSelectFile}
|
||||
onToggleDir={onToggleDir}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(row("README.md")?.getAttribute("aria-selected")).toBe("true");
|
||||
|
||||
act(() => {
|
||||
row("docs/guide.md")?.click();
|
||||
});
|
||||
expect(onSelectFile).toHaveBeenCalledWith("docs/guide.md");
|
||||
|
||||
act(() => {
|
||||
row("docs")?.click();
|
||||
});
|
||||
expect(onToggleDir).toHaveBeenCalledWith("docs");
|
||||
});
|
||||
|
||||
it("marks partially selected directories as indeterminate", () => {
|
||||
const nodes = buildFileTree({
|
||||
"docs/a.md": "",
|
||||
"docs/b.md": "",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={null}
|
||||
expandedDirs={new Set(["docs"])}
|
||||
checkedFiles={new Set(["docs/a.md"])}
|
||||
onSelectFile={() => {}}
|
||||
onToggleDir={() => {}}
|
||||
onToggleCheck={() => {}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const input = row("docs")?.querySelector("input[type='checkbox']") as HTMLInputElement | null;
|
||||
expect(input?.checked).toBe(false);
|
||||
expect(input?.indeterminate).toBe(true);
|
||||
expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed");
|
||||
});
|
||||
|
||||
it("renders file badges and host-only file extras", () => {
|
||||
const nodes = buildFileTree({
|
||||
"wiki/very-long-page-slug.md": "",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={null}
|
||||
expandedDirs={new Set(["wiki"])}
|
||||
onSelectFile={() => {}}
|
||||
onToggleDir={() => {}}
|
||||
fileBadges={{
|
||||
"wiki/very-long-page-slug.md": {
|
||||
label: "fresh",
|
||||
status: "ok",
|
||||
tooltip: "Synced",
|
||||
},
|
||||
}}
|
||||
renderFileExtra={(node) => (
|
||||
node.kind === "file" ? <span data-testid="file-extra">{node.name.length} chars</span> : null
|
||||
)}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("fresh");
|
||||
expect(container.querySelector("[title='Synced']")).not.toBeNull();
|
||||
expect(container.querySelector("[data-testid='file-extra']")?.textContent).toBe("22 chars");
|
||||
});
|
||||
|
||||
it("wraps long labels by default and can opt back into truncation", () => {
|
||||
const nodes = buildFileTree({
|
||||
"wiki/extremely-long-page-slug-that-wraps-on-mobile.md": "",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={null}
|
||||
expandedDirs={new Set(["wiki"])}
|
||||
onSelectFile={() => {}}
|
||||
onToggleDir={() => {}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("break-all");
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={null}
|
||||
expandedDirs={new Set(["wiki"])}
|
||||
onSelectFile={() => {}}
|
||||
onToggleDir={() => {}}
|
||||
wrapLabels={false}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(row("wiki/extremely-long-page-slug-that-wraps-on-mobile.md")?.innerHTML).toContain("truncate");
|
||||
});
|
||||
|
||||
it("supports tree keyboard expansion and checkbox toggling", () => {
|
||||
const onToggleDir = vi.fn();
|
||||
const onToggleCheck = vi.fn();
|
||||
const nodes = buildFileTree({
|
||||
"docs/a.md": "",
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<FileTree
|
||||
nodes={nodes}
|
||||
selectedFile={null}
|
||||
expandedDirs={new Set()}
|
||||
onSelectFile={() => {}}
|
||||
onToggleDir={onToggleDir}
|
||||
onToggleCheck={onToggleCheck}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const docsRow = row("docs");
|
||||
act(() => {
|
||||
docsRow?.focus();
|
||||
docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
|
||||
});
|
||||
expect(onToggleDir).toHaveBeenCalledWith("docs");
|
||||
|
||||
act(() => {
|
||||
docsRow?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true }));
|
||||
});
|
||||
expect(onToggleCheck).toHaveBeenCalledWith("docs", "dir");
|
||||
});
|
||||
|
||||
it("keeps hidden descendants in folder selection and restores a tab stop when filtering", () => {
|
||||
const nodes = buildFileTree({ "docs/a.md": "", "docs/b.md": "" });
|
||||
const props = { nodes, selectedFile: null, expandedDirs: new Set(["docs"]), checkedFiles: new Set(["docs/a.md"]), onSelectFile: () => {}, onToggleDir: () => {} };
|
||||
act(() => root.render(<FileTree {...props} />));
|
||||
act(() => row("docs/b.md")?.focus());
|
||||
act(() => root.render(<FileTree {...props} visiblePaths={new Set(["docs", "docs/a.md"])} renderLabel={node => <span>{node.name} description</span>} />));
|
||||
expect(row("docs/b.md")).toBeNull();
|
||||
expect(row("docs")?.getAttribute("aria-checked")).toBe("mixed");
|
||||
expect(row("docs")?.tabIndex).toBe(0);
|
||||
expect(row("docs/a.md")?.textContent).toContain("a.md description");
|
||||
});
|
||||
|
||||
it("blocks mouse and keyboard changes while disabled", () => {
|
||||
const onToggleDir = vi.fn();
|
||||
const onToggleCheck = vi.fn();
|
||||
const onSelectFile = vi.fn();
|
||||
act(() => root.render(<FileTree nodes={buildFileTree({ "docs/a.md": "" })} selectedFile={null} expandedDirs={new Set(["docs"])} onToggleDir={onToggleDir} onToggleCheck={onToggleCheck} onSelectFile={onSelectFile} disabled />));
|
||||
act(() => {
|
||||
row("docs/a.md")?.click();
|
||||
row("docs")?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true }));
|
||||
container.querySelector<HTMLButtonElement>('[aria-label="Collapse docs"]')?.click();
|
||||
});
|
||||
expect(onToggleCheck).not.toHaveBeenCalled();
|
||||
expect(onSelectFile).not.toHaveBeenCalled();
|
||||
expect(onToggleDir).not.toHaveBeenCalled();
|
||||
expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,500 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Dialog, DialogContent, DialogTitle } from "./ui/dialog";
|
||||
import { InlineEntitySelector } from "./InlineEntitySelector";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
describe("InlineEntitySelector", () => {
|
||||
let container: HTMLDivElement;
|
||||
let originalMatchMedia: typeof window.matchMedia;
|
||||
|
||||
beforeEach(() => {
|
||||
originalMatchMedia = window.matchMedia;
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
window.matchMedia = originalMatchMedia;
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it.each([false, true])("allows wheel and touch scrolling outside a parent dialog (mobile: %s)", async (mobile) => {
|
||||
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||
matches: mobile && query === "(max-width: 40rem)",
|
||||
media: query,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
}));
|
||||
const root = createRoot(container);
|
||||
await act(() => {
|
||||
root.render(
|
||||
<Dialog defaultOpen>
|
||||
<DialogContent aria-describedby={undefined}>
|
||||
<DialogTitle>New task</DialogTitle>
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={Array.from({ length: 20 }, (_, index) => ({ id: `agent-${index}`, label: `Agent ${index}` }))}
|
||||
placeholder="Assignee"
|
||||
noneLabel="No assignee"
|
||||
searchPlaceholder="Search assignees..."
|
||||
emptyMessage="No assignees found."
|
||||
onChange={vi.fn()}
|
||||
triggerTestId="nested-assignee-picker"
|
||||
openOnFocus={false}
|
||||
modal
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>,
|
||||
);
|
||||
});
|
||||
try {
|
||||
await act(() => {
|
||||
document.querySelector<HTMLButtonElement>("[data-testid=nested-assignee-picker]")!.click();
|
||||
});
|
||||
// Let both real Radix scroll locks install their document listeners.
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
const list = document.querySelector<HTMLElement>("[data-mobile-entity-picker-list]")!;
|
||||
expect(list).not.toBeNull();
|
||||
expect(document.querySelector("[data-slot=dialog-content]")!.contains(list)).toBe(false);
|
||||
// jsdom has no layout; supply the geometry of a list with more rows than fit.
|
||||
list.style.overflowY = "auto";
|
||||
Object.defineProperties(list, {
|
||||
scrollHeight: { configurable: true, value: 1000 },
|
||||
clientHeight: { configurable: true, value: 200 },
|
||||
});
|
||||
const option = list.querySelector("button")!;
|
||||
const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 });
|
||||
option.dispatchEvent(wheel);
|
||||
expect(wheel.defaultPrevented).toBe(false);
|
||||
const touch = (type: string, y: number) => {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperties(event, {
|
||||
touches: { value: [{ clientX: 100, clientY: y }] },
|
||||
changedTouches: { value: [{ clientX: 100, clientY: y }] },
|
||||
});
|
||||
option.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
touch("touchstart", 150);
|
||||
expect(touch("touchmove", 100).defaultPrevented).toBe(false);
|
||||
// The background stays locked while the picker is open.
|
||||
const outsideMove = new Event("touchmove", { bubbles: true, cancelable: true });
|
||||
Object.defineProperties(outsideMove, {
|
||||
touches: { value: [{ clientX: 100, clientY: 100 }] },
|
||||
changedTouches: { value: [{ clientX: 100, clientY: 100 }] },
|
||||
});
|
||||
document.body.dispatchEvent(outsideMove);
|
||||
expect(outsideMove.defaultPrevented).toBe(true);
|
||||
} finally {
|
||||
await act(() => root.unmount());
|
||||
}
|
||||
});
|
||||
|
||||
it("opens on the next keyboard focus after a desktop outside dismissal", async () => {
|
||||
const root = createRoot(container);
|
||||
await act(() => {
|
||||
root.render(<>
|
||||
<button type="button" data-testid="outside-picker">Outside</button>
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[{ id: "agent-1", label: "Agent One" }]}
|
||||
placeholder="Assignee"
|
||||
noneLabel="No assignee"
|
||||
searchPlaceholder="Search assignees..."
|
||||
emptyMessage="No assignees found."
|
||||
onChange={vi.fn()}
|
||||
triggerTestId="desktop-assignee-picker"
|
||||
/>
|
||||
</>);
|
||||
});
|
||||
try {
|
||||
const trigger = container.querySelector<HTMLButtonElement>("[data-testid=desktop-assignee-picker]")!;
|
||||
const outside = container.querySelector<HTMLButtonElement>("[data-testid=outside-picker]")!;
|
||||
await act(() => trigger.click());
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
await act(() => {
|
||||
outside.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true, cancelable: true }));
|
||||
outside.focus();
|
||||
outside.click();
|
||||
});
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull();
|
||||
expect(document.activeElement).toBe(outside);
|
||||
await act(() => trigger.focus());
|
||||
expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull();
|
||||
} finally {
|
||||
await act(() => root.unmount());
|
||||
}
|
||||
});
|
||||
|
||||
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();
|
||||
const documentKeyDown = vi.fn();
|
||||
document.addEventListener("keydown", documentKeyDown);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[
|
||||
{ id: "agent:agent-1", label: "CodexCoder" },
|
||||
{ id: "agent:agent-2", label: "DesignBot" },
|
||||
]}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null;
|
||||
expect(searchInput).not.toBeNull();
|
||||
searchInput?.focus();
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "ArrowDown" }));
|
||||
});
|
||||
|
||||
expect(documentKeyDown).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" }));
|
||||
});
|
||||
|
||||
expect(documentKeyDown).not.toHaveBeenCalled();
|
||||
expect(onChange).toHaveBeenCalledWith("agent:agent-1");
|
||||
|
||||
document.removeEventListener("keydown", documentKeyDown);
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("focuses the search input when opened on coarse pointers", async () => {
|
||||
window.matchMedia = vi.fn().mockImplementation((query: string) => ({
|
||||
matches: query === "(pointer: coarse)" || query === "(max-width: 40rem)",
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[
|
||||
{ id: "agent:agent-1", label: "CodexCoder" },
|
||||
{ id: "agent:agent-2", label: "DesignBot" },
|
||||
]}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={vi.fn()}
|
||||
disablePortal
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null;
|
||||
expect(searchInput).not.toBeNull();
|
||||
expect(searchInput?.className).toContain("text-base");
|
||||
expect(document.querySelector("[data-mobile-entity-picker]")).not.toBeNull();
|
||||
expect(container.contains(document.querySelector("[data-mobile-entity-picker]"))).toBe(false);
|
||||
expect(document.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Responsible");
|
||||
expect(document.querySelector('button[aria-label="Close selector"]')).not.toBeNull();
|
||||
expect(document.activeElement).toBe(searchInput);
|
||||
|
||||
await act(async () => {
|
||||
(document.querySelector('button[aria-label="Close selector"]') as HTMLButtonElement | null)?.click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(document.querySelector("[data-mobile-entity-picker]")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("opens on programmatic focus without toggling an open popover closed", async () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[{ id: "project-1", label: "Project One" }]}
|
||||
placeholder="Project"
|
||||
noneLabel="No project"
|
||||
searchPlaceholder="Search projects..."
|
||||
emptyMessage="No projects found."
|
||||
onChange={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
trigger?.focus();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(
|
||||
document.querySelector('input[placeholder="Search projects..."]'),
|
||||
).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
trigger?.focus();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(
|
||||
document.querySelector('input[placeholder="Search projects..."]'),
|
||||
).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the no-selection action first when requested", async () => {
|
||||
const root = createRoot(container);
|
||||
const onChange = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value="project-1"
|
||||
options={[
|
||||
{ id: "project-1", label: "Project One" },
|
||||
{ id: "project-2", label: "Project Two" },
|
||||
]}
|
||||
recentOptionIds={["project-2"]}
|
||||
placeholder="Project"
|
||||
noneLabel="No project"
|
||||
noneAtTop
|
||||
searchPlaceholder="Search projects..."
|
||||
emptyMessage="No projects found."
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement;
|
||||
await act(() => trigger.click());
|
||||
|
||||
const options = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("[data-mobile-entity-picker-list] > button"),
|
||||
);
|
||||
expect(options.map((option) => option.textContent)).toEqual([
|
||||
"No project",
|
||||
"Project One",
|
||||
"Project Two",
|
||||
]);
|
||||
|
||||
const searchInput = document.querySelector<HTMLInputElement>('input[placeholder="Search projects..."]');
|
||||
const nativeInputValue = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
await act(() => {
|
||||
nativeInputValue?.call(searchInput, "Two");
|
||||
searchInput?.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
|
||||
const filteredOptions = Array.from(
|
||||
document.querySelectorAll<HTMLButtonElement>("[data-mobile-entity-picker-list] > button"),
|
||||
);
|
||||
expect(filteredOptions.map((option) => option.textContent)).toEqual([
|
||||
"No project",
|
||||
"Project Two",
|
||||
]);
|
||||
|
||||
await act(() => {
|
||||
searchInput?.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Enter" }));
|
||||
});
|
||||
expect(onChange).toHaveBeenCalledWith("project-2");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("does not open the popover when disabled", async () => {
|
||||
const root = createRoot(container);
|
||||
const onChange = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[{ id: "agent:agent-1", label: "CodexCoder" }]}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={onChange}
|
||||
disabled
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
expect(trigger?.disabled).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(document.querySelector('input[placeholder="Search responsible..."]')).toBeNull();
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("filters options as the user types in the search box", async () => {
|
||||
const root = createRoot(container);
|
||||
const onChange = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<InlineEntitySelector
|
||||
value=""
|
||||
options={[
|
||||
{ id: "agent:agent-1", label: "CodexCoder" },
|
||||
{ id: "agent:agent-2", label: "DesignBot" },
|
||||
]}
|
||||
placeholder="Responsible"
|
||||
noneLabel="No responsible"
|
||||
searchPlaceholder="Search responsible..."
|
||||
emptyMessage="No responsible found."
|
||||
onChange={onChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const trigger = container.querySelector("button") as HTMLButtonElement | null;
|
||||
await act(async () => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
const searchInput = document.querySelector('input[placeholder="Search responsible..."]') as HTMLInputElement | null;
|
||||
expect(searchInput).not.toBeNull();
|
||||
|
||||
const nativeInputValue = Object.getOwnPropertyDescriptor(
|
||||
window.HTMLInputElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
await act(async () => {
|
||||
nativeInputValue?.call(searchInput, "design");
|
||||
searchInput?.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
|
||||
const optionLabels = Array.from(document.querySelectorAll("[role='dialog'] button, .max-h-56 button")).map(
|
||||
(el) => el.textContent ?? "",
|
||||
);
|
||||
const joined = optionLabels.join("|");
|
||||
expect(joined).toContain("DesignBot");
|
||||
expect(joined).not.toContain("CodexCoder");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,241 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act as reactAct } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ISSUE_THREAD_INTERACTION_KINDS,
|
||||
type InteractionResolverGovernance,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
// Routine offers are always answered by a person, so they have no audience row.
|
||||
const INTERACTION_KINDS = ISSUE_THREAD_INTERACTION_KINDS.filter((kind) => kind !== "suggest_routine" && kind !== "propose_responsibility_bar" && kind !== "propose_automation" && kind !== "propose_dashboard_changes");
|
||||
import {
|
||||
GOVERNANCE_UNSET,
|
||||
InteractionGovernancePanel,
|
||||
applyGovernanceChange,
|
||||
toGovernanceSelectValue,
|
||||
} from "./InteractionGovernancePanel";
|
||||
import { TooltipProvider } from "./ui/tooltip";
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
if (typeof reactAct === "function") {
|
||||
await reactAct(callback);
|
||||
return;
|
||||
}
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
function renderPanel(governance: InteractionResolverGovernance = {}, onChange = vi.fn()) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<InteractionGovernancePanel governance={governance} onChange={onChange} />
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
return { host: container, onChange };
|
||||
}
|
||||
|
||||
/** Exact visible text of a closed select trigger (the chevron contributes none). */
|
||||
function triggerText(host: HTMLElement, testId: string): string {
|
||||
const trigger = host.querySelector(`[data-testid="${testId}"]`);
|
||||
expect(trigger).toBeTruthy();
|
||||
return (trigger?.textContent ?? "").replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => root?.unmount());
|
||||
}
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe("InteractionGovernancePanel", () => {
|
||||
it("presents Anyone as the visible default for a company with no overrides", () => {
|
||||
const { host } = renderPanel();
|
||||
|
||||
const defaultSelect = host.querySelector('[data-testid="governance-request_confirmation-default"]');
|
||||
expect(defaultSelect?.textContent).toContain("Anyone (default)");
|
||||
const cap = host.querySelector('[data-testid="governance-request_confirmation-cap"]');
|
||||
expect(cap?.textContent).toContain("No cap");
|
||||
});
|
||||
|
||||
it("describes the open default without presenting it as board-required", () => {
|
||||
const { host } = renderPanel();
|
||||
const copy = host.textContent ?? "";
|
||||
|
||||
expect(copy).toContain("Thread interactions are open by default");
|
||||
expect(copy).toContain("the board or any agent, including the one that asked");
|
||||
expect(copy).not.toContain("Board only");
|
||||
expect(copy).not.toContain("always require the board");
|
||||
// Governed tool approvals keep their human-only guarantee.
|
||||
expect(copy).toContain("Tool-approval confirmations always stay");
|
||||
expect(copy).toContain("Human only");
|
||||
});
|
||||
|
||||
it("shows a stored narrowing override on the matching row", () => {
|
||||
const { host } = renderPanel({
|
||||
request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" },
|
||||
});
|
||||
|
||||
expect(
|
||||
host.querySelector('[data-testid="governance-request_confirmation-default"]')?.textContent,
|
||||
).toContain("Human only");
|
||||
expect(
|
||||
host.querySelector('[data-testid="governance-request_confirmation-cap"]')?.textContent,
|
||||
).toContain("Anyone except creator");
|
||||
// Untouched kinds still read as open.
|
||||
expect(
|
||||
host.querySelector('[data-testid="governance-suggest_tasks-default"]')?.textContent,
|
||||
).toContain("Anyone (default)");
|
||||
});
|
||||
|
||||
/**
|
||||
* PAP-17297: an empty `<SelectValue />` lets Radix portal the selected
|
||||
* option's whole subtree — label *and* effect sentence — into the closed
|
||||
* trigger, where `line-clamp-1` clipped it. `toContain` assertions cannot see
|
||||
* that, so these check the trigger's exact text.
|
||||
*/
|
||||
it("shows only the complete selected label in a closed trigger", () => {
|
||||
const { host } = renderPanel();
|
||||
|
||||
for (const kind of INTERACTION_KINDS) {
|
||||
expect(triggerText(host, `governance-${kind}-default`)).toBe("Anyone (default)");
|
||||
expect(triggerText(host, `governance-${kind}-cap`)).toBe("No cap");
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a narrowed trigger free of the option effect sentence", () => {
|
||||
const { host } = renderPanel({
|
||||
request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" },
|
||||
});
|
||||
|
||||
expect(triggerText(host, "governance-request_confirmation-default")).toBe("Human only");
|
||||
expect(triggerText(host, "governance-request_confirmation-cap")).toBe("Anyone except creator");
|
||||
// The effect prose belongs to the option list, never the trigger.
|
||||
expect(host.textContent).not.toContain("New cards wait for a person on the board");
|
||||
expect(host.textContent).not.toContain("narrowed to exclude its creator");
|
||||
expect(host.textContent).not.toContain("New cards are open");
|
||||
});
|
||||
|
||||
it("still offers the effect sentence inside the open option list", async () => {
|
||||
const { host } = renderPanel();
|
||||
const trigger = host.querySelector<HTMLElement>(
|
||||
'[data-testid="governance-request_confirmation-default"]',
|
||||
);
|
||||
expect(trigger).toBeTruthy();
|
||||
|
||||
await act(() => {
|
||||
trigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
|
||||
});
|
||||
|
||||
const listbox = document.querySelector('[data-slot="select-content"]');
|
||||
const listText = listbox?.textContent ?? "";
|
||||
expect(listText).toContain("Anyone (default)");
|
||||
expect(listText).toContain(
|
||||
"New cards are open — the board or any agent can respond, including the one that asked.",
|
||||
);
|
||||
expect(listText).toContain("New cards wait for a person on the board. Agents are turned away.");
|
||||
// Each option keeps a label-only typeahead value so keyboard search does not
|
||||
// match the effect prose.
|
||||
expect(
|
||||
Array.from(listbox?.querySelectorAll('[data-slot="select-item"]') ?? []).length,
|
||||
).toBe(3);
|
||||
// Reflow guard: the popover is capped so long prose wraps instead of
|
||||
// stretching past a narrow viewport.
|
||||
expect(listbox?.className).toContain("max-w-(--sz-280px)");
|
||||
});
|
||||
|
||||
it("renders a select for every governable interaction kind", () => {
|
||||
const { host } = renderPanel();
|
||||
expect(host.querySelector('[data-testid="governance-suggest_routine-default"]')).toBeNull();
|
||||
expect(host.querySelector('[data-testid="governance-propose_responsibility_bar-default"]')).toBeNull();
|
||||
expect(host.querySelector('[data-testid="governance-propose_automation-default"]')).toBeNull();
|
||||
expect(host.querySelector('[data-testid="governance-propose_dashboard_changes-default"]')).toBeNull();
|
||||
expect(host.querySelectorAll('[data-testid$="-default"]')).toHaveLength(
|
||||
INTERACTION_KINDS.length,
|
||||
);
|
||||
expect(host.querySelectorAll('[data-testid$="-cap"]')).toHaveLength(
|
||||
INTERACTION_KINDS.length,
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces a save failure", () => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<InteractionGovernancePanel
|
||||
governance={{}}
|
||||
onChange={vi.fn()}
|
||||
errorMessage="Failed to save interaction governance"
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
expect(container.textContent).toContain("Failed to save interaction governance");
|
||||
});
|
||||
});
|
||||
|
||||
describe("toGovernanceSelectValue", () => {
|
||||
it("treats an absent override as the open default", () => {
|
||||
expect(toGovernanceSelectValue(undefined)).toBe(GOVERNANCE_UNSET);
|
||||
});
|
||||
|
||||
it("treats a stored open audience — canonical or legacy alias — as the default", () => {
|
||||
expect(toGovernanceSelectValue("anyone")).toBe(GOVERNANCE_UNSET);
|
||||
expect(toGovernanceSelectValue("board_or_agents")).toBe(GOVERNANCE_UNSET);
|
||||
});
|
||||
|
||||
it("canonicalizes stored narrowing values, including the legacy board_only alias", () => {
|
||||
expect(toGovernanceSelectValue("not_creator")).toBe("not_creator");
|
||||
expect(toGovernanceSelectValue("human_only")).toBe("human_only");
|
||||
expect(toGovernanceSelectValue("board_only")).toBe("human_only");
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyGovernanceChange", () => {
|
||||
it("stores a narrowing override", () => {
|
||||
expect(applyGovernanceChange({}, "request_confirmation", "defaultPolicy", "human_only")).toEqual({
|
||||
request_confirmation: { defaultPolicy: "human_only" },
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the override when the open default is re-selected", () => {
|
||||
const current: InteractionResolverGovernance = {
|
||||
request_confirmation: { defaultPolicy: "human_only" },
|
||||
};
|
||||
expect(
|
||||
applyGovernanceChange(current, "request_confirmation", "defaultPolicy", GOVERNANCE_UNSET),
|
||||
).toEqual({});
|
||||
// Immutable: the caller's map is untouched.
|
||||
expect(current.request_confirmation?.defaultPolicy).toBe("human_only");
|
||||
});
|
||||
|
||||
it("keeps a sibling field when only one is cleared", () => {
|
||||
const current: InteractionResolverGovernance = {
|
||||
request_confirmation: { defaultPolicy: "human_only", cap: "not_creator" },
|
||||
};
|
||||
expect(applyGovernanceChange(current, "request_confirmation", "cap", GOVERNANCE_UNSET)).toEqual({
|
||||
request_confirmation: { defaultPolicy: "human_only" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,968 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act as reactAct } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import type { Issue } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IssueRow } from "./IssueRow";
|
||||
import { StatusIcon } from "./StatusIcon";
|
||||
import { TooltipProvider } from "./ui/tooltip";
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({
|
||||
children,
|
||||
className,
|
||||
to,
|
||||
disableIssueQuicklook: _disableIssueQuicklook,
|
||||
issuePrefetch,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & { to?: string; disableIssueQuicklook?: boolean; issuePrefetch?: Issue | null }) => (
|
||||
<a
|
||||
href={to}
|
||||
className={className}
|
||||
data-disable-issue-quicklook={_disableIssueQuicklook ? "true" : undefined}
|
||||
data-issue-prefetch-id={issuePrefetch?.id}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}));
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function act(callback: () => void) {
|
||||
if (typeof reactAct === "function") {
|
||||
reactAct(callback);
|
||||
return;
|
||||
}
|
||||
|
||||
flushSync(callback);
|
||||
}
|
||||
|
||||
function createIssue(overrides: Partial<Issue> = {}): Issue {
|
||||
return {
|
||||
id: "issue-1",
|
||||
identifier: "PAP-1",
|
||||
companyId: "company-1",
|
||||
projectId: null,
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
title: "Inbox item",
|
||||
description: null,
|
||||
status: "todo",
|
||||
priority: "medium",
|
||||
reviewPolicy: null,
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
responsibleUserId: null,
|
||||
createdByAgentId: null,
|
||||
createdByUserId: null,
|
||||
issueNumber: 1,
|
||||
requestDepth: 0,
|
||||
billingCode: null,
|
||||
assigneeAdapterOverrides: null,
|
||||
executionWorkspaceId: null,
|
||||
executionWorkspacePreference: null,
|
||||
executionWorkspaceSettings: null,
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionAgentNameKey: null,
|
||||
executionLockedAt: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
cancelledAt: null,
|
||||
hiddenAt: null,
|
||||
createdAt: new Date("2026-03-11T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-03-11T00:00:00.000Z"),
|
||||
labels: [],
|
||||
labelIds: [],
|
||||
myLastTouchAt: null,
|
||||
lastExternalCommentAt: null,
|
||||
isUnreadForMe: false,
|
||||
...overrides,
|
||||
workMode: overrides.workMode ?? "standard",
|
||||
};
|
||||
}
|
||||
|
||||
describe("IssueRow", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
container.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("renders the list status glyph at md (16px)", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue({ status: "in_progress" })} />);
|
||||
});
|
||||
|
||||
// jsdom 30 does not value-match a CSS attribute selector against a
|
||||
// mixed-case SVG attribute name, so `svg[viewBox="0 0 24 24"]` matches
|
||||
// nothing. Select the glyph SVGs by attribute presence, then compare the
|
||||
// viewBox value with getAttribute to keep the exact-value assertion.
|
||||
const glyphs = Array.from(container.querySelectorAll("svg[viewBox]")).filter(
|
||||
(svg) => svg.getAttribute("viewBox") === "0 0 24 24",
|
||||
);
|
||||
expect(glyphs.length).toBeGreaterThan(0);
|
||||
glyphs.forEach((glyph) => {
|
||||
expect(glyph.getAttribute("width")).toBe("16");
|
||||
expect(glyph.getAttribute("height")).toBe("16");
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("uses stable canonical identifier and timestamp columns at the trailing edge", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue({ identifier: "PAP-42", title: "Canonical task" })}
|
||||
presentation="task"
|
||||
metadata={<span>Live</span>}
|
||||
actions={<button type="button">More</button>}
|
||||
trailingMeta="Updated now"
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const row = container.querySelector('[data-slot="task-row"]');
|
||||
const leading = row?.querySelector('[data-slot="task-row-leading"]');
|
||||
const title = row?.querySelector('[data-slot="task-row-title"]');
|
||||
const metadata = row?.querySelector('[data-slot="task-row-metadata"]');
|
||||
const identifier = row?.querySelector('[data-slot="task-row-identifier"]');
|
||||
const timestamp = row?.querySelector('[data-slot="task-row-timestamp"]');
|
||||
const actions = row?.querySelector('[data-slot="task-row-actions"]');
|
||||
const link = row?.querySelector('[data-inbox-issue-link]');
|
||||
|
||||
expect(leading?.querySelector("svg")).not.toBeNull();
|
||||
expect(title?.textContent).toContain("Canonical task");
|
||||
expect(metadata?.textContent).toBe("Live");
|
||||
expect(identifier?.textContent).toBe("PAP-42");
|
||||
expect(timestamp?.textContent).toBe("Updated now");
|
||||
expect(actions?.textContent).toBe("More");
|
||||
expect(identifier?.className).toContain("w-20");
|
||||
expect(timestamp?.className).toContain("w-24");
|
||||
if (!link || !metadata || !identifier || !timestamp || !actions) throw new Error("Expected canonical task row slots");
|
||||
expect(link.contains(actions)).toBe(false);
|
||||
expect(metadata.compareDocumentPosition(actions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(actions.compareDocumentPosition(identifier) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(identifier.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(timestamp.nextElementSibling).toBeNull();
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps the canonical archive action within the shared task-row height", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue()}
|
||||
presentation="task"
|
||||
onArchive={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const archiveButton = container.querySelector<HTMLButtonElement>('button[aria-label="Archive"]');
|
||||
expect(archiveButton?.className).toContain("h-5");
|
||||
expect(archiveButton?.className).toContain("py-0");
|
||||
expect(archiveButton?.className).not.toContain("py-1");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("restores a task independently of its row link", () => {
|
||||
const root = createRoot(container);
|
||||
const restore = vi.fn();
|
||||
act(() => root.render(
|
||||
<TooltipProvider>
|
||||
<IssueRow
|
||||
issue={createIssue()}
|
||||
presentation="task"
|
||||
appearance="refreshed"
|
||||
columnValues={{ lastUpdated: "Just now" }}
|
||||
archiveAction={{ archived: true, onClick: restore }}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
));
|
||||
|
||||
const button = container.querySelector<HTMLButtonElement>('button[aria-label="Restore from archive"]')!;
|
||||
expect(button.closest("a")).toBeNull();
|
||||
act(() => button.click());
|
||||
expect(restore).toHaveBeenCalledOnce();
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("starts a truncated title reveal on link focus and keeps actions independent", async () => {
|
||||
const bounds = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 16));
|
||||
const createRange = document.createRange.bind(document);
|
||||
const rangeBounds = vi.spyOn(document, "createRange").mockImplementation(() => Object.assign(createRange(), {
|
||||
getBoundingClientRect: () => new DOMRect(0, 0, 400, 16),
|
||||
}));
|
||||
vi.stubGlobal("ResizeObserver", class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
});
|
||||
const root = createRoot(container);
|
||||
const title = "Define connector health states, failure recovery, and escalation ownership across teams";
|
||||
const onExpand = vi.fn();
|
||||
const onArchive = vi.fn();
|
||||
const onMarkRead = vi.fn();
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<IssueRow
|
||||
issue={createIssue({ title })}
|
||||
presentation="task"
|
||||
appearance="refreshed"
|
||||
unreadState="visible"
|
||||
onMarkRead={onMarkRead}
|
||||
leadingControl={<button type="button" onClick={onExpand}>Expand subtasks</button>}
|
||||
onArchive={onArchive}
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
const link = container.querySelector<HTMLAnchorElement>("[data-inbox-issue-link]");
|
||||
const expand = container.querySelector<HTMLButtonElement>('button:not([aria-label])');
|
||||
const archive = container.querySelector<HTMLButtonElement>('button[aria-label="Archive"]');
|
||||
expect(link?.href).toContain("/issues/PAP-1");
|
||||
expect(link?.contains(expand)).toBe(false);
|
||||
expect(link?.contains(archive)).toBe(false);
|
||||
// An inbox callback must not restore the old unread dot or its reserved slot.
|
||||
expect(container.querySelector('button[aria-label="Mark as read"]')).toBeNull();
|
||||
expect(container.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull();
|
||||
|
||||
await reactAct(async () => link?.focus());
|
||||
expect(document.activeElement).toBe(link);
|
||||
expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true");
|
||||
expect(container.querySelector('[data-slot="task-row-title-text"]')?.textContent).toBe(title);
|
||||
expect(document.querySelector('[role="tooltip"]')).toBeNull();
|
||||
|
||||
act(() => link?.dispatchEvent(new MouseEvent("mouseout", { bubbles: true, relatedTarget: document.body })));
|
||||
expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull();
|
||||
await reactAct(async () => { link?.blur(); link?.focus(); });
|
||||
expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBe("true");
|
||||
|
||||
act(() => {
|
||||
link?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
expand?.click();
|
||||
archive?.click();
|
||||
});
|
||||
expect(document.querySelector('[role="tooltip"]')).toBeNull();
|
||||
expect(container.querySelector('[data-slot="task-row-title"]')?.getAttribute("data-revealing")).toBeNull();
|
||||
expect(onExpand).toHaveBeenCalledTimes(1);
|
||||
expect(onArchive).toHaveBeenCalledTimes(1);
|
||||
|
||||
act(() => root.unmount());
|
||||
bounds.mockRestore();
|
||||
rangeBounds.mockRestore();
|
||||
});
|
||||
|
||||
it("preserves the legacy archive action density", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} onArchive={() => undefined} />);
|
||||
});
|
||||
|
||||
const archiveButton = container.querySelector<HTMLButtonElement>('button[aria-label="Archive"]');
|
||||
expect(archiveButton?.className).toContain("py-1");
|
||||
expect(archiveButton?.className).not.toContain("h-5");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("emphasizes unread canonical titles and overlays the accessible mark-read control", () => {
|
||||
const root = createRoot(container);
|
||||
const onMarkRead = vi.fn();
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue()}
|
||||
presentation="task"
|
||||
unreadState="visible"
|
||||
onMarkRead={onMarkRead}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const row = container.querySelector('[data-slot="task-row"]');
|
||||
const title = row?.querySelector('[data-slot="task-row-title"]');
|
||||
const unreadSlot = row?.querySelector('[data-testid="issue-row-unread-slot"]');
|
||||
const markReadButton = unreadSlot?.querySelector<HTMLButtonElement>('button[aria-label="Mark as read"]');
|
||||
expect(row?.getAttribute("data-unread")).toBe("true");
|
||||
expect(title?.className).toContain("font-semibold");
|
||||
expect(unreadSlot).not.toBeNull();
|
||||
expect(unreadSlot?.className).toContain("absolute");
|
||||
expect(markReadButton).not.toBeNull();
|
||||
expect(markReadButton?.closest("a")).toBeNull();
|
||||
|
||||
act(() => markReadButton?.click());
|
||||
expect(onMarkRead).toHaveBeenCalledTimes(1);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps read and unread rows aligned while allowing a smaller plain-row gutter", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(
|
||||
<>
|
||||
<IssueRow issue={createIssue({ id: "read" })} presentation="task" unreadState="hidden" />
|
||||
<IssueRow issue={createIssue({ id: "plain" })} presentation="task" />
|
||||
<IssueRow issue={createIssue({ id: "unread" })} presentation="task" unreadState="visible" />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
|
||||
const rows = Array.from(container.querySelectorAll('[data-slot="task-row"]'));
|
||||
const unreadSlot = rows[0]?.querySelector('[data-testid="issue-row-unread-slot"]');
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(rows[0]?.className).toBe(rows[2]?.className);
|
||||
expect(rows[1]?.className).toContain("pl-2 sm:pl-4");
|
||||
expect(unreadSlot).not.toBeNull();
|
||||
expect(unreadSlot?.className).toContain("absolute");
|
||||
expect(unreadSlot?.querySelector('button[aria-label="Mark as read"]')).toBeNull();
|
||||
expect(rows[1]?.querySelector('[data-testid="issue-row-unread-slot"]')).toBeNull();
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("preserves task-tree indentation slots in the canonical layout", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue()}
|
||||
presentation="task"
|
||||
treeGuides={2}
|
||||
chevronInGuide
|
||||
leadingControl={<button type="button">Expand</button>}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.querySelectorAll('[data-slot="task-row-tree-guide"]')).toHaveLength(2);
|
||||
expect(container.querySelector('[data-slot="task-row-leading"]')?.textContent).toContain("Expand");
|
||||
for (const connector of container.querySelectorAll('[data-slot="task-row-tree-connector"]')) {
|
||||
expect(connector.className).toContain("left-7");
|
||||
}
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps editable row controls keyboard-accessible and outside the navigation link", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue()}
|
||||
desktopMetaLeading={<StatusIcon status="todo" onChange={() => undefined} />}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const link = container.querySelector<HTMLAnchorElement>("[data-inbox-issue-link]");
|
||||
const statusButton = container.querySelector<HTMLButtonElement>(
|
||||
'button[aria-label="Change status (current: Todo)"]',
|
||||
);
|
||||
|
||||
expect(link).not.toBeNull();
|
||||
expect(statusButton).not.toBeNull();
|
||||
expect(statusButton?.tabIndex).toBe(0);
|
||||
expect(link?.contains(statusButton)).toBe(false);
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("suppresses accent hover styling when the row is selected", () => {
|
||||
const root = createRoot(container);
|
||||
const issue = createIssue();
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={issue} selected />);
|
||||
});
|
||||
|
||||
// The hover wash lives on the ROOT row band (not the overlay link) so the
|
||||
// tint paints behind the content. Selected rows suppress the accent hover.
|
||||
const row = container.firstElementChild as HTMLElement | null;
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(row).not.toBeNull();
|
||||
expect(row?.className).toContain("hover:bg-transparent");
|
||||
expect(row?.className).not.toContain("hover:bg-accent/50");
|
||||
// The overlay link no longer carries the hover wash.
|
||||
expect(link?.className ?? "").not.toContain("hover:bg-transparent");
|
||||
expect(link?.className ?? "").not.toContain("hover:bg-accent/50");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("neutralizes selected status and unread dot accents", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} selected unreadState="visible" />);
|
||||
});
|
||||
|
||||
const markReadButton = container.querySelector('button[aria-label="Mark as read"]');
|
||||
const unreadDot = markReadButton?.querySelector("span");
|
||||
// Selected rows neutralize the status glyph to muted via `!`-important
|
||||
// utilities, which override the glyph's inline colour var. The glyph is an
|
||||
// <svg> (SVGAnimatedString className), so match on the class attribute.
|
||||
const statusGlyph = container.querySelector('svg[class*="text-muted-foreground"]');
|
||||
|
||||
expect(markReadButton).not.toBeNull();
|
||||
expect(markReadButton?.className).toContain("hover:bg-muted/80");
|
||||
expect(markReadButton?.className).not.toContain("hover:bg-blue-500/20");
|
||||
expect(unreadDot).not.toBeNull();
|
||||
expect(unreadDot?.className).toContain("bg-muted-foreground/70");
|
||||
expect(unreadDot?.className).not.toContain("bg-blue-600");
|
||||
expect(statusGlyph).not.toBeNull();
|
||||
expect(statusGlyph?.getAttribute("class")).toContain("!text-muted-foreground");
|
||||
expect(statusGlyph?.getAttribute("class")).toContain("!border-muted-foreground");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("reserves the leading dot slot on read rows so unread rows never indent past them", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
// A read inbox row still supplies `unreadState` (as "hidden").
|
||||
root.render(<IssueRow issue={createIssue()} unreadState="hidden" />);
|
||||
});
|
||||
|
||||
// The desktop dot slot is reserved even when read (empty), so unread rows
|
||||
// add no column and line up with read rows.
|
||||
const slot = container.querySelector('[data-testid="issue-row-unread-slot"]');
|
||||
expect(slot).not.toBeNull();
|
||||
expect(slot?.className).toContain("w-4");
|
||||
expect(slot?.className).toContain("sm:inline-flex");
|
||||
// In flow, not an absolute overlay.
|
||||
expect(slot?.className).not.toContain("absolute");
|
||||
// Read rows carry no dot button in the slot.
|
||||
expect(slot?.querySelector('button[aria-label="Mark as read"]')).toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("puts the unread dot in the reserved desktop slot and overlays it on mobile", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} unreadState="visible" />);
|
||||
});
|
||||
|
||||
// Desktop: the dot lives in the reserved leading slot (far left, ahead of
|
||||
// any leading control such as a parent's collapse caret).
|
||||
const slot = container.querySelector('[data-testid="issue-row-unread-slot"]');
|
||||
expect(slot).not.toBeNull();
|
||||
expect(slot?.querySelector('button[aria-label="Mark as read"]')).not.toBeNull();
|
||||
|
||||
// Mobile: all inbox rows reserve a gutter and the dot stays fully inside
|
||||
// it, so the control cannot be clipped or indent the status/title.
|
||||
const mobileDot = container
|
||||
.querySelector('button[aria-label="Mark as read"].sm\\:hidden, span.sm\\:hidden button[aria-label="Mark as read"]')
|
||||
?.closest("span.sm\\:hidden");
|
||||
expect(mobileDot).not.toBeNull();
|
||||
expect(mobileDot?.className).toContain("absolute");
|
||||
expect(mobileDot?.className).toContain("left-0");
|
||||
expect(mobileDot?.className).not.toContain("order-first");
|
||||
expect(container.firstElementChild?.className).toContain("pl-4");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the issue detail breadcrumb source and href in the link target", () => {
|
||||
const root = createRoot(container);
|
||||
const issue = createIssue();
|
||||
const state = {
|
||||
issueDetailBreadcrumb: { label: "Inbox", href: "/PAP/inbox/mine" },
|
||||
issueDetailSource: "inbox",
|
||||
};
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={issue} issueLinkState={state} />);
|
||||
});
|
||||
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(link).not.toBeNull();
|
||||
expect(link?.getAttribute("to") ?? link?.getAttribute("href")).toBe("/issues/PAP-1");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("opts issue quicklook out for dense inbox rows", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} />);
|
||||
});
|
||||
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(link).not.toBeNull();
|
||||
expect(link?.getAttribute("data-disable-issue-quicklook")).toBe("true");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the visible row issue into the navigation prefetch path", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} />);
|
||||
});
|
||||
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(link?.getAttribute("data-issue-prefetch-id")).toBe("issue-1");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders titleSuffix inline after the issue title", () => {
|
||||
const root = createRoot(container);
|
||||
const issue = createIssue({ title: "Parent task" });
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={issue}
|
||||
titleSuffix={<span data-testid="suffix">(3 sub-tasks)</span>}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const titleEl = container.querySelector(".line-clamp-2, .truncate");
|
||||
expect(titleEl?.textContent).toContain("Parent task");
|
||||
expect(titleEl?.textContent).toContain("(3 sub-tasks)");
|
||||
expect(container.querySelector('[data-testid="suffix"]')).not.toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders checklist step numbers beside the issue identifier", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue({ identifier: "PAP-42" })}
|
||||
checklistStepNumber="2.1"
|
||||
mobileMeta="updated now"
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const metaRow = Array.from(container.querySelectorAll("span.flex.items-center.gap-2"))
|
||||
.find((element) => element.textContent?.includes("PAP-42"));
|
||||
|
||||
expect(metaRow).not.toBeUndefined();
|
||||
expect(metaRow?.textContent?.replace(/\s+/g, "")).toContain("2.1.PAP-42");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("marks the current checklist step without adding a left border", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={createIssue({ identifier: "PAP-42" })}
|
||||
checklistStepNumber="2.1"
|
||||
checklistCurrentStep
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
// `aria-current="step"` stays on the overlay link (the focusable target),
|
||||
// but the current-step wash moved to the ROOT row band alongside the hover
|
||||
// wash so it paints behind the content.
|
||||
const row = container.firstElementChild as HTMLElement | null;
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
|
||||
expect(link).not.toBeNull();
|
||||
expect(link?.getAttribute("aria-current")).toBe("step");
|
||||
expect(row?.className).toContain("bg-primary/5");
|
||||
expect(row?.className).not.toContain("border-l-");
|
||||
expect(link?.className ?? "").not.toContain("bg-primary/5");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("does not render a planning mode marker for planning work mode issues", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue({ workMode: "planning" })} />);
|
||||
});
|
||||
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(link).not.toBeNull();
|
||||
expect(link?.textContent).not.toContain("Planning");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders without error when titleSuffix is omitted", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} />);
|
||||
});
|
||||
|
||||
const titleEl = container.querySelector(".line-clamp-2, .truncate");
|
||||
expect(titleEl?.textContent).toContain("Inbox item");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("flags rows blocked by an assigned-backlog leaf with a parked-work badge", () => {
|
||||
const root = createRoot(container);
|
||||
const issue = createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "blocker-1",
|
||||
identifier: "PAP-2",
|
||||
title: "Parked child",
|
||||
status: "backlog",
|
||||
priority: "high",
|
||||
assigneeAgentId: "agent-99",
|
||||
assigneeUserId: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={issue} />);
|
||||
});
|
||||
|
||||
const badges = container.querySelectorAll('[data-testid="issue-row-parked-blocker"]');
|
||||
expect(badges.length).toBeGreaterThan(0);
|
||||
expect(badges[0]?.textContent).toContain("Blocked by parked work");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show the parked-work badge when assigned blocker is not in backlog", () => {
|
||||
const root = createRoot(container);
|
||||
const issue = createIssue({
|
||||
blockedBy: [
|
||||
{
|
||||
id: "blocker-1",
|
||||
identifier: "PAP-2",
|
||||
title: "Active child",
|
||||
status: "in_progress",
|
||||
priority: "high",
|
||||
assigneeAgentId: "agent-99",
|
||||
assigneeUserId: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={issue} />);
|
||||
});
|
||||
|
||||
expect(container.querySelector('[data-testid="issue-row-parked-blocker"]')).toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders no bottom divider by default", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} />);
|
||||
});
|
||||
|
||||
// Dividers are opt-in: without `showDivider` no row-separating border
|
||||
// renders on either the root band or the overlay link.
|
||||
const row = container.firstElementChild as HTMLElement | null;
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(row).not.toBeNull();
|
||||
expect(row?.className).not.toContain("border-b");
|
||||
expect(link?.className ?? "").not.toContain("border-b");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders an opt-in bottom divider on the row root when showDivider is set", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} showDivider />);
|
||||
});
|
||||
|
||||
// The divider lives on the ROOT row band with `last:border-b-0` so the real
|
||||
// last row drops its border — it is not on the overlay link.
|
||||
const row = container.firstElementChild as HTMLElement | null;
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
expect(row?.className).toContain("border-b");
|
||||
expect(row?.className).toContain("last:border-b-0");
|
||||
expect(link?.className ?? "").not.toContain("border-b");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("never renders a horizontal divider in canonical task presentation", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} presentation="task" showDivider />);
|
||||
});
|
||||
|
||||
const row = container.querySelector('[data-slot="task-row"]');
|
||||
expect(row?.className).not.toContain("border-b");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps the hover wash on the row root while the overlay link stays a bare positioning layer", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={createIssue()} />);
|
||||
});
|
||||
|
||||
const row = container.firstElementChild as HTMLElement | null;
|
||||
const link = container.querySelector("[data-inbox-issue-link]") as HTMLAnchorElement | null;
|
||||
// Hover wash paints behind the content on the root band...
|
||||
expect(row?.className).toContain("hover:bg-accent/50");
|
||||
expect(link?.className ?? "").not.toContain("hover:bg-accent/50");
|
||||
// ...and the overlay link keeps only positioning + focus concerns.
|
||||
expect(link?.className).toContain("absolute");
|
||||
expect(link?.className).toContain("inset-0");
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("recovery chip liveness", () => {
|
||||
const NOW = new Date("2026-08-18T12:00:00.000Z");
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function at(offsetMs: number) {
|
||||
return new Date(NOW.getTime() + offsetMs).toISOString();
|
||||
}
|
||||
|
||||
function recoveryIssue(retryAt: string, scheduledRetry: Issue["scheduledRetry"] = null): Issue {
|
||||
return createIssue({
|
||||
status: "in_progress",
|
||||
scheduledRetry,
|
||||
activeRecoveryAction: {
|
||||
id: "action-1",
|
||||
companyId: "company-1",
|
||||
sourceIssueId: "issue-1",
|
||||
recoveryIssueId: null,
|
||||
kind: "deliberate_wait_without_target",
|
||||
status: "active",
|
||||
ownerType: "agent",
|
||||
ownerAgentId: "agent-owner",
|
||||
ownerUserId: null,
|
||||
previousOwnerAgentId: "agent-owner",
|
||||
returnOwnerAgentId: "agent-owner",
|
||||
cause: "deliberate_wait_without_target",
|
||||
fingerprint: "fp",
|
||||
evidence: {},
|
||||
nextAction: "Record a real next step.",
|
||||
wakePolicy: {
|
||||
type: "bounded_owner_disposition_repair",
|
||||
retryAgentId: "agent-owner",
|
||||
attempt: 1,
|
||||
maxAttempts: 5,
|
||||
retryAt,
|
||||
scheduledRunId: "run-2",
|
||||
},
|
||||
monitorPolicy: null,
|
||||
attemptCount: 1,
|
||||
maxAttempts: 5,
|
||||
timeoutAt: retryAt,
|
||||
lastAttemptAt: retryAt,
|
||||
outcome: null,
|
||||
resolutionNote: null,
|
||||
resolvedAt: null,
|
||||
createdAt: at(-10 * 60_000),
|
||||
updatedAt: at(-10 * 60_000),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderChip(issue: Issue): HTMLElement | null {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<IssueRow issue={issue} />);
|
||||
});
|
||||
const chip = container.querySelector<HTMLElement>(
|
||||
"[data-testid='issue-row-recovery-indicator']",
|
||||
);
|
||||
const snapshot = chip?.cloneNode(true) as HTMLElement | null;
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
it.each(["working", "retry_scheduled", "failed"] as const)(
|
||||
"omits %s system interruption feedback without exposing legacy recovery in list rows",
|
||||
(state) => {
|
||||
const root = createRoot(container);
|
||||
const issue = recoveryIssue(at(3 * 60_000));
|
||||
issue.interruption = {
|
||||
intentId: "saved-input", responsibility: "system", state,
|
||||
nextRetryAt: state === "retry_scheduled" ? at(3 * 60_000) : null,
|
||||
canRetry: state === "failed", userAction: null,
|
||||
sourceRunIds: ["run-1"], observedRunId: "run-1",
|
||||
};
|
||||
try {
|
||||
for (const presentation of ["task", "legacy"] as const) {
|
||||
act(() => root.render(<IssueRow issue={issue} presentation={presentation} />));
|
||||
expect(container.textContent).toContain(issue.title);
|
||||
expect(container.querySelector("[data-inbox-issue-link]")?.getAttribute("href")).toBe("/issues/PAP-1");
|
||||
expect(container.textContent).not.toMatch(/Retry available|Thinking|Trying again soon|Recovery in progress/);
|
||||
expect(container.querySelector("[data-testid='issue-row-recovery-indicator']")).toBeNull();
|
||||
}
|
||||
} finally {
|
||||
act(() => root.unmount());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("shows native export activity from the action even without a scheduled retry", () => {
|
||||
const issue = recoveryIssue(at(-5 * 60_000));
|
||||
Object.assign(issue.activeRecoveryAction!, {
|
||||
kind: "active_run_watchdog", cause: "native_finalization_invalid",
|
||||
wakePolicy: { kind: "resume_native_run", runId: "native-run", notBefore: at(-5 * 60_000) },
|
||||
nativeRunActivity: { runId: "native-run", status: "running", workspaceOperationId: "export-operation" },
|
||||
});
|
||||
const chip = renderChip(issue);
|
||||
expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress");
|
||||
expect(chip?.getAttribute("aria-label")).not.toContain("missed");
|
||||
});
|
||||
|
||||
it("stays calm while the next attempt is still ahead", () => {
|
||||
const chip = renderChip(recoveryIssue(at(3 * 60_000)));
|
||||
expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress");
|
||||
expect(chip?.getAttribute("aria-label")).toContain("next try in 3m");
|
||||
});
|
||||
|
||||
it("warns once the stored attempt came due and never ran", () => {
|
||||
// The inbox chip must reach the same verdict as the source card, so a parent scanning
|
||||
// the inbox is not told recovery is running when nothing is.
|
||||
const chip = renderChip(recoveryIssue(at(-5 * 60_000)));
|
||||
expect(chip?.getAttribute("data-recovery-state")).toBe("needed");
|
||||
const label = chip?.getAttribute("aria-label") ?? "";
|
||||
expect(label).toContain("Recovery needed");
|
||||
expect(label).toContain("retry missed 5m ago");
|
||||
expect(label).not.toContain("next try");
|
||||
});
|
||||
|
||||
it.each(["task", "legacy"] as const)(
|
||||
"places the recovery chip immediately after the title in %s list rows",
|
||||
(presentation) => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(
|
||||
<IssueRow
|
||||
issue={recoveryIssue(at(-5 * 60_000))}
|
||||
presentation={presentation}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const titleCluster = container.querySelector('[data-slot="task-row-title-cluster"]');
|
||||
const title = titleCluster?.querySelector('[data-slot="task-row-title"]');
|
||||
const chip = titleCluster?.querySelector('[data-testid="issue-row-recovery-indicator"]');
|
||||
expect(titleCluster).not.toBeNull();
|
||||
expect(title).not.toBeNull();
|
||||
expect(chip).not.toBeNull();
|
||||
if (!title || !chip) throw new Error("Expected the title and recovery chip");
|
||||
expect(title.compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("stays calm when the overdue attempt is a verified live run", () => {
|
||||
const chip = renderChip(
|
||||
recoveryIssue(at(-5 * 60_000), {
|
||||
runId: "run-2",
|
||||
status: "running",
|
||||
agentId: "agent-owner",
|
||||
agentName: "CodexCoder",
|
||||
retryOfRunId: null,
|
||||
scheduledRetryAt: at(-5 * 60_000),
|
||||
scheduledRetryAttempt: 1,
|
||||
scheduledRetryReason: null,
|
||||
}),
|
||||
);
|
||||
expect(chip?.getAttribute("data-recovery-state")).toBe("in_progress");
|
||||
expect(chip?.getAttribute("aria-label")).toContain("attempt running now");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { $getSelection, $isRangeSelection, getNearestEditorFromDOMNode } from "lexical";
|
||||
import { buildSkillMentionHref } from "@paperclipai/shared";
|
||||
import { MarkdownEditor, type MentionOption } from "./MarkdownEditor";
|
||||
import type { SlashCommandOption } from "../context/EditorAutocompleteContext";
|
||||
|
||||
const mentions: MentionOption[] = [
|
||||
{ id: "agent:ada", kind: "agent", agentId: "ada", name: "Ada" },
|
||||
{ id: "user:pat", kind: "user", userId: "pat", name: "Pat" },
|
||||
{ id: "project:paperclip", kind: "project", projectId: "paperclip", name: "Paperclip" },
|
||||
{ id: "issue:task", kind: "issue", issueIdentifier: "TST-123", name: "TST-123 Example task" },
|
||||
];
|
||||
|
||||
const commands: SlashCommandOption[] = [
|
||||
{
|
||||
id: "skill:deploy", kind: "skill", skillId: "deploy", key: "deploy", name: "Deploy",
|
||||
slug: "deploy", description: null, href: buildSkillMentionHref("deploy", "deploy"), aliases: ["deploy"],
|
||||
},
|
||||
{
|
||||
id: "routine:nightly", kind: "routine", routineId: "nightly", name: "Nightly",
|
||||
status: "active", href: "routine://nightly", aliases: ["routine:Nightly"],
|
||||
},
|
||||
{ id: "action:goal", kind: "action", command: "goal", name: "Goal", description: "Set a goal", aliases: ["goal"] },
|
||||
];
|
||||
|
||||
describe("MarkdownEditor autocomplete separators", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: ReturnType<typeof createRoot>;
|
||||
let originalRangeRect: typeof Range.prototype.getBoundingClientRect;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("ResizeObserver", class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
});
|
||||
originalRangeRect = Range.prototype.getBoundingClientRect;
|
||||
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 10, 20);
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
Range.prototype.getBoundingClientRect = originalRangeRect;
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["skill", "/dep", "/deploy", true, ""],
|
||||
["routine", "/routine:Nigh", "/routine:Nightly", true, ""],
|
||||
["action", "/go", "/goal", false, ""],
|
||||
["agent", "@Ada", "@Ada", true, ""],
|
||||
["user", "@Pat", "@Pat", true, ""],
|
||||
["project", "@Paper", "@Paperclip", true, ""],
|
||||
["task", "@TST", "TST-123", true, ""],
|
||||
["project after a typed space", "@Paperclip", "@Paperclip", true, " "],
|
||||
["routine after typed spaces", "/routine:Nightly", "/routine:Nightly", true, " "],
|
||||
])("keeps a space after a completed %s and types outside its link", async (_kind, value, completion, linked, typedSuffix) => {
|
||||
const onChange = vi.fn();
|
||||
function ControlledEditor() {
|
||||
const [markdown, setMarkdown] = useState(value);
|
||||
return <MarkdownEditor value={markdown} onChange={(next) => {
|
||||
onChange(next);
|
||||
setMarkdown(next);
|
||||
}} actionCommands={commands} mentions={mentions} />;
|
||||
}
|
||||
await act(async () => {
|
||||
root.render(<ControlledEditor />);
|
||||
});
|
||||
|
||||
const editable = container.querySelector<HTMLElement>('[contenteditable="true"]')!;
|
||||
expect(editable).not.toBeNull();
|
||||
await act(async () => {
|
||||
editable.focus();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(editable.querySelector('[data-lexical-text="true"]')!.firstChild!);
|
||||
range.collapse(false);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
});
|
||||
if (typedSuffix) {
|
||||
const editor = getNearestEditorFromDOMNode(editable)!;
|
||||
await act(async () => {
|
||||
editor.update(() => {
|
||||
const selection = $getSelection();
|
||||
expect($isRangeSelection(selection)).toBe(true);
|
||||
if ($isRangeSelection(selection)) selection.insertText(typedSuffix);
|
||||
});
|
||||
});
|
||||
await act(async () => document.dispatchEvent(new Event("selectionchange")));
|
||||
}
|
||||
await vi.waitFor(() => expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).not.toBeNull());
|
||||
|
||||
await act(async () => {
|
||||
editable.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(editable.textContent).toBe(`${completion} `);
|
||||
expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null);
|
||||
const caretPrefix = document.createRange();
|
||||
caretPrefix.selectNodeContents(editable);
|
||||
const selection = window.getSelection()!;
|
||||
caretPrefix.setEnd(selection.anchorNode!, selection.anchorOffset);
|
||||
expect(caretPrefix.toString()).toBe(`${completion} `);
|
||||
});
|
||||
expect(onChange.mock.lastCall?.[0]).toMatch(/ $/);
|
||||
expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0");
|
||||
expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).toBeNull();
|
||||
|
||||
const editor = getNearestEditorFromDOMNode(editable)!;
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new Event("selectionchange"));
|
||||
editor.update(() => {
|
||||
const selection = $getSelection();
|
||||
expect($isRangeSelection(selection)).toBe(true);
|
||||
if ($isRangeSelection(selection)) selection.insertText("next");
|
||||
});
|
||||
});
|
||||
expect(editable.textContent).toBe(`${completion} next`);
|
||||
expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null);
|
||||
expect(onChange.mock.lastCall?.[0]).toMatch(/ next$/);
|
||||
expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0");
|
||||
});
|
||||
});
|
||||
@@ -1,306 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity";
|
||||
import { QueryErrorState, QueryView, queryViewKind, useQueryView, type QueryViewState } from "./QueryView";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const unavailable = () => new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" });
|
||||
const notFound = () => new ApiError("Issue not found", 404, { error: "Issue not found" });
|
||||
const forbidden = () => new ApiError("Forbidden", 403, { error: "Forbidden" });
|
||||
|
||||
describe("queryViewKind", () => {
|
||||
const base = { data: undefined, error: null, status: "pending" as const, fetchStatus: "fetching" as const };
|
||||
|
||||
it("loads, then is ready", () => {
|
||||
expect(queryViewKind(base)).toBe("loading");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" })).toBe("ready");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" })).toBe("ready");
|
||||
});
|
||||
|
||||
it("keeps data through a transient failure (stale) and shows an error only for real failures", () => {
|
||||
expect(queryViewKind({ ...base, data: 1, status: "error", error: unavailable() })).toBe("stale");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "error", error: notFound() })).toBe("error");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "error", error: forbidden() })).toBe("error");
|
||||
});
|
||||
|
||||
it("reconnects quietly when nothing has loaded yet and the app is waiting out an outage", () => {
|
||||
expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "reconnecting")).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, status: "error", error: unavailable() }, "offline")).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") }, "reconnecting")).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, status: "error", error: notFound() }, "reconnecting")).toBe("error");
|
||||
expect(queryViewKind({ ...base, status: "error", error: new Error("boom") }, "reconnecting")).toBe("error");
|
||||
});
|
||||
|
||||
it("shows retryable copy when a route keeps failing while the server is reachable", () => {
|
||||
// Nothing would refetch these: the probe loop only runs while the app is
|
||||
// not online. A placeholder here would never fill in.
|
||||
expect(queryViewKind({ ...base, status: "error", error: unavailable() })).toBe("error");
|
||||
expect(queryViewKind({ ...base, status: "error", error: new ApiError("Gateway timeout", 504, "upstream timed out") })).toBe("error");
|
||||
expect(queryViewKind({ ...base, status: "error", error: new TypeError("Failed to fetch") })).toBe("error");
|
||||
});
|
||||
|
||||
it("shows retryable copy for a route-level blip with no data, but keeps data through it", () => {
|
||||
const busy = new ApiError("Too many requests", 429, { error: "rate_limited" });
|
||||
const worker = new ApiError("WORKER_UNAVAILABLE", 503, { code: "WORKER_UNAVAILABLE", message: "restarting" });
|
||||
expect(queryViewKind({ ...base, status: "error", error: busy })).toBe("error");
|
||||
expect(queryViewKind({ ...base, status: "error", error: worker })).toBe("error");
|
||||
expect(queryViewKind({ ...base, status: "error", error: busy }, "reconnecting")).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "error", error: busy })).toBe("stale");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "error", error: worker })).toBe("stale");
|
||||
});
|
||||
|
||||
it("treats a paused fetch and in-flight transient retries as an outage", () => {
|
||||
expect(queryViewKind({ ...base, fetchStatus: "paused" })).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, failureReason: unavailable() })).toBe("reconnecting");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "paused" })).toBe("stale");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", failureReason: unavailable() })).toBe("stale");
|
||||
});
|
||||
|
||||
it("follows the app-wide connectivity state", () => {
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "fetching" }, "reconnecting")).toBe("stale");
|
||||
expect(queryViewKind({ ...base, data: 1, status: "success", fetchStatus: "idle" }, "reconnecting")).toBe("stale");
|
||||
expect(queryViewKind(base, "offline")).toBe("reconnecting");
|
||||
// A disabled query is not waiting on the network.
|
||||
expect(queryViewKind({ ...base, fetchStatus: "idle" }, "reconnecting")).toBe("loading");
|
||||
});
|
||||
|
||||
it("does not treat null data as missing", () => {
|
||||
expect(queryViewKind({ ...base, data: null, status: "success", fetchStatus: "idle" })).toBe("ready");
|
||||
expect(queryViewKind({ ...base, data: null, status: "error", error: unavailable() })).toBe("stale");
|
||||
});
|
||||
});
|
||||
|
||||
type Deferred<T> = { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void };
|
||||
function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((nextResolve, nextReject) => {
|
||||
resolve = nextResolve;
|
||||
reject = nextReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
describe("useQueryView and <QueryView>", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let client: QueryClient;
|
||||
let store: ConnectivityStore;
|
||||
let probe: ReturnType<typeof vi.fn<() => Promise<{ reachable: true }>>>;
|
||||
let attempts: Deferred<{ title: string }>[];
|
||||
let fetchCount: number;
|
||||
let views: QueryViewState<{ title: string }>[];
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false, networkMode: "always" } } });
|
||||
probe = vi.fn(async () => ({ reachable: true as const }));
|
||||
store = createConnectivityStore({ probe, browserOnline: true });
|
||||
attempts = [];
|
||||
fetchCount = 0;
|
||||
views = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
client.clear();
|
||||
store.dispose();
|
||||
});
|
||||
|
||||
function Harness({ staleHint = false, notFound }: { staleHint?: boolean; notFound?: React.ReactNode }) {
|
||||
const query = useQuery({
|
||||
queryKey: ["thing"],
|
||||
queryFn: () => {
|
||||
const attempt = deferred<{ title: string }>();
|
||||
attempts.push(attempt);
|
||||
fetchCount += 1;
|
||||
return attempt.promise;
|
||||
},
|
||||
});
|
||||
views.push(useQueryView(query));
|
||||
return (
|
||||
<QueryView query={query} action="load the thing" staleHint={staleHint} notFound={notFound}>
|
||||
{(data) => <p data-testid="data">{data.title}</p>}
|
||||
</QueryView>
|
||||
);
|
||||
}
|
||||
|
||||
function mount(props: { staleHint?: boolean; notFound?: React.ReactNode } = {}) {
|
||||
act(() => {
|
||||
root.render(
|
||||
<ConnectivityProvider store={store}>
|
||||
<QueryClientProvider client={client}>
|
||||
<Harness {...props} />
|
||||
</QueryClientProvider>
|
||||
</ConnectivityProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const last = () => views[views.length - 1]!;
|
||||
// React Query batches observer notifications on a timer, so flush macrotasks.
|
||||
const settle = async () => {
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
};
|
||||
|
||||
it("shows a placeholder, then the data", async () => {
|
||||
mount();
|
||||
expect(last().kind).toBe("loading");
|
||||
expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull();
|
||||
attempts[0]!.resolve({ title: "Loaded" });
|
||||
await settle();
|
||||
expect(last().kind).toBe("ready");
|
||||
expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded");
|
||||
});
|
||||
|
||||
it("keeps loaded data on screen when a refetch fails with a transient error", async () => {
|
||||
mount({ staleHint: true });
|
||||
attempts[0]!.resolve({ title: "Loaded" });
|
||||
await settle();
|
||||
await act(async () => {
|
||||
void client.refetchQueries({ queryKey: ["thing"] });
|
||||
});
|
||||
attempts[1]!.reject(unavailable());
|
||||
await settle();
|
||||
expect(last().kind).toBe("stale");
|
||||
expect(last().data).toEqual({ title: "Loaded" });
|
||||
expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Loaded");
|
||||
expect(container.querySelector('[data-query-view="stale"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
|
||||
expect(container.querySelector(".text-destructive")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a quiet placeholder when the first load fails during an outage", async () => {
|
||||
// The server is down: the probe fails, so the store is reconnecting and
|
||||
// will refetch every live query on recovery.
|
||||
probe.mockResolvedValue({ reachable: false, retryAfterMs: null } as unknown as { reachable: true });
|
||||
mount();
|
||||
attempts[0]!.reject(unavailable());
|
||||
store.reportError(unavailable());
|
||||
await settle();
|
||||
expect(store.getSnapshot().status).toBe("reconnecting");
|
||||
expect(last().kind).toBe("reconnecting");
|
||||
expect(container.querySelector('[data-query-view="placeholder"]')).not.toBeNull();
|
||||
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
|
||||
expect(container.textContent).not.toContain("tenant_app_unavailable");
|
||||
});
|
||||
|
||||
it("shows readable copy with Retry when one route keeps failing while the server is reachable", async () => {
|
||||
// The probe says the server is fine, so no recovery loop will ever refetch
|
||||
// this query: a placeholder would spin forever.
|
||||
mount();
|
||||
attempts[0]!.reject(unavailable());
|
||||
store.reportError(unavailable());
|
||||
await settle();
|
||||
expect(store.getSnapshot().status).toBe("online");
|
||||
expect(last().kind).toBe("error");
|
||||
expect(last().errorKind).toBe("transient");
|
||||
const alert = container.querySelector('[data-query-view="error"]');
|
||||
expect(alert).not.toBeNull();
|
||||
expect(alert?.textContent).not.toContain("tenant_app_unavailable");
|
||||
expect(alert?.querySelector("button")?.textContent).toContain("Retry");
|
||||
expect(container.querySelector('[data-query-view="placeholder"]')).toBeNull();
|
||||
await act(async () => {
|
||||
alert!.querySelector("button")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
expect(fetchCount).toBe(2);
|
||||
attempts[1]!.resolve({ title: "Recovered" });
|
||||
await settle();
|
||||
expect(last().kind).toBe("ready");
|
||||
expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered");
|
||||
});
|
||||
|
||||
it("shows readable copy and retries for a real error", async () => {
|
||||
mount();
|
||||
attempts[0]!.reject(new ApiError("Request failed: 500", 500, { error: "internal_error" }));
|
||||
await settle();
|
||||
expect(last().kind).toBe("error");
|
||||
expect(last().errorKind).toBe("unknown");
|
||||
const alert = container.querySelector('[data-query-view="error"]');
|
||||
expect(alert?.textContent).toContain("Couldn't load the thing");
|
||||
expect(alert?.textContent).not.toContain("internal_error");
|
||||
const retry = alert?.querySelector("button");
|
||||
expect(retry?.textContent).toContain("Retry");
|
||||
await act(async () => {
|
||||
retry!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
expect(fetchCount).toBe(2);
|
||||
attempts[1]!.resolve({ title: "Recovered" });
|
||||
await settle();
|
||||
expect(last().kind).toBe("ready");
|
||||
expect(container.querySelector('[data-testid="data"]')?.textContent).toBe("Recovered");
|
||||
});
|
||||
|
||||
it("renders not_found only for a real 404", async () => {
|
||||
mount({ notFound: <p data-testid="missing">Gone</p> });
|
||||
attempts[0]!.reject(notFound());
|
||||
await settle();
|
||||
expect(last().errorKind).toBe("not_found");
|
||||
expect(container.querySelector('[data-testid="missing"]')?.textContent).toBe("Gone");
|
||||
});
|
||||
|
||||
it("retry probes the server during an outage", async () => {
|
||||
mount();
|
||||
attempts[0]!.reject(unavailable());
|
||||
await settle();
|
||||
// The failed query made the store suspect an outage and probe; make the probe fail so the store is reconnecting.
|
||||
probe.mockResolvedValueOnce({ reachable: false, retryAfterMs: null } as unknown as { reachable: true });
|
||||
await settle();
|
||||
store.reportError(unavailable());
|
||||
await settle();
|
||||
probe.mockClear();
|
||||
act(() => last().retry());
|
||||
expect(fetchCount).toBe(2);
|
||||
if (store.getSnapshot().status !== "online") expect(probe).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("<QueryErrorState>", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("uses readable copy and leaves out Retry for errors a retry cannot fix", () => {
|
||||
act(() => {
|
||||
root.render(<QueryErrorState error={forbidden()} onRetry={() => undefined} size="inline" />);
|
||||
});
|
||||
expect(container.textContent).toContain("Forbidden");
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.render(<QueryErrorState error={new ApiError("access_denied", 403, { error: "access_denied" })} onRetry={() => undefined} />);
|
||||
});
|
||||
expect(container.textContent).not.toContain("access_denied");
|
||||
expect(container.textContent).toContain("permission");
|
||||
expect(container.querySelector("button")).toBeNull();
|
||||
|
||||
act(() => {
|
||||
root.render(<QueryErrorState error={new ApiError("x", 409, { error: "stale_revision" })} onRetry={() => undefined} size="page" />);
|
||||
});
|
||||
expect(container.textContent).not.toContain("stale_revision");
|
||||
expect(container.querySelector("button")?.textContent).toContain("Retry");
|
||||
});
|
||||
});
|
||||
@@ -1,133 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { useState } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ScheduleEditor,
|
||||
buildCron,
|
||||
getScheduleCronValidation,
|
||||
parseCronToPreset,
|
||||
} from "./ScheduleEditor";
|
||||
|
||||
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function Harness({
|
||||
initial,
|
||||
onChange,
|
||||
onValidityChange,
|
||||
}: {
|
||||
initial: string;
|
||||
onChange?: (value: string) => void;
|
||||
onValidityChange?: (valid: boolean) => void;
|
||||
}) {
|
||||
const [value, setValue] = useState(initial);
|
||||
return (
|
||||
<ScheduleEditor
|
||||
value={value}
|
||||
onValidityChange={onValidityChange}
|
||||
onChange={(cron) => {
|
||||
setValue(cron);
|
||||
onChange?.(cron);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function typeCron(input: HTMLInputElement, value: string) {
|
||||
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
|
||||
setter?.call(input, value);
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
function act(callback: () => void) {
|
||||
flushSync(callback);
|
||||
}
|
||||
|
||||
describe("ScheduleEditor cron helpers", () => {
|
||||
it("classifies unknown valid 5-field cron expressions as custom", () => {
|
||||
expect(parseCronToPreset("0 8-18/2 * * 1-5").preset).toBe("custom");
|
||||
expect(getScheduleCronValidation("0 8-18/2 * * 1-5").valid).toBe(true);
|
||||
});
|
||||
|
||||
it("still recognizes supported presets and emits their expected cron", () => {
|
||||
expect(parseCronToPreset("0 10 * * 1-5")).toMatchObject({
|
||||
preset: "weekdays",
|
||||
hour: "10",
|
||||
minute: "0",
|
||||
});
|
||||
expect(buildCron("weekdays", "8", "15", "1", "1")).toBe("15 8 * * 1-5");
|
||||
});
|
||||
|
||||
it("reports partial cron edits as invalid without treating them as presets", () => {
|
||||
const validation = getScheduleCronValidation("0 8-18/2 *");
|
||||
expect(validation.valid).toBe(false);
|
||||
expect(validation.message).toContain("5 fields");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ScheduleEditor", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function cronInput() {
|
||||
return container.querySelector<HTMLInputElement>('input[aria-label="Cron expression"]');
|
||||
}
|
||||
|
||||
it("renders unknown valid cron expressions in Custom with the original text", () => {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(<Harness initial="0 8-18/2 * * 1-5" />);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Custom (cron)");
|
||||
expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5");
|
||||
expect(container.textContent).toContain("Valid cron.");
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("keeps Custom open while partial edits and pasted valid cron values round-trip through parent state", () => {
|
||||
const onChange = vi.fn();
|
||||
const onValidityChange = vi.fn();
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(
|
||||
<Harness
|
||||
initial="0 8-18/2 * * 1-5"
|
||||
onChange={onChange}
|
||||
onValidityChange={onValidityChange}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
typeCron(cronInput()!, "0 8-18/2 *");
|
||||
});
|
||||
expect(cronInput()?.value).toBe("0 8-18/2 *");
|
||||
expect(cronInput()?.getAttribute("aria-invalid")).toBe("true");
|
||||
expect(container.textContent).toContain("Use exactly 5 fields");
|
||||
expect(onChange).not.toHaveBeenCalledWith("0 8-18/2 *");
|
||||
expect(onValidityChange).toHaveBeenLastCalledWith(false);
|
||||
|
||||
act(() => {
|
||||
typeCron(cronInput()!, "0 8-18/2 * * 1-5");
|
||||
});
|
||||
expect(cronInput()?.value).toBe("0 8-18/2 * * 1-5");
|
||||
expect(cronInput()?.getAttribute("aria-invalid")).toBe("false");
|
||||
expect(onChange).toHaveBeenLastCalledWith("0 8-18/2 * * 1-5");
|
||||
expect(onValidityChange).toHaveBeenLastCalledWith(true);
|
||||
|
||||
act(() => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -1,539 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
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,
|
||||
type ReusableExecutionWorkspaceLike,
|
||||
type ReusableWorkspaceOption,
|
||||
} from "@/lib/reusable-execution-workspaces";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> | undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
async function flush() {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
|
||||
function render(node: ReactNode, container: HTMLElement) {
|
||||
const root = createRoot(container);
|
||||
act(() => {
|
||||
root.render(node);
|
||||
});
|
||||
return root;
|
||||
}
|
||||
|
||||
function setInputValue(input: HTMLInputElement, value: string) {
|
||||
act(() => {
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
|
||||
valueSetter?.call(input, value);
|
||||
input.dispatchEvent(new InputEvent("input", { bubbles: true, data: value, inputType: "insertText" }));
|
||||
});
|
||||
}
|
||||
|
||||
function keyDown(target: Element, key: string) {
|
||||
act(() => {
|
||||
target.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
|
||||
});
|
||||
}
|
||||
|
||||
function workspace(overrides: Partial<ReusableExecutionWorkspaceLike>): ReusableExecutionWorkspaceLike {
|
||||
return {
|
||||
id: overrides.id ?? "workspace-id",
|
||||
name: overrides.name ?? "Workspace",
|
||||
cwd: overrides.cwd ?? null,
|
||||
lastUsedAt: overrides.lastUsedAt ?? "2026-06-24T00:00:00.000Z",
|
||||
status: overrides.status,
|
||||
branchName: overrides.branchName,
|
||||
};
|
||||
}
|
||||
|
||||
function buildWorkspaceSelectGroups(workspaces: readonly ReusableExecutionWorkspaceLike[]) {
|
||||
return buildReusableExecutionWorkspaceOptionGroups(workspaces, {
|
||||
now: "2026-06-24T12:00:00.000Z",
|
||||
}).map((group) => ({
|
||||
id: group.id,
|
||||
label: group.label,
|
||||
options: group.options,
|
||||
})) satisfies SearchableSelectGroup<string, ReusableWorkspaceOption>[];
|
||||
}
|
||||
|
||||
describe("SearchableSelect", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root | null;
|
||||
let originalResizeObserver: typeof ResizeObserver | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
originalResizeObserver = globalThis.ResizeObserver;
|
||||
globalThis.ResizeObserver = class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => {
|
||||
root?.unmount();
|
||||
});
|
||||
}
|
||||
globalThis.ResizeObserver = originalResizeObserver!;
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("renders grouped duplicate options while keeping selection by value", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
const alpha: SearchableSelectOption = { key: "recent:alpha", value: "alpha", label: "Alpha" };
|
||||
const groups: SearchableSelectGroup[] = [
|
||||
{ id: "recent", label: "Recent", options: [alpha] },
|
||||
{ id: "all", label: "All", options: [{ ...alpha, key: "all:alpha" }] },
|
||||
];
|
||||
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value="alpha"
|
||||
groups={groups}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
disablePortal
|
||||
renderOption={(option) => <span data-option-key={option.key}>{option.label}</span>}
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
expect(trigger?.textContent).toContain("Alpha");
|
||||
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(container.querySelector("[data-option-key='recent:alpha']")).not.toBeNull();
|
||||
expect(container.querySelector("[data-option-key='all:alpha']")).not.toBeNull();
|
||||
expect(container.querySelector("[data-mobile-entity-picker]")).not.toBeNull();
|
||||
expect(container.querySelector("[data-mobile-entity-picker-header]")?.textContent).toContain("Pick one");
|
||||
expect(container.querySelector('button[aria-label="Close selector"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("filters options and returns the selected option object", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
const bravo = { key: "all:bravo", value: "bravo", label: "Bravo", searchText: "secondary branch" };
|
||||
const groups: SearchableSelectGroup[] = [
|
||||
{
|
||||
id: "all",
|
||||
label: "All",
|
||||
options: [
|
||||
{ key: "all:alpha", value: "alpha", label: "Alpha", searchText: "primary branch" },
|
||||
bravo,
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={groups}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
searchPlaceholder="Search options..."
|
||||
disablePortal
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
setInputValue(input!, "sec br");
|
||||
await flush();
|
||||
|
||||
expect(container.textContent).not.toContain("Alpha");
|
||||
expect(container.textContent).toContain("Bravo");
|
||||
|
||||
const bravoItem = Array.from(container.querySelectorAll("[cmdk-item]")).find((item) => item.textContent?.includes("Bravo"));
|
||||
expect(bravoItem).not.toBeUndefined();
|
||||
act(() => {
|
||||
bravoItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(onValueChange).toHaveBeenCalledWith("bravo", bravo);
|
||||
});
|
||||
|
||||
it("ranks visible label matches ahead of lower-quality search text matches", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
const groups: SearchableSelectGroup[] = [
|
||||
{
|
||||
id: "all",
|
||||
label: "All",
|
||||
options: [
|
||||
{
|
||||
key: "all:path-only",
|
||||
value: "path-only",
|
||||
label: "Paperclip app",
|
||||
searchText: "/srv/paperclip/mobile-checkout",
|
||||
},
|
||||
{
|
||||
key: "all:mobile",
|
||||
value: "mobile",
|
||||
label: "Mobile agent chat",
|
||||
searchText: "/srv/paperclip/agent-chat",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={groups}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
searchPlaceholder="Search options..."
|
||||
disablePortal
|
||||
renderOption={(option) => <span data-option-key={option.key}>{option.label}</span>}
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
setInputValue(input!, "mobile");
|
||||
await flush();
|
||||
|
||||
const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) =>
|
||||
item.getAttribute("data-option-key"),
|
||||
);
|
||||
expect(renderedKeys).toEqual(["all:mobile", "all:path-only"]);
|
||||
|
||||
const commandList = container.querySelector("[data-slot='command-list']");
|
||||
expect(commandList?.className).toContain("overscroll-contain");
|
||||
expect(commandList?.className).toContain("touch-pan-y");
|
||||
});
|
||||
|
||||
it("applies custom filtering before custom scoring", async () => {
|
||||
const groups: SearchableSelectGroup[] = [
|
||||
{
|
||||
id: "all",
|
||||
options: [
|
||||
{ key: "all:alpha", value: "alpha", label: "Alpha", searchText: "visible" },
|
||||
{ key: "all:hidden", value: "hidden", label: "Hidden", searchText: "visible" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={groups}
|
||||
onValueChange={vi.fn()}
|
||||
placeholder="Pick one"
|
||||
searchPlaceholder="Search options..."
|
||||
disablePortal
|
||||
filterOption={(option, query) => option.value !== "hidden" && option.searchText === query}
|
||||
scoreOption={() => 0}
|
||||
renderOption={(option) => <span data-option-key={option.key}>{option.label}</span>}
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
setInputValue(input!, "visible");
|
||||
await flush();
|
||||
|
||||
const renderedKeys = Array.from(container.querySelectorAll("[data-option-key]")).map((item) =>
|
||||
item.getAttribute("data-option-key"),
|
||||
);
|
||||
expect(renderedKeys).toEqual(["all:alpha"]);
|
||||
});
|
||||
|
||||
it("shows loading, empty, and disabled states", async () => {
|
||||
const onValueChange = vi.fn();
|
||||
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={[{ id: "all", options: [{ key: "all:alpha", value: "alpha", label: "Alpha" }] }]}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
loading
|
||||
loadingMessage="Loading choices..."
|
||||
disablePortal
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
expect(container.textContent).toContain("Loading choices...");
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={[{ id: "all", options: [{ key: "all:alpha", value: "alpha", label: "Alpha" }] }]}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
searchPlaceholder="Search options..."
|
||||
emptyMessage="Nothing matched."
|
||||
disablePortal
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
setInputValue(input!, "zzz");
|
||||
await flush();
|
||||
expect(container.textContent).toContain("Nothing matched.");
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={[]}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Pick one"
|
||||
disabled
|
||||
disablePortal
|
||||
/>,
|
||||
);
|
||||
});
|
||||
expect(container.querySelector("button[role='combobox']")?.hasAttribute("disabled")).toBe(true);
|
||||
});
|
||||
|
||||
it("opens on focus and closes with Escape", async () => {
|
||||
root = render(
|
||||
<SearchableSelect
|
||||
value=""
|
||||
groups={[{ id: "all", options: [{ key: "all:alpha", value: "alpha", label: "Alpha" }] }]}
|
||||
onValueChange={vi.fn()}
|
||||
placeholder="Pick one"
|
||||
searchPlaceholder="Search options..."
|
||||
disablePortal
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
act(() => {
|
||||
trigger?.focus();
|
||||
});
|
||||
await flush();
|
||||
|
||||
const input = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
expect(trigger?.getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
keyDown(input!, "Escape");
|
||||
await flush();
|
||||
|
||||
expect(container.querySelector("input[placeholder='Search options...']")).toBeNull();
|
||||
expect(trigger?.getAttribute("aria-expanded")).toBe("false");
|
||||
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new Event("pointerdown", { bubbles: true, cancelable: true }));
|
||||
trigger?.focus();
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(container.querySelector("input[placeholder='Search options...']")).not.toBeNull();
|
||||
expect(trigger?.getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
const reopenedInput = container.querySelector("input[placeholder='Search options...']") as HTMLInputElement | null;
|
||||
expect(reopenedInput).not.toBeNull();
|
||||
setInputValue(reopenedInput!, "alp");
|
||||
await flush();
|
||||
|
||||
keyDown(reopenedInput!, "Escape");
|
||||
await flush();
|
||||
|
||||
expect(container.querySelector("input[placeholder='Search options...']")).toBeNull();
|
||||
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([
|
||||
workspace({
|
||||
id: "workspace-paperclip",
|
||||
name: "Paperclip app",
|
||||
cwd: "/srv/paperclip/home/paperclipai/paperclip/.paperclip/worktrees/PAP-11722-new-existing-workspace-selector",
|
||||
branchName: "feature/reusable-workspaces",
|
||||
status: "running",
|
||||
lastUsedAt: "2026-06-24T10:00:00.000Z",
|
||||
}),
|
||||
workspace({
|
||||
id: "workspace-marketing",
|
||||
name: "Marketing site",
|
||||
cwd: "/srv/paperclip/home/marketing-site",
|
||||
branchName: "landing-refresh",
|
||||
status: "idle",
|
||||
lastUsedAt: "2026-06-20T10:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
root = render(
|
||||
<SearchableSelect<string, ReusableWorkspaceOption>
|
||||
value=""
|
||||
groups={groups}
|
||||
onValueChange={onValueChange}
|
||||
placeholder="Choose an existing workspace"
|
||||
searchPlaceholder="Search workspaces..."
|
||||
filterOption={(option, query) => reusableWorkspaceOptionMatches(option, query)}
|
||||
disablePortal
|
||||
renderOption={(option, { selected }) => (
|
||||
<span data-option-key={option.key} data-selected={String(selected)}>
|
||||
{option.label}
|
||||
</span>
|
||||
)}
|
||||
/>,
|
||||
container,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector("button[role='combobox']") as HTMLButtonElement | null;
|
||||
act(() => {
|
||||
trigger?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
await flush();
|
||||
|
||||
const input = container.querySelector("input[placeholder='Search workspaces...']") as HTMLInputElement | null;
|
||||
expect(input).not.toBeNull();
|
||||
expect(container.textContent).toContain("Recent");
|
||||
expect(container.textContent).toContain("All workspaces");
|
||||
|
||||
setInputValue(input!, "pclip reusable");
|
||||
await flush();
|
||||
|
||||
expect(container.textContent).toContain("Paperclip app");
|
||||
expect(container.textContent).not.toContain("Marketing site");
|
||||
|
||||
const selectedOptionKey = () => (
|
||||
container.querySelector("[cmdk-item][aria-selected='true'] [data-option-key]")?.getAttribute("data-option-key")
|
||||
);
|
||||
|
||||
expect(selectedOptionKey()).toBe("recent:workspace-paperclip");
|
||||
keyDown(input!, "ArrowDown");
|
||||
await flush();
|
||||
expect(selectedOptionKey()).toBe("all:workspace-paperclip");
|
||||
|
||||
keyDown(input!, "ArrowUp");
|
||||
await flush();
|
||||
expect(selectedOptionKey()).toBe("recent:workspace-paperclip");
|
||||
|
||||
keyDown(input!, "ArrowDown");
|
||||
await flush();
|
||||
keyDown(input!, "Enter");
|
||||
await flush();
|
||||
|
||||
expect(onValueChange).toHaveBeenCalledWith(
|
||||
"workspace-paperclip",
|
||||
expect.objectContaining({
|
||||
key: "all:workspace-paperclip",
|
||||
value: "workspace-paperclip",
|
||||
workspaceId: "workspace-paperclip",
|
||||
}),
|
||||
);
|
||||
expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull();
|
||||
expect(trigger?.getAttribute("aria-expanded")).toBe("false");
|
||||
|
||||
act(() => {
|
||||
trigger?.focus();
|
||||
});
|
||||
await flush();
|
||||
|
||||
expect(container.querySelector("input[placeholder='Search workspaces...']")).toBeNull();
|
||||
expect(trigger?.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
});
|
||||
@@ -1,170 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { flushSync } from "react-dom";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { ToastProvider } from "../context/ToastContext";
|
||||
import { StandaloneBrowserControls } from "./StandaloneBrowserControls";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> = undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
await result;
|
||||
}
|
||||
|
||||
async function flushReact() {
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
|
||||
function installMatchMedia(initialMatches: Record<string, boolean> = {}) {
|
||||
type Listener = (event: MediaQueryListEvent) => void;
|
||||
const queries = new Map<string, { matches: boolean; listeners: Set<Listener> }>();
|
||||
|
||||
function getQuery(query: string) {
|
||||
let entry = queries.get(query);
|
||||
if (!entry) {
|
||||
entry = { matches: initialMatches[query] ?? false, listeners: new Set<Listener>() };
|
||||
queries.set(query, entry);
|
||||
}
|
||||
|
||||
return {
|
||||
get matches() {
|
||||
return entry.matches;
|
||||
},
|
||||
media: query,
|
||||
addEventListener: (_type: "change", listener: Listener) => {
|
||||
entry.listeners.add(listener);
|
||||
},
|
||||
removeEventListener: (_type: "change", listener: Listener) => {
|
||||
entry.listeners.delete(listener);
|
||||
},
|
||||
addListener: (listener: Listener) => {
|
||||
entry.listeners.add(listener);
|
||||
},
|
||||
removeListener: (listener: Listener) => {
|
||||
entry.listeners.delete(listener);
|
||||
},
|
||||
} as unknown as MediaQueryList;
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
configurable: true,
|
||||
value: (query: string) => getQuery(query),
|
||||
});
|
||||
|
||||
return {
|
||||
setMatches(query: string, matches: boolean) {
|
||||
const entry = queries.get(query) ?? { matches: false, listeners: new Set<Listener>() };
|
||||
entry.matches = matches;
|
||||
queries.set(query, entry);
|
||||
entry.listeners.forEach((listener) => listener({ matches, media: query } as MediaQueryListEvent));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("StandaloneBrowserControls", () => {
|
||||
let container: HTMLDivElement;
|
||||
const originalMatchMedia = window.matchMedia;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
Object.defineProperty(navigator, "standalone", { configurable: true, value: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete (navigator as Navigator & { standalone?: boolean }).standalone;
|
||||
if (originalMatchMedia) {
|
||||
Object.defineProperty(window, "matchMedia", { configurable: true, value: originalMatchMedia });
|
||||
} else {
|
||||
Object.defineProperty(window, "matchMedia", { configurable: true, value: undefined });
|
||||
}
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows refresh, share, and open-in-browser controls in mobile standalone mode", async () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<ToastProvider>
|
||||
<StandaloneBrowserControls mobile />
|
||||
</ToastProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull();
|
||||
expect(container.querySelector('[aria-label="Share"]')).not.toBeNull();
|
||||
expect(container.querySelector('[aria-label="Open in Browser"]')).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("hides controls in normal mobile browser mode", async () => {
|
||||
Object.defineProperty(navigator, "standalone", { configurable: true, value: false });
|
||||
installMatchMedia();
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<ToastProvider>
|
||||
<StandaloneBrowserControls mobile />
|
||||
</ToastProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(container.querySelector('[aria-label="Refresh"]')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("responds to all chromeless display-mode media query changes", async () => {
|
||||
Object.defineProperty(navigator, "standalone", { configurable: true, value: false });
|
||||
const media = installMatchMedia();
|
||||
const root = createRoot(container);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<TooltipProvider>
|
||||
<ToastProvider>
|
||||
<StandaloneBrowserControls mobile />
|
||||
</ToastProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(container.querySelector('[aria-label="Refresh"]')).toBeNull();
|
||||
|
||||
await act(() => {
|
||||
media.setMatches("(display-mode: fullscreen)", true);
|
||||
});
|
||||
await flushReact();
|
||||
|
||||
expect(container.querySelector('[aria-label="Refresh"]')).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,480 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FolderListResult } from "@paperclipai/shared";
|
||||
import {
|
||||
AllUnfiledBanner,
|
||||
BulkBar,
|
||||
DeleteFolderDialog,
|
||||
FolderFormDialog,
|
||||
FolderRail,
|
||||
MobileFolderSheet,
|
||||
MoveToMenu,
|
||||
folderSearchValue,
|
||||
normalizeFolderSelection,
|
||||
} from "./FolderControls";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
if (!globalThis.PointerEvent) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).PointerEvent = MouseEvent;
|
||||
}
|
||||
if (!Element.prototype.hasPointerCapture) {
|
||||
Element.prototype.hasPointerCapture = () => false;
|
||||
}
|
||||
if (!Element.prototype.scrollIntoView) {
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
}
|
||||
|
||||
function act(callback: () => void | Promise<void>) {
|
||||
let result: void | Promise<void> | undefined;
|
||||
flushSync(() => {
|
||||
result = callback();
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
const folderResult: FolderListResult = {
|
||||
kind: "routine",
|
||||
allCount: 4,
|
||||
unfiledCount: 1,
|
||||
folders: [
|
||||
{
|
||||
id: "folder-reporting",
|
||||
companyId: "company-1",
|
||||
kind: "routine",
|
||||
parentId: null,
|
||||
name: "Reporting",
|
||||
slug: "reporting",
|
||||
systemKey: null,
|
||||
path: "reporting",
|
||||
depth: 1,
|
||||
color: "indigo",
|
||||
position: 0,
|
||||
itemCount: 3,
|
||||
createdAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const skillFolderResult: FolderListResult = {
|
||||
kind: "skill",
|
||||
allCount: 8,
|
||||
unfiledCount: 1,
|
||||
folders: [
|
||||
{
|
||||
...folderResult.folders[0]!,
|
||||
id: "my",
|
||||
kind: "skill",
|
||||
name: "my",
|
||||
slug: "my",
|
||||
systemKey: "my",
|
||||
path: "my",
|
||||
itemCount: 1,
|
||||
},
|
||||
{
|
||||
...folderResult.folders[0]!,
|
||||
id: "engineering",
|
||||
kind: "skill",
|
||||
name: "Engineering",
|
||||
slug: "engineering",
|
||||
path: "engineering",
|
||||
itemCount: 3,
|
||||
},
|
||||
{
|
||||
...folderResult.folders[0]!,
|
||||
id: "code-review",
|
||||
kind: "skill",
|
||||
parentId: "engineering",
|
||||
name: "Code Review",
|
||||
slug: "code-review",
|
||||
path: "engineering/code-review",
|
||||
depth: 2,
|
||||
itemCount: 2,
|
||||
},
|
||||
{
|
||||
...folderResult.folders[0]!,
|
||||
id: "projects",
|
||||
kind: "skill",
|
||||
name: "projects",
|
||||
slug: "projects",
|
||||
systemKey: "projects",
|
||||
path: "projects",
|
||||
itemCount: 2,
|
||||
},
|
||||
{
|
||||
...folderResult.folders[0]!,
|
||||
id: "bundled",
|
||||
kind: "skill",
|
||||
name: "bundled",
|
||||
slug: "bundled",
|
||||
systemKey: "bundled",
|
||||
path: "bundled",
|
||||
itemCount: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("FolderControls", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root | null;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = null;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => {
|
||||
root?.unmount();
|
||||
});
|
||||
}
|
||||
container.remove();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("normalizes URL selection values for folder persistence", () => {
|
||||
expect(normalizeFolderSelection(null)).toBe("all");
|
||||
expect(normalizeFolderSelection("unfiled")).toBe("unfiled");
|
||||
expect(normalizeFolderSelection("folder-reporting")).toBe("folder-reporting");
|
||||
expect(folderSearchValue("all")).toBe("");
|
||||
expect(folderSearchValue("unfiled")).toBe("unfiled");
|
||||
expect(folderSearchValue("folder-reporting")).toBe("folder-reporting");
|
||||
});
|
||||
|
||||
it("renders All, user folders, and Unfiled with counts and selection callbacks", () => {
|
||||
const onSelect = vi.fn();
|
||||
root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<FolderRail
|
||||
result={folderResult}
|
||||
selection="all"
|
||||
itemLabelPlural="routines"
|
||||
allLabel="All routines"
|
||||
onSelect={onSelect}
|
||||
onCreate={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
onEdit={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("All routines");
|
||||
expect(container.textContent).toContain("Reporting");
|
||||
expect(container.textContent).toContain("Unfiled");
|
||||
expect(container.textContent).toContain("4");
|
||||
expect(container.textContent).toContain("3");
|
||||
expect(container.textContent).toContain("1");
|
||||
|
||||
const reportingButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Reporting"),
|
||||
);
|
||||
expect(reportingButton).toBeTruthy();
|
||||
|
||||
act(() => {
|
||||
reportingButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith("folder-reporting");
|
||||
});
|
||||
|
||||
it("marks the active row with aria-current, including virtual Unfiled", () => {
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<FolderRail
|
||||
result={folderResult}
|
||||
selection="unfiled"
|
||||
itemLabelPlural="routines"
|
||||
allLabel="All routines"
|
||||
onSelect={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
onRename={vi.fn()}
|
||||
onEdit={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const current = container.querySelector('[aria-current="page"]');
|
||||
expect(current?.textContent).toContain("Unfiled");
|
||||
});
|
||||
|
||||
it("renames a folder inline via double-click and Enter", () => {
|
||||
const onRename = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<FolderRail
|
||||
result={folderResult}
|
||||
selection="all"
|
||||
itemLabelPlural="routines"
|
||||
allLabel="All routines"
|
||||
onSelect={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
onRename={onRename}
|
||||
onEdit={vi.fn()}
|
||||
onDelete={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const nameButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Reporting"),
|
||||
);
|
||||
act(() => {
|
||||
nameButton?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
const input = container.querySelector<HTMLInputElement>("input");
|
||||
expect(input).toBeTruthy();
|
||||
expect(input?.value).toBe("Reporting");
|
||||
|
||||
act(() => {
|
||||
if (!input) return;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
||||
setter?.call(input, "Monthly reports");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
act(() => {
|
||||
input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onRename).toHaveBeenCalledWith(folderResult.folders[0], "Monthly reports");
|
||||
});
|
||||
|
||||
it("moves via MoveToMenu: Unfiled, a folder, and new-folder chaining", () => {
|
||||
const onMove = vi.fn();
|
||||
const onCreateAndMove = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<DropdownMenu open modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button type="button">Row actions</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<MoveToMenu
|
||||
folders={folderResult.folders}
|
||||
currentFolderId={null}
|
||||
onMove={onMove}
|
||||
onCreateAndMove={onCreateAndMove}
|
||||
/>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>,
|
||||
);
|
||||
});
|
||||
|
||||
const subTrigger = Array.from(document.querySelectorAll("[data-radix-collection-item]")).find(
|
||||
(element) => element.textContent?.includes("Move to"),
|
||||
);
|
||||
expect(subTrigger).toBeTruthy();
|
||||
act(() => {
|
||||
subTrigger?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
|
||||
});
|
||||
|
||||
const menuItems = Array.from(document.querySelectorAll('[role="menuitem"]'));
|
||||
const unfiledItem = menuItems.find((element) => element.textContent?.includes("Unfiled"));
|
||||
const folderItem = menuItems.find((element) => element.textContent?.includes("Reporting"));
|
||||
const newFolderItem = menuItems.find((element) => element.textContent?.includes("New folder"));
|
||||
expect(unfiledItem).toBeTruthy();
|
||||
expect(folderItem).toBeTruthy();
|
||||
expect(newFolderItem).toBeTruthy();
|
||||
|
||||
act(() => {
|
||||
unfiledItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onMove).toHaveBeenCalledWith(null);
|
||||
|
||||
act(() => {
|
||||
folderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onMove).toHaveBeenCalledWith("folder-reporting");
|
||||
|
||||
act(() => {
|
||||
newFolderItem?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onCreateAndMove).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates a folder through FolderFormDialog and disables submit on empty name", () => {
|
||||
const onSubmit = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<FolderFormDialog
|
||||
open
|
||||
kind="routine"
|
||||
folder={null}
|
||||
onOpenChange={vi.fn()}
|
||||
onSubmit={onSubmit}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const submit = Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent === "Create folder",
|
||||
) as HTMLButtonElement | undefined;
|
||||
expect(submit).toBeTruthy();
|
||||
expect(submit?.disabled).toBe(true);
|
||||
|
||||
const nameInput = document.querySelector<HTMLInputElement>("#folder-name");
|
||||
act(() => {
|
||||
if (!nameInput) return;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
|
||||
setter?.call(nameInput, "Reporting");
|
||||
nameInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(submit?.disabled).toBe(false);
|
||||
act(() => {
|
||||
submit?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onSubmit).toHaveBeenCalledWith({ name: "Reporting", color: expect.any(String) });
|
||||
});
|
||||
|
||||
it("states the forgiving delete behavior and confirms", () => {
|
||||
const onConfirm = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<DeleteFolderDialog
|
||||
open
|
||||
folder={folderResult.folders[0]!}
|
||||
itemLabelPlural="routines"
|
||||
onOpenChange={vi.fn()}
|
||||
onConfirm={onConfirm}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(document.body.textContent).toContain("3 routines in this folder won't be deleted");
|
||||
expect(document.body.textContent).toContain("They'll move to Unfiled");
|
||||
|
||||
const confirmButton = Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent === "Delete folder",
|
||||
);
|
||||
act(() => {
|
||||
confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
expect(onConfirm).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("selects a folder from the mobile sheet and dismisses", () => {
|
||||
const onSelect = vi.fn();
|
||||
const onOpenChange = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<MobileFolderSheet
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
result={folderResult}
|
||||
selection="all"
|
||||
allLabel="All routines"
|
||||
itemLabelPlural="Routines"
|
||||
onSelect={onSelect}
|
||||
onCreate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(document.body.textContent).toContain("All routines");
|
||||
expect(document.body.textContent).toContain("Unfiled");
|
||||
|
||||
const reportingRow = Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.includes("Reporting"),
|
||||
);
|
||||
act(() => {
|
||||
reportingRow?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith("folder-reporting");
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("preserves skill root grouping and child hierarchy in the mobile sheet", () => {
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<MobileFolderSheet
|
||||
open
|
||||
onOpenChange={vi.fn()}
|
||||
result={skillFolderResult}
|
||||
selection="all"
|
||||
allLabel="All skills"
|
||||
itemLabelPlural="Skills"
|
||||
onSelect={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const body = document.body.textContent ?? "";
|
||||
expect(body.indexOf("My Skills")).toBeLessThan(body.indexOf("Organization"));
|
||||
expect(body.indexOf("Organization")).toBeLessThan(body.indexOf("Engineering"));
|
||||
expect(body.indexOf("Engineering")).toBeLessThan(body.indexOf("Code Review"));
|
||||
expect(body.indexOf("Code Review")).toBeLessThan(body.indexOf("Projects"));
|
||||
expect(body.indexOf("Projects")).toBeLessThan(body.indexOf("Bundled"));
|
||||
expect(document.querySelector('[data-folder-id="engineering"] > .pl-3 [data-folder-id="code-review"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("persists AllUnfiledBanner dismissal across mounts", () => {
|
||||
const storageKey = "paperclip:test-folder-nudge";
|
||||
window.localStorage.removeItem(storageKey);
|
||||
const onCreateFolder = vi.fn();
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<AllUnfiledBanner
|
||||
storageKey={storageKey}
|
||||
itemLabelPlural="routines"
|
||||
onCreateFolder={onCreateFolder}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(container.textContent).toContain("Create your first folder");
|
||||
|
||||
const dismissButton = container.querySelector<HTMLButtonElement>(
|
||||
'button[aria-label="Dismiss folder suggestion"]',
|
||||
);
|
||||
act(() => {
|
||||
dismissButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
|
||||
});
|
||||
|
||||
expect(container.textContent).not.toContain("Create your first folder");
|
||||
expect(window.localStorage.getItem(storageKey)).toBe("1");
|
||||
|
||||
act(() => {
|
||||
root?.unmount();
|
||||
});
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<AllUnfiledBanner
|
||||
storageKey={storageKey}
|
||||
itemLabelPlural="routines"
|
||||
onCreateFolder={onCreateFolder}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
expect(container.textContent).not.toContain("Create your first folder");
|
||||
window.localStorage.removeItem(storageKey);
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FolderListResult } from "@paperclipai/shared";
|
||||
import { SkillFolderRail } from "./SkillFolderTree";
|
||||
|
||||
function pointerEvent(type: string, clientX: number) {
|
||||
const event = new MouseEvent(type, { bubbles: true, clientX });
|
||||
Object.defineProperty(event, "pointerId", { value: 1 });
|
||||
return event;
|
||||
}
|
||||
|
||||
const result: FolderListResult = {
|
||||
kind: "skill",
|
||||
allCount: 12,
|
||||
unfiledCount: 2,
|
||||
folders: [
|
||||
{
|
||||
id: "my-root",
|
||||
companyId: "company-1",
|
||||
kind: "skill",
|
||||
parentId: null,
|
||||
name: "My Skills",
|
||||
slug: "my",
|
||||
systemKey: "my",
|
||||
path: "my",
|
||||
depth: 1,
|
||||
color: null,
|
||||
position: 0,
|
||||
itemCount: 4,
|
||||
createdAt: new Date("2026-07-16T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-16T00:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "personal-root",
|
||||
companyId: "company-1",
|
||||
kind: "skill",
|
||||
parentId: "my-root",
|
||||
name: "Ada",
|
||||
slug: "ada",
|
||||
systemKey: "my:user-1",
|
||||
path: "my/ada",
|
||||
depth: 2,
|
||||
color: null,
|
||||
position: 0,
|
||||
itemCount: 4,
|
||||
createdAt: new Date("2026-07-16T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-16T00:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("SkillFolderRail", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
const onSelect = vi.fn<(selection: string) => void>();
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
onSelect.mockClear();
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<SkillFolderRail
|
||||
result={result}
|
||||
selection="all"
|
||||
tags={[]}
|
||||
activeTag={null}
|
||||
onSelect={onSelect}
|
||||
onSelectTag={vi.fn()}
|
||||
onCreateFolder={vi.fn()}
|
||||
onRenameFolder={vi.fn()}
|
||||
onEditFolder={vi.fn()}
|
||||
onMoveFolder={vi.fn()}
|
||||
onDeleteFolder={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
it("uses the wider default and persists drag resizing", () => {
|
||||
const rail = container.firstElementChild as HTMLDivElement;
|
||||
const separator = container.querySelector('[role="separator"]') as HTMLDivElement;
|
||||
expect(rail.style.width).toBe("288px");
|
||||
separator.setPointerCapture = vi.fn();
|
||||
|
||||
flushSync(() => {
|
||||
separator.dispatchEvent(pointerEvent("pointerdown", 288));
|
||||
separator.dispatchEvent(pointerEvent("pointermove", 320));
|
||||
separator.dispatchEvent(pointerEvent("pointerup", 320));
|
||||
});
|
||||
|
||||
expect(rail.style.width).toBe("320px");
|
||||
expect(window.localStorage.getItem("paperclip.skills.folderRail.width")).toBe("320");
|
||||
});
|
||||
|
||||
it("keeps virtual and folder counts on the same grid column", () => {
|
||||
const allRow = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("All skills"));
|
||||
const myLabel = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("My Skills"));
|
||||
const myRow = myLabel?.parentElement;
|
||||
|
||||
expect(allRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)");
|
||||
expect(myRow?.className).toContain("grid-cols-(--gtc-folder-row-actions)");
|
||||
expect(allRow?.querySelector(".tabular-nums")?.textContent).toBe("12");
|
||||
expect(myRow?.querySelector(".tabular-nums")?.textContent).toBe("4");
|
||||
});
|
||||
|
||||
it("selects and toggles a folder when its row label is clicked", () => {
|
||||
const myLabel = Array.from(container.querySelectorAll("button"))
|
||||
.find((button) => button.textContent?.includes("My Skills"));
|
||||
|
||||
expect(container.textContent).not.toContain("Ada");
|
||||
flushSync(() => myLabel?.click());
|
||||
|
||||
expect(onSelect).toHaveBeenCalledWith("my-root");
|
||||
expect(container.textContent).toContain("Ada");
|
||||
expect(container.querySelector('[aria-label="Collapse folder"]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
|
||||
const list = vi.fn<(issueId: string) => Promise<McpAppViewSummary[]>>();
|
||||
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: (issueId: string) => list(issueId) } }));
|
||||
|
||||
const { McpAppIssueProvider, useMcpAppViewsForRun } = await import("./McpAppIssueContext");
|
||||
|
||||
function view(id: string, runId: string): McpAppViewSummary {
|
||||
return {
|
||||
id, issueId: "issue-1", runId, connectionId: "conn-1", applicationName: "Circleback",
|
||||
toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function wrapper(client: QueryClient) {
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={client}>
|
||||
<McpAppIssueProvider issueId="issue-1">{children}</McpAppIssueProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function renderHook<P, R>(hook: (props: P) => R, options: { wrapper: (props: { children: ReactNode }) => ReactNode; initialProps?: P }) {
|
||||
const result = { current: undefined as unknown as R };
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
const Wrapper = options.wrapper;
|
||||
function Probe({ props }: { props: P }) {
|
||||
result.current = hook(props);
|
||||
return null;
|
||||
}
|
||||
const render = (props: P) => act(() => root.render(<Wrapper><Probe props={props} /></Wrapper>));
|
||||
await render(options.initialProps as P);
|
||||
return { result, rerender: (props: P) => render(props), unmount: () => act(() => root.unmount()) };
|
||||
}
|
||||
|
||||
async function waitFor(check: () => void, timeoutMs = 2000) {
|
||||
const started = Date.now();
|
||||
for (;;) {
|
||||
try {
|
||||
check();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (Date.now() - started > timeoutMs) throw error;
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => list.mockReset());
|
||||
|
||||
describe("useMcpAppViewsForRun", () => {
|
||||
it("refreshes the task's list once when a live run completes another MCP tool call", async () => {
|
||||
list.mockResolvedValueOnce([]).mockResolvedValueOnce([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result, rerender } = await renderHook(
|
||||
({ refreshKey }: { refreshKey: string }) => useMcpAppViewsForRun("run-1", { refreshKey }),
|
||||
{ wrapper: wrapper(client), initialProps: { refreshKey: "0:running" } },
|
||||
);
|
||||
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
|
||||
expect(result.current.views).toEqual([]);
|
||||
await rerender({ refreshKey: "1:running" });
|
||||
await waitFor(() => expect(list).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"]));
|
||||
await rerender({ refreshKey: "1:running" });
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("refreshes once for a settled reply newer than the loaded list", async () => {
|
||||
list.mockResolvedValueOnce([]).mockResolvedValue([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result } = await renderHook(
|
||||
() => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() + 60_000 }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.views.map((v) => v.id)).toEqual(["v1"]));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not refresh for a reply older than the loaded list", async () => {
|
||||
list.mockResolvedValue([view("v1", "run-1")]);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const { result } = await renderHook(
|
||||
() => useMcpAppViewsForRun("run-1", { notBeforeMs: Date.now() - 60_000 }),
|
||||
{ wrapper: wrapper(client) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.views).toHaveLength(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(list).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,111 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { McpAppViewSummary } from "@paperclipai/shared";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
|
||||
const detail = vi.fn(() => new Promise(() => undefined));
|
||||
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { list: vi.fn(), detail: (...args: unknown[]) => detail(...(args as [])), callTool: vi.fn() } }));
|
||||
|
||||
const { McpAppIssueProvider } = await import("./McpAppIssueContext");
|
||||
const { McpAppTurnViews } = await import("./McpAppTurnViews");
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function views(count: number): McpAppViewSummary[] {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
id: `00000000-0000-4000-8000-00000000000${index}`, issueId: "issue-1", runId: "run-1", connectionId: "conn-1",
|
||||
applicationName: "Circleback", toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings",
|
||||
resourceUri: "ui://circleback/meetings", toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
}));
|
||||
}
|
||||
|
||||
let observers: Array<{ callback: IntersectionObserverCallback; targets: Element[] }> = [];
|
||||
class FakeIntersectionObserver {
|
||||
targets: Element[] = [];
|
||||
constructor(public callback: IntersectionObserverCallback) { observers.push(this); }
|
||||
observe(target: Element) { this.targets.push(target); }
|
||||
disconnect() { this.targets = []; }
|
||||
unobserve() {}
|
||||
takeRecords() { return []; }
|
||||
}
|
||||
|
||||
async function render(input: number | McpAppViewSummary[]) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(queryKeys.mcpApps.views("issue-1"), typeof input === "number" ? views(input) : input);
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<McpAppIssueProvider issueId="issue-1"><McpAppTurnViews runId="run-1" /></McpAppIssueProvider>
|
||||
</QueryClientProvider>,
|
||||
));
|
||||
return { container, root };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
observers = [];
|
||||
detail.mockClear();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("McpAppTurnViews", () => {
|
||||
const identityViews = (): McpAppViewSummary[] => views(4).map((view) => ({
|
||||
...view,
|
||||
id: `profile-${view.id}`,
|
||||
applicationName: "GitHub",
|
||||
toolName: "mcp.github:get-me",
|
||||
upstreamToolName: "get_me",
|
||||
resourceUri: "ui://github-mcp-server/get-me",
|
||||
}));
|
||||
|
||||
it("renders no cards or documents for repeated saved GitHub identity lookups", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
const { container, root } = await render(identityViews());
|
||||
expect(container.childElementCount).toBe(0);
|
||||
expect(observers).toHaveLength(0);
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("counts only visible widgets toward the per-run limit", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
const { container, root } = await render([...identityViews(), ...views(7)]);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5);
|
||||
expect(container.textContent).not.toContain("Get me");
|
||||
const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more");
|
||||
expect(more).toBeTruthy();
|
||||
await act(async () => more!.click());
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7);
|
||||
expect(container.textContent).not.toContain("Get me");
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("loads a view's document only when it nears the viewport", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const { container, root } = await render(2);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(2);
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
const first = observers[0]!;
|
||||
await act(async () => first.callback([{ isIntersecting: true, target: first.targets[0]! } as IntersectionObserverEntry], first as unknown as IntersectionObserver));
|
||||
expect(detail).toHaveBeenCalledTimes(1);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-view-placeholder]")).toHaveLength(1);
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("shows five views per run and the rest on request", async () => {
|
||||
vi.stubGlobal("IntersectionObserver", FakeIntersectionObserver);
|
||||
const { container, root } = await render(7);
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(5);
|
||||
const more = [...container.querySelectorAll("button")].find((button) => button.textContent === "Show 2 more")!;
|
||||
expect(more).toBeTruthy();
|
||||
await act(async () => more.click());
|
||||
expect(container.querySelectorAll("[data-testid=mcp-app-turn-view]")).toHaveLength(7);
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { messageSent: vi.fn(async () => ({ commentId: "c1" })) } }));
|
||||
import type { McpAppViewDetail } from "@paperclipai/shared";
|
||||
import { McpAppViewContent, useMcpAppMessageProposal, type McpAppViewContentProps } from "./McpAppView";
|
||||
import { McpAppFrame } from "./McpAppFrame";
|
||||
import { McpAppIssueProvider } from "./McpAppIssueContext";
|
||||
import { mcpAppNavigationGuardSupported } from "./mcp-app-host";
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
const detail: McpAppViewDetail = {
|
||||
id: "view-1", issueId: "issue-1", runId: "run-1", connectionId: "conn-1", applicationName: "Circleback",
|
||||
toolName: "mcp.circleback:displaymeetings", upstreamToolName: "DisplayMeetings", resourceUri: "ui://circleback/meetings",
|
||||
toolInput: {}, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
toolResult: { content: [] },
|
||||
resource: { uri: "ui://circleback/meetings", html: "<p>cards</p>", csp: {}, permissions: {}, prefersBorder: true },
|
||||
};
|
||||
|
||||
async function render(props: Partial<McpAppViewContentProps> = {}) {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(
|
||||
<McpAppViewContent detail={detail} status="ready" callTool={async () => ({ content: [] })} displayName="Display meetings" {...props} />,
|
||||
));
|
||||
return { container, root };
|
||||
}
|
||||
|
||||
function button(label: string): HTMLButtonElement {
|
||||
const found = [...document.querySelectorAll("button")].find((element) => element.textContent?.trim() === label);
|
||||
if (!found) throw new Error(`No button "${label}"`);
|
||||
return found as HTMLButtonElement;
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("McpAppViewContent", () => {
|
||||
it("does not mount a view where the navigation guard cannot work", async () => {
|
||||
expect(mcpAppNavigationGuardSupported()).toBe(false);
|
||||
const { container, root } = await render();
|
||||
expect(container.querySelector("iframe")).toBeNull();
|
||||
expect(container.textContent).toContain("This browser can't show this app's widget safely.");
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("mounts the view where the Navigation API is available", async () => {
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const { container, root } = await render();
|
||||
expect(container.querySelector("iframe")).not.toBeNull();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("shows a view's proposed message under the widget and sends it only on Send", async () => {
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const onSendProposal = vi.fn();
|
||||
const onDismissProposal = vi.fn();
|
||||
const { container, root } = await render({
|
||||
proposal: { text: "Summarize the Heavybit meeting", status: "pending" }, onSendProposal, onDismissProposal,
|
||||
});
|
||||
const card = container.querySelector("[data-testid=mcp-app-message-proposal]")!;
|
||||
expect(card.textContent).toContain("Circleback wants to send:");
|
||||
expect(card.textContent).toContain("Summarize the Heavybit meeting");
|
||||
// The card comes after the widget.
|
||||
expect(container.querySelector("iframe")!.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(onSendProposal).not.toHaveBeenCalled();
|
||||
await act(async () => button("Dismiss").click());
|
||||
expect(onDismissProposal).toHaveBeenCalledTimes(1);
|
||||
await act(async () => button("Send").click());
|
||||
expect(onSendProposal).toHaveBeenCalledTimes(1);
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("shows the view full screen in a dialog, with one frame at a time", async () => {
|
||||
vi.stubGlobal("navigation", { addEventListener: () => undefined });
|
||||
const onDisplayModeChange = vi.fn();
|
||||
const { container, root } = await render({ displayMode: "fullscreen", onDisplayModeChange });
|
||||
const dialog = document.querySelector("[data-testid=mcp-app-fullscreen]")!;
|
||||
expect(dialog).not.toBeNull();
|
||||
expect(dialog.querySelectorAll("iframe")).toHaveLength(1);
|
||||
expect(dialog.querySelector("iframe")!.getAttribute("data-display-mode")).toBe("fullscreen");
|
||||
expect(document.querySelectorAll("iframe")).toHaveLength(1);
|
||||
expect(container.querySelector("[data-testid=mcp-app-view-fullscreen-placeholder]")).not.toBeNull();
|
||||
await act(async () => button("Exit full screen").click());
|
||||
expect(onDisplayModeChange).toHaveBeenCalledWith("inline");
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("starts a new frame when the host's capabilities change, so the view handshakes again", async () => {
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
const frame = (proposeMessage?: (text: string) => Promise<void>) => (
|
||||
<McpAppFrame title="Circleback" viewId="view-1" toolName="DisplayMeetings" resource={detail.resource}
|
||||
toolInput={{}} toolResult={{ content: [] }} callTool={async () => ({ content: [] })} proposeMessage={proposeMessage} />
|
||||
);
|
||||
await act(async () => root.render(frame()));
|
||||
const first = container.querySelector("iframe");
|
||||
await act(async () => root.render(frame(async () => undefined)));
|
||||
expect(container.querySelector("iframe")).not.toBe(first);
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
|
||||
it("retries a failed Send with the same request id, so the comment is posted once", async () => {
|
||||
const sendMessage = vi.fn()
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
let api: ReturnType<typeof useMcpAppMessageProposal> | null = null;
|
||||
function Harness() {
|
||||
api = useMcpAppMessageProposal("issue-1", "view-1");
|
||||
return null;
|
||||
}
|
||||
const container = document.createElement("div");
|
||||
const root = createRoot(container);
|
||||
await act(async () => root.render(<McpAppIssueProvider issueId="issue-1" sendMessage={sendMessage}><Harness /></McpAppIssueProvider>));
|
||||
let settled = false;
|
||||
await act(async () => { void api!.proposeMessage!("Summarize m1").then(() => { settled = true; }); });
|
||||
await act(async () => { api!.onSend!(); });
|
||||
expect(api!.proposal).toMatchObject({ status: "error" });
|
||||
expect(settled).toBe(false);
|
||||
await act(async () => { api!.onSend!(); });
|
||||
expect(sendMessage).toHaveBeenCalledTimes(2);
|
||||
expect(sendMessage.mock.calls[0]![1]).toBe(sendMessage.mock.calls[1]![1]);
|
||||
expect(settled).toBe(true);
|
||||
expect(api!.proposal).toBeNull();
|
||||
await act(async () => root.unmount());
|
||||
});
|
||||
});
|
||||
@@ -1,226 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, type ReactElement } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MarkdownEditor } from "../MarkdownEditor";
|
||||
import { IssueAttachmentsSection } from "../IssueAttachmentsSection";
|
||||
import { ArtifactDropzone } from "../artifacts/ArtifactDropzone";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
|
||||
import { Dialog, DialogContent, DialogTitle } from "../ui/dialog";
|
||||
import { ComposerFileDropTarget } from "./ComposerFileDropTarget";
|
||||
|
||||
let host: HTMLDivElement;
|
||||
let root: Root;
|
||||
const file = new File(["image"], "screenshot.png", { type: "image/png" });
|
||||
function render(content: ReactElement) { act(() => root.render(content)); }
|
||||
function drag(type: string, target: EventTarget = document.body, types = ["Files"], relatedTarget: EventTarget | null = null) {
|
||||
const event = new MouseEvent(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperties(event, {
|
||||
dataTransfer: { value: { types, files: types.includes("Files") ? [file] : [], items: types.includes("Files") ? [{ kind: "file", type: file.type, getAsFile: () => file }] : [], dropEffect: "none" } },
|
||||
relatedTarget: { value: relatedTarget },
|
||||
});
|
||||
act(() => { target.dispatchEvent(event); });
|
||||
return event;
|
||||
}
|
||||
const overlay = () => document.querySelector('[data-testid="composer-file-drop-overlay"]');
|
||||
beforeEach(() => { vi.stubGlobal("DragEvent", MouseEvent); host = document.createElement("div"); document.body.append(host); root = createRoot(host); });
|
||||
afterEach(() => { act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); });
|
||||
|
||||
describe("composer screen file drops", () => {
|
||||
it("accepts a drop outside the composer exactly once and clears the overlay", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<ComposerFileDropTarget enabled onFiles={onFiles} />);
|
||||
expect(drag("dragenter").defaultPrevented).toBe(true);
|
||||
expect(overlay()?.textContent).toContain("Drop files to attach");
|
||||
expect(drag("dragover").defaultPrevented).toBe(true);
|
||||
const downstream = vi.fn();
|
||||
document.body.addEventListener("drop", downstream, { once: true });
|
||||
expect(drag("drop").defaultPrevented).toBe(true);
|
||||
expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
expect(downstream).not.toHaveBeenCalled();
|
||||
document.body.removeEventListener("drop", downstream);
|
||||
expect(overlay()).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the overlay while moving between children, then clears on exit or cancellation", () => {
|
||||
render(<ComposerFileDropTarget enabled onFiles={vi.fn()} />);
|
||||
drag("dragenter"); drag("dragenter", host); drag("dragleave", document.body, ["Files"], host);
|
||||
expect(overlay()).not.toBeNull();
|
||||
drag("dragleave", host);
|
||||
expect(overlay()).toBeNull();
|
||||
for (const cancel of ["dragend", "blur"]) {
|
||||
drag("dragenter");
|
||||
act(() => { window.dispatchEvent(new Event(cancel)); });
|
||||
expect(overlay()).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears a nested drag when the pointer leaves the window", () => {
|
||||
render(<ComposerFileDropTarget enabled onFiles={vi.fn()} />);
|
||||
drag("dragenter"); drag("dragenter", host);
|
||||
drag("dragleave", document.documentElement);
|
||||
expect(overlay()).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves description editor file uploads and clears both overlays", async () => {
|
||||
const onFiles = vi.fn(); const onDropFile = vi.fn().mockResolvedValue(undefined);
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<MarkdownEditor value="Description" onChange={vi.fn()} onDropFile={onDropFile} />
|
||||
</>);
|
||||
const editor = host.querySelector('[contenteditable="true"]')!;
|
||||
expect(editor).not.toBeNull();
|
||||
drag("dragenter"); expect(overlay()).not.toBeNull();
|
||||
drag("dragenter", editor); drag("dragover", editor);
|
||||
expect(overlay()).toBeNull();
|
||||
expect(host.textContent).toContain("Drop file to upload");
|
||||
const attachment = new File(["notes"], "notes.txt", { type: "text/plain" });
|
||||
const event = new MouseEvent("drop", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, "dataTransfer", { value: { types: ["Files"], files: [attachment] } });
|
||||
await act(async () => { editor.dispatchEvent(event); });
|
||||
expect(onDropFile).toHaveBeenCalledExactlyOnceWith(attachment);
|
||||
expect(onFiles).not.toHaveBeenCalled();
|
||||
expect(host.textContent).not.toContain("Drop file to upload");
|
||||
expect(overlay()).toBeNull();
|
||||
drag("drop"); expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
});
|
||||
|
||||
it("keeps image drops in the description image plugin", async () => {
|
||||
const onFiles = vi.fn();
|
||||
const uploadImage = vi.fn().mockResolvedValue("/description-image.png");
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<MarkdownEditor value="Description" onChange={vi.fn()} imageUploadHandler={uploadImage} />
|
||||
</>);
|
||||
const editor = host.querySelector('[contenteditable="true"]')!;
|
||||
drag("dragenter", editor); expect(overlay()).toBeNull();
|
||||
expect(host.textContent).toContain("Drop image to upload");
|
||||
await act(async () => { drag("drop", editor); });
|
||||
expect(uploadImage).toHaveBeenCalledExactlyOnceWith(file);
|
||||
expect(onFiles).not.toHaveBeenCalled();
|
||||
expect(host.textContent).not.toContain("Drop image to upload");
|
||||
});
|
||||
|
||||
it.each(["parent", "readOnly"])("leaves %s editor drops with the composer", (mode) => {
|
||||
const onFiles = vi.fn(); const onDropFile = vi.fn();
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<MarkdownEditor value="Description" onChange={vi.fn()} onDropFile={onDropFile}
|
||||
readOnly={mode === "readOnly"} fileDropTarget={mode === "parent" ? "parent" : "editor"} />
|
||||
</>);
|
||||
drag("drop", host.querySelector(".paperclip-mdxeditor-scope")!);
|
||||
expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
expect(onDropFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves the task attachments section drop handler", () => {
|
||||
const onFiles = vi.fn(); const onDrop = vi.fn();
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<IssueAttachmentsSection attachments={[]} onImageClick={vi.fn()} onDrop={onDrop} />
|
||||
</>);
|
||||
const label = Array.from(host.querySelectorAll("h3")).find(item => item.textContent === "Attachments")!;
|
||||
drag("drop", label);
|
||||
expect(onDrop).toHaveBeenCalledOnce(); expect(onFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores text and link drags", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<ComposerFileDropTarget enabled onFiles={onFiles} />);
|
||||
expect(drag("dragenter", host, ["text/plain", "text/uri-list"]).defaultPrevented).toBe(false);
|
||||
expect(drag("drop", host, ["text/plain"]).defaultPrevented).toBe(false);
|
||||
expect(overlay()).toBeNull();
|
||||
expect(onFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("gives the open dialog exclusive ownership and restores the task on close", () => {
|
||||
const taskFiles = vi.fn(); const newFiles = vi.fn();
|
||||
const content = (open: boolean, enabled = true) => <>
|
||||
<ComposerFileDropTarget enabled onFiles={taskFiles} />
|
||||
{open ? <Dialog open><DialogContent aria-describedby={undefined}><DialogTitle>New task</DialogTitle><ComposerFileDropTarget newTask enabled={enabled} onFiles={newFiles} /></DialogContent></Dialog> : null}
|
||||
</>;
|
||||
render(content(true));
|
||||
drag("dragenter");
|
||||
expect(overlay()?.textContent).toContain("your new task");
|
||||
drag("drop");
|
||||
expect(newFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
expect(taskFiles).not.toHaveBeenCalled();
|
||||
render(content(true, false));
|
||||
drag("dragenter"); drag("drop");
|
||||
expect(overlay()).toBeNull();
|
||||
expect(taskFiles).not.toHaveBeenCalled();
|
||||
render(content(false));
|
||||
drag("drop");
|
||||
expect(taskFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
});
|
||||
|
||||
it("does not send files to the underlying task while another dialog is open", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} /><Dialog open><DialogContent aria-describedby={undefined}><DialogTitle>Settings</DialogTitle></DialogContent></Dialog></>);
|
||||
drag("dragenter"); drag("drop");
|
||||
expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves artifact uploads with an external target: %s", (external) => {
|
||||
const onFiles = vi.fn(); const onUpload = vi.fn();
|
||||
const frame = document.createElement("div");
|
||||
const header = document.createElement("button");
|
||||
frame.append(header); document.body.append(frame);
|
||||
try {
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<ArtifactDropzone onUpload={onUpload} target={external ? frame : undefined}><button data-artifact-file>File</button></ArtifactDropzone></>);
|
||||
const destination = external ? header : host.querySelector("[data-artifact-file]")!;
|
||||
drag("dragenter"); expect(overlay()).not.toBeNull();
|
||||
drag("dragenter", destination); drag("dragover", destination);
|
||||
expect(overlay()).toBeNull();
|
||||
expect(document.querySelector("[data-artifact-drop-overlay]")).not.toBeNull();
|
||||
expect(drag("drop", destination).defaultPrevented).toBe(true);
|
||||
expect(onUpload).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
expect(onFiles).not.toHaveBeenCalled();
|
||||
drag("dragenter"); expect(overlay()).not.toBeNull(); drag("drop");
|
||||
expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
render(<div />);
|
||||
expect(frame.hasAttribute("data-file-drop-target")).toBe(false);
|
||||
} finally { frame.remove(); }
|
||||
});
|
||||
|
||||
it("keeps composer drops available while a portaled picker is open", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<><ComposerFileDropTarget enabled onFiles={onFiles} />
|
||||
<Popover open><PopoverTrigger>Model</PopoverTrigger><PopoverContent>Choose model</PopoverContent></Popover></>);
|
||||
const picker = document.querySelector('[data-slot="popover-content"]')!;
|
||||
expect(picker.getAttribute("role")).toBe("dialog");
|
||||
expect(host.contains(picker)).toBe(false);
|
||||
drag("dragenter"); expect(overlay()).not.toBeNull();
|
||||
expect(drag("drop", picker).defaultPrevented).toBe(true);
|
||||
expect(onFiles).toHaveBeenCalledExactlyOnceWith([file]);
|
||||
});
|
||||
|
||||
it("prevents browser navigation while the new task is read-only", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<Dialog open><DialogContent aria-describedby={undefined}><DialogTitle>New task</DialogTitle>
|
||||
<ComposerFileDropTarget newTask enabled={false} onFiles={onFiles} />
|
||||
</DialogContent></Dialog>);
|
||||
expect(drag("dragenter").defaultPrevented).toBe(true);
|
||||
expect(drag("dragover").defaultPrevented).toBe(true);
|
||||
expect(drag("drop").defaultPrevented).toBe(true);
|
||||
expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not accept drops for a concealed composer", () => {
|
||||
const onFiles = vi.fn();
|
||||
render(<div inert><ComposerFileDropTarget enabled onFiles={onFiles} /></div>);
|
||||
drag("dragenter"); drag("drop");
|
||||
expect(overlay()).toBeNull(); expect(onFiles).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the latest callback and clears on disable and unmount", () => {
|
||||
const previous = vi.fn(); const next = vi.fn();
|
||||
render(<ComposerFileDropTarget enabled onFiles={previous} />);
|
||||
drag("dragenter");
|
||||
render(<ComposerFileDropTarget enabled={false} onFiles={next} />);
|
||||
expect(overlay()).toBeNull(); drag("drop");
|
||||
render(<ComposerFileDropTarget enabled onFiles={next} />);
|
||||
drag("drop");
|
||||
expect(next).toHaveBeenCalledExactlyOnceWith([file]); expect(previous).not.toHaveBeenCalled();
|
||||
drag("dragenter"); render(<div />);
|
||||
expect(overlay()).toBeNull();
|
||||
expect(drag("drop").defaultPrevented).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,453 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { sampleHarnesses } from "@/test-support/harness-availability";
|
||||
|
||||
import { act, useState, 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, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { ComposerRunSettingsPicker } from "./ComposerRunSettingsPicker";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import type { ComposerRunSettings } from "./composer-run-settings";
|
||||
import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
|
||||
const agent = {
|
||||
id: "a1", companyId: "company-1", name: "Clippy",
|
||||
role: "Engineering Lead",
|
||||
adapterType: "codex_local", adapterConfig: { model: "gpt-6-sol" },
|
||||
} as unknown as Agent;
|
||||
const options = [{ id: "agent:a1", label: "Clippy" }];
|
||||
const agents = new Map([[agent.id, agent]]);
|
||||
let container: HTMLDivElement | null = null;
|
||||
let root: ReturnType<typeof createRoot> | null = null;
|
||||
globalThis.ResizeObserver = class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
unobserve() {}
|
||||
};
|
||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
async function click(label: string) {
|
||||
const button = document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)
|
||||
?? [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')].find((item) => item.textContent?.trim().startsWith(label));
|
||||
expect(button).toBeDefined();
|
||||
flushSync(() => button!.click());
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
}
|
||||
|
||||
function render(onAssigneeChange: (value: string) => void, onSettingsChange: () => void, useCatalog = false, props: Partial<ComponentProps<typeof ComposerRunSettingsPicker>> = {}, insideDialog = false) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const picker = <QueryClientProvider client={queryClient}>
|
||||
<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 : []} {...props} />
|
||||
</QueryClientProvider>;
|
||||
flushSync(() => root!.render(insideDialog ? <Dialog defaultOpen><DialogContent aria-describedby={undefined}><DialogTitle>New task</DialogTitle>{picker}</DialogContent></Dialog> : picker));
|
||||
return queryClient;
|
||||
}
|
||||
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
flushSync(() => root?.unmount());
|
||||
root = null;
|
||||
container?.remove();
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe("composer assignee picker", () => {
|
||||
it.each(["antigravity", "copilot"])("applies the Cloud allowlist to saved %s model settings", async acpxAgent => {
|
||||
const selectedAgent = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent, model: "saved-model" } } as Agent;
|
||||
const client = render(vi.fn(), vi.fn(), false, { agents: new Map([[selectedAgent.id, selectedAgent]]) });
|
||||
await act(async () => {
|
||||
client.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true, availableHarnesses: sampleHarnesses } });
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
});
|
||||
expect(document.querySelector('[aria-label="Select model and effort"]') !== null).toBe(acpxAgent === "copilot");
|
||||
if (acpxAgent === "copilot") {
|
||||
await click("Select model and effort");
|
||||
expect(document.querySelector('[aria-label="Choose exact model"]')).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([false, true])("allows model and effort changes with a fixed conversation agent (mobile: %s)", async (mobile) => {
|
||||
const onAssigneeChange = vi.fn();
|
||||
const onSettingsChange = vi.fn();
|
||||
render(onAssigneeChange, onSettingsChange, false, { allowAssigneeChange: false, mobile,
|
||||
modelOptionsOverride: [{ id: "gpt-6-astra", label: "GPT-6 Astra" }] });
|
||||
expect(container!.querySelector('[aria-label="Select assignee"]')).toBeNull();
|
||||
await click("Select model and effort");
|
||||
expect(document.querySelector('[aria-label="Choose assignee"]')).toBeNull();
|
||||
expect(document.querySelector('input[aria-label="Effort"]')).not.toBeNull();
|
||||
await click("Choose exact model");
|
||||
await click("GPT-6 Astra");
|
||||
expect(onSettingsChange).toHaveBeenLastCalledWith({ model: "gpt-6-astra", effort: "high", fast: false });
|
||||
expect(onAssigneeChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps the trigger stable until the picker closes (mobile: %s)", async (mobile) => {
|
||||
function ControlledPicker() {
|
||||
const [settings, setSettings] = useState({ model: "gpt-6-sol", effort: "high", fast: false });
|
||||
return <ComposerRunSettingsPicker companyId="company-1" assigneeValue="agent:a1" currentAssigneeValue="agent:a1"
|
||||
options={options} agents={agents} settings={settings} onSettingsChange={(next) => setSettings(next! as typeof settings)}
|
||||
onAssigneeChange={vi.fn()} mobile={mobile} modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }, { id: "gpt-6-astra", label: "GPT-6 Astra" }]} />;
|
||||
}
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
const queryClient = new QueryClient();
|
||||
flushSync(() => root!.render(<QueryClientProvider client={queryClient}><ControlledPicker /></QueryClientProvider>));
|
||||
const label = () => container!.querySelector('[data-testid="task-chat-composer-model-label"]')!.textContent;
|
||||
expect(label()).toBe("GPT-6 Sol");
|
||||
await click("Select model and effort");
|
||||
expect(label()).toBe("Select model");
|
||||
const range = document.querySelector<HTMLInputElement>('input[aria-label="Effort"]')!;
|
||||
flushSync(() => {
|
||||
Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(range, "1");
|
||||
range.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect(range.getAttribute("aria-valuetext")).toBe("Low");
|
||||
expect(label()).toBe("Select model");
|
||||
expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).not.toContain("Low");
|
||||
await click("Choose assignee");
|
||||
expect(label()).toBe("Select model");
|
||||
await click("Clippy");
|
||||
expect(label()).toBe("GPT-6 Sol");
|
||||
expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low");
|
||||
await click("Select model and effort");
|
||||
await click("Choose exact model");
|
||||
await click("GPT-6 Astra");
|
||||
expect(label()).toBe("Select model");
|
||||
if (mobile) await click("Close picker");
|
||||
else {
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
}
|
||||
expect(label()).toBe("GPT-6 Astra");
|
||||
expect(container!.querySelector('[aria-label="Select model and effort"]')!.textContent).toContain("Low");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ mobile: false, view: "settings" as const },
|
||||
{ mobile: false, view: "models" as const },
|
||||
{ mobile: false, view: "agents" as const },
|
||||
{ mobile: true, view: "settings" as const },
|
||||
{ mobile: true, view: "models" as const },
|
||||
{ mobile: true, view: "agents" as const },
|
||||
])("allows wheel and touch scrolling in a nested $view picker (mobile: $mobile)", async ({ mobile, view }) => {
|
||||
render(vi.fn(), vi.fn(), false, { mobile, initialOpen: true, initialView: view }, true);
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
const list = document.querySelector<HTMLElement>(view === "settings"
|
||||
? '[data-testid="composer-run-settings-view"]'
|
||||
: `[role="listbox"][aria-label="${view === "models" ? "Models" : "Assignees"}"]`)!;
|
||||
expect(list).not.toBeNull();
|
||||
list.style.overflowY = "auto";
|
||||
Object.defineProperties(list, {
|
||||
scrollHeight: { configurable: true, value: 1000 },
|
||||
clientHeight: { configurable: true, value: 200 },
|
||||
});
|
||||
const option = list.querySelector("button")!;
|
||||
const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 });
|
||||
option.dispatchEvent(wheel);
|
||||
expect(wheel.defaultPrevented).toBe(false);
|
||||
const touch = (type: string, y: number) => {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperties(event, {
|
||||
touches: { value: [{ clientX: 100, clientY: y }] },
|
||||
changedTouches: { value: [{ clientX: 100, clientY: y }] },
|
||||
});
|
||||
option.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
touch("touchstart", 150);
|
||||
expect(touch("touchmove", 100).defaultPrevented).toBe(false);
|
||||
const outsideWheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 100 });
|
||||
document.body.dispatchEvent(outsideWheel);
|
||||
expect(outsideWheel.defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
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 = container!.querySelector('[data-testid="task-chat-composer-model-label"]');
|
||||
|
||||
expect(trigger?.className).toContain("max-w-full");
|
||||
expect(trigger?.className).not.toContain("max-w-64");
|
||||
expect(assignee?.className).toContain("min-w-0");
|
||||
expect(assignee?.className).not.toContain("max-w-24");
|
||||
expect(model?.className).toContain("min-w-0");
|
||||
expect(assignee?.className).toContain("truncate");
|
||||
expect(model?.className).toContain("truncate");
|
||||
});
|
||||
|
||||
it("finds assignees by their displayed role and harness", async () => {
|
||||
render(vi.fn(), vi.fn());
|
||||
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!;
|
||||
for (const query of ["Engineering Lead", "Codex"]) {
|
||||
flushSync(() => {
|
||||
setValue.call(input, query);
|
||||
input!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
expect([...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')]
|
||||
.some((option) => option.textContent?.includes("Clippy"))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("offers the Codex CLI catalog instead of unrelated OpenAI API models", async () => {
|
||||
vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([
|
||||
{ id: "gpt-6-sol", label: "GPT-6 Sol" },
|
||||
{ id: "gpt-5.5", label: "GPT-5.5" },
|
||||
]);
|
||||
render(vi.fn(), vi.fn(), true);
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
await click("Select model and effort");
|
||||
await click("Choose exact model");
|
||||
const options = [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')]
|
||||
.map((item) => item.textContent ?? "");
|
||||
expect(options.some((item) => item.includes("gpt-5.5"))).toBe(true);
|
||||
expect(options.some((item) => item.includes("gpt-6-sol"))).toBe(true);
|
||||
expect(options.some((item) => item.includes("gpt-image"))).toBe(false);
|
||||
expect(options.some((item) => item.includes("text-embedding"))).toBe(false);
|
||||
expect(document.body.textContent).not.toContain("Loading models…");
|
||||
});
|
||||
|
||||
it("shows an instance-declared Codex model list instead of bundled alternatives", async () => {
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([
|
||||
{ id: "private-codex", label: "Private Codex" },
|
||||
]);
|
||||
render(vi.fn(), vi.fn(), true);
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
expect(loadModels).toHaveBeenCalledWith("company-1", "codex_local", {
|
||||
environmentId: null,
|
||||
provider: undefined,
|
||||
});
|
||||
await click("Select model and effort");
|
||||
await click("Choose exact model");
|
||||
const choices = [...document.querySelectorAll<HTMLButtonElement>('button[role="option"]')]
|
||||
.map((item) => item.textContent ?? "");
|
||||
expect(choices.some((item) => item.includes("Private Codex"))).toBe(true);
|
||||
expect(choices.some((item) => item.includes("GPT-6 Sol"))).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["copilot", "antigravity"])("keeps %s discovery passive during reconnect reconciliation and refreshes on opening", async acpxAgent => {
|
||||
const copilot = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent, model: "gpt-5.6-luna" } } as Agent;
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels")
|
||||
.mockResolvedValueOnce([{ id: "gpt-5.6-luna", label: "Copilot Luna" }])
|
||||
.mockResolvedValue([{ id: "gpt-5.6-luna", label: "Updated Copilot Luna" }]);
|
||||
const client = render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, copilot]]), settings: null });
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
expect(loadModels).not.toHaveBeenCalled();
|
||||
await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); });
|
||||
expect(loadModels).not.toHaveBeenCalled();
|
||||
await click("Select model and effort");
|
||||
expect(loadModels).toHaveBeenCalledTimes(1);
|
||||
await act(async () => { await client.invalidateQueries({ type: "active" }, { cancelRefetch: false }); });
|
||||
expect(loadModels).toHaveBeenCalledTimes(1);
|
||||
await act(async () => {
|
||||
document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
await click("Select model and effort");
|
||||
expect(loadModels).toHaveBeenCalledTimes(2);
|
||||
await click("Choose exact model");
|
||||
expect(document.body.textContent).toContain("Updated Copilot Luna");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "Copilot", acpxAgent: "copilot", provider: "github", method: "api_key", model: "gpt-5.6-luna", label: "Copilot Luna" },
|
||||
{ name: "Antigravity", acpxAgent: "antigravity", provider: "google", method: "subscription", model: "gemini-exact", label: "Personal Gemini" },
|
||||
] as const)("discovers $name task models with the assignee connection and environment", async ({ acpxAgent, provider, method, model, label }) => {
|
||||
const binding = { provider, method, mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const;
|
||||
const selectedAgent = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent, model }, runtimeConfig: { aiConnection: binding } } as Agent;
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([{ id: model, label }]);
|
||||
render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, selectedAgent]]), settings: null });
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
expect(loadModels).not.toHaveBeenCalled();
|
||||
await click("Select model and effort");
|
||||
expect(loadModels).toHaveBeenCalledWith("company-1", "paperclip_runner", {
|
||||
environmentId: "daytona-1", provider: "acpx", poolId: undefined,
|
||||
acpxAgent, agentId: agent.id, aiConnection: binding,
|
||||
});
|
||||
await click("Choose exact model");
|
||||
expect(document.body.textContent).toContain(label);
|
||||
expect(document.body.textContent).not.toContain("Claude Sonnet");
|
||||
});
|
||||
|
||||
it.each(["subscription", "api_key"] as const)("allows an exact Antigravity model absent from its %s catalog", async method => {
|
||||
const selectedAgent = { ...agent, adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-default" },
|
||||
runtimeConfig: { aiConnection: { provider: "google", method, mode: "responsible_user" } } } as Agent;
|
||||
vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([{ id: "gemini-listed", label: "Listed native model" }]);
|
||||
const onSettingsChange = vi.fn();
|
||||
render(vi.fn(), onSettingsChange, true, { agents: new Map([[agent.id, selectedAgent]]), settings: null,
|
||||
initialOpen: true, initialView: "models", initialModelSearch: "gemini-custom-exact" });
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||
const manual = [...document.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.includes("Use exact ID"));
|
||||
expect(manual?.disabled).toBe(false);
|
||||
await act(async () => manual!.click());
|
||||
expect(onSettingsChange).toHaveBeenLastCalledWith(expect.objectContaining({ model: "gemini-custom-exact" }));
|
||||
});
|
||||
|
||||
it("preserves settings when the selected assignee is chosen again", async () => {
|
||||
const onAssigneeChange = vi.fn();
|
||||
const onSettingsChange = vi.fn();
|
||||
render(onAssigneeChange, onSettingsChange);
|
||||
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");
|
||||
await click("No assignee");
|
||||
expect(onAssigneeChange).toHaveBeenCalledWith("");
|
||||
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.each([false, true])("hides unsupported Muse settings without loading a catalog (mobile: %s)", async (mobile) => {
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([]);
|
||||
const onSettingsChange = vi.fn();
|
||||
const muse = { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse", model: "old-model" } } as Agent;
|
||||
rememberComposerEffort("company-1", "high");
|
||||
render(vi.fn(), onSettingsChange, true, { mobile, settings: null, agents: new Map([[muse.id, muse]]) });
|
||||
expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull();
|
||||
expect(container!.querySelector('[data-testid="task-chat-composer-model-label"]')).toBeNull();
|
||||
await click("Select assignee");
|
||||
expect(document.querySelector('[aria-label="Search assignees"]')).not.toBeNull();
|
||||
expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull();
|
||||
expect(document.querySelector('[aria-label="Effort"]')).toBeNull();
|
||||
expect(loadModels).not.toHaveBeenCalled();
|
||||
expect(onSettingsChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([false, true])("removes an open model menu when the same agent switches to Muse (mobile: %s)", async (mobile) => {
|
||||
const onSettingsChange = vi.fn();
|
||||
function ControlledPicker() {
|
||||
const [muse, setMuse] = useState(false);
|
||||
const [settings, setSettings] = useState<ComposerRunSettings | null>({ model: "gpt-6-sol", effort: "high", fast: true });
|
||||
const selectedAgent = muse
|
||||
? { ...agent, adapterType: "paperclip_runner", adapterConfig: { provider: "muse" } } as Agent
|
||||
: agent;
|
||||
return <>
|
||||
<button type="button" aria-label="Switch to Muse" onClick={() => setMuse(true)}>Switch to Muse</button>
|
||||
<ComposerRunSettingsPicker companyId="company-1" assigneeValue="agent:a1" currentAssigneeValue="agent:a1"
|
||||
options={options} agents={new Map([[agent.id, selectedAgent]])} settings={settings}
|
||||
onSettingsChange={(next) => { onSettingsChange(next); setSettings(next); }} onAssigneeChange={vi.fn()} mobile={mobile}
|
||||
modelOptionsOverride={[{ id: "gpt-6-sol", label: "GPT-6 Sol" }]} />
|
||||
</>;
|
||||
}
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
flushSync(() => root!.render(<QueryClientProvider client={new QueryClient()}><ControlledPicker /></QueryClientProvider>));
|
||||
await click("Select model and effort");
|
||||
await click("Choose exact model");
|
||||
expect(document.querySelector('[aria-label="Search or paste a model ID"]')).not.toBeNull();
|
||||
await click("Switch to Muse");
|
||||
expect(container!.querySelector('[aria-label="Select model and effort"]')).toBeNull();
|
||||
expect(document.querySelector('[aria-label="Search or paste a model ID"]')).toBeNull();
|
||||
expect(document.querySelector('[aria-label="Choose exact model"]')).toBeNull();
|
||||
expect(document.querySelector('[aria-label="Effort"]')).toBeNull();
|
||||
expect(document.querySelector('[data-testid="model-unavailable"]')?.textContent).toContain("Muse chooses its model and effort");
|
||||
expect(onSettingsChange).toHaveBeenCalledOnce();
|
||||
expect(onSettingsChange).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,705 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, type ComponentProps } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { IssueQueuedCommentQueue } from "@paperclipai/shared";
|
||||
import { mergePendingIssueQueuedComments } from "@/lib/issue-queued-comment-queue";
|
||||
import { ThemeProvider } from "@/context/ThemeContext";
|
||||
import { MemoryRouter } from "@/lib/router";
|
||||
import {
|
||||
reorderQueuedMessageEntries,
|
||||
TaskChatQueuedMessages,
|
||||
} from "./TaskChatQueuedMessages";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((innerResolve, innerReject) => {
|
||||
resolve = innerResolve;
|
||||
reject = innerReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const queue: IssueQueuedCommentQueue = {
|
||||
issueId: "issue-1",
|
||||
queueId: "wake-1",
|
||||
state: "deferred",
|
||||
targetRunId: "run-1",
|
||||
revision: "rev-1",
|
||||
protocol: "paperclip_runner_v1",
|
||||
steeringDisposition: "available",
|
||||
entries: ["First queued message", "Second queued message"].map(
|
||||
(body, position) => ({
|
||||
comment: {
|
||||
id: `comment-${position + 1}`,
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
authorType: "user",
|
||||
authorAgentId: null,
|
||||
authorUserId: "user-1",
|
||||
body,
|
||||
presentation: null,
|
||||
metadata: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
position,
|
||||
canEdit: true,
|
||||
canDiscard: true,
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
describe("TaskChatQueuedMessages", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function render(
|
||||
overrides: Partial<ComponentProps<typeof TaskChatQueuedMessages>> = {},
|
||||
) {
|
||||
const props = {
|
||||
queue,
|
||||
onEdit: vi.fn(),
|
||||
onReorder: vi.fn().mockResolvedValue(undefined),
|
||||
onSteer: vi.fn().mockResolvedValue(undefined),
|
||||
onDiscard: vi.fn().mockResolvedValue(undefined),
|
||||
...overrides,
|
||||
};
|
||||
flushSync(() => root.render(<MemoryRouter><ThemeProvider><TaskChatQueuedMessages {...props} /></ThemeProvider></MemoryRouter>));
|
||||
return props;
|
||||
}
|
||||
|
||||
it("keeps saved input visible without duplicating the task status", () => {
|
||||
const message = "Waiting for the previous environment to stop. Your message will start automatically.";
|
||||
render({ queue: { ...queue, executionWait: { reason: "remote_cleanup", message } } });
|
||||
expect(container.textContent).not.toContain(message);
|
||||
expect(container.textContent).toContain("First queued message");
|
||||
render();
|
||||
expect(container.textContent).not.toContain(message);
|
||||
});
|
||||
|
||||
it("says why a chat message held in the outbox waits, without offering queue actions", () => {
|
||||
const message = "CEO reached its daily run limit. Your message is saved and sends automatically when the limit resets at 00:00 UTC.";
|
||||
render({ queue: { ...queue, queueId: null, targetRunId: null, steeringDisposition: "unsupported",
|
||||
executionWait: { reason: "heartbeat.daily_run_limit", message },
|
||||
entries: queue.entries.slice(0, 1).map(entry => ({ ...entry, canEdit: false, canDiscard: false })) } });
|
||||
expect([...container.querySelectorAll('p[role="status"]')].map(node => node.textContent)).toEqual([message]);
|
||||
expect(container.textContent).toContain("First queued message");
|
||||
expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled ?? true).toBe(true);
|
||||
expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-discard-comment-1"]')?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("renders each queued message once as a compact one-line row", () => {
|
||||
render();
|
||||
const pane = container.querySelector(
|
||||
'[data-testid="task-chat-queued-messages"]',
|
||||
);
|
||||
expect(pane?.classList).toContain("mx-3");
|
||||
expect(pane?.classList).toContain("rounded-b-none");
|
||||
expect(pane?.classList).toContain("border-b-0");
|
||||
expect(pane?.classList).toContain("-mb-px");
|
||||
expect(
|
||||
container.querySelectorAll('[data-testid^="task-chat-queued-message-"]'),
|
||||
).toHaveLength(2);
|
||||
expect(container.textContent).toContain("First queued message");
|
||||
expect(container.textContent).toContain("Second queued message");
|
||||
});
|
||||
|
||||
it("renders queued Markdown and screenshot thumbnails without showing image syntax", () => {
|
||||
const body = "Check **mobile** and *desktop* with `pnpm verify`.\n\n\n";
|
||||
render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } });
|
||||
const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!;
|
||||
expect(row.querySelector("strong")?.textContent).toBe("mobile");
|
||||
expect(row.querySelector("em")?.textContent).toBe("desktop");
|
||||
expect(row.querySelector("code")?.textContent).toBe("pnpm verify");
|
||||
expect([...row.querySelectorAll("img")].map(img => [img.alt, img.getAttribute("src")])).toEqual([
|
||||
["mobile.png", "/api/attachments/mobile/content"],
|
||||
["desktop.png", "/api/attachments/desktop/content"],
|
||||
]);
|
||||
expect(row.textContent).not.toContain("";
|
||||
render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } });
|
||||
expect(container.querySelector('img[alt="screen.png"]')?.getAttribute("src")).toBe("/api/attachments/screen/content");
|
||||
expect(container.textContent).not.toContain(body);
|
||||
});
|
||||
|
||||
it("only loads local attachment images and counts the remaining screenshots", () => {
|
||||
const urls = [
|
||||
"/api/attachments/first/content", "/api/assets/second/content?download=0",
|
||||
"/api/attachments/third/content", "/api/attachments/fourth/content",
|
||||
"https://other.example/api/attachments/pixel/content", "//other.example/pixel.png",
|
||||
"javascript:alert", "data:image/png;base64,AAAA", "/other/pixel.png",
|
||||
"/api/attachments/first/content/extra", "/api/attachments/first/content#fragment",
|
||||
];
|
||||
const body = urls.map((url, index) => ``).join("\n");
|
||||
render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } });
|
||||
const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!;
|
||||
expect([...row.querySelectorAll("img")].map(image => image.getAttribute("src"))).toEqual(urls.slice(0, 3));
|
||||
expect(row.querySelector('[aria-label="Queued images"]')?.textContent).toBe("+1");
|
||||
});
|
||||
|
||||
it("omits inline images from the compact text without exposing their URLs", () => {
|
||||
const body = "Check  then **retry**.";
|
||||
render({ queue: { ...queue, entries: [{ ...queue.entries[0], comment: { ...queue.entries[0].comment, body } }] } });
|
||||
const row = container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')!;
|
||||
expect(row.querySelector("strong")?.textContent).toBe("retry");
|
||||
expect(row.textContent).toContain("Check then retry.");
|
||||
expect(row.textContent).not.toContain("/api/attachments");
|
||||
expect(row.querySelector("img")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["legacy", "native", "native-plan"] as const)("shows a read-only response and sends it only on click for %s", async (runtime) => {
|
||||
const entry = { ...queue.entries[0], canEdit: false, canDiscard: false,
|
||||
comment: { ...queue.entries[0].comment, body: 'Accepted: Build the app\n\n{"revision": "v1"}' },
|
||||
source: { kind: "interaction" as const, interactionId: "confirmation-1", interactionKind: "request_confirmation",
|
||||
requiresFreshSession: runtime === "native-plan" } };
|
||||
const props = render({ queue: { ...queue, entries: [entry],
|
||||
protocol: runtime === "legacy" ? "legacy" : "paperclip_runner_v1" },
|
||||
onInterrupt: vi.fn().mockResolvedValue(undefined) });
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
expect(props.onInterrupt).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Accepted: Build the app");
|
||||
expect(container.textContent).not.toContain('"revision"');
|
||||
expect(container.querySelector<HTMLButtonElement>('[aria-label^="Reorder"]')?.disabled).toBe(true);
|
||||
expect(container.querySelector<HTMLButtonElement>('[data-testid^="task-chat-queued-discard-"]')?.disabled).toBe(true);
|
||||
expect(reorderQueuedMessageEntries([entry, queue.entries[1]], "comment-1", "comment-2")).toBeNull();
|
||||
const action = runtime === "native" ? "steer" : "interrupt";
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); });
|
||||
if (action === "steer") expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1");
|
||||
else expect(props.onInterrupt).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("shows a declined connection request as readable text, never its raw JSON receipt (BUG-08)", () => {
|
||||
const receipt = JSON.stringify({ interactionId: "slack-1", kind: "connection_intent", status: "rejected",
|
||||
payload: { serviceSlug: "slack", serviceName: "Slack" }, result: { outcome: "declined" } }, null, 2);
|
||||
const entry = { ...queue.entries[0], canEdit: false, canDiscard: false,
|
||||
comment: { ...queue.entries[0].comment, id: "slack-1", body: `Rejected: Connect Slack\n\n${receipt}` },
|
||||
source: { kind: "interaction" as const, interactionId: "slack-1", interactionKind: "connection_intent",
|
||||
summary: "Declined: Slack connection" } };
|
||||
render({ queue: { ...queue, entries: [entry], steeringDisposition: "temporarily_unavailable" } });
|
||||
const row = container.querySelector('[data-testid="task-chat-queued-message-slack-1"]')!;
|
||||
const hoverAndLabels = [...row.querySelectorAll("[title], [aria-label]")]
|
||||
.flatMap((element) => [element.getAttribute("title"), element.getAttribute("aria-label")])
|
||||
.filter((text): text is string => Boolean(text));
|
||||
expect(hoverAndLabels.length).toBeGreaterThan(0);
|
||||
for (const text of hoverAndLabels) {
|
||||
expect(text).not.toContain("{");
|
||||
expect(text).not.toContain("interactionId");
|
||||
}
|
||||
expect(row.textContent).toContain("Declined: Slack connection");
|
||||
expect(row.querySelector('[title="Declined: Slack connection"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("reorders the complete queue and rewrites contiguous positions", () => {
|
||||
const next = reorderQueuedMessageEntries(
|
||||
queue.entries,
|
||||
"comment-2",
|
||||
"comment-1",
|
||||
);
|
||||
|
||||
expect(next?.map((entry) => entry.comment.id)).toEqual([
|
||||
"comment-2",
|
||||
"comment-1",
|
||||
]);
|
||||
expect(next?.map((entry) => entry.position)).toEqual([0, 1]);
|
||||
});
|
||||
|
||||
it("removes the selected steering row before the provider acknowledges it", async () => {
|
||||
const acknowledgement = deferred<void>();
|
||||
const props = render({
|
||||
onSteer: vi.fn().mockReturnValue(acknowledgement.promise),
|
||||
});
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-steer-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1");
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(container.textContent).toContain("Steering queued message.");
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-2"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
render({ ...props, queue: { ...queue, entries: [...queue.entries] } });
|
||||
});
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
acknowledgement.resolve();
|
||||
await acknowledgement.promise;
|
||||
});
|
||||
});
|
||||
|
||||
it("clears the entire interrupt queue immediately and restores it inline on failure", async () => {
|
||||
let rejectInterrupt!: (error: Error) => void;
|
||||
const interrupted = new Promise<void>((_, reject) => { rejectInterrupt = reject; });
|
||||
const props = render({ queue: { ...queue, protocol: "legacy", steeringDisposition: "unsupported" },
|
||||
onInterrupt: vi.fn().mockReturnValue(interrupted) });
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click();
|
||||
});
|
||||
expect(props.onInterrupt).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull();
|
||||
await act(async () => { rejectInterrupt(new Error("Connection lost")); await interrupted.catch(() => undefined); });
|
||||
expect(container.querySelectorAll('[data-testid^="task-chat-queued-message-"]')).toHaveLength(2);
|
||||
expect(container.textContent).toContain("Couldn’t interrupt. Message is still queued.");
|
||||
});
|
||||
|
||||
it.each(["steer", "interrupt"] as const)("shows a delivery error even when the queue becomes empty while %s is pending", async action => {
|
||||
const delivery = deferred<void>();
|
||||
const props = render({ queue: { ...queue, protocol: action === "interrupt" ? "legacy" : "paperclip_runner_v1" },
|
||||
onSteer: vi.fn().mockReturnValue(delivery.promise), onInterrupt: vi.fn().mockReturnValue(delivery.promise) });
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>(`[data-testid="task-chat-queued-${action}-comment-1"]`)!.click(); });
|
||||
await act(async () => { render({ ...props, queue: { ...props.queue, revision: "empty-poll", entries: [] } }); });
|
||||
await act(async () => { delivery.reject(new Error("Connection lost")); await delivery.promise.catch(() => undefined); });
|
||||
const error = action === "steer" ? "Couldn’t steer." : "Couldn’t interrupt.";
|
||||
expect([...container.querySelectorAll('[role="status"]')].some(status => status.textContent?.includes(error))).toBe(true);
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("does not restore a message discarded elsewhere while steering was pending", async () => {
|
||||
let rejectSteer!: (error: Error) => void;
|
||||
const delivery = new Promise<void>((_, reject) => { rejectSteer = reject; });
|
||||
const props = render({ onSteer: vi.fn().mockReturnValue(delivery) });
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-steer-comment-1"]')!.click(); });
|
||||
await act(async () => { render({ ...props, queue: { ...queue, revision: "rev-2", entries: [queue.entries[1]] } }); });
|
||||
await act(async () => { rejectSteer(new Error("Queue changed")); await delivery.catch(() => undefined); });
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-message-comment-2"]')).not.toBeNull();
|
||||
expect(container.textContent).toContain("Couldn’t steer.");
|
||||
});
|
||||
|
||||
it("keeps a row queued when steering fails and announces the retryable state", async () => {
|
||||
render({
|
||||
onSteer: vi.fn().mockRejectedValue(new Error("steering_timeout")),
|
||||
});
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-steer-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
});
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(container.textContent).toContain(
|
||||
"Couldn’t steer. Message is still queued.",
|
||||
);
|
||||
});
|
||||
|
||||
it("disables steering when the provider does not advertise it", () => {
|
||||
render({ queue: { ...queue, steeringDisposition: "unsupported" } });
|
||||
expect(
|
||||
container.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-steer-comment-1"]',
|
||||
)?.disabled,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["temporarily_unavailable", "unsupported"] as const)(
|
||||
"offers an explicit interrupt fallback when native steering is %s",
|
||||
async (steeringDisposition) => {
|
||||
const props = render({
|
||||
queue: { ...queue, steeringDisposition },
|
||||
onInterrupt: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
const interrupt = container.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-interrupt-comment-1"]',
|
||||
);
|
||||
expect(interrupt).not.toBeNull();
|
||||
expect(interrupt!.disabled).toBe(false);
|
||||
expect(interrupt!.textContent).toContain("Interrupt");
|
||||
await act(async () => { interrupt!.click(); });
|
||||
expect(props.onInterrupt).toHaveBeenCalledOnce();
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps same-turn steering when the provider is available, even with an interrupt callback", async () => {
|
||||
const props = render({ onInterrupt: vi.fn().mockResolvedValue(undefined) });
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-interrupt-comment-1"]')).toBeNull();
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-steer-comment-1"]')!.click();
|
||||
});
|
||||
expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1");
|
||||
expect(props.onInterrupt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits for authoritative discard acknowledgement before removing the row", async () => {
|
||||
const acknowledgement = deferred<void>();
|
||||
render({ onDiscard: vi.fn().mockReturnValue(acknowledgement.promise) });
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(container.textContent).not.toContain("Queued message discarded.");
|
||||
|
||||
await act(async () => {
|
||||
acknowledgement.resolve();
|
||||
await acknowledgement.promise;
|
||||
});
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(container.textContent).toContain("Queued message discarded.");
|
||||
});
|
||||
|
||||
it.each(["wake-1", null])("keeps a too-late discard visible with an explicit error (queue=%s)", async (queueId) => {
|
||||
render({
|
||||
queue: { ...queue, queueId },
|
||||
onDiscard: vi.fn().mockRejectedValue({
|
||||
body: { details: { code: "queued_comment_already_dispatching" } },
|
||||
}),
|
||||
});
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
});
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(container.textContent).toContain(
|
||||
"Too late to discard: this message is already being sent.",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows stale revisions without announcing a discard", async () => {
|
||||
render({
|
||||
onDiscard: vi.fn().mockRejectedValue({
|
||||
body: { details: { code: "queued_comment_revision_conflict" } },
|
||||
}),
|
||||
});
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
});
|
||||
expect(container.textContent).toContain(
|
||||
"The queue changed in another session. Review it and try again.",
|
||||
);
|
||||
expect(container.textContent).not.toContain("Queued message discarded.");
|
||||
});
|
||||
|
||||
it("can discard a saved message while queue acknowledgement is pending", async () => {
|
||||
const merged = mergePendingIssueQueuedComments({
|
||||
issueId: queue.issueId,
|
||||
authoritativeQueue: queue,
|
||||
pendingComments: [{
|
||||
comment: { ...queue.entries[0].comment, id: "optimistic-next" },
|
||||
targetRunId: queue.targetRunId,
|
||||
}],
|
||||
fallbackProtocol: queue.protocol,
|
||||
})!;
|
||||
expect(merged.queueId).toBeNull();
|
||||
const props = render({ queue: merged });
|
||||
const discard = container.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-comment-1"]',
|
||||
);
|
||||
expect(discard?.disabled).toBe(false);
|
||||
expect(container.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-steer-comment-1"]',
|
||||
)?.disabled).toBe(true);
|
||||
await act(async () => { discard!.click(); });
|
||||
expect(props.onDiscard).toHaveBeenCalledWith("comment-1", "rev-1");
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-message-comment-1"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps another author's saved message protected while acknowledgement is pending", () => {
|
||||
const props = render({
|
||||
queue: {
|
||||
...queue,
|
||||
queueId: null,
|
||||
entries: [{ ...queue.entries[0], canDiscard: false }],
|
||||
},
|
||||
});
|
||||
const discard = container.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-comment-1"]',
|
||||
);
|
||||
expect(discard?.disabled).toBe(true);
|
||||
discard!.click();
|
||||
expect(props.onDiscard).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("can discard a local optimistic row before the queue id is acknowledged", async () => {
|
||||
const optimisticQueue = {
|
||||
...queue,
|
||||
queueId: null,
|
||||
state: "deferred" as const,
|
||||
entries: [
|
||||
{
|
||||
...queue.entries[0],
|
||||
comment: {
|
||||
...queue.entries[0].comment,
|
||||
id: "optimistic-local-1",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
const props = render({ queue: optimisticQueue });
|
||||
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-discard-optimistic-local-1"]',
|
||||
)
|
||||
?.click();
|
||||
});
|
||||
|
||||
expect(props.onDiscard).toHaveBeenCalledWith("optimistic-local-1", "rev-1");
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-optimistic-local-1"]',
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("delivers legacy queued messages to a live target", async () => {
|
||||
const targetRunId = "run-1";
|
||||
const onInterrupt = vi.fn().mockResolvedValue(undefined);
|
||||
render({
|
||||
queue: {
|
||||
...queue,
|
||||
targetRunId,
|
||||
protocol: "legacy",
|
||||
steeringDisposition: "unsupported",
|
||||
},
|
||||
onInterrupt,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
container
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-testid="task-chat-queued-interrupt-comment-1"]',
|
||||
)
|
||||
?.click();
|
||||
});
|
||||
|
||||
expect(onInterrupt).toHaveBeenCalledOnce();
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-steer-comment-1"]',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
container.querySelector(
|
||||
'[data-testid="task-chat-queued-message-comment-1"]',
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
it("keeps deferred sends visible and explains their current wait", async () => {
|
||||
const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } };
|
||||
const onInterrupt = vi.fn().mockResolvedValue(saved);
|
||||
render({ queue: saved, onInterrupt });
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); });
|
||||
expect(container.textContent).toContain("First queued message");
|
||||
expect(container.textContent).toContain(saved.executionWait.message);
|
||||
expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')?.disabled).toBe(false);
|
||||
});
|
||||
it("shows an Interrupt as sent while the stopped turn hands off, with no wait or error text", async () => {
|
||||
const handoff = { ...queue, targetRunId: null,
|
||||
executionWait: { reason: "interrupt_handoff", message: "Sending your messages." } };
|
||||
const onInterrupt = vi.fn().mockResolvedValue(handoff);
|
||||
render({ queue: { ...queue, steeringDisposition: "temporarily_unavailable" }, onInterrupt });
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); });
|
||||
// A poll during the hand-off still lists the saved messages.
|
||||
render({ queue: handoff, onInterrupt });
|
||||
await act(async () => {});
|
||||
expect(container.textContent).not.toContain("First queued message");
|
||||
expect(container.textContent).not.toContain("Sending your messages.");
|
||||
expect(container.textContent).not.toContain("Couldn’t");
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull();
|
||||
});
|
||||
it("clears a deferred wait message when a refreshed queue finishes sending", async () => {
|
||||
const saved = { ...queue, targetRunId: null, executionWait: { reason: "decision_pending", message: "Resolve the pending approval before sending." } };
|
||||
render({ queue: saved, onInterrupt: vi.fn().mockResolvedValue(saved) });
|
||||
await act(async () => { container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]')!.click(); });
|
||||
expect(container.textContent).toContain(saved.executionWait.message);
|
||||
render({ queue: { ...saved, queueId: null, entries: [], state: null, executionWait: null } });
|
||||
await act(async () => {});
|
||||
expect(container.textContent).not.toContain(saved.executionWait.message);
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-messages"]')).toBeNull();
|
||||
});
|
||||
it.each(["legacy", "paperclip_runner_v1"] as const)("sends a saved %s queue explicitly after Stop", async (protocol) => {
|
||||
const onInterrupt = vi.fn().mockResolvedValue(undefined);
|
||||
render({ queue: { ...queue, targetRunId: null, protocol, steeringDisposition: "temporarily_unavailable" }, onInterrupt });
|
||||
expect(onInterrupt).not.toHaveBeenCalled();
|
||||
const send = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-interrupt-comment-1"]');
|
||||
expect(send?.textContent).toBe("Send");
|
||||
expect(send?.getAttribute("aria-label")).toBe("Send queued messages");
|
||||
expect(send?.disabled).toBe(false);
|
||||
await act(async () => { send!.click(); });
|
||||
expect(onInterrupt).toHaveBeenCalledOnce();
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
describe("automatic steering", () => {
|
||||
const delay = 5_000;
|
||||
const fresh = (overrides: Partial<IssueQueuedCommentQueue> = {}): IssueQueuedCommentQueue => {
|
||||
const at = new Date(Date.now());
|
||||
return { ...queue, ...overrides, entries: queue.entries.slice(0, 1).map(entry => ({
|
||||
...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } })) };
|
||||
};
|
||||
const advance = async (ms: number) => { await act(async () => { vi.advanceTimersByTime(ms); await Promise.resolve(); }); };
|
||||
const countdown = () => container.querySelector('[data-testid="task-chat-queued-auto-steer-comment-1"]');
|
||||
|
||||
beforeEach(() => { vi.useFakeTimers({ now: new Date("2026-11-07T12:00:00Z") }); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
it("shows a countdown with Edit and Cancel, then steers into the live turn", async () => {
|
||||
const props = render({ queue: fresh(), autoSteerDelayMs: delay });
|
||||
expect(countdown()?.textContent).toContain("Sending in 5s");
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).toBeNull();
|
||||
await advance(2_100);
|
||||
expect(countdown()?.textContent).toContain("Sending in 3s");
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
await advance(3_000);
|
||||
expect(props.onSteer).toHaveBeenCalledOnce();
|
||||
expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-1");
|
||||
});
|
||||
|
||||
it("gives a saved edit a full window while another row's countdown keeps the clock running", async () => {
|
||||
const start = Date.now();
|
||||
const twoRows: IssueQueuedCommentQueue = { ...queue, entries: queue.entries.slice(0, 2).map((entry, index) => {
|
||||
const at = new Date(start + index * 4_000);
|
||||
return { ...entry, comment: { ...entry.comment, createdAt: at, updatedAt: at } };
|
||||
}) };
|
||||
// comment-1 counts down first; the person opens it for editing at 1 s.
|
||||
const props = render({ queue: twoRows, autoSteerDelayMs: delay });
|
||||
await advance(1_000);
|
||||
await act(async () => { render({ ...props, editingCommentId: "comment-1" }); });
|
||||
// comment-2 counts down to start + 9 s and keeps the clock ticking past
|
||||
// comment-1's old deadline.
|
||||
await advance(5_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
const saved = { ...twoRows, revision: "rev-2", entries: twoRows.entries.map((entry, index) => index === 0
|
||||
? { ...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } } : entry) };
|
||||
await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); });
|
||||
await advance(500);
|
||||
expect(props.onSteer).not.toHaveBeenCalledWith("comment-1", expect.anything());
|
||||
expect(countdown()?.textContent).toContain("Sending in");
|
||||
await advance(5_000);
|
||||
expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2");
|
||||
});
|
||||
|
||||
it("keeps a cancelled message in the queue with its explicit Steer button", async () => {
|
||||
const props = render({ queue: fresh(), autoSteerDelayMs: delay });
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-auto-steer-cancel-comment-1"]')?.click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
expect(countdown()).toBeNull();
|
||||
expect(container.querySelector('[data-testid="task-chat-queued-steer-comment-1"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("waits while the message is being edited and restarts from the saved revision", async () => {
|
||||
const queued = fresh();
|
||||
const props = render({ queue: queued, autoSteerDelayMs: delay });
|
||||
await act(async () => {
|
||||
container.querySelector<HTMLButtonElement>('[data-testid="task-chat-queued-auto-steer-edit-comment-1"]')?.click();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(props.onEdit).toHaveBeenCalledWith("comment-1");
|
||||
render({ ...props, editingCommentId: "comment-1" });
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
// The save changes the comment; its countdown starts again from that change.
|
||||
const saved = { ...queued, revision: "rev-2", entries: queued.entries.map(entry => ({
|
||||
...entry, comment: { ...entry.comment, body: "Edited", updatedAt: new Date(Date.now()) } })) };
|
||||
await act(async () => { render({ ...props, queue: saved, editingCommentId: null }); });
|
||||
expect(countdown()?.textContent).toContain("Sending in 5s");
|
||||
await advance(5_100);
|
||||
expect(props.onSteer).toHaveBeenCalledWith("comment-1", "rev-2");
|
||||
});
|
||||
|
||||
it("keeps the ordinary queue while steering is unavailable or unsupported", async () => {
|
||||
for (const steeringDisposition of ["temporarily_unavailable", "unsupported"] as const) {
|
||||
const props = render({ queue: fresh({ steeringDisposition }), autoSteerDelayMs: delay });
|
||||
expect(countdown()).toBeNull();
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("tries each message revision once, then leaves it queued after a failure", async () => {
|
||||
const props = render({ queue: fresh(), autoSteerDelayMs: delay, onSteer: vi.fn().mockRejectedValue(new Error("rejected")) });
|
||||
await advance(5_100);
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).toHaveBeenCalledOnce();
|
||||
expect(container.textContent).toContain("Couldn’t steer. Message is still queued.");
|
||||
expect(countdown()).toBeNull();
|
||||
});
|
||||
|
||||
it("never sends someone else’s message or a saved card response automatically", async () => {
|
||||
const notMine = fresh();
|
||||
notMine.entries = notMine.entries.map(entry => ({ ...entry, canEdit: false }));
|
||||
const card = fresh();
|
||||
card.entries = card.entries.map(entry => ({ ...entry, source: { kind: "interaction", summary: "Approved" } as never }));
|
||||
for (const candidate of [notMine, card]) {
|
||||
const props = render({ queue: candidate, autoSteerDelayMs: delay });
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("stays off unless the caller enables it", async () => {
|
||||
const props = render({ queue: fresh() });
|
||||
expect(countdown()).toBeNull();
|
||||
await advance(10_000);
|
||||
expect(props.onSteer).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,686 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TaskMessageScroller } from "./TaskMessageScroller";
|
||||
import { TaskChatScrollNavigation } from "./scroll-navigation";
|
||||
|
||||
const PILL_SELECTOR = 'button[aria-label="Scroll to latest"]';
|
||||
|
||||
/**
|
||||
* jsdom has no layout, so scroll geometry is faked per element: scrollHeight /
|
||||
* clientHeight are pinned and scrollTop is backed by a plain variable.
|
||||
*/
|
||||
function fakeGeometry(el: HTMLElement, { scrollHeight = 1000, clientHeight = 400, clamp = false } = {}) {
|
||||
let scrollTop = 0;
|
||||
Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true });
|
||||
Object.defineProperty(el, "clientHeight", { value: clientHeight, configurable: true });
|
||||
Object.defineProperty(el, "scrollTop", {
|
||||
get: () => scrollTop,
|
||||
set: (v: number) => {
|
||||
scrollTop = clamp ? Math.max(0, Math.min(v, el.scrollHeight - el.clientHeight)) : v;
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
|
||||
function fakeResizableGeometry(
|
||||
el: HTMLElement,
|
||||
{ scrollHeight = 1000, clientHeight = 400 } = {},
|
||||
) {
|
||||
let currentClientHeight = clientHeight;
|
||||
let scrollTop = 0;
|
||||
Object.defineProperty(el, "scrollHeight", {
|
||||
value: scrollHeight,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(el, "clientHeight", {
|
||||
get: () => currentClientHeight,
|
||||
configurable: true,
|
||||
});
|
||||
Object.defineProperty(el, "scrollTop", {
|
||||
get: () => scrollTop,
|
||||
set: (value: number) => {
|
||||
scrollTop = value;
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
return {
|
||||
setClientHeight(value: number) {
|
||||
currentClientHeight = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Scroll/wheel are continuous-priority events, so React flushes the resulting
|
||||
* state updates asynchronously — wait a macrotask after dispatching.
|
||||
*/
|
||||
function flushEvents() {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
describe("TaskMessageScroller", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
function render(contentKey: unknown = 0) {
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
<TaskMessageScroller contentKey={contentKey}>
|
||||
<div>messages</div>
|
||||
</TaskMessageScroller>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function scroller(): HTMLDivElement {
|
||||
return container.querySelector<HTMLDivElement>('[data-testid="task-chat-scroller"]')!;
|
||||
}
|
||||
|
||||
function pill(): HTMLButtonElement | null {
|
||||
return container.querySelector<HTMLButtonElement>(PILL_SELECTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the pill to reach a state, rather than for a fixed number of turns.
|
||||
* `flushEvents` yields exactly one macrotask, which is enough on an idle
|
||||
* machine and not when the suite runs many workers in parallel — React
|
||||
* flushes continuous-priority updates asynchronously, so the DOM read can
|
||||
* land before the state does. Sites that dereference `pill()!` turn that into
|
||||
* a hard failure rather than a retry.
|
||||
*/
|
||||
async function waitForPill(present: boolean): Promise<void> {
|
||||
await vi.waitFor(() =>
|
||||
present ? expect(pill()).not.toBeNull() : expect(pill()).toBeNull(),
|
||||
);
|
||||
}
|
||||
|
||||
/** Set scrollTop and fire a scroll event, like a user or the browser would. */
|
||||
async function scrollTo(el: HTMLElement, top: number) {
|
||||
el.scrollTop = top;
|
||||
el.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
await flushEvents();
|
||||
}
|
||||
|
||||
async function dispatch(el: HTMLElement, event: Event) {
|
||||
el.dispatchEvent(event);
|
||||
await flushEvents();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
document.documentElement.style.removeProperty("--motion-scrollbar-idle-delay");
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("loads one older page on upward scroll, keeps the status slot, and pauses after failure", async () => {
|
||||
let release!: () => void;
|
||||
const load = vi.fn(() => new Promise<void>(resolve => { release = resolve; }));
|
||||
const history = { hasMore: true, loading: false, error: false, load };
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick} scrollingHistory={{ ...history }}><div>saved messages</div></TaskMessageScroller>,
|
||||
));
|
||||
update(0);
|
||||
fakeGeometry(scroller());
|
||||
update(1);
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
await scrollTo(scroller(), 400);
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
await scrollTo(scroller(), 150);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
await scrollTo(scroller(), 100);
|
||||
scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
|
||||
await flushEvents();
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
const status = container.querySelector('[data-testid="chat-history-status"]');
|
||||
history.loading = true;
|
||||
update(2);
|
||||
expect(container.querySelector('[data-testid="chat-history-status"]')).toBe(status);
|
||||
expect(status?.textContent).toBe("Loading earlier messages…");
|
||||
release();
|
||||
await flushEvents();
|
||||
history.loading = false;
|
||||
history.error = true;
|
||||
update(3);
|
||||
await scrollTo(scroller(), 50);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
expect(status?.textContent).toContain("Earlier messages couldn’t load.");
|
||||
(status?.querySelector('button') as HTMLButtonElement).click();
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
release();
|
||||
await flushEvents();
|
||||
history.error = false;
|
||||
history.hasMore = false;
|
||||
update(4);
|
||||
await scrollTo(scroller(), 0);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("follows a late image resize in the message body after the history status", () => {
|
||||
const observers: { targets: Set<Element>; resize: () => void }[] = [];
|
||||
vi.stubGlobal("ResizeObserver", class {
|
||||
targets = new Set<Element>();
|
||||
constructor(callback: ResizeObserverCallback) { observers.push({ targets: this.targets, resize: () => callback([], this as unknown as ResizeObserver) }); }
|
||||
observe(target: Element) { this.targets.add(target); }
|
||||
disconnect() {}
|
||||
});
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick} scrollingHistory={{ hasMore: true, loading: false, load: vi.fn() }}><div data-testid="image-body">image content</div></TaskMessageScroller>,
|
||||
));
|
||||
update(0); fakeGeometry(scroller(), { clamp: true }); update(1);
|
||||
const body = container.querySelector('[data-testid="image-body"]')!;
|
||||
Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true });
|
||||
for (const observer of observers) if (observer.targets.has(body)) observer.resize();
|
||||
expect(scroller().scrollTop).toBe(1000);
|
||||
});
|
||||
|
||||
it("keeps following when content grows before the previous scroll event is delivered", async () => {
|
||||
render(0);
|
||||
fakeGeometry(scroller(), { clamp: true });
|
||||
render(1);
|
||||
expect(scroller().scrollTop).toBe(600);
|
||||
Object.defineProperty(scroller(), "scrollHeight", { value: 1400, configurable: true });
|
||||
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
|
||||
expect(scroller().scrollTop).toBe(1000);
|
||||
expect(pill()).toBeNull();
|
||||
scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
|
||||
Object.defineProperty(scroller(), "scrollHeight", { value: 1600, configurable: true });
|
||||
await scrollTo(scroller(), 900);
|
||||
render(2);
|
||||
expect(scroller().scrollTop).toBe(900);
|
||||
await waitForPill(true);
|
||||
});
|
||||
|
||||
it("retains the reading anchor when a resize scroll event precedes the next width reflow", async () => {
|
||||
const resize: (() => void)[] = [];
|
||||
vi.stubGlobal("ResizeObserver", class {
|
||||
constructor(callback: ResizeObserverCallback) { resize.push(() => callback([], this as unknown as ResizeObserver)); }
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
});
|
||||
let width = 400, rowTop = 100;
|
||||
flushSync(() => root.render(<TaskMessageScroller contentKey="width-transition">
|
||||
<div ref={node => {
|
||||
if (!node) return;
|
||||
const viewport = node.parentElement!;
|
||||
fakeGeometry(viewport, { clamp: true });
|
||||
Object.defineProperty(viewport, "clientWidth", { get: () => width, configurable: true });
|
||||
viewport.getBoundingClientRect = () => ({ top: 0, bottom: 400 } as DOMRect);
|
||||
}}>
|
||||
<div data-thread-anchor="reading-row" ref={node => {
|
||||
if (node) node.getBoundingClientRect = () => ({ top: rowTop - scroller().scrollTop, bottom: rowTop + 100 - scroller().scrollTop, height: 100 } as DOMRect);
|
||||
}}>Saved reply</div>
|
||||
</div>
|
||||
</TaskMessageScroller>));
|
||||
await scrollTo(scroller(), 150);
|
||||
width = 500; rowTop = 80;
|
||||
for (const callback of resize) callback();
|
||||
expect(scroller().scrollTop).toBe(130);
|
||||
rowTop = 70;
|
||||
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
|
||||
for (const callback of resize) callback();
|
||||
expect(scroller().scrollTop).toBe(120);
|
||||
width = 600; rowTop = 60;
|
||||
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
|
||||
for (const callback of resize) callback();
|
||||
expect(rowTop - scroller().scrollTop).toBe(-50);
|
||||
expect(pill()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("retains upward intent when content reconciles before the scroll event", async () => {
|
||||
const load = vi.fn();
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick} scrollingHistory={{ hasMore: true, loading: false, load }}><div>saved messages</div></TaskMessageScroller>,
|
||||
));
|
||||
update(0); fakeGeometry(scroller()); update(1);
|
||||
await scrollTo(scroller(), 400);
|
||||
scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -1000 }));
|
||||
scroller().scrollTop = 0;
|
||||
update(2);
|
||||
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("holds a short conversation when an upward wheel gesture loads history", async () => {
|
||||
const load = vi.fn().mockResolvedValue(undefined);
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick} scrollingHistory={{ hasMore: true, loading: false, load }}><div>short conversation</div></TaskMessageScroller>,
|
||||
));
|
||||
update(0);
|
||||
fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true });
|
||||
update(1);
|
||||
await scrollTo(scroller(), 0);
|
||||
scroller().dispatchEvent(new WheelEvent("wheel", { bubbles: true, deltaY: -100 }));
|
||||
await flushEvents();
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
Object.defineProperty(scroller(), "scrollHeight", { value: 1200, configurable: true });
|
||||
update(2);
|
||||
expect(scroller().scrollTop).toBe(0);
|
||||
});
|
||||
|
||||
it("pages short conversations with touch and keyboard gestures", async () => {
|
||||
const load = vi.fn().mockResolvedValue(undefined);
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick} scrollingHistory={{ hasMore: true, loading: false, load }}><div>short conversation</div></TaskMessageScroller>,
|
||||
));
|
||||
update(0); fakeGeometry(scroller(), { scrollHeight: 200, clientHeight: 400, clamp: true }); update(1);
|
||||
await scrollTo(scroller(), 0);
|
||||
const touch = (type: string, y: number) => {
|
||||
const event = new Event(type, { bubbles: true });
|
||||
Object.defineProperty(event, "touches", { value: [{ clientY: y }] });
|
||||
scroller().dispatchEvent(event);
|
||||
};
|
||||
touch("touchstart", 100); touch("touchmove", 200); touch("touchmove", 250);
|
||||
await flushEvents();
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
scroller().dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Home" }));
|
||||
await flushEvents();
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not measure historical rows on each streaming update while following the bottom", () => {
|
||||
let initialized = false;
|
||||
let rowMeasurements = 0;
|
||||
const update = (tick: number) => flushSync(() => root.render(
|
||||
<TaskMessageScroller contentKey={tick}>
|
||||
<div ref={(node) => {
|
||||
if (node && !initialized) {
|
||||
fakeGeometry(node.parentElement!, { scrollHeight: 20000, clientHeight: 400 });
|
||||
initialized = true;
|
||||
}
|
||||
}}>
|
||||
{Array.from({ length: 200 }, (_, index) => <div key={index} data-thread-anchor={`history-${index}`} ref={(node) => {
|
||||
if (node) node.getBoundingClientRect = () => {
|
||||
rowMeasurements++;
|
||||
const top = index * 100 - scroller().scrollTop;
|
||||
return { top, bottom: top + 100, height: 100 } as DOMRect;
|
||||
};
|
||||
}}>History {index}</div>)}
|
||||
<p>Live response {tick}</p>
|
||||
</div>
|
||||
</TaskMessageScroller>,
|
||||
));
|
||||
update(0);
|
||||
rowMeasurements = 0;
|
||||
for (let tick = 1; tick <= 30; tick++) update(tick);
|
||||
expect(container.textContent).toContain("Live response 30");
|
||||
expect(scroller().scrollTop).toBe(20000);
|
||||
expect(rowMeasurements).toBe(0);
|
||||
});
|
||||
|
||||
it("applies same-task hash changes and restores each history entry without remounting", async () => {
|
||||
let initialized = false;
|
||||
function navigate(key: string, hash: string, restore = false) {
|
||||
flushSync(() => root.render(
|
||||
<TaskChatScrollNavigation.Provider value={{ key, hash, restore }}>
|
||||
<TaskMessageScroller contentKey="unchanged">
|
||||
<div ref={(node) => {
|
||||
if (node && !initialized) {
|
||||
fakeGeometry(node.parentElement!);
|
||||
initialized = true;
|
||||
}
|
||||
}}>
|
||||
{[100, 500].map((top, index) => <div key={index} id={`nav-comment-${index}`} data-thread-anchor={`nav-comment-${index}`} ref={(node) => {
|
||||
if (node) node.getBoundingClientRect = () => ({ top: top - scroller().scrollTop, bottom: top + 100 - scroller().scrollTop, height: 100 } as DOMRect);
|
||||
}}>Comment {index}</div>)}
|
||||
</div>
|
||||
</TaskMessageScroller>
|
||||
</TaskChatScrollNavigation.Provider>,
|
||||
));
|
||||
}
|
||||
navigate("desktop-entry-one", "#nav-comment-0");
|
||||
const viewport = scroller();
|
||||
expect(viewport.scrollTop).toBe(100);
|
||||
await scrollTo(viewport, 150);
|
||||
navigate("desktop-entry-two", "#nav-comment-1");
|
||||
expect(scroller()).toBe(viewport);
|
||||
expect(viewport.scrollTop).toBe(500);
|
||||
navigate("desktop-entry-one", "#nav-comment-0", true);
|
||||
expect(viewport.scrollTop).toBe(150);
|
||||
navigate("desktop-entry-one", "#nav-comment-1", true);
|
||||
expect(viewport.scrollTop).toBe(500);
|
||||
});
|
||||
|
||||
it.each([[false, "none"], [false, "wheel"], [false, "pointer"], [true, "none"], [true, "wheel"], [true, "pointer"]] as const)("positions a late hash target unless the reader moved on (restore=%s, readerMoved=%s)", async (restore, readerMoved) => {
|
||||
let initialized = false;
|
||||
const show = (targetReady: boolean) => flushSync(() => root.render(
|
||||
<TaskChatScrollNavigation.Provider value={{ key: `late-target-${restore}-${readerMoved}`, hash: "#late-target", restore }}>
|
||||
<TaskMessageScroller contentKey={targetReady}>
|
||||
<div ref={node => {
|
||||
if (node && !initialized) { fakeGeometry(node.parentElement!, { clamp: true }); initialized = true; }
|
||||
}}>
|
||||
Saved conversation
|
||||
{targetReady ? <div id="late-target" data-thread-anchor="late-target" ref={node => {
|
||||
if (node) node.getBoundingClientRect = () => ({ top: 100 - scroller().scrollTop, bottom: 200 - scroller().scrollTop, height: 100 } as DOMRect);
|
||||
}}>Linked comment</div> : null}
|
||||
</div>
|
||||
</TaskMessageScroller>
|
||||
</TaskChatScrollNavigation.Provider>,
|
||||
));
|
||||
show(false);
|
||||
if (readerMoved !== "none") {
|
||||
await scrollTo(scroller(), 300);
|
||||
await dispatch(scroller(), readerMoved === "wheel" ? new WheelEvent("wheel", { bubbles: true, deltaY: -100 }) : new Event("pointerdown", { bubbles: true }));
|
||||
}
|
||||
show(true);
|
||||
expect(scroller().scrollTop).toBe(readerMoved === "none" ? 100 : 300);
|
||||
});
|
||||
|
||||
it("does not replace a saved reading position with a hidden route's geometry", async () => {
|
||||
function mount(restore: boolean) {
|
||||
flushSync(() => root.render(
|
||||
<TaskChatScrollNavigation.Provider value={{ key: "hidden-route-entry", hash: "", restore }}>
|
||||
<TaskMessageScroller contentKey="saved-thread">
|
||||
<div ref={(node) => { if (node) fakeGeometry(node.parentElement!); }}>Saved messages</div>
|
||||
</TaskMessageScroller>
|
||||
</TaskChatScrollNavigation.Provider>,
|
||||
));
|
||||
}
|
||||
mount(false);
|
||||
const viewport = scroller();
|
||||
await scrollTo(viewport, 150);
|
||||
Object.defineProperty(viewport, "clientHeight", { value: 0, configurable: true });
|
||||
await scrollTo(viewport, 0);
|
||||
flushSync(() => root.render(null));
|
||||
mount(true);
|
||||
expect(scroller().scrollTop).toBe(150);
|
||||
});
|
||||
|
||||
it("restores bottom-follow on Back after the viewport and message heights change", () => {
|
||||
const configured = new WeakSet<HTMLElement>();
|
||||
function mount(restore: boolean, scrollHeight: number, clientHeight: number) {
|
||||
flushSync(() => root.render(
|
||||
<TaskChatScrollNavigation.Provider value={{ key: "rotated-bottom-entry", hash: "", restore }}>
|
||||
<TaskMessageScroller contentKey={scrollHeight}>
|
||||
<div ref={(node) => {
|
||||
const viewport = node?.parentElement;
|
||||
if (viewport && !configured.has(viewport)) {
|
||||
fakeGeometry(viewport, { scrollHeight, clientHeight });
|
||||
let top = 0;
|
||||
Object.defineProperty(viewport, "scrollTop", {
|
||||
configurable: true,
|
||||
get: () => top,
|
||||
set: (value: number) => {
|
||||
top = Math.max(0, Math.min(value, viewport.scrollHeight - viewport.clientHeight));
|
||||
},
|
||||
});
|
||||
configured.add(viewport);
|
||||
}
|
||||
}}>Latest response</div>
|
||||
</TaskMessageScroller>
|
||||
</TaskChatScrollNavigation.Provider>,
|
||||
));
|
||||
}
|
||||
mount(false, 1000, 400);
|
||||
flushSync(() => root.render(null));
|
||||
// Rotation changed wrapping and the available message viewport while away.
|
||||
mount(true, 2000, 500);
|
||||
expect(scroller().scrollTop).toBe(1500);
|
||||
expect(pill()).toBeNull();
|
||||
Object.defineProperty(scroller(), "scrollHeight", { value: 2400, configurable: true });
|
||||
mount(true, 2400, 500);
|
||||
expect(scroller().scrollTop).toBe(1900);
|
||||
});
|
||||
|
||||
it("renders children inside the scroll container, pill hidden, scrolled to bottom on mount", () => {
|
||||
render();
|
||||
const el = scroller();
|
||||
expect(el.textContent).toContain("messages");
|
||||
expect(pill()).toBeNull();
|
||||
// Mount effect pins to the bottom.
|
||||
expect(el.scrollTop).toBe(el.scrollHeight);
|
||||
});
|
||||
|
||||
it("extends only the streamlined scroll box through the page gutter", () => {
|
||||
render();
|
||||
const el = scroller();
|
||||
const frame = el.parentElement;
|
||||
|
||||
expect(frame?.className).toBe("relative min-h-0 flex-1");
|
||||
expect(el.classList).toContain("-right-4");
|
||||
expect(el.classList).toContain("pr-4");
|
||||
expect(el.classList).toContain("md:-right-6");
|
||||
expect(el.classList).toContain("md:pr-6");
|
||||
expect(el.classList).not.toContain("right-0");
|
||||
});
|
||||
|
||||
it("shows the scrollbar only while scroll activity is recent", () => {
|
||||
vi.useFakeTimers();
|
||||
document.documentElement.style.setProperty("--motion-scrollbar-idle-delay", "600ms");
|
||||
render();
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
|
||||
expect(el.className).toContain("scrollbar-while-scrolling");
|
||||
expect(el.getAttribute("data-scroll-active")).toBeNull();
|
||||
|
||||
el.scrollTop = 100;
|
||||
el.dispatchEvent(new Event("scroll", { bubbles: true }));
|
||||
expect(el.getAttribute("data-scroll-active")).toBe("true");
|
||||
|
||||
vi.advanceTimersByTime(599);
|
||||
expect(el.getAttribute("data-scroll-active")).toBe("true");
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(el.getAttribute("data-scroll-active")).toBeNull();
|
||||
});
|
||||
|
||||
it("contains horizontal overflow so no scrollbar appears above the composer", () => {
|
||||
render();
|
||||
|
||||
expect(scroller().classList).toContain("overflow-x-hidden");
|
||||
expect(scroller().classList).toContain("overflow-y-auto");
|
||||
});
|
||||
|
||||
it("auto-follows content instantly while pinned", async () => {
|
||||
render(1);
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
await scrollTo(el, 600); // bottom: 1000 - 600 - 400 = 0 → pinned
|
||||
await waitForPill(false); // pinned state settled before content grows
|
||||
render(2);
|
||||
expect(el.scrollTop).toBe(1000);
|
||||
expect(pill()).toBeNull();
|
||||
});
|
||||
|
||||
it("holds position and shows the icon-only pill when scrolled up", async () => {
|
||||
render(1);
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
await scrollTo(el, 100); // 500px from bottom → unpinned
|
||||
await waitForPill(true);
|
||||
const btn = pill();
|
||||
expect(btn).not.toBeNull();
|
||||
expect(btn!.className).toContain("tc-scroll-pill-in");
|
||||
expect(btn!.className).toContain("size-8");
|
||||
expect(btn!.className).toContain("bottom-7");
|
||||
expect(btn!.className).not.toContain("bottom-3");
|
||||
expect(btn!.className).not.toContain("-translate-x-1/2");
|
||||
// Icon-only: no visible text.
|
||||
expect(btn!.textContent).toBe("");
|
||||
// New content must not yank the held position.
|
||||
render(2);
|
||||
expect(el.scrollTop).toBe(100);
|
||||
});
|
||||
|
||||
it("follows a shrinking viewport while pinned so a growing composer cannot cover the latest text", async () => {
|
||||
let triggerResize = () => {};
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
triggerResize = () =>
|
||||
callback([], this as unknown as ResizeObserver);
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
render();
|
||||
const el = scroller();
|
||||
const geometry = fakeResizableGeometry(el);
|
||||
triggerResize();
|
||||
await scrollTo(el, 600);
|
||||
|
||||
geometry.setClientHeight(200);
|
||||
triggerResize();
|
||||
|
||||
expect(el.scrollTop).toBe(el.scrollHeight);
|
||||
expect(pill()).toBeNull();
|
||||
});
|
||||
|
||||
it("holds a reader's position when the composer grows while they are scrolled up", async () => {
|
||||
let triggerResize = () => {};
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
triggerResize = () =>
|
||||
callback([], this as unknown as ResizeObserver);
|
||||
}
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
render();
|
||||
const el = scroller();
|
||||
const geometry = fakeResizableGeometry(el);
|
||||
triggerResize();
|
||||
await scrollTo(el, 100);
|
||||
await waitForPill(true);
|
||||
|
||||
geometry.setClientHeight(200);
|
||||
triggerResize();
|
||||
|
||||
expect(el.scrollTop).toBe(100);
|
||||
expect(pill()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("small drifts within the pin threshold do not show the pill", async () => {
|
||||
render();
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
await scrollTo(el, 560); // 40px from bottom, threshold is 48
|
||||
expect(pill()).toBeNull();
|
||||
});
|
||||
|
||||
it("clicking the pill smooth-scrolls, ignores intermediate scroll events, re-pins on arrival", async () => {
|
||||
vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false }));
|
||||
render(1);
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
const scrollToSpy = vi.fn();
|
||||
el.scrollTo = scrollToSpy as unknown as typeof el.scrollTo;
|
||||
|
||||
await scrollTo(el, 100);
|
||||
await waitForPill(true);
|
||||
const btn = pill()!;
|
||||
btn.click();
|
||||
await flushEvents();
|
||||
expect(scrollToSpy).toHaveBeenCalledWith({ top: 1000, behavior: "smooth" });
|
||||
|
||||
// Intermediate glide positions fire scroll events; they must not unpin
|
||||
// (i.e. the easing flag swallows them and the pill state stays put).
|
||||
await scrollTo(el, 250);
|
||||
await scrollTo(el, 400);
|
||||
expect(pill()).not.toBeNull();
|
||||
|
||||
// Arrival within the threshold re-pins and hides the pill (immediately
|
||||
// here: no matchMedia in jsdom → reduced-motion/unmount-now path).
|
||||
vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: true }));
|
||||
await scrollTo(el, 600);
|
||||
expect(pill()).toBeNull();
|
||||
|
||||
// Re-pinned: content growth follows instantly again.
|
||||
render(2);
|
||||
expect(el.scrollTop).toBe(1000);
|
||||
});
|
||||
|
||||
it("finishes following at the new bottom when content changes during the latest glide", async () => {
|
||||
vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false }));
|
||||
render(1);
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
el.scrollTo = vi.fn() as unknown as typeof el.scrollTo;
|
||||
await scrollTo(el, 100);
|
||||
await waitForPill(true);
|
||||
pill()!.click();
|
||||
await flushEvents();
|
||||
await scrollTo(el, 250);
|
||||
render(2);
|
||||
expect(el.scrollTop).toBe(1000);
|
||||
});
|
||||
|
||||
it("a wheel gesture during the glide cancels easing and stays unpinned", async () => {
|
||||
vi.stubGlobal("matchMedia", vi.fn().mockReturnValue({ matches: false }));
|
||||
render(1);
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
el.scrollTo = vi.fn() as unknown as typeof el.scrollTo;
|
||||
|
||||
await scrollTo(el, 100);
|
||||
await waitForPill(true);
|
||||
pill()!.click();
|
||||
await flushEvents();
|
||||
await dispatch(el, new Event("wheel", { bubbles: true }));
|
||||
|
||||
// Easing cancelled → user is unpinned, pill visible, content holds.
|
||||
expect(pill()).not.toBeNull();
|
||||
render(2);
|
||||
expect(el.scrollTop).toBe(100);
|
||||
|
||||
// Scroll events far from the bottom now behave normally (still unpinned).
|
||||
await scrollTo(el, 200);
|
||||
expect(pill()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("plays the exit animation before unmounting when motion is enabled", async () => {
|
||||
vi.stubGlobal(
|
||||
"matchMedia",
|
||||
vi.fn().mockReturnValue({ matches: false }), // motion allowed
|
||||
);
|
||||
render();
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
await scrollTo(el, 100);
|
||||
await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-in"));
|
||||
|
||||
// Scrolling back to the bottom starts the exit animation but keeps the
|
||||
// pill mounted until animationend.
|
||||
await scrollTo(el, 600);
|
||||
await vi.waitFor(() => expect(pill()?.className).toContain("tc-scroll-pill-out"));
|
||||
const exiting = pill();
|
||||
expect(exiting).not.toBeNull();
|
||||
|
||||
// jsdom has no window.AnimationEvent, so React's vendor-prefix detection
|
||||
// maps onAnimationEnd to "webkitAnimationEnd" here (real browsers get the
|
||||
// unprefixed event).
|
||||
await dispatch(exiting!, new Event("webkitAnimationEnd", { bubbles: true }));
|
||||
await waitForPill(false);
|
||||
});
|
||||
|
||||
it("unmounts immediately on hide under prefers-reduced-motion", async () => {
|
||||
vi.stubGlobal(
|
||||
"matchMedia",
|
||||
vi.fn().mockReturnValue({ matches: true }), // reduce
|
||||
);
|
||||
render();
|
||||
const el = scroller();
|
||||
fakeGeometry(el);
|
||||
await scrollTo(el, 100);
|
||||
await waitForPill(true);
|
||||
await scrollTo(el, 600);
|
||||
await waitForPill(false); // no animationend needed
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user