diff --git a/.claude/skills/editor-conventions/SKILL.md b/.claude/skills/editor-conventions/SKILL.md index 5b54fc7..a87096d 100644 --- a/.claude/skills/editor-conventions/SKILL.md +++ b/.claude/skills/editor-conventions/SKILL.md @@ -6,6 +6,7 @@ description: "Change the email template editor UI, AI assistant or API client. U # Editor conventions - Editor UI lives in `src/editor/Main`, not `src/pages` (Next.js would treat `pages` as routes). +- The editor edits one template: `Main` gets `templateId` from `app/templates/[id]/page.tsx` and passes it to every component that calls the API. The list pages live in `src/templates` and `src/sent`; they reuse `notifyError` and `Preview/EmailFrame` from the editor. - Interactive components need `"use client"`. - All HTTP calls go through `src/api/main.ts`. Do not call axios from UI files. - Types belong in `src/api/main.types.ts` and `src/types`. API types are generated from the backend contract: `npm run api:sync`, never edited by hand in `openapi.types.ts`. diff --git a/.claude/skills/run-app/SKILL.md b/.claude/skills/run-app/SKILL.md index b17b721..3f0ac27 100644 --- a/.claude/skills/run-app/SKILL.md +++ b/.claude/skills/run-app/SKILL.md @@ -10,7 +10,7 @@ The editor needs two processes: this Next.js app on **:3000** and the backend AP ## 1. Reuse what is already running - Frontend: `next dev` writes its PID, port and URL to `.next/dev/lock`. If it exists and the process is alive, use that server. Starting a second `next dev` only prints the running one's URL. -- Backend: `curl -s localhost:9000/tree` answers JSON when it is up. +- Backend: `curl -s localhost:9000/templates` answers JSON when it is up. ## 2. Start what is missing (in the background) @@ -22,12 +22,12 @@ cd ../email-template-editor-nodejs && npm install && npm run dev # :9000 npm run dev # :3000 ``` -No backend checkout? The UI still loads (tree and elements show errors); for UI-only checks Playwright e2e specs mock the API with `page.route` instead. +No backend checkout? The UI still loads (the templates list and the editor show errors); for UI-only checks Playwright e2e specs mock the API with `page.route` instead. ## 3. Check the change - **Framework errors** (Next DevTools MCP, `.mcp.json`): `nextjs_index` to find the server, then `nextjs_call` → `get_errors`, `get_logs`, `compile_route`. Faster than `npm run build` while editing. -- **The page itself** (Playwright MCP): open `http://localhost:3000`, take a snapshot or screenshot, click through the flow you changed. +- **The page itself** (Playwright MCP): open `http://localhost:3000` (redirects to `/templates`; the editor is `/templates/`), take a snapshot or screenshot, click through the flow you changed. - The browser console is forwarded to the `next dev` terminal output. ## 4. Before finishing diff --git a/.claude/skills/testing/SKILL.md b/.claude/skills/testing/SKILL.md index 9cec1fe..8af3847 100644 --- a/.claude/skills/testing/SKILL.md +++ b/.claude/skills/testing/SKILL.md @@ -14,7 +14,11 @@ description: "Write and fix tests for the email template editor. Use when adding ```ts // Mock every function the component under test (and its children) imports. +// Tree, element, generate and send functions take the template id first: getTree("t1"). vi.mock("@/api/main", () => ({ + getTemplate: vi.fn(() => + Promise.resolve({ id: "t1", name: "Weekly digest", createdAt: "", updatedAt: "" }), + ), getTree: vi.fn(() => Promise.resolve([])), saveTree: vi.fn(() => Promise.resolve({})), generate: vi.fn(() => Promise.resolve("")), @@ -41,7 +45,8 @@ Run: `npm test`. Coverage: `npm run test:coverage` (HTML report in `coverage/`). ## E2E (Playwright) - Config: `playwright.config.ts`. Specs: `e2e/`. -- Intercept `/tree` and `/elements` with `page.route` so tests do not need the backend. +- Intercept the backend with `page.route` so tests do not need it. The editor is at `/templates/t1`: mock `GET /templates/t1` with `mockTemplate(page)` from `e2e/backend.ts`, and `**/templates/t1/tree` / `**/templates/t1/elements`. Give backend URLs in full (`API_URL` from `e2e/backend.ts`) when the path could also match a page, e.g. `/templates` or `/templates/t1`. +- Components that use `useRouter()` (`TemplatesPage`, `SendEmailModal`, and so `Main`) need `vi.mock("next/navigation", …)` in unit tests. - Mock AI providers with `page.route` too (see `e2e/ai-assistant.spec.ts`), and check the key never reaches our backend. - `e2e/csp.spec.ts` guards the Content-Security-Policy; update it when adding an origin. - Run: `npm run test:e2e` diff --git a/AGENTS.md b/AGENTS.md index b533bec..bc4e106 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,10 @@ This is a **visual email template editor**. Users build a tree of email elements ``` app/ # Next.js App Router entry layout.tsx # Root layout (Ant Design reset + global CSS) - page.tsx # Home page → renders
+ page.tsx # Home page → redirects to /templates + templates/page.tsx # /templates → (list of templates) + templates/[id]/page.tsx # /templates/[id] →
(the editor) + sent/page.tsx # /sent → (log of sent emails) proxy.ts # Per-request nonce Content-Security-Policy + color-scheme client hint (Next 16 "proxy", formerly middleware) @@ -42,18 +45,22 @@ src/ errors.ts # errorMessage(): readable message from a failed API call ai/ # AI assistant (no React): providers, tools, agent loop, keyStore editor/Main/ # Editor UI (client components) - Main.tsx # Root editor screen + Main.tsx # Editor screen for one template (templateId prop): header, toolbar, workspace Elements/ # Element list + add/edit modals TemplateTree/ # Tree view + context-menu actions AddRootElementForm/ # Form to create the root node Chat/ # AI assistant panel (left column) + settings (lazy-loaded) - Preview/ # Live email preview (sandboxed iframe) + client-side renderer + Preview/ # Live email preview + client-side renderer; EmailFrame (sandboxed iframe, reused by src/sent) + SendEmailModal/ # "Send email" dialog: recipients + subject → sendEmail() + templates/ # Templates list page: create, rename, delete, open in the editor + sent/ # Sent emails log page with a drawer that shows the sent HTML security/ # Content-Security-Policy builder shell/ # App frame: sidebar navigation, header with the System/Light/Dark theme menu (cookie + OS hint, read in app/layout.tsx) types/ # Shared types (e.g. TemplateTree) index.css # Global styles setupTests.ts # Vitest setup (jest-dom, matchMedia/ResizeObserver polyfills) e2e/ # Playwright specs (backend and AI providers are mocked with page.route) + backend.ts # Backend origin, the sample template t1 and mockTemplate(); mock backend URLs in full public/ # favicon.ico, robots.txt .claude/skills/ # Claude skills: best practices, testing, deployment, editor conventions, run-app @@ -78,10 +85,11 @@ tsconfig.json # Paths: @/* → ./src/* - Anything that uses hooks, Ant Design, `window`, or browser APIs must be a **client component**. - Add `"use client";` at the top of the file. -- Currently marked client: `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `Preview.tsx`, `Chat/ChatPanel.tsx`, `Chat/AiSettingsModal.tsx`, `src/shell/AppShell.tsx`. +- Currently marked client: `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `Preview.tsx`, `Preview/EmailFrame.tsx`, `SendEmailModal/SendEmailModal.tsx`, `Chat/ChatPanel.tsx`, `Chat/AiSettingsModal.tsx`, `src/templates/TemplatesPage.tsx`, `src/templates/TemplateNameModal.tsx`, `src/sent/SentEmailsPage.tsx`, `src/shell/AppShell.tsx`. +- Routes (`app/`) stay server components that render one client page component. Dynamic `params` are a Promise in Next 16: `const { id } = await params`. - Theme: colors come from antd tokens (`var(--ant-…)` in CSS, `theme.useToken()` in TSX) so they follow the dark theme; do not hard-code light colors. - Pages are rendered per request (`export const dynamic = "force-dynamic"` in `app/layout.tsx`) because the CSP nonce changes on every request. Do not switch to static export (`output: "export"`). -- New interactive UI under `src/editor/Main/**` should also be client components. +- New interactive UI under `src/editor/Main/**`, `src/templates/` and `src/sent/` should also be client components. ### API client (`src/api/main.ts`) @@ -153,7 +161,7 @@ tsconfig.json # Paths: @/* → ./src/* 1. Get the backend's current contract and regenerate the types: `npm run api:sync` (`OPENAPI_URL=http://localhost:9000/openapi.json npm run api:sync` for a local backend or an unmerged backend branch). Commit both `src/api/openapi.json` and `src/api/openapi.types.ts`; a test fails if they disagree. 2. Update the function in `src/api/main.ts`; add or adjust an alias in `src/api/main.types.ts` if a new schema is needed. -3. Run `npm run typecheck`: callers that no longer match the contract fail here. Fix them in `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx` or `src/ai/tools.ts`. +3. Run `npm run typecheck`: callers that no longer match the contract fail here. Fix them in `Main.tsx`, `Elements.tsx`, `TemplateTree.tsx`, `SendEmailModal.tsx`, `src/templates/`, `src/sent/` or `src/ai/tools.ts`. 4. Keep the mock in tests in sync. ### Run locally @@ -204,10 +212,13 @@ docker run -p 3000:3000 email-template-editor ## Related - Backend is a separate service (not in this repo): [email-template-editor-nodejs](https://github.com/LLazyEmail/email-template-editor-nodejs). Frontend expects its REST API: - - Tree: `GET /tree`, `PUT /tree`, `POST /tree/nodes`, `PATCH /tree/nodes/:key`, `DELETE /tree/nodes/:key` - - Elements: `GET /elements`, `POST /elements`, `PATCH /elements/:key`, `DELETE /elements/:key` - - `POST /generate` → `{ url }` - - Keys in paths are URL-encoded. Errors are `{ error: { code, message, details?, requestId } }`. + - Templates: `GET /templates`, `POST /templates` `{ name }`, `GET /templates/:templateId`, `PATCH /templates/:templateId` `{ name }`, `DELETE /templates/:templateId` + - Tree (per template): `GET /templates/:templateId/tree`, `PUT …/tree`, `POST …/tree/nodes`, `PATCH …/tree/nodes/:key`, `DELETE …/tree/nodes/:key` + - Elements (per template): `GET /templates/:templateId/elements`, `POST …/elements`, `PATCH …/elements/:key`, `DELETE …/elements/:key` + - `POST /templates/:templateId/generate` → `{ url }` + - `POST /templates/:templateId/send` `{ to, subject }` → the log entry. Delivery is not configured: the email is only logged (`status: "logged"`); an empty tree is `422 TREE_EMPTY`. + - Sent emails: `GET /sent-emails` (newest first, no HTML), `GET /sent-emails/:id` (with the HTML snapshot) + - Template ids and keys in paths are URL-encoded. An unknown template is `404 NOT_FOUND`. Errors are `{ error: { code, message, details?, requestId } }`. - **Contract:** the backend's [`openapi.json`](https://github.com/LLazyEmail/email-template-editor-nodejs/blob/main/openapi.json) (OpenAPI 3.1, also served at `GET http://localhost:9000/openapi.json`) is the source of truth. The frontend keeps a copy in `src/api/openapi.json` and generates its types from it (see "Change an API call"). - Product description, charts, and screenshots: `README.md`. diff --git a/README.md b/README.md index 653a9f0..b6c22b3 100644 --- a/README.md +++ b/README.md @@ -56,19 +56,31 @@ The tree, the Elements library and the modals follow the theme too. ### Regenerating the screenshots -Start the backend on `:9000` with the sample `db.json` and run `npm run dev`. Then capture the editor at 1440×900 (device scale 2) with the `theme` cookie set to `light`: the overview, the preview scrolled to the first recipe row, both panels expanded (capture the panels only), and the **edit** modal of `{{recipeCard}}`. Repeat with `theme=dark` for the theme menu open, the panels and the edit modal (`-dark` suffix). Hide the Next.js dev badge before you capture. +Start the backend on `:9000` with the sample `db.json` and run `npm run dev`. Then open the sample template from `/templates` and capture the editor at 1440×900 (device scale 2) with the `theme` cookie set to `light`: the overview, the preview scrolled to the first recipe row, both panels expanded (capture the panels only), and the **edit** modal of `{{recipeCard}}`. Repeat with `theme=dark` for the theme menu open, the panels and the edit modal (`-dark` suffix). Hide the Next.js dev badge before you capture. ## How it works +The app has three pages, reachable from the sidebar: + +| Page | What it does | +| ----------------- | ------------------------------------------------------------------------------------------------------- | +| `/templates` | All templates: create, rename, delete, or open one in the editor. `/` redirects here. | +| `/templates/[id]` | The editor for one template: preview, AI assistant, tree and elements, **Generate** and **Send email**. | +| `/sent` | The log of sent emails, newest first, filterable by template; a row opens the email as it was sent. | + +Each template has its own tree and its own elements library. **Send email** does not deliver anything yet: the backend renders the template and records it (recipients, subject, HTML) in the sent emails log. + ```mermaid flowchart LR - User[Author] --> UI[Editor UI] + User[Author] --> List[Templates list] + List -->|open| UI[Editor UI] UI --> Tree[Template tree] UI --> Lib[Elements library] - UI -->|Generate| API[Backend API] + UI -->|Generate / Send| API[Backend API] Tree -->|load / save / update| API Lib -->|CRUD| API API --> HTML[Generated HTML] + API --> Log[Sent emails log] ``` ```mermaid @@ -76,19 +88,24 @@ sequenceDiagram participant U as User participant UI as Editor participant API as Backend - U->>UI: Open app - UI->>API: GET /tree + U->>UI: Open a template from /templates + UI->>API: GET /templates/:id/tree API-->>UI: Current tree U->>UI: Add / edit / delete nodes UI->>API: save / update / add / delete U->>UI: Generate - UI->>API: POST /generate + UI->>API: POST /templates/:id/generate API-->>UI: { url } of generated HTML UI-->>U: Open generated template + U->>UI: Send email (to, subject) + UI->>API: POST /templates/:id/send + API-->>UI: Log entry (status "logged") ``` ## Features +- Several templates, each with its own tree and elements, listed on one page +- Send a template to a list of addresses; sent emails are kept in a log you can browse (delivery itself is not connected yet) - Add a root element and grow a template tree - Context menu on each node: add, edit, delete - Live preview of the email next to the AI assistant @@ -105,13 +122,17 @@ sequenceDiagram ```mermaid flowchart TB subgraph Frontend[This repo] - Page[app/page.tsx] + Page["app/templates/[id]/page.tsx"] + List[src/templates] + Sent[src/sent] Main[Main.tsx] Tree[TemplateTree] Elements[Elements] Client[src/api/main.ts] end Page --> Main + List --> Client + Sent --> Client Main --> Tree Main --> Elements Main --> Client @@ -127,7 +148,7 @@ npm install npm run dev ``` -Open [http://localhost:3000](http://localhost:3000). +Open [http://localhost:3000](http://localhost:3000) (it redirects to the templates list). The frontend expects a backend on port **9000**. Override the base URL with `NEXT_PUBLIC_API_URL`. @@ -162,11 +183,14 @@ The assistant sits on the left of the editor, next to the preview. Open **Settin ## Project layout ``` -app/ Next.js App Router (layout, page) +app/ Next.js App Router (layout; /templates, /templates/[id], /sent) src/ api/ Axios client and types ai/ AI assistant: providers, tools, agent loop, key storage - editor/Main/ Editor UI (tree, elements, forms, AI chat) + editor/Main/ Editor UI (tree, elements, forms, AI chat, send dialog) + templates/ Templates list page + sent/ Sent emails log page + shell/ Sidebar, header and theme types/ Shared types AGENTS.md Guide for AI coding agents docs/AI_AGENT.md Extended agent reference diff --git a/app/page.tsx b/app/page.tsx index baccd7f..44d4ab3 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,5 +1,6 @@ -import Main from "../src/editor/Main/Main"; +import { redirect } from "next/navigation"; +/** The editor opens from the templates list, so the home page is that list. */ export default function HomePage() { - return
; + redirect("/templates"); } diff --git a/app/sent/page.tsx b/app/sent/page.tsx new file mode 100644 index 0000000..c3d85b7 --- /dev/null +++ b/app/sent/page.tsx @@ -0,0 +1,5 @@ +import SentEmailsPage from "../../src/sent/SentEmailsPage"; + +export default function SentRoute() { + return ; +} diff --git a/app/templates/[id]/page.tsx b/app/templates/[id]/page.tsx new file mode 100644 index 0000000..afc6969 --- /dev/null +++ b/app/templates/[id]/page.tsx @@ -0,0 +1,7 @@ +import Main from "../../../src/editor/Main/Main"; + +export default async function TemplatePage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + // `key`: opening another template starts the editor (tree, chat, modals) from scratch. + return
; +} diff --git a/app/templates/page.tsx b/app/templates/page.tsx new file mode 100644 index 0000000..f346650 --- /dev/null +++ b/app/templates/page.tsx @@ -0,0 +1,5 @@ +import TemplatesPage from "../../src/templates/TemplatesPage"; + +export default function TemplatesRoute() { + return ; +} diff --git a/docs/AI_AGENT.md b/docs/AI_AGENT.md index 8314514..f8a388b 100644 --- a/docs/AI_AGENT.md +++ b/docs/AI_AGENT.md @@ -14,19 +14,27 @@ Axios client (src/api/main.ts) Backend API (port 9000 by default) ← separate service ``` -The editor is a single-page experience: +The app has three pages inside the shell (`src/shell/AppShell.tsx`: sidebar with **Templates** and **Sent emails**, the current one highlighted from the path): -- Root layout loads Ant Design reset CSS and global styles. -- Home page renders `
`. -- `Main` loads the template tree on mount, shows action buttons, and embeds the tree + elements list. +- Root layout loads Ant Design reset CSS and global styles. `/` redirects to `/templates`. +- `/templates` (`src/templates/TemplatesPage.tsx`): table of templates; create (then open), rename, delete. +- `/templates/[id]` (`app/templates/[id]/page.tsx` → `
`): the editor for one template. `Main` loads the template (name in the heading; a 404 shows "Template not found") and its tree, shows the action buttons, and embeds the preview, the tree, the elements list and the chat. The route renders `Main` with `key={id}`, so opening another template starts from a clean state. +- `/sent` (`src/sent/SentEmailsPage.tsx`): log of sent emails; a row opens a drawer with the email's HTML in `EmailFrame`. + +Every template has its own tree and its own element library. Node and element keys are unique within a template only. ## Data flow -1. **Load tree:** `Main` calls `getTree()` → `GET /tree`. -2. **Add root:** User submits `AddRootElementForm` → `saveTree({ treeData })` → `PUT /tree`. -3. **Edit tree nodes:** Context menu in `TemplateTree` → `updateTreeNode` / `addTreeNode` / `deleteTreeNode` (`PATCH` / `POST` / `DELETE` under `/tree/nodes`). -4. **Manage elements:** `Elements` list → `getAllElements` / `addElement` / `updateElement` / `deleteElement` (REST under `/elements`). -5. **Generate:** Button calls `generate()` → `POST /generate` → `{ url }`; `generate()` resolves to the link that can be opened. +All tree, element, generate and send calls take the template id first; their URLs start with `/templates/:templateId` (`T` below). `Main` passes `templateId` down to `TemplateTree`, `Elements`, `ChatPanel` and, through it, `createEditorTools({ templateId, … })`. + +1. **Templates:** `TemplatesPage` → `listTemplates` / `createTemplate` / `renameTemplate` / `deleteTemplate` (`GET` / `POST /templates`, `PATCH` / `DELETE /templates/:templateId`). `Main` reads the name with `getTemplate(templateId)`. +2. **Load tree:** `Main` calls `getTree(templateId)` → `GET T/tree`. +3. **Add root:** User submits `AddRootElementForm` → `saveTree(templateId, { treeData })` → `PUT T/tree`. +4. **Edit tree nodes:** Context menu in `TemplateTree` → `updateTreeNode` / `addTreeNode` / `deleteTreeNode` (`PATCH` / `POST` / `DELETE` under `T/tree/nodes`). +5. **Manage elements:** `Elements` list → `getAllElements` / `addElement` / `updateElement` / `deleteElement` (REST under `T/elements`). +6. **Generate:** Button calls `generate(templateId)` → `POST T/generate` → `{ url }`; `generate()` resolves to the link that can be opened. +7. **Send:** "Send email" opens `SendEmailModal` → `sendEmail(templateId, { to, subject })` → `POST T/send`. Delivery is not configured yet: the backend renders the tree and only records it in the log (`status: "logged"`). +8. **Sent emails:** `SentEmailsPage` → `listSentEmails()` (`GET /sent-emails`, no HTML) and `getSentEmail(id)` (`GET /sent-emails/:id`, with the HTML snapshot) when a row is opened. The template filter works on the client. The backend's request and response shapes are described in its [`openapi.json`](https://github.com/LLazyEmail/email-template-editor-nodejs/blob/main/openapi.json) (served at `GET /openapi.json`). It is generated from the backend's validation schemas, so trust it over this document. The frontend keeps a copy in `src/api/openapi.json` and generates `src/api/openapi.types.ts` from it, both with `npm run api:sync`; `src/api/main.types.ts` only names those generated types. @@ -35,21 +43,27 @@ The backend's request and response shapes are described in its [`openapi.json`]( | File | Role | | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | `app/layout.tsx` | HTML shell, metadata, global CSS imports; `dynamic = "force-dynamic"` (per-request CSP nonce) | -| `app/page.tsx` | Renders the editor | +| `app/page.tsx` | Redirects to `/templates` | +| `app/templates/page.tsx`, `app/sent/page.tsx` | Render `TemplatesPage` and `SentEmailsPage` | +| `app/templates/[id]/page.tsx` | Awaits `params` (a Promise in Next 16) and renders `
` | +| `src/templates/TemplatesPage.tsx` | Templates table: open, create (`TemplateNameModal`), rename, delete | +| `src/sent/SentEmailsPage.tsx` | Sent emails table with a client-side template filter and a drawer that shows the email | | `proxy.ts` | Sets a per-request nonce Content-Security-Policy (Next 16 "proxy", formerly middleware) | -| `src/editor/Main/Main.tsx` | Top-level state and actions; lazy-loads the chat | +| `src/editor/Main/Main.tsx` | Editor for one template: heading, actions, "not found" state; lazy-loads the chat | +| `src/editor/Main/SendEmailModal/SendEmailModal.tsx` | Recipients (tags) and subject; sends and links the success message to `/sent` | | `src/editor/Main/TemplateTree/TemplateTree.tsx` | Tree UI + add/edit/delete node modals | | `src/editor/Main/TemplateTree/nodeBuilders.ts` | Node construction shared by the tree UI and the AI tools | | `src/editor/Main/Elements/Elements.tsx` | Element library UI | | `src/editor/Main/AddRootElementForm/AddRootElementForm.tsx` | Form that creates the root node | -| `src/editor/Main/Preview/Preview.tsx` | Live email preview in a sandboxed iframe | +| `src/editor/Main/Preview/Preview.tsx` | Live email preview of the current tree | +| `src/editor/Main/Preview/EmailFrame.tsx` | The sandboxed iframe for email HTML, shared by the preview and the sent emails drawer | | `src/editor/Main/Preview/renderTemplate.ts` | Client-side renderer of the tree into email HTML | | `src/editor/Main/Chat/` | AI assistant panel and settings (see below) | | `src/api/main.ts` | All HTTP calls | | `src/api/main.types.ts` | Request/response types: aliases over the generated `openapi.types.ts` | | `src/api/openapi.json`, `src/api/openapi.types.ts` | Copy of the backend contract and the types generated from it (do not edit the `.ts` by hand) | | `src/api/apiUrl.ts` | Backend URL resolution, shared with the CSP | -| `src/api/errors.ts` | `errorMessage()`: the backend's `{ error: { message } }` or the plain error message | +| `src/api/errors.ts` | `errorMessage()`: the backend's message or the plain one; `isNotFound()`: a 404 response | | `src/editor/Main/notifyError.ts` | `.catch` handler that shows a failed backend call as an antd notification | | `src/security/contentSecurityPolicy.ts` | CSP builder: every external origin the page calls must be listed here | | `src/types/index.ts` | `TemplateTree` type | @@ -72,12 +86,17 @@ The backend's request and response shapes are described in its [`openapi.json`]( ```ts // Example pattern used in src/editor/Main/Main.test.tsx vi.mock("@/api/main", () => ({ + getTemplate: vi.fn(() => + Promise.resolve({ id: "t1", name: "Weekly digest", createdAt, updatedAt }), + ), getTree: vi.fn(() => Promise.resolve([])), generate: vi.fn(() => Promise.resolve("")), saveTree: vi.fn(() => Promise.resolve({})), })); ``` +Components that call `useRouter()` (`TemplatesPage`, `SendEmailModal`, so also `Main`) need `vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }))`. In e2e, mock the backend by full URL (`e2e/backend.ts`): a glob like `**/templates/t1` would also catch the page `/templates/t1`. + Run once: `npm test` Watch mode: `npm run test:watch` @@ -136,6 +155,7 @@ Rules when changing it: - **Step budget.** `MAX_STEPS` (12) caps model ↔ tool round-trips per message, so prefer tools that do a whole job in one call (`compose_blocks`, `get_element` with several `keys`) over many small calls. When the limit cuts a run short, the chat says so. - **Never send the key to our backend** or log it. `e2e/ai-assistant.spec.ts` checks this. - **Keep `ChatPanel` lazy-loaded** (`next/dynamic` in `Main.tsx`) so the AI SDK stays out of the initial bundle. +- **One template per chat.** The tools get the open template's id (`createEditorTools({ templateId, … })`) and `Main` renders `ChatPanel` with `key={templateId}`, so a conversation never carries over to another template. There is no tool for sending; that stays a user action. - **Tests:** mock `src/api/main`. Use `MockLanguageModelV4` from `ai/test` for agent tests, and mock Gemini with `page.route` in e2e. ### Building an email from text (`compose_blocks`) @@ -152,7 +172,7 @@ compose_blocks({ parentKey?, after?, replace?, blocks: [ - **One level of nesting.** `slots` put an element into a placeholder of another (a recipe card into a column of a two-column row). Deeper nesting would need a recursive schema (`$ref`), which not every provider handles, so it is left out on purpose. - **Placeholders are managed by the tool.** Each block gets a new placeholder in the parent (`{{block1}}`, `{{block2}}`, … skipping names already used), inserted after the anchor: `after`, or the parent's last placeholder. If the anchor occurs once and is empty (e.g. `{{content}}` of a new root), the first block takes it. `parentKey` defaults to the root. - **`replace: true`** removes the parent's children and their placeholders and puts the new blocks where the first of them was. The user confirms first. -- **Validate, then write once.** All blocks are checked before anything changes: unknown elements, `fills`/`slots` keys that aren't placeholders of the element (`title` is accepted for `{{title}}`), a key in both, and fill text containing `{{…}}` (generation would put another child into it). Every error comes back in one result so the model can fix them in one retry. The new tree is built locally from one `getTree()` and saved with one `saveTree()` (`PUT /tree`), which the backend writes atomically: a failure leaves the tree as it was. Trade-off: an edit made in the UI between that read and write (milliseconds, no model call in between) is overwritten. +- **Validate, then write once.** All blocks are checked before anything changes: unknown elements, `fills`/`slots` keys that aren't placeholders of the element (`title` is accepted for `{{title}}`), a key in both, and fill text containing `{{…}}` (generation would put another child into it). Every error comes back in one result so the model can fix them in one retry. The new tree is built locally from one `getTree()` and saved with one `saveTree()` (`PUT …/tree`), which the backend writes atomically: a failure leaves the tree as it was. Trade-off: an edit made in the UI between that read and write (milliseconds, no model call in between) is overwritten. - **Result:** keys and titles of the added nodes, `removedCount`, and `unfilled` placeholders (e.g. `blocks[2] {{item2}}`), which render as nothing. - **Pasted content is data.** The system prompt says so explicitly; the model also must not invent URLs or images. As everywhere, the chat renders the model's reply as text only, and fills go only into the email, which the preview shows in the sandboxed iframe. - Elements have only `key`, `title` and `value`, so the model judges them by placeholder names and HTML. An optional `description` field (backend + frontend) is a possible follow-up. @@ -181,9 +201,9 @@ Consequences when changing code: ### Email preview (`src/editor/Main/Preview/`) -`Preview.tsx` shows the email next to the tree. `renderTemplate.ts` renders the tree in the browser with the same rules as the backend's `POST /generate` (`src/modules/generate/generate-html.ts` in the backend repo); change both together. The preview re-renders whenever `Main` reloads the tree, including after the assistant's changes. +`Preview.tsx` shows the email next to the tree. `renderTemplate.ts` renders the tree in the browser with the same rules as the backend's `POST /templates/:templateId/generate` (`src/modules/generate/generate-html.ts` in the backend repo); change both together. The preview re-renders whenever `Main` reloads the tree, including after the assistant's changes. -- The email HTML is untrusted, so it goes into `