Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ npm test # unit tests
Avoid `npm run build` during local development — it writes to `.next/` and
interferes with the dev server. Builds are for release work.

### React tests

Tests use `node:test` and `jiti`; no Jest or Vitest configuration is required.
For interactive components and hooks, import `tests/setup-dom.mjs` before
`@testing-library/react/pure.js`, and register `cleanup` with `afterEach`.
Use DOM queries and `@testing-library/user-event` for component interactions,
and `renderHook` for hook state and lifecycle tests. Keep the real jsdom
`window` and `document`; mock only the browser or network APIs a scenario needs.

Static HTML tests can continue using `react-dom/server`. Layout, scrolling,
and native browser navigation still require real-browser verification.
The jsdom dependency stays on 29.x to support the Node 22.19.0 baseline.

## Conventions

- **Styling**: use the design tokens in `app/globals.css` (colors, radius,
Expand Down
117 changes: 50 additions & 67 deletions components/ChatInput.navigation.test.mjs
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
import "../tests/setup-dom.mjs";
import assert from "node:assert/strict";
import test from "node:test";
import test, { afterEach, beforeEach } from "node:test";
import React, { act } from "react";
import TestRenderer from "react-test-renderer";
import { cleanup, render, screen, waitFor } from "@testing-library/react/pure.js";
import userEvent from "@testing-library/user-event";
import { createJiti } from "jiti";

const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true });
const { ChatInput } = await jiti.import("./ChatInput.tsx");
const { useSidebarHistory } = await jiti.import("@/hooks/useSidebarHistory");
const { clearDraft, getDraft } = await jiti.import("@/lib/draft-store");
globalThis.IS_REACT_ACT_ENVIRONMENT = true;

function installBrowser() {
const listeners = new Map();
globalThis.window = {
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, new Set());
listeners.get(type).add(fn);
},
removeEventListener(type, fn) { listeners.get(type)?.delete(fn); },
};
globalThis.document = { documentElement: {}, addEventListener() {}, removeEventListener() {} };
globalThis.localStorage = { getItem: () => null };
globalThis.requestAnimationFrame = () => 0;
return () => {
const event = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; } };
for (const fn of listeners.get("beforeunload") ?? []) fn(event);
return event.defaultPrevented;
};
beforeEach(() => {
window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
});
afterEach(() => {
cleanup();
clearDraft("new:unassigned");
clearDraft("draft-a");
clearDraft("draft-b");
localStorage.clear();
delete window.matchMedia;
});

function warnsOnExit() {
const event = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(event);
return event.defaultPrevented;
}

function Guard() {
Expand All @@ -37,41 +36,32 @@ function Guard() {
return null;
}

const enter = { key: "Enter", nativeEvent: {}, preventDefault() {}, shiftKey: false };

test("no-key composer text survives minimization and warns on document exit until sent", async () => {
const warnsOnExit = installBrowser();
const ref = React.createRef();
const user = userEvent.setup();
const sent = [];
function Shell({ minimized = false }) {
return React.createElement(React.Fragment, null,
React.createElement(Guard),
React.createElement("div", { style: { display: minimized ? "none" : undefined } },
React.createElement(ChatInput, { ref, onSend: (text) => sent.push(text), onAbort() {}, isStreaming: false })),
React.createElement(ChatInput, { onSend: (text) => sent.push(text), onAbort() {}, isStreaming: false })),
);
}
let renderer;
try {
await act(() => { renderer = TestRenderer.create(React.createElement(Shell)); });
assert.equal(warnsOnExit(), false);
await act(() => ref.current.insertText("unsent in a new composer"));
assert.equal(warnsOnExit(), true);
await act(() => renderer.update(React.createElement(Shell, { minimized: true })));
assert.equal(warnsOnExit(), true);
assert.equal(renderer.root.findByType("textarea").props.value, "unsent in a new composer");
await act(() => renderer.root.findByType("textarea").props.onKeyDown(enter));
assert.deepEqual(sent, ["unsent in a new composer"]);
assert.equal(warnsOnExit(), false);
} finally {
await act(() => renderer?.unmount());
clearDraft("new:unassigned");
delete globalThis.window;
delete globalThis.document;
}
const { rerender } = render(React.createElement(Shell));
assert.equal(warnsOnExit(), false);
await user.type(screen.getByRole("textbox"), "unsent in a new composer");
assert.equal(warnsOnExit(), true);
rerender(React.createElement(Shell, { minimized: true }));
assert.equal(warnsOnExit(), true);
assert.equal(screen.getByRole("textbox", { hidden: true }).value, "unsent in a new composer");
rerender(React.createElement(Shell));
await user.click(screen.getByRole("textbox"));
await user.keyboard("{Enter}");
assert.deepEqual(sent, ["unsent in a new composer"]);
assert.equal(warnsOnExit(), false);
});

test("attachment-only drafts stay protected across live draft-key changes and restore without warning on internal picks", async () => {
const warnsOnExit = installBrowser();
const user = userEvent.setup();
const ref = React.createRef();
const sent = [];
function Shell({ session }) {
Expand All @@ -80,26 +70,19 @@ test("attachment-only drafts stay protected across live draft-key changes and re
React.createElement(ChatInput, { draftKey: session, ref, onSend: (text) => sent.push(text), onAbort() {}, isStreaming: false }),
);
}
let renderer;
try {
await act(() => { renderer = TestRenderer.create(React.createElement(Shell, { session: "draft-a" })); });
await act(async () => {
ref.current.addFiles([new File(["important attachment"], "notes.txt", { type: "text/plain" })]);
});
assert.equal(warnsOnExit(), true);
await act(() => renderer.update(React.createElement(Shell, { session: "draft-b" })));
assert.equal(renderer.root.findByType("textarea").props.value, "");
assert.equal(getDraft("draft-a")?.files[0]?.content, "important attachment");
assert.equal(warnsOnExit(), true);
await act(() => renderer.update(React.createElement(Shell, { session: "draft-a" })));
await act(() => renderer.root.findByType("textarea").props.onKeyDown(enter));
assert.match(sent[0], /important attachment/);
assert.equal(warnsOnExit(), false);
} finally {
await act(() => renderer?.unmount());
clearDraft("draft-a");
clearDraft("draft-b");
delete globalThis.window;
delete globalThis.document;
}
const { rerender } = render(React.createElement(Shell, { session: "draft-a" }));
await act(async () => {
ref.current.addFiles([new File(["important attachment"], "notes.txt", { type: "text/plain" })]);
});
await waitFor(() => assert.equal(getDraft("draft-a")?.files[0]?.content, "important attachment"));
assert.equal(warnsOnExit(), true);
rerender(React.createElement(Shell, { session: "draft-b" }));
assert.equal(screen.getByRole("textbox").value, "");
assert.equal(getDraft("draft-a")?.files[0]?.content, "important attachment");
assert.equal(warnsOnExit(), true);
rerender(React.createElement(Shell, { session: "draft-a" }));
await user.click(screen.getByRole("textbox"));
await user.keyboard("{Enter}");
assert.match(sent[0], /important attachment/);
assert.equal(warnsOnExit(), false);
});
64 changes: 29 additions & 35 deletions components/MessageView.test.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import test from "node:test";
import React, { act } from "react";
import TestRenderer from "react-test-renderer";
import "../tests/setup-dom.mjs";
import test, { afterEach } from "node:test";
import React from "react";
import { cleanup, fireEvent, render } from "@testing-library/react/pure.js";
import { renderToStaticMarkup } from "react-dom/server";
import { createJiti } from "jiti";

Expand All @@ -11,7 +12,7 @@ const jiti = createJiti(import.meta.url, {
});
const { MessageView, SafeMarkdownBody, TaskResultPanel, isInterruptedMessage } = await jiti.import("./MessageView.tsx");
const { CodeBlock } = await jiti.import("./MermaidBlock.tsx");
const { Collapsible } = await jiti.import("./ui/primitives.tsx");
afterEach(cleanup);

test("sent messages without timestamps or branch metadata still offer copy", () => {
const html = renderToStaticMarkup(React.createElement(MessageView, {
Expand All @@ -20,9 +21,7 @@ test("sent messages without timestamps or branch metadata still offer copy", ()
assert.match(html, /<button[^>]*aria-label="Copy message"/);
});

test("expanded grouped tool inputs follow streaming arguments without toggling output", async () => {
const previousActEnvironment = globalThis.IS_REACT_ACT_ENVIRONMENT;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
test("expanded grouped tool inputs follow streaming arguments without toggling output", () => {
const code = "print('first')\nprint('complete')";
const editInput = { path: "/tmp/example.ts", patch: "-old\n+new", options: { dryRun: false } };
const toolResults = new Map([["edit-call", {
Expand All @@ -40,34 +39,29 @@ test("expanded grouped tool inputs follow streaming arguments without toggling o
],
},
});
let renderer;
try {
await act(() => { renderer = TestRenderer.create(React.createElement(MessageView, props("print('first')"))); });
// Open both tool rows through the shared disclosure's public change handler.
await act(() => {
for (const row of renderer.root.findAllByType(Collapsible).slice(1)) row.props.onOpenChange(true);
});
const toggles = () => renderer.root.findAllByType("button").filter((node) => node.props["aria-controls"] && node.children.includes("Show full input"));
const inputPanels = () => renderer.root.findAll((node) => node.type === "div" && node.props.className === "tool-call-input");
assert.equal(toggles().length, 2);
assert.ok(inputPanels().every((node) => node.props.hidden));
await act(() => { for (const toggle of toggles()) toggle.props.onClick(); });
assert.equal(inputPanels()[0].findAllByType("pre")[1].children.join(""), "print('first')");
assert.equal(inputPanels()[1].findAllByType("pre")[1].children.join(""), editInput.patch);
assert.deepEqual(JSON.parse(inputPanels()[1].findAllByType("pre")[2].children.join("")), editInput.options);
await act(() => renderer.update(React.createElement(MessageView, props(code))));
assert.equal(inputPanels()[0].findAllByType("pre")[1].children.join(""), code);
const output = () => renderer.root.findAll((node) => node.type === "pre" && node.props["data-tool-output"] === "true").map((node) => node.children.join(""));
assert.deepEqual(output(), ["Edit complete"]);
await act(() => {
for (const toggle of renderer.root.findAllByType("button").filter((node) => node.children.includes("Collapse input"))) toggle.props.onClick();
});
assert.ok(inputPanels().every((node) => node.props.hidden));
assert.deepEqual(output(), ["Edit complete"]);
} finally {
await act(() => renderer?.unmount());
globalThis.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
}
const { container, rerender } = render(React.createElement(MessageView, props("print('first')")));
// Open both tool rows through their disclosure triggers. The collapsible
// group header is not a row, so only the group-item triggers are clicked.
const rowTriggers = () => [...container.querySelectorAll("button.activity-group-item-trigger")];
assert.equal(rowTriggers().length, 2);
for (const trigger of rowTriggers()) fireEvent.click(trigger);
const toggles = (label) => [...container.querySelectorAll("button.tool-call-input-toggle")]
.filter((button) => (button.textContent ?? "").includes(label));
const inputPanels = () => [...container.querySelectorAll("div.tool-call-input")];
const pres = (panel) => [...panel.querySelectorAll("pre")];
assert.equal(toggles("Show full input").length, 2);
assert.ok(inputPanels().every((panel) => panel.hidden));
for (const toggle of toggles("Show full input")) fireEvent.click(toggle);
assert.equal(pres(inputPanels()[0])[1].textContent, "print('first')");
assert.equal(pres(inputPanels()[1])[1].textContent, editInput.patch);
assert.deepEqual(JSON.parse(pres(inputPanels()[1])[2].textContent ?? ""), editInput.options);
rerender(React.createElement(MessageView, props(code)));
assert.equal(pres(inputPanels()[0])[1].textContent, code);
const output = () => [...container.querySelectorAll('pre[data-tool-output="true"]')].map((node) => node.textContent);
assert.deepEqual(output(), ["Edit complete"]);
for (const toggle of toggles("Collapse input")) fireEvent.click(toggle);
assert.ok(inputPanels().every((panel) => panel.hidden));
assert.deepEqual(output(), ["Edit complete"]);
});

test("large message content avoids the markdown pipeline until requested", () => {
Expand Down
Loading
Loading