mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 22:24:16 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The first-run experience (onboarding wizard) and the chat surfaces
(conference-room/board chat, task threads, composers) are the product's
front door — they decide whether a new operator understands "hire
agents, give them work, review results" in the first five minutes
> - Today those surfaces feel ticket-y and form-like: the wizard is a
static multi-step form that ends in an anticlimactic "Launch" screen,
the task composer and board chat behave differently from each other, and
agent-feed issue quicklooks misbehave (multiple flyouts open at once,
cards jump on hover)
> - We wanted to iterate toward a conversational, team-centric NUX — but
without risking the workflows of everyone already running Paperclip
> - This PR reworks the NUX behind a new default-OFF
`enableConferenceRoomChat` experimental flag: a capsule-motif onboarding
wizard that builds your team as you answer, a conference-room chat
surface, one shared ChatComposer across surfaces, brand-accurate status
chips, and feed-quicklook fixes — with the pre-existing UI
fork-and-frozen as `*Classic` components that flag-OFF users keep
> - The benefit is a complete, testable modern NUX that anyone can opt
into from Settings → Experimental, with zero default behavior change and
a clean path to either graduate or drop the experiment
## Linked Issues or Issue Description
No pre-existing GitHub issue — feature description per
`feature_request.yml`:
- **Problem / motivation:** Paperclip's onboarding wizard and chat
surfaces grew up as separate ticket-centric forms. New users get a
form-filling experience rather than the feeling of standing up a team;
the board chat and task threads use different composers with different
affordances; the agent feed's issue quicklook can stack multiple
popovers and shifts cards on hover.
- **Proposed solution:** A coherent NUX experiment behind one
experimental flag (`enableConferenceRoomChat`, Settings → Experimental,
default OFF): capsule onboarding wizard with an evolving team capsule,
conference-room chat, unified `ChatComposer`, team-centric copy, brand
status chips, quicklook single-flight fix. Flag-OFF users get the exact
pre-experiment UI via frozen `*Classic` forks, verified by an on/off
parity test matrix.
- **Alternatives considered:** (a) incremental unflagged restyling —
rejected: the changes interlock across surfaces and would drip risk into
every release; (b) a separate app shell / route for the new NUX —
rejected: too much divergence, the flag + classic-fork pattern keeps the
diff reviewable and reversible.
- **Roadmap alignment:** `ROADMAP.md` lists **CEO Chat** ("a
lighter-weight way to talk to leadership agents... should still resolve
to real work objects"). This experiment is groundwork in that direction
(conference-room chat resolves to issues/tasks via the same composer
used in task threads) and does not change the core task-and-comments
model.
Related PRs found in the dedup search (same area, none duplicate this
work — they target the classic wizard, which this PR intentionally
leaves intact and mergeable):
- #5385 — Coach-driven onboarding: conversational entry +
agent-companies package import
- #5378 — Onboarding wizard: reusable adapter picker + probe card
- #6636 — ui(onboarding): friendly error surface + retry for the wizard
- #7005 — fix(onboarding): explicitly await first-task wake
- #2616 — fix: restore workspace directory config in onboarding wizard
## What Changed
- **Experimental flag plumbing** — `enableConferenceRoomChat` in shared
types/validators, server instance-settings service + API, Settings →
Experimental card with explicit enable/disable copy
- **Onboarding wizard** — classic wizard forked and frozen
(`OnboardingWizardClassic`); flag-ON variant is a 5-step capsule wizard
with a persistent evolving `AgentCapsule` (gradient/glow motif),
team-centric reframed copy, and a typing-dots intro (hardened with
fake-timer tests)
- **Conference-room chat** — flag-ON board-chat surface with agent
bubble name/icon headers and copy/vote/timestamp action rows
(`AgentBubbleActionRow`)
- **Unified composer** — shared `ChatComposer` adopted across surfaces;
translucent surface + scroll-mask removal; "Agent mode"/"Plan mode"
relabels; no-assignee confirmation `AlertDialog` (new
`ui/alert-dialog.tsx` primitive); `@task` reference picker +
linkification in mentions
- **Agent feed** — single-flight issue-quicklook store (one popover at a
time), flyouts open to the left, removed hover translate-y jitter
- **Status chips** — brand-accurate task status chips behind the flag
(light/dark, 1px borders per paperclip.ing/brand)
- **Tests** — flag on/off parity matrix across IssueDetail,
NewIssueDialog, Sidebar, wizard, gate components; component tests for
all new pieces
- **Merge with `master`** — one conflict in
`ui/src/components/IssueChatThread.tsx`, resolved by keeping master's
new `AssigneeChip`/`HandoffWakeRow`/`RunStatusBadge` components inside
the flag-gated metadata-row chrome (details in commit `21a5642a`);
post-merge fixes: vitest 4 mock typing in `MarkdownEditor.test.tsx`,
flag hook made safe for provider-less mounts (master's new isolated
component tests)
- **Branch hygiene** — internal design wireframes/mockups stripped
before the PR (they live in the Paperclip issue threads)
- No user-facing documentation changes required: the flag is
intentionally experimental and self-described in the Settings card; no
existing docs reference the affected surfaces
## Verification
- `pnpm run typecheck` — green across the workspace (ui, server, shared,
plugins)
- Full UI suite (`vitest run` in `ui/`, clean worktree at this HEAD):
**1593/1595 passing, 223/224 files** — the 2 remaining failures are in
`src/components/artifacts/ArtifactCard.test.tsx` and **fail identically
on pristine `origin/master`** (pre-existing upstream, unrelated to this
branch)
- Full server suite (`vitest run` in `server/`, same clean worktree):
results in PR checks; flag plumbing covered by instance-settings tests
- Targeted post-merge resolution check: `IssueChatThread`,
`IssueChatThreadSystemNotice`, `IssueDetail`, `Sidebar`,
`ConferenceRoomChatGate`, `OnboardingWizardVariant`, `NewIssueDialog`,
`InstanceExperimentalSettings`, `MarkdownEditor` — 172/172 passing
- Manual walkthrough: flag OFF (default) → onboarding wizard, task
thread, board chat, composer all render the classic UI; flag ON via
Settings → Experimental → capsule wizard, conference-room chat, unified
composer, status chips active
- Screenshots: see below
**Flag on/off screenshots** (committed on this branch under
`screenshots/PR-8000-*`):
| Surface | Flag OFF (classic, default) | Flag ON (experimental) |
| --- | --- | --- |
| Settings → Experimental | 
| 
|
| Task thread | 
| 
|
| Home / nav | 
| 
|
| Conference Room (flag-ON only surface) | — | 
|
Capsule onboarding wizard walkthrough screenshots (flag ON) are attached
to the Paperclip design/implementation threads; the wizard requires a
fresh instance so it is captured via the e2e harness
(`tests/e2e/nux-phase4-screenshots.spec.ts`).
## Risks
- **Large surface, but gated:** all new behavior sits behind
`enableConferenceRoomChat`, default OFF; flag-OFF rendering is locked by
frozen `*Classic` forks plus an on/off parity test suite
- **Classic forks are frozen at the fork point (`e3aada1d`):** master
features added to the live thread component after that point (assignee
handoff chips, run status badge, composer mention coach) render in the
flag-ON path; the flag-OFF task thread keeps the fork-point behavior
until the experiment graduates (forks deleted) or is dropped (forks
restored as canonical). Called out for reviewer attention.
- **Merge-conflict resolution in `IssueChatThread.tsx`** (commit
`21a5642a`) deserves reviewer eyes: master's new handoff/run-status
components were kept; the base toast-style no-assignee flow remains
replaced by the AlertDialog flow introduced on this branch
- Schema/server changes are additive (one optional boolean instance
setting); no migrations of existing data
## Model Used
- Claude (Anthropic) via Claude Code running in the Paperclip agent
harness (agent: ClaudeCoder)
- Branch implemented across multiple agent sessions on Claude Opus-class
models with extended thinking + tool use (file edits, shell, Playwright
screenshots); merge/PR session model ID as reported by the harness:
`claude-fable-5` (Claude Code CLI)
- All code was agent-authored and board-reviewed through Paperclip issue
threads (plans, wireframes, confirmations) before merging
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes (none
required — experimental flag, self-documenting Settings card; noted
above)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green (run 3 on `8af3041a`: all 16
gates SUCCESS, incl. e2e and all 4 serialized-suite shards)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(re-review verdict: Confidence 5/5, “Safe to merge”; all 4 round-1
findings fixed + confirmed resolved; both summary notes addressed in
`8af3041a`)
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
996 lines
29 KiB
TypeScript
996 lines
29 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { act } from "react";
|
|
import { createRoot } from "react-dom/client";
|
|
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
|
|
import { buildIssueReferenceHref, buildProjectMentionHref, buildRoutineMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
|
|
import {
|
|
computeMentionMenuPosition,
|
|
findClosestAutocompleteAnchor,
|
|
findMentionMatch,
|
|
isSameAutocompleteSession,
|
|
issueMentionTitle,
|
|
MarkdownEditor,
|
|
type MentionOption,
|
|
placeCaretAfterMentionAnchor,
|
|
shouldAcceptAutocompleteKey,
|
|
} from "./MarkdownEditor";
|
|
|
|
const mdxEditorMockState = vi.hoisted(() => ({
|
|
emitMountEmptyReset: false,
|
|
emitMountParseError: false,
|
|
emitMountSilentEmptyState: false,
|
|
markdownValues: [] as string[],
|
|
suppressHtmlProcessingValues: [] as boolean[],
|
|
}));
|
|
|
|
function containsHtmlLikeTag(markdown: string) {
|
|
return /<\/?[A-Za-z][A-Za-z0-9:-]*(?:\s[^>]*)?\/?>/.test(markdown);
|
|
}
|
|
|
|
vi.mock("@mdxeditor/editor", async () => {
|
|
const React = await import("react");
|
|
|
|
function setForwardedRef<T>(ref: React.ForwardedRef<T | null>, value: T | null) {
|
|
if (typeof ref === "function") {
|
|
ref(value);
|
|
return;
|
|
}
|
|
if (ref) {
|
|
(ref as React.MutableRefObject<T | null>).current = value;
|
|
}
|
|
}
|
|
|
|
const MDXEditor = React.forwardRef(function MockMDXEditor(
|
|
{
|
|
markdown,
|
|
placeholder,
|
|
onChange,
|
|
onError,
|
|
className,
|
|
suppressHtmlProcessing,
|
|
}: {
|
|
markdown: string;
|
|
placeholder?: string;
|
|
onChange?: (value: string) => void;
|
|
onError?: (error: unknown) => void;
|
|
suppressHtmlProcessing?: boolean;
|
|
className?: string;
|
|
},
|
|
forwardedRef: React.ForwardedRef<{ setMarkdown: (value: string) => void; focus: () => void } | null>,
|
|
) {
|
|
mdxEditorMockState.markdownValues.push(markdown);
|
|
mdxEditorMockState.suppressHtmlProcessingValues.push(Boolean(suppressHtmlProcessing));
|
|
const [content, setContent] = React.useState(markdown);
|
|
const editableRef = React.useRef<HTMLDivElement>(null);
|
|
const handle = React.useMemo(() => ({
|
|
setMarkdown: (value: string) => setContent(value),
|
|
focus: () => editableRef.current?.focus(),
|
|
}), []);
|
|
|
|
React.useEffect(() => {
|
|
if (!suppressHtmlProcessing && containsHtmlLikeTag(markdown)) {
|
|
setContent("");
|
|
onError?.({
|
|
error: "Error parsing markdown: HTML-like formatting requires suppressHtmlProcessing",
|
|
source: markdown,
|
|
});
|
|
return;
|
|
}
|
|
setContent(markdown);
|
|
}, [markdown, onError, suppressHtmlProcessing]);
|
|
|
|
React.useEffect(() => {
|
|
setForwardedRef(forwardedRef, null);
|
|
const timer = window.setTimeout(() => {
|
|
setForwardedRef(forwardedRef, handle);
|
|
if (mdxEditorMockState.emitMountEmptyReset) {
|
|
setContent("");
|
|
onChange?.("");
|
|
}
|
|
if (mdxEditorMockState.emitMountSilentEmptyState) {
|
|
setContent("");
|
|
}
|
|
if (mdxEditorMockState.emitMountParseError) {
|
|
setContent("");
|
|
onError?.({
|
|
error: "Unsupported markdown syntax",
|
|
source: markdown,
|
|
});
|
|
}
|
|
}, 0);
|
|
return () => {
|
|
window.clearTimeout(timer);
|
|
setForwardedRef(forwardedRef, null);
|
|
};
|
|
}, []);
|
|
|
|
return (
|
|
<div
|
|
ref={editableRef}
|
|
data-testid="mdx-editor"
|
|
className={className}
|
|
contentEditable
|
|
suppressContentEditableWarning
|
|
>
|
|
{content || placeholder || ""}
|
|
</div>
|
|
);
|
|
});
|
|
|
|
return {
|
|
CodeMirrorEditor: () => null,
|
|
MDXEditor,
|
|
codeBlockPlugin: () => ({}),
|
|
codeMirrorPlugin: () => ({}),
|
|
createRootEditorSubscription$: Symbol("createRootEditorSubscription$"),
|
|
headingsPlugin: () => ({}),
|
|
imagePlugin: () => ({}),
|
|
linkDialogPlugin: () => ({}),
|
|
linkPlugin: () => ({}),
|
|
listsPlugin: () => ({}),
|
|
markdownShortcutPlugin: () => ({}),
|
|
quotePlugin: () => ({}),
|
|
realmPlugin: (plugin: unknown) => plugin,
|
|
tablePlugin: () => ({}),
|
|
thematicBreakPlugin: () => ({}),
|
|
};
|
|
});
|
|
|
|
vi.mock("../lib/mention-deletion", () => ({
|
|
mentionDeletionPlugin: () => ({}),
|
|
}));
|
|
|
|
vi.mock("../lib/paste-normalization", () => ({
|
|
pasteNormalizationPlugin: () => ({}),
|
|
}));
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
async function flush() {
|
|
await act(async () => {
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
});
|
|
}
|
|
|
|
function createFileDragEvent(type: string) {
|
|
const event = new Event(type, { bubbles: true, cancelable: true }) as Event & {
|
|
dataTransfer: { types: string[]; files: File[]; dropEffect?: string };
|
|
};
|
|
event.dataTransfer = {
|
|
types: ["Files"],
|
|
files: [],
|
|
};
|
|
return event;
|
|
}
|
|
|
|
describe("issueMentionTitle", () => {
|
|
it("strips the leading identifier from the mention name", () => {
|
|
expect(
|
|
issueMentionTitle({
|
|
id: "issue:1",
|
|
kind: "issue",
|
|
name: "PAP-102 @task references",
|
|
issueIdentifier: "PAP-102",
|
|
}),
|
|
).toBe("@task references");
|
|
});
|
|
|
|
it("returns the full name when there is no separate title", () => {
|
|
expect(
|
|
issueMentionTitle({
|
|
id: "issue:1",
|
|
kind: "issue",
|
|
name: "PAP-7",
|
|
issueIdentifier: "PAP-7",
|
|
}),
|
|
).toBe("");
|
|
});
|
|
|
|
it("falls back to the name when the identifier is missing", () => {
|
|
expect(
|
|
issueMentionTitle({ id: "issue:1", kind: "issue", name: "Some task" }),
|
|
).toBe("Some task");
|
|
});
|
|
});
|
|
|
|
describe("MarkdownEditor", () => {
|
|
let container: HTMLDivElement;
|
|
let originalRangeRect: typeof Range.prototype.getBoundingClientRect;
|
|
|
|
beforeEach(() => {
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
originalRangeRect = Range.prototype.getBoundingClientRect;
|
|
Range.prototype.getBoundingClientRect = () => ({
|
|
x: 32,
|
|
y: 24,
|
|
width: 12,
|
|
height: 18,
|
|
top: 24,
|
|
right: 44,
|
|
bottom: 42,
|
|
left: 32,
|
|
toJSON: () => ({}),
|
|
});
|
|
});
|
|
|
|
afterEach(() => {
|
|
container.remove();
|
|
Range.prototype.getBoundingClientRect = originalRangeRect;
|
|
vi.clearAllMocks();
|
|
mdxEditorMockState.emitMountEmptyReset = false;
|
|
mdxEditorMockState.emitMountParseError = false;
|
|
mdxEditorMockState.emitMountSilentEmptyState = false;
|
|
mdxEditorMockState.markdownValues = [];
|
|
mdxEditorMockState.suppressHtmlProcessingValues = [];
|
|
});
|
|
|
|
it("applies async external value updates once the editor ref becomes ready", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value=""
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value="Loaded plan body"
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
expect(container.textContent).toContain("Loaded plan body");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("keeps the external value when the unfocused editor emits an empty mount reset", async () => {
|
|
mdxEditorMockState.emitMountEmptyReset = true;
|
|
const handleChange = vi.fn();
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value="Loaded plan body"
|
|
onChange={handleChange}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
expect(container.textContent).toContain("Loaded plan body");
|
|
expect(handleChange).not.toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("converts advisory-style html image tags to markdown image syntax before mounting the editor", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value={`Before\n\n<img width="10" height="10" alt="image" src="https://example.com/test.png" />\n\nAfter`}
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
expect(mdxEditorMockState.markdownValues.at(-1)).toContain("");
|
|
expect(mdxEditorMockState.markdownValues.at(-1)).not.toContain("<img");
|
|
expect(mdxEditorMockState.suppressHtmlProcessingValues).toContain(true);
|
|
expect(container.textContent).toContain("Before");
|
|
expect(container.textContent).toContain("After");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("keeps arbitrary HTML-like tags in the rich editor instead of falling back to raw source", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value={'<section data-source="paste">\n## My take\n\n<p>Benchmark notes</p>\n</section>'}
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
expect(mdxEditorMockState.suppressHtmlProcessingValues).toContain(true);
|
|
expect(container.querySelector("textarea")).toBeNull();
|
|
expect(container.textContent).toContain("Benchmark notes");
|
|
expect(container.textContent).not.toContain("Rich editor unavailable for this markdown");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("keeps scriptable pasted HTML inert in the rich editor", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value={'<script>fetch("/api/secrets")</script>\n<iframe src="https://example.com"></iframe>\n<p onclick="steal()">Plain text</p>'}
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
expect(mdxEditorMockState.suppressHtmlProcessingValues).toContain(true);
|
|
expect(container.querySelector("textarea")).toBeNull();
|
|
expect(container.querySelector("script, iframe, p[onclick]")).toBeNull();
|
|
expect(container.textContent).toContain('fetch("/api/secrets")');
|
|
expect(container.textContent).toContain("Plain text");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("falls back to a raw textarea when the rich parser rejects the markdown", async () => {
|
|
mdxEditorMockState.emitMountParseError = true;
|
|
const handleChange = vi.fn();
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value="Affected versions: <= v0.3.1"
|
|
onChange={handleChange}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
await vi.waitFor(() => {
|
|
expect(container.querySelector("textarea")).not.toBeNull();
|
|
});
|
|
const textarea = container.querySelector("textarea");
|
|
expect(textarea).not.toBeNull();
|
|
expect(textarea?.value).toBe("Affected versions: <= v0.3.1");
|
|
expect(container.textContent).toContain("Rich editor unavailable for this markdown");
|
|
expect(handleChange).not.toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("falls back to a raw textarea when the rich editor mounts into the placeholder without callbacks", async () => {
|
|
mdxEditorMockState.emitMountSilentEmptyState = true;
|
|
const handleChange = vi.fn();
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value="Affected versions: <= v0.3.1"
|
|
onChange={handleChange}
|
|
placeholder="Add a description..."
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
await vi.waitFor(() => {
|
|
expect(container.querySelector("textarea")).not.toBeNull();
|
|
});
|
|
const textarea = container.querySelector("textarea");
|
|
expect(textarea).not.toBeNull();
|
|
expect(textarea?.value).toBe("Affected versions: <= v0.3.1");
|
|
expect(container.textContent).toContain("Rich editor unavailable for this markdown");
|
|
expect(handleChange).not.toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("shows the editor-scoped dropzone by default when files are dragged over it", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value=""
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
imageUploadHandler={async () => "https://example.com/image.png"}
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
|
|
const scope = container.querySelector('[data-testid="mdx-editor"]')?.parentElement as HTMLDivElement | null;
|
|
expect(scope).not.toBeNull();
|
|
|
|
act(() => {
|
|
scope?.dispatchEvent(createFileDragEvent("dragenter"));
|
|
});
|
|
|
|
expect(scope?.className).toContain("ring-1");
|
|
expect(container.textContent).toContain("Drop image to upload");
|
|
|
|
act(() => {
|
|
scope?.dispatchEvent(createFileDragEvent("dragleave"));
|
|
});
|
|
|
|
expect(scope?.className).not.toContain("ring-1");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("defers file-drop visuals to a parent container when requested", async () => {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value=""
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
imageUploadHandler={async () => "https://example.com/image.png"}
|
|
fileDropTarget="parent"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
|
|
const scope = container.querySelector('[data-testid="mdx-editor"]')?.parentElement as HTMLDivElement | null;
|
|
expect(scope).not.toBeNull();
|
|
|
|
act(() => {
|
|
scope?.dispatchEvent(createFileDragEvent("dragenter"));
|
|
});
|
|
|
|
expect(scope?.className).not.toContain("ring-1");
|
|
expect(container.textContent).not.toContain("Drop image to upload");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("does not show the raw fallback while image-only markdown is settling", async () => {
|
|
mdxEditorMockState.emitMountSilentEmptyState = true;
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value=""
|
|
onChange={() => {}}
|
|
placeholder="Markdown body"
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
await flush();
|
|
|
|
expect(container.querySelector("textarea")).toBeNull();
|
|
expect(container.textContent).not.toContain("Rich editor unavailable for this markdown");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("places the menu top on the caret line and offsets the left a space-width past the caret", () => {
|
|
expect(
|
|
computeMentionMenuPosition(
|
|
{ viewportTop: 100, viewportBottom: 118, viewportLeft: 240 },
|
|
{ offsetLeft: 0, offsetTop: 0, width: 800, height: 600 },
|
|
),
|
|
).toEqual({
|
|
top: 100,
|
|
left: 250,
|
|
});
|
|
});
|
|
|
|
it("applies visual viewport offsets when present", () => {
|
|
expect(
|
|
computeMentionMenuPosition(
|
|
{ viewportTop: 20, viewportBottom: 38, viewportLeft: 120 },
|
|
{ offsetLeft: 24, offsetTop: 320, width: 320, height: 260 },
|
|
),
|
|
).toEqual({
|
|
top: 340,
|
|
left: 154,
|
|
});
|
|
});
|
|
|
|
it("clamps the mention menu back into view near the viewport edges", () => {
|
|
expect(
|
|
computeMentionMenuPosition(
|
|
{ viewportTop: 260, viewportBottom: 278, viewportLeft: 240 },
|
|
{ offsetLeft: 0, offsetTop: 0, width: 280, height: 220 },
|
|
),
|
|
).toEqual({
|
|
top: 12,
|
|
left: 92,
|
|
});
|
|
});
|
|
|
|
it("flips the menu above the caret line when it would overflow below", () => {
|
|
expect(
|
|
computeMentionMenuPosition(
|
|
{ viewportTop: 560, viewportBottom: 580, viewportLeft: 200 },
|
|
{ offsetLeft: 0, offsetTop: 0, width: 800, height: 600 },
|
|
),
|
|
).toEqual({
|
|
top: 372,
|
|
left: 210,
|
|
});
|
|
});
|
|
|
|
it("keeps a short mention menu on the same line when it fits below the caret", () => {
|
|
expect(
|
|
computeMentionMenuPosition(
|
|
{ viewportTop: 160, viewportBottom: 178, viewportLeft: 120 },
|
|
{ offsetLeft: 0, offsetTop: 0, width: 320, height: 220 },
|
|
{ width: 188, height: 42 },
|
|
),
|
|
).toEqual({
|
|
top: 160,
|
|
left: 130,
|
|
});
|
|
});
|
|
|
|
it("keeps mention queries active across spaces", () => {
|
|
expect(findMentionMatch("Ping @Paperclip App", "Ping @Paperclip App".length)).toEqual({
|
|
trigger: "mention",
|
|
marker: "@",
|
|
query: "Paperclip App",
|
|
atPos: 5,
|
|
endPos: "Ping @Paperclip App".length,
|
|
});
|
|
});
|
|
|
|
it("still rejects slash commands once spaces are typed", () => {
|
|
expect(findMentionMatch("/open issue", "/open issue".length)).toBeNull();
|
|
});
|
|
|
|
it("keeps routine slash queries active across spaces", () => {
|
|
expect(findMentionMatch("/routine:Weekly release review", "/routine:Weekly release review".length)).toEqual({
|
|
trigger: "skill",
|
|
marker: "/",
|
|
query: "routine:Weekly release review",
|
|
atPos: 0,
|
|
endPos: "/routine:Weekly release review".length,
|
|
});
|
|
});
|
|
|
|
it("does not treat Enter as skill autocomplete accept", () => {
|
|
expect(shouldAcceptAutocompleteKey("Enter", "skill")).toBe(false);
|
|
expect(shouldAcceptAutocompleteKey("Enter", "skill", true)).toBe(true);
|
|
expect(shouldAcceptAutocompleteKey("Enter", "mention")).toBe(true);
|
|
expect(shouldAcceptAutocompleteKey("Tab", "skill")).toBe(true);
|
|
});
|
|
|
|
it("keeps the same autocomplete session active while the slash query is unchanged", () => {
|
|
const textNode = document.createTextNode("/agent");
|
|
expect(isSameAutocompleteSession(
|
|
{
|
|
trigger: "skill",
|
|
marker: "/",
|
|
query: "agent",
|
|
textNode,
|
|
atPos: 0,
|
|
endPos: 6,
|
|
},
|
|
{
|
|
trigger: "skill",
|
|
marker: "/",
|
|
query: "agent",
|
|
textNode,
|
|
atPos: 0,
|
|
endPos: 6,
|
|
},
|
|
)).toBe(true);
|
|
|
|
expect(isSameAutocompleteSession(
|
|
{
|
|
trigger: "skill",
|
|
marker: "/",
|
|
query: "agent",
|
|
textNode,
|
|
atPos: 0,
|
|
endPos: 6,
|
|
},
|
|
{
|
|
trigger: "skill",
|
|
marker: "/",
|
|
query: "agent-browser",
|
|
textNode,
|
|
atPos: 0,
|
|
endPos: 14,
|
|
},
|
|
)).toBe(false);
|
|
});
|
|
|
|
it("finds skill anchors by mention metadata instead of visible text", () => {
|
|
const editable = document.createElement("div");
|
|
const skillLink = document.createElement("a");
|
|
skillLink.setAttribute("href", buildSkillMentionHref("skill-123", "agent-browser"));
|
|
skillLink.textContent = "/agent-browser ";
|
|
editable.appendChild(skillLink);
|
|
|
|
const found = findClosestAutocompleteAnchor(editable, {
|
|
id: "skill:skill-123",
|
|
kind: "skill",
|
|
skillId: "skill-123",
|
|
key: "agent-browser",
|
|
name: "Agent Browser",
|
|
slug: "agent-browser",
|
|
description: null,
|
|
href: buildSkillMentionHref("skill-123", "agent-browser"),
|
|
aliases: ["agent-browser", "Agent Browser"],
|
|
});
|
|
|
|
expect(found).toBe(skillLink);
|
|
});
|
|
|
|
it("finds routine anchors by mention metadata instead of visible text", () => {
|
|
const editable = document.createElement("div");
|
|
const routineLink = document.createElement("a");
|
|
routineLink.setAttribute("href", buildRoutineMentionHref("routine-123"));
|
|
routineLink.textContent = "/routine:Weekly release review ";
|
|
editable.appendChild(routineLink);
|
|
|
|
const found = findClosestAutocompleteAnchor(editable, {
|
|
id: "routine:routine-123",
|
|
kind: "routine",
|
|
routineId: "routine-123",
|
|
name: "Weekly release review",
|
|
status: "active",
|
|
href: buildRoutineMentionHref("routine-123"),
|
|
aliases: ["routine:Weekly release review", "Weekly release review"],
|
|
});
|
|
|
|
expect(found).toBe(routineLink);
|
|
});
|
|
|
|
it("places the caret after the mention's trailing space when present", () => {
|
|
const editable = document.createElement("div");
|
|
editable.contentEditable = "true";
|
|
document.body.appendChild(editable);
|
|
|
|
const skillLink = document.createElement("a");
|
|
skillLink.setAttribute("href", buildSkillMentionHref("skill-123", "agent-browser"));
|
|
skillLink.textContent = "/agent-browser";
|
|
const trailingSpace = document.createTextNode(" ");
|
|
editable.append(skillLink, trailingSpace);
|
|
|
|
expect(placeCaretAfterMentionAnchor(skillLink)).toBe(true);
|
|
|
|
const selection = window.getSelection();
|
|
expect(selection?.anchorNode).toBe(trailingSpace);
|
|
expect(selection?.anchorOffset).toBe(1);
|
|
|
|
editable.remove();
|
|
});
|
|
|
|
function createTouchEvent(
|
|
type: "touchstart" | "touchmove" | "touchend",
|
|
touches: Array<{ clientX: number; clientY: number }>,
|
|
) {
|
|
const event = new Event(type, { bubbles: true, cancelable: true });
|
|
const list = touches as unknown as TouchList;
|
|
Object.defineProperty(event, "touches", { value: type === "touchend" ? [] : list });
|
|
Object.defineProperty(event, "changedTouches", { value: list });
|
|
return event;
|
|
}
|
|
|
|
async function openMentionMenuFor(
|
|
handleChange: Mock<(value: string) => void>,
|
|
mentions: MentionOption[] = [
|
|
{
|
|
id: "project:project-123",
|
|
kind: "project" as const,
|
|
name: "Paperclip App",
|
|
projectId: "project-123",
|
|
projectColor: "#336699",
|
|
},
|
|
],
|
|
matchText = "Paperclip App",
|
|
): Promise<{ option: HTMLButtonElement; root: ReturnType<typeof createRoot>; menu: HTMLElement }> {
|
|
const root = createRoot(container);
|
|
|
|
await act(async () => {
|
|
root.render(
|
|
<MarkdownEditor
|
|
value="@Pap"
|
|
onChange={handleChange}
|
|
mentions={mentions}
|
|
/>,
|
|
);
|
|
});
|
|
|
|
await flush();
|
|
|
|
const editable = container.querySelector('[contenteditable="true"]');
|
|
expect(editable).not.toBeNull();
|
|
const textNode = editable?.firstChild;
|
|
expect(textNode?.nodeType).toBe(Node.TEXT_NODE);
|
|
|
|
const selection = window.getSelection();
|
|
const range = document.createRange();
|
|
range.setStart(textNode!, "@Pap".length);
|
|
range.collapse(true);
|
|
selection?.removeAllRanges();
|
|
selection?.addRange(range);
|
|
|
|
act(() => {
|
|
document.dispatchEvent(new Event("selectionchange"));
|
|
});
|
|
await flush();
|
|
|
|
const option = Array.from(document.body.querySelectorAll('button[type="button"]'))
|
|
.find((node) => node.textContent?.includes(matchText)) as HTMLButtonElement | undefined;
|
|
expect(option).toBeTruthy();
|
|
const menu = document.body.querySelector('[data-testid="mention-autocomplete-menu"]') as HTMLElement | null;
|
|
expect(menu).toBeTruthy();
|
|
return { option: option!, root, menu: menu! };
|
|
}
|
|
|
|
it("accepts mention selection from a touch tap", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(handleChange);
|
|
const point = { clientX: 100, clientY: 50 };
|
|
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchstart", [point]));
|
|
});
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchend", [point]));
|
|
});
|
|
|
|
expect(handleChange).toHaveBeenCalledWith(
|
|
`[@Paperclip App](${buildProjectMentionHref("project-123", "#336699")}) `,
|
|
);
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("inserts a compact issue link when an @task reference is selected", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(
|
|
handleChange,
|
|
[
|
|
{
|
|
id: "issue:issue-1",
|
|
kind: "issue" as const,
|
|
name: "PAP-102 @task references",
|
|
issueId: "issue-1",
|
|
issueIdentifier: "PAP-102",
|
|
},
|
|
],
|
|
"PAP-102",
|
|
);
|
|
const point = { clientX: 100, clientY: 50 };
|
|
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchstart", [point]));
|
|
});
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchend", [point]));
|
|
});
|
|
|
|
expect(handleChange).toHaveBeenCalledWith(
|
|
`[PAP-102](${buildIssueReferenceHref("PAP-102")}) `,
|
|
);
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("renders the task tag and identifier for issue mention options", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(
|
|
handleChange,
|
|
[
|
|
{
|
|
id: "issue:issue-1",
|
|
kind: "issue" as const,
|
|
name: "PAP-102 @task references",
|
|
issueId: "issue-1",
|
|
issueIdentifier: "PAP-102",
|
|
},
|
|
],
|
|
"PAP-102",
|
|
);
|
|
|
|
expect(option.textContent).toContain("PAP-102");
|
|
expect(option.textContent).toContain("@task references");
|
|
expect(option.textContent).toContain("Task");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("marks the autocomplete portal as floating UI for modal pointer handling", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(handleChange);
|
|
|
|
const menu = option.closest("[data-paperclip-floating-ui]");
|
|
expect(menu).toBeTruthy();
|
|
expect(menu?.className).toContain("pointer-events-auto");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("does not preventDefault on touchstart so the mention menu can scroll on mobile", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(handleChange);
|
|
|
|
const touchstart = createTouchEvent("touchstart", [{ clientX: 100, clientY: 50 }]);
|
|
act(() => {
|
|
option.dispatchEvent(touchstart);
|
|
});
|
|
|
|
expect(touchstart.defaultPrevented).toBe(false);
|
|
expect(handleChange).not.toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("renders all mention matches inside a bounded scroll container", async () => {
|
|
const handleChange = vi.fn();
|
|
const mentions = Array.from({ length: 12 }, (_, index) => ({
|
|
id: `project:project-${index}`,
|
|
kind: "project" as const,
|
|
name: `Paperclip App ${index}`,
|
|
projectId: `project-${index}`,
|
|
projectColor: "#336699",
|
|
}));
|
|
const { menu, root } = await openMentionMenuFor(handleChange, mentions);
|
|
|
|
const options = Array.from(menu.querySelectorAll('button[type="button"]'));
|
|
expect(options).toHaveLength(12);
|
|
expect(menu.className).toContain("max-h-[208px]");
|
|
expect(menu.className).toContain("overflow-y-auto");
|
|
expect(menu.style.touchAction).toBe("pan-y");
|
|
|
|
const wheel = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: 80 });
|
|
act(() => {
|
|
menu.dispatchEvent(wheel);
|
|
});
|
|
expect(wheel.defaultPrevented).toBe(false);
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("caps rendered mention matches while keeping the menu scrollable", async () => {
|
|
const handleChange = vi.fn();
|
|
const mentions = Array.from({ length: 60 }, (_, index) => ({
|
|
id: `project:project-${index}`,
|
|
kind: "project" as const,
|
|
name: `Paperclip App ${index}`,
|
|
projectId: `project-${index}`,
|
|
projectColor: "#336699",
|
|
}));
|
|
const { menu, root } = await openMentionMenuFor(handleChange, mentions);
|
|
|
|
const options = Array.from(menu.querySelectorAll('button[type="button"]'));
|
|
expect(options).toHaveLength(50);
|
|
expect(menu.className).toContain("overflow-y-auto");
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
|
|
it("scrolls the active mention option into view during keyboard navigation", async () => {
|
|
const handleChange = vi.fn();
|
|
const scrollIntoView = vi.fn();
|
|
const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;
|
|
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
|
|
configurable: true,
|
|
value: scrollIntoView,
|
|
});
|
|
const mentions = Array.from({ length: 12 }, (_, index) => ({
|
|
id: `project:project-${index}`,
|
|
kind: "project" as const,
|
|
name: `Paperclip App ${index}`,
|
|
projectId: `project-${index}`,
|
|
projectColor: "#336699",
|
|
}));
|
|
const { root } = await openMentionMenuFor(handleChange, mentions);
|
|
scrollIntoView.mockClear();
|
|
|
|
const editorScope = container.querySelector('[data-testid="mdx-editor"]')?.parentElement;
|
|
expect(editorScope).toBeTruthy();
|
|
|
|
act(() => {
|
|
editorScope?.dispatchEvent(new KeyboardEvent("keydown", {
|
|
key: "ArrowDown",
|
|
bubbles: true,
|
|
cancelable: true,
|
|
}));
|
|
});
|
|
await flush();
|
|
|
|
expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
if (originalScrollIntoView) {
|
|
Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {
|
|
configurable: true,
|
|
value: originalScrollIntoView,
|
|
});
|
|
} else {
|
|
delete (HTMLElement.prototype as unknown as { scrollIntoView?: unknown }).scrollIntoView;
|
|
}
|
|
});
|
|
|
|
it("does not select when the touch moves like a scroll", async () => {
|
|
const handleChange = vi.fn();
|
|
const { option, root } = await openMentionMenuFor(handleChange);
|
|
const start = { clientX: 100, clientY: 50 };
|
|
const moved = { clientX: 100, clientY: 90 };
|
|
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchstart", [start]));
|
|
});
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchmove", [moved]));
|
|
});
|
|
act(() => {
|
|
option.dispatchEvent(createTouchEvent("touchend", [moved]));
|
|
});
|
|
|
|
expect(handleChange).not.toHaveBeenCalled();
|
|
|
|
await act(async () => {
|
|
root.unmount();
|
|
});
|
|
});
|
|
});
|