Sync script: pin b2e and b2x to latest, sync skills from template

- Pin both template packages to latest in sync-webapp-skills.js
- Update package.json / package-lock.json (b2x 1.109.0)
- Sync skills: managing-webapp-agentforce-conversation-client, bar-line-chart,
  remove building-webapp-analytics-charts and integrating-webapp-agentforce-conversation-client
- Minor skill content updates

Made-with: Cursor
This commit is contained in:
k-j-kim 2026-03-18 15:05:39 -07:00
parent 78575f5272
commit 01686db713
No known key found for this signature in database
GPG Key ID: 40FA25A7DE938B04
19 changed files with 996 additions and 304 deletions

20
package-lock.json generated
View File

@ -9,8 +9,8 @@
"version": "1.1.0",
"license": "CC-BY-NC-4.0",
"devDependencies": {
"@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.107.3",
"@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.107.3",
"@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.109.1",
"@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.109.1",
"tsx": "^4.21.0"
}
},
@ -732,20 +732,20 @@
}
},
"node_modules/@salesforce/webapp-template-app-react-sample-b2e-experimental": {
"version": "1.107.3",
"resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2e-experimental/-/webapp-template-app-react-sample-b2e-experimental-1.107.3.tgz",
"integrity": "sha512-9oLj1sxPS0Cwcr1VGGF27oI5kiPoNw/rN7cD4LEHqbsb0w91KOIh6j3O61LhBrWNKB572slk1woaVA9ai0IkNw==",
"version": "1.109.1",
"resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2e-experimental/-/webapp-template-app-react-sample-b2e-experimental-1.109.1.tgz",
"integrity": "sha512-ju77WQp0dsIDroito/xgZrLI7DuIQfo8NgMLB8qVgnhE7Tssma8KAtqDHjK9HsmL/HTPlMXZUEhEqh8nJNq5Sw==",
"dev": true,
"license": "SEE LICENSE IN LICENSE.txt",
"dependencies": {
"@salesforce/webapp-experimental": "^1.107.3",
"@salesforce/webapp-template-feature-react-global-search-experimental": "^1.107.3"
"@salesforce/webapp-experimental": "^1.109.1",
"@salesforce/webapp-template-feature-react-global-search-experimental": "^1.109.1"
}
},
"node_modules/@salesforce/webapp-template-app-react-sample-b2x-experimental": {
"version": "1.107.3",
"resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2x-experimental/-/webapp-template-app-react-sample-b2x-experimental-1.107.3.tgz",
"integrity": "sha512-YpZxmiUlLntpWDDOZ7wBPgvo3nlq/8tpFZIxEfufyPi4jiwEa3D4KLQJvjN/KSHXP8YDoHyuIB2ZjYKIoRW1Ww==",
"version": "1.109.1",
"resolved": "https://registry.npmjs.org/@salesforce/webapp-template-app-react-sample-b2x-experimental/-/webapp-template-app-react-sample-b2x-experimental-1.109.1.tgz",
"integrity": "sha512-Pf4cC1fbDJ5o7gJlztDCArqimQN60+iCAxNpHHDsz8hHUBO2lteD5jK3I9WSPeoBDNm7VMOgLFIssWiGPvRlVg==",
"dev": true,
"license": "SEE LICENSE IN LICENSE.txt"
},

View File

@ -11,8 +11,8 @@
"registry": "https://registry.npmjs.org"
},
"devDependencies": {
"@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.107.3",
"@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.107.3",
"@salesforce/webapp-template-app-react-sample-b2e-experimental": "1.109.1",
"@salesforce/webapp-template-app-react-sample-b2x-experimental": "1.109.1",
"tsx": "^4.21.0"
},
"scripts": {

View File

@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
* Sync webapp skills: pins @salesforce/webapp-template-app-react-sample-b2e-experimental
* to the latest npm version, runs npm install, then copies skills from
* dist/.a4drules/skills/ into skills/. Run from repo root.
* Sync webapp skills: pins b2e and b2x template packages to latest npm versions,
* runs npm install, then copies skills from dist/.a4drules/skills/ into skills/.
* Run from repo root.
*/
const fs = require('fs');
@ -10,30 +10,39 @@ const path = require('path');
const { execSync } = require('child_process');
const { copyRecursive } = require('./lib/copy-recursive');
const PACKAGE_NAME = '@salesforce/webapp-template-app-react-sample-b2e-experimental';
const TEMPLATE_PACKAGES = [
'@salesforce/webapp-template-app-react-sample-b2e-experimental',
'@salesforce/webapp-template-app-react-sample-b2x-experimental',
];
const PACKAGE_NAME = TEMPLATE_PACKAGES[0]; // used for syncing skills
const SKILLS_SRC = 'dist/.a4drules/skills';
const repoRoot = process.cwd();
const pkgPath = path.join(repoRoot, 'package.json');
const skillsDir = path.join(repoRoot, 'skills');
// ── Pin to latest npm version ────────────────────────────────────────
// ── Pin template packages to latest npm versions ────────────────────
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const current = (pkg.devDependencies || {})[PACKAGE_NAME];
if (current && !current.startsWith('file:')) {
let pkgChanged = false;
for (const name of TEMPLATE_PACKAGES) {
const current = (pkg.devDependencies || {})[name];
if (!current || current.startsWith('file:')) continue;
let latest;
try {
latest = execSync(`npm view ${PACKAGE_NAME} version`, { encoding: 'utf8' }).trim();
latest = execSync(`npm view ${name} version`, { encoding: 'utf8' }).trim();
} catch (_) {
console.warn(`Could not resolve ${PACKAGE_NAME} on npm, using current version.`);
latest = current;
console.warn(`Could not resolve ${name} on npm, using current version.`);
continue;
}
if (current !== latest) {
console.log(`${PACKAGE_NAME}: ${current} -> ${latest}`);
pkg.devDependencies[PACKAGE_NAME] = latest;
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
console.log(`${name}: ${current} -> ${latest}`);
pkg.devDependencies[name] = latest;
pkgChanged = true;
}
}
if (pkgChanged) {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8');
}
// ── Install ──────────────────────────────────────────────────────────
console.log('Installing dependencies...');
@ -61,6 +70,11 @@ function addWebappPrefix(name) {
return parts[0] + '-webapp-' + parts.slice(1).join('-');
}
/** Dirs in skills/ that look like synced webapp skills (e.g. *-webapp-*, creating-webapp). */
function isSyncedWebappSkillDir(name) {
return name.includes('webapp');
}
/** Set front matter `name` in SKILL.md to match the destination folder name. */
function setSkillFrontMatterName(skillDir, destName) {
const skillPath = path.join(skillDir, 'SKILL.md');
@ -70,11 +84,25 @@ function setSkillFrontMatterName(skillDir, destName) {
fs.writeFileSync(skillPath, content, 'utf8');
}
const syncedDirs = [];
for (const srcName of fs.readdirSync(srcDir)) {
const src = path.join(srcDir, srcName);
if (!fs.statSync(src).isDirectory()) continue;
// ── Clean up: remove skills no longer in the package ───────────────────
const srcNames = fs.readdirSync(srcDir).filter((name) =>
fs.statSync(path.join(srcDir, name)).isDirectory()
);
const currentDestNames = new Set(srcNames.map(addWebappPrefix));
for (const name of fs.readdirSync(skillsDir)) {
const dirPath = path.join(skillsDir, name);
if (!fs.statSync(dirPath).isDirectory()) continue;
if (!isSyncedWebappSkillDir(name)) continue;
if (currentDestNames.has(name)) continue;
fs.rmSync(dirPath, { recursive: true });
console.log(`Removed skills/${name}/ (no longer in package)`);
}
// ── Copy each skill from package ──────────────────────────────────────
const syncedDirs = [];
for (const srcName of srcNames) {
const src = path.join(srcDir, srcName);
const destName = addWebappPrefix(srcName);
const dest = path.join(skillsDir, destName);
if (fs.existsSync(dest)) fs.rmSync(dest, { recursive: true });

View File

@ -149,6 +149,19 @@ const res = await sdk.fetch?.("/services/data/v65.0/chatter/users/me");
---
## Clarifying Vague Data Requests
When a user asks about data and the request is vague, **clarify before implementing**. Ask which of the following they want:
- **Application code** — Add or modify code in a specific web app so the app performs the data interaction at runtime (e.g., GraphQL query in the React app)
- **Local SF CLI** — Run Salesforce CLI commands locally (e.g., `sf data query`, `sf data import tree`) to interact with the org from the terminal
- **Local example data** — Update or add local fixture/example data files (e.g., JSON in `data/`) for development or testing
- **Other** — Data export, report generation, setup script, etc.
Do not assume. A request like "fetch accounts" could mean: (1) add a GraphQL query to the app, (2) run `sf data query` in the terminal, or (3) update sample data files. Confirm the intent before proceeding.
---
## Decision Flow
1. **Need to query or mutate Salesforce records?** → Use GraphQL via the Data SDK. Invoke the `using-graphql` skill.

View File

@ -1,41 +0,0 @@
---
name: building-webapp-analytics-charts
description: Add or change charts from raw data. Use when the user asks for a chart, graph, or analytics visualization from JSON/data.
---
# Analytics charts (workflow)
When the user wants a chart or visualization from data, follow this workflow. Charts use **Recharts** via the **AnalyticsChart** component.
## Dependencies
Ensure the following package is installed in the project:
```bash
npm install recharts
```
## 1. Interpret data type
- **Time-series**: data over time or ordered (dates, timestamps). Use a line chart. Raw shape often has date-like keys and a numeric value.
- **Categorical**: data by category (labels, segments). Use a bar chart. Raw shape often has a category name and a numeric value.
If the user says "over time", "trend", or uses date-like keys → time-series. If they say "by category", "by X", or use label-like keys → categorical.
## 2. Map data to chart shape
- **Time-series**: produce `[{ x: string, y: number }, ...]` (e.g. map `date`→`x`, `value`→`y`).
- **Categorical**: produce `[{ name: string, value: number }, ...]` (e.g. map `category`→`name`, `total`→`value`).
See [schema-mapping.md](docs/schema-mapping.md) for examples.
## 3. Choose theme
- **red**: declining, loss, negative trend.
- **green**: growth, gain, positive trend.
- **neutral**: default or mixed.
## 4. Generate and place the chart
- Use **AnalyticsChart** with `chartType` (`"time-series"` or `"categorical"`), `data` (mapped array), `theme`, and optional `title`. Wrap in **ChartContainer** if the app uses it for chart blocks.
- Insert the chart inside the existing app (e.g. main content or a route), not as the entire page.

View File

@ -1,4 +0,0 @@
# Schema mapping (Recharts)
- **Time-series**: `{ x: string, y: number }` — e.g. map `date`→`x`, `value`→`y`.
- **Categorical**: `{ name: string, value: number }` — e.g. map `category`→`name`, `total`→`value`.

View File

@ -46,8 +46,8 @@ Recharts is built on D3 and provides declarative React components. No additional
Read the corresponding guide:
- **Bar chart**use the **`building-analytics-charts`** skill in `feature-react-chart` (AnalyticsChart component for categorical data).
- **Line / area chart**use the **`building-analytics-charts`** skill in `feature-react-chart` (AnalyticsChart component for time-series data).
- **Bar chart**read `implementation/bar-line-chart.md` (categorical data)
- **Line / area chart**read `implementation/bar-line-chart.md` (time-series data)
- **Donut / pie chart** — read `implementation/donut-chart.md`
- **Stat card with trend** — read `implementation/stat-card.md`
- **Dashboard layout** — read `implementation/dashboard-layout.md`

View File

@ -0,0 +1,316 @@
# Bar & Line / Area Chart — Implementation Guide
Requires **recharts** (install from the web app directory; see SKILL.md Step 2).
---
## Data shapes
### Time-series (line / area chart)
Use when data represents a trend over time or ordered sequence.
```ts
interface TimeSeriesDataPoint {
x: string; // date or label on the x-axis
y: number; // numeric value
}
```
Map raw fields to this shape: e.g. `date``x`, `revenue``y`.
### Categorical (bar chart)
Use when data compares discrete categories.
```ts
interface CategoricalDataPoint {
name: string; // category label
value: number; // numeric value
}
```
Map raw fields to this shape: e.g. `product``name`, `sales``value`.
### How to decide
| Signal | Type |
|--------|------|
| "over time", "trend", date-like keys | Time-series → line chart |
| "by category", "by X", label-like keys | Categorical → bar chart |
---
## Theme colors
Pick a theme based on the data's sentiment:
| Theme | Stroke / Fill | When to use |
|-------|---------------|-------------|
| `green` | `#22c55e` | Growth, gain, positive trend |
| `red` | `#ef4444` | Decline, loss, negative trend |
| `neutral` | `#6366f1` | Default or mixed data |
Define colors as constants — do not use inline hex values.
```ts
const THEME_COLORS = {
red: "#ef4444",
green: "#22c55e",
neutral: "#6366f1",
} as const;
type ChartTheme = keyof typeof THEME_COLORS;
```
---
## Line chart component
Create at `components/LineChart.tsx` (or colocate with the page):
```tsx
import React from "react";
import {
LineChart as RechartsLineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from "recharts";
const THEME_COLORS = {
red: "#ef4444",
green: "#22c55e",
neutral: "#6366f1",
} as const;
type ChartTheme = keyof typeof THEME_COLORS;
interface TimeSeriesDataPoint {
x: string;
y: number;
}
interface TimeSeriesChartProps {
data: TimeSeriesDataPoint[];
theme?: ChartTheme;
title?: string;
className?: string;
}
export function TimeSeriesChart({
data,
theme = "neutral",
title,
className = "",
}: TimeSeriesChartProps) {
if (data.length === 0) {
return <p className="text-muted-foreground text-center py-8">No data to display</p>;
}
const color = THEME_COLORS[theme];
return (
<div className={className}>
{title && (
<h3 className="text-sm font-medium text-primary mb-2 uppercase tracking-wide">
{title}
</h3>
)}
<ResponsiveContainer width="100%" height={300}>
<RechartsLineChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="x" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="y" stroke={color} strokeWidth={2} dot={false} />
</RechartsLineChart>
</ResponsiveContainer>
</div>
);
}
```
---
## Bar chart component
Create at `components/BarChart.tsx` (or colocate with the page):
```tsx
import React from "react";
import {
BarChart as RechartsBarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
} from "recharts";
const THEME_COLORS = {
red: "#ef4444",
green: "#22c55e",
neutral: "#6366f1",
} as const;
type ChartTheme = keyof typeof THEME_COLORS;
interface CategoricalDataPoint {
name: string;
value: number;
}
interface CategoricalChartProps {
data: CategoricalDataPoint[];
theme?: ChartTheme;
title?: string;
className?: string;
}
export function CategoricalChart({
data,
theme = "neutral",
title,
className = "",
}: CategoricalChartProps) {
if (data.length === 0) {
return <p className="text-muted-foreground text-center py-8">No data to display</p>;
}
const color = THEME_COLORS[theme];
return (
<div className={className}>
{title && (
<h3 className="text-sm font-medium text-primary mb-2 uppercase tracking-wide">
{title}
</h3>
)}
<ResponsiveContainer width="100%" height={300}>
<RechartsBarChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="value" fill={color} radius={[4, 4, 0, 0]} />
</RechartsBarChart>
</ResponsiveContainer>
</div>
);
}
```
---
## Area chart variant
For a filled area chart (useful for volume-over-time), swap `Line` for `Area`:
```tsx
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from "recharts";
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={data}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="x" />
<YAxis />
<Tooltip />
<Area type="monotone" dataKey="y" stroke={color} fill={color} fillOpacity={0.2} />
</AreaChart>
</ResponsiveContainer>
```
---
## Chart container wrapper
Wrap any chart in a styled card for consistent spacing:
```tsx
import { Card } from "@/components/ui/card";
interface ChartContainerProps {
children: React.ReactNode;
className?: string;
}
export function ChartContainer({ children, className = "" }: ChartContainerProps) {
return (
<Card className={`p-4 border-gray-200 shadow-sm ${className}`}>
{children}
</Card>
);
}
```
Usage:
```tsx
<ChartContainer>
<TimeSeriesChart data={monthlyData} theme="green" title="Monthly Revenue" />
</ChartContainer>
```
---
## Preparing raw data
Map API responses to the expected shape before passing to the chart:
```tsx
const timeSeriesData = useMemo(
() => apiRecords.map((r) => ({ x: r.date, y: r.revenue })),
[apiRecords],
);
const categoricalData = useMemo(
() => apiRecords.map((r) => ({ name: r.product, value: r.sales })),
[apiRecords],
);
```
---
## Key Recharts concepts
| Component | Purpose |
|-----------|---------|
| `ResponsiveContainer` | Wraps chart to fill parent width |
| `CartesianGrid` | Background grid lines |
| `XAxis` / `YAxis` | Axis labels; `dataKey` maps to the data field |
| `Tooltip` | Hover info |
| `Legend` | Series labels |
| `Line` | Line series; `type="monotone"` for smooth curves |
| `Bar` | Bar series; `radius` rounds top corners |
| `Area` | Filled area; `fillOpacity` controls transparency |
---
## Accessibility
- Always include a text legend (not just colors).
- Chart should be wrapped in a section with a visible heading.
- For critical data, provide a text summary or table alternative.
- Use sufficient color contrast between the chart stroke/fill and background.
- Consider `prefers-reduced-motion` for chart animations.
---
## Common mistakes
| Mistake | Fix |
|---------|-----|
| Missing `ResponsiveContainer` | Chart won't resize; always wrap |
| Fixed width/height on chart | Let `ResponsiveContainer` control sizing |
| No empty-data handling | Show "No data" message when `data.length === 0` |
| Inline colors | Extract to `THEME_COLORS` constant |
| Using raw Recharts for every chart type | Use `DonutChart` (see `donut-chart.md`) for pie/donut |

View File

@ -156,7 +156,7 @@ Keep chart colors consistent with the app's design system. Define them as consta
## Other chart types
For **bar charts** and **line charts**, use the `AnalyticsChart` component from `feature-react-chart` instead of raw Recharts. See the **`building-analytics-charts`** skill for usage.
For **bar charts** and **line / area charts**, see `bar-line-chart.md` in this directory.
---

View File

@ -68,13 +68,29 @@ Once you have identified the type and gathered answers to the clarifying questio
---
## Verification
## TypeScript Standards
Before completing, run from the web app directory `force-app/main/default/webapplications/<appName>/` (use the actual app folder name):
- **Never use `any`** — use proper types, generics, or `unknown` with type guards.
- **Event handlers:** `(event: React.FormEvent<HTMLFormElement>): void`
- **State:** `useState<User | null>(null)` — always provide the type parameter.
- **No unsafe assertions** (`obj as User`). Use type guards:
```typescript
function isUser(obj: unknown): obj is User {
return typeof obj === 'object' && obj !== null && typeof (obj as User).id === 'string';
}
```
---
## Verification (MANDATORY)
Before completing, run from the web app directory `force-app/main/default/webapplications/<appName>/`:
```bash
cd force-app/main/default/webapplications/<appName> && npm run lint && npm run build
```
- **Lint:** MUST result in 0 errors. Fix any ESLint or TypeScript issues.
- **Build:** MUST succeed. Resolve any compilation or Vite build failures before finishing.
- **Lint:** MUST result in 0 errors.
- **Build:** MUST succeed (includes TypeScript check).
If either fails, fix the errors and re-run. Do not leave the session with failing quality gates.

View File

@ -11,7 +11,10 @@ paths:
# Skills-First (MUST FOLLOW)
**Before writing any code or running any command**, search for relevant skills (`SKILL.md` files) that cover your task. Read the full skill and follow its instructions. Skills live in `.a4drules/skills/` and `feature/*/skills/`. See **webapp-skills-first.md** for the full protocol and a task-to-skill lookup table.
**Before writing any code or running any command**, search for relevant skills (`SKILL.md` files) that cover your task. Read the full skill and follow its instructions. Skills live in `.a4drules/skills/` and `feature/*/skills/`.
- Do not write custom scripts or complex bash commands for a workflow already covered by a loaded skill.
- Only proceed with manual execution after confirming no relevant skill exists.
# Deployment Order (MUST FOLLOW)
@ -91,6 +94,25 @@ Agents consistently miss these. **You must not leave them default.**
| Root page content | Component at root route (often `Home` in `routes.tsx`) |
# React & TypeScript Constraints
## Routing (React Router)
Use a **single** router package. When using `createBrowserRouter` / `RouterProvider`, all imports MUST come from **`react-router`** — not `react-router-dom`.
## Component Library + Styling
- **shadcn/ui** for components: `import { Button } from '@/components/ui/button';`
- **Tailwind CSS** utility classes
## URL & Path Handling
Apps run behind dynamic base paths. Router navigation (`<Link to>`, `navigate()`) prefer absolute paths (`/x`). Non-router attributes (`<img src>`) use dot-relative (`./x`) to resolve against `<base>`. Prefer Vite `import` for static assets.
## Module Restrictions
React apps must NOT import Salesforce platform modules like `lightning/*` or `@wire` (LWC-only). For data access, invoke the **accessing-data** skill.
# Frontend Aesthetics
**Avoid AI slop.** Make creative, distinctive frontends:

View File

@ -1,11 +1,11 @@
---
name: installing-webapp-features
description: Search, describe, and install pre-built UI features (authentication, shadcn components, navigation, charts, search, GraphQL, Agentforce AI) into Salesforce webapps. Use this when the user wants to add functionality to a webapp, or when determining what salesforce-provided features are available — whether prompted by the user or on your own initiative. Always check for an existing feature before building from scratch.
description: Search, describe, and install pre-built UI features (authentication, shadcn components, navigation, search, GraphQL, Agentforce AI) into Salesforce webapps. Use this when the user wants to add functionality to a webapp, or when determining what salesforce-provided features are available — whether prompted by the user or on your own initiative. Always check for an existing feature before building from scratch.
---
# webapps-features-experimental CLI — Agent Reference
**Always check for an existing feature before building something yourself.** This CLI installs pre-built, tested feature packages into Salesforce webapps. Features range from foundational UI component libraries (shadcn/ui with Button, Card, Input, Table, etc.) to full-stack application capabilities like authentication (login, registration, password flows, session management, and Apex backend classes), global search, navigation menus, data visualization charts, GraphQL integrations, and Agentforce AI conversation UIs. Each feature ships as a complete implementation — including React components, context providers, route guards, and any required Salesforce server-side code — that already handles platform-specific concerns like Salesforce API integration, session management, and SFDX metadata structure. Building these from scratch is error-prone and unnecessary when a feature exists. **If no existing feature is found, ask the user before proceeding with a custom implementation — a relevant feature may exist under a different name or keyword.**
**Always check for an existing feature before building something yourself.** This CLI installs pre-built, tested feature packages into Salesforce webapps. Features range from foundational UI component libraries (shadcn/ui with Button, Card, Input, Table, etc.) to full-stack application capabilities like authentication (login, registration, password flows, session management, and Apex backend classes), global search, navigation menus, GraphQL integrations, and Agentforce AI conversation UIs. Each feature ships as a complete implementation — including React components, context providers, route guards, and any required Salesforce server-side code — that already handles platform-specific concerns like Salesforce API integration, session management, and SFDX metadata structure. Building these from scratch is error-prone and unnecessary when a feature exists. **If no existing feature is found, ask the user before proceeding with a custom implementation — a relevant feature may exist under a different name or keyword.**
```
npx @salesforce/webapps-features-experimental <command> [options]

View File

@ -1,92 +0,0 @@
---
name: integrating-webapp-agentforce-conversation-client
description: Embed an Agentforce conversation client (chat UI) into a React web application using the AgentforceConversationClient component. Use when the user wants to add or integrate a chat widget, chatbot, conversation client, agent chat, or conversational interface in a React app, or when they mention Agentforce chat, Agentforce widget, employee agent, travel agent, HR agent, or embedding a Salesforce agent. ALWAYS use this skill instead of building a chat UI from scratch. NEVER generate custom chat components, use third-party chat libraries, or implement chat with WebSockets or REST APIs. Do NOT use for Lightning Web Components (LWC), non-React frameworks.
---
# Embedded Agentforce chat (flat-prop API)
Use this workflow whenever the user wants add or update Agentforce chat in React.
## 1) Get agent id first
Ask for the Salesforce agent id (18-char id starting with `0Xx`). Do not proceed without it.
Placeholder convention for all examples in this file:
`<AgentforceConversationClient agentId="<USER_AGENT_ID_18_CHAR_0Xx...>" />`
## 2) Install package
```bash
npm install @salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental
```
## 3) Use component in app layout
Render a single instance in the shared layout (alongside `<Outlet />`).
```tsx
import { Outlet } from "react-router";
import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental";
export default function AppLayout() {
return (
<>
<Outlet />
<AgentforceConversationClient agentId="<USER_AGENT_ID_18_CHAR_0Xx...>" />
</>
);
}
```
## 4) Flat props only
This package uses a flat prop API. Use these props directly on the component:
- `agentId` (required in practice)
- `inline` (`true` = inline, omitted/false = floating)
- `headerEnabled` (defaults to true for floating; actual use case for inline mode)
- `width`, `height` (actual work is when inline mode is true)
- `styleTokens`
- `salesforceOrigin`, `frontdoorUrl`
## 5) Inline mode example
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
inline
width={420}
height={600}
/>
```
## 6) Theming example
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
}}
/>
```
## 7) Do not do this
- Do not create custom chat UIs.
- Do not use third-party chat libraries.
- Do not call `embedAgentforceClient` directly from @salesforce/agentforce-conversation-client.
## 8) Prerequisites
Ensure org setup is valid:
1. Agent is active and deployed to the correct channel.
2. `localhost:<PORT>` is trusted for inline frames in local dev.
3. First-party Salesforce cookie restriction is disabled when required for embedding.
## Troubleshooting
If the chat widget does not appear, fails to authenticate, or behaves unexpectedly, see [troubleshooting.md](docs/troubleshooting.md).

View File

@ -1,116 +0,0 @@
# Embed examples (flat-prop API)
All examples use `AgentforceConversationClient` with flat props.
> `agentId` is required in practice. Use this placeholder pattern in examples: `"<USER_AGENT_ID_18_CHAR_0Xx...>"`.
---
## Floating mode (default)
```tsx
<AgentforceConversationClient agentId="<USER_AGENT_ID_18_CHAR_0Xx...>" />
```
## Explicit floating
```tsx
<AgentforceConversationClient agentId="<USER_AGENT_ID_18_CHAR_0Xx...>" />
```
---
## Inline mode
### Fixed pixels
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
inline
width={420}
height={600}
/>
```
### CSS string size
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
inline
width="100%"
height="80vh"
/>
```
### Inline sidebar
```tsx
<div style={{ display: "flex", height: "100vh" }}>
<main style={{ flex: 1 }}>{/* App content */}</main>
<aside style={{ width: 400 }}>
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
inline
width="100%"
height="100%"
/>
</aside>
</div>
```
---
## Theming
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
messageBlockInboundColor: "#0176d3",
}}
/>
```
---
## Inline with header enabled
```tsx
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
inline
width={420}
height={600}
headerEnabled
/>
```
`headerEnabled` defaults to `true` for floating mode, and you can use it in inline mode to add/remove the header.
---
## Full layout example
```tsx
import { Outlet } from "react-router";
import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental";
export default function AppLayout() {
return (
<>
<Outlet />
<AgentforceConversationClient
agentId="<USER_AGENT_ID_18_CHAR_0Xx...>"
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
}}
/>
</>
);
}
```

View File

@ -0,0 +1,186 @@
---
name: managing-webapp-agentforce-conversation-client
description: Adds or modifies AgentforceConversationClient in React apps (.tsx or .jsx files). Use when user says "add chat widget", "embed agentforce", "add agent", "add chatbot", "integrate conversational AI", or asks to change colors, dimensions, styling, or configure agentId, width, height, inline mode, or styleTokens for travel agent, HR agent, employee agent, or any Salesforce agent chat.
metadata:
author: ACC Components
version: 1.0.0
package: "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental"
sdk-package: "@salesforce/agentforce-conversation-client"
last-updated: 2025-03-18
---
# Managing Agentforce Conversation Client
## Instructions
### Step 1: Check if component already exists
Search for existing usage across all app files (not implementation files):
```bash
grep -r "AgentforceConversationClient" --include="*.tsx" --include="*.jsx" --exclude-dir=node_modules
```
**Important:** Look for React files that import and USE the component (for example, shared shells, route components, or feature pages). Do NOT open files named `AgentforceConversationClient.tsx` or `AgentforceConversationClient.jsx` - those are the component implementation.
**If found:** Read the file and check the current `agentId` value.
**Agent ID validation rule (deterministic):**
- Valid only if it matches: `^0Xx[a-zA-Z0-9]{15}$`
- Meaning: starts with `0Xx` and total length is 18 characters
**Decision:**
- If `agentId` matches `^0Xx[a-zA-Z0-9]{15}$` and user wants to update other props → Go to Step 4 (update props)
- If `agentId` is missing, empty, or does NOT match `^0Xx[a-zA-Z0-9]{15}$` → Continue to Step 2 (need real ID)
- If not found → Continue to Step 2 (add new)
### Step 2: Get agent ID
If component doesn't exist or has an invalid placeholder value, ask user for their Salesforce agent ID.
Treat these as placeholder/invalid values:
- `"0Xx..."`
- `"Placeholder"`
- `"YOUR_AGENT_ID"`
- `"<USER_AGENT_ID_18_CHAR_0Xx...>"`
- Any value that does not match `^0Xx[a-zA-Z0-9]{15}$`
Skip this step if:
- Component exists with a real agent ID
- User only wants to update styling or dimensions
### Step 3: Canonical import strategy
Use this import path by default in app code:
```tsx
import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental";
```
If the package is not installed, install it:
```bash
npm install @salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental
```
Only use a local relative import (for example, `./components/AgentforceConversationClient`) when the user explicitly asks to use a patched/local component in that app.
Do not infer import path from file discovery alone. Prefer one consistent package import across the codebase.
### Step 4: Add or update component
**For new installations:**
Add to the target React component file using the canonical package import:
```tsx
import { Outlet } from "react-router";
import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental";
export default function AgentChatHost() {
return (
<>
<Outlet />
<AgentforceConversationClient agentId="0Xx..." />
</>
);
}
```
**Fallback note:** Use a local relative import only when the user explicitly requests patched/local component usage in that app.
**For updates:**
Read the file where component is used and modify only the props that need to change. Preserve all other props. Never delete and recreate.
**Replacing placeholder values:**
If the component has a placeholder agentId (e.g., `agentId="Placeholder"` or `agentId="0Xx..."`), replace it with the real agent ID:
```tsx
// Before (template with placeholder)
<AgentforceConversationClient agentId="Placeholder" />
// After (with real agent ID)
<AgentforceConversationClient agentId="0Xx8X00000001AbCDE" />
```
### Step 5: Configure props
**Available props (use directly on component):**
- `agentId` (string, required) - Salesforce agent ID
- `inline` (boolean) - `true` for inline mode, omit for floating
- `width` (number | string) - e.g., `420` or `"100%"`
- `height` (number | string) - e.g., `600` or `"80vh"`
- `headerEnabled` (boolean) - Show/hide header
- `styleTokens` (object) - For all styling (colors, fonts, spacing)
- `salesforceOrigin` (string) - Auto-resolved
- `frontdoorUrl` (string) - Auto-resolved
**Examples:**
Floating mode (default):
```tsx
<AgentforceConversationClient agentId="0Xx..." />
```
Inline mode with dimensions:
```tsx
<AgentforceConversationClient agentId="0Xx..." inline width="420px" height="600px" />
```
Styling with styleTokens:
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
messageBlockInboundBackgroundColor: "#4CAF50",
}}
/>
```
**For complex patterns,** consult `references/examples.md` for:
- Sidebar containers and responsive sizing
- Dark theme and advanced theming combinations
- Inline without header, calculated dimensions
- Complete host component examples
**For styling:** For ANY color, font, or spacing changes, use `styleTokens` prop only. See `references/style-tokens.md` for complete token list and examples.
**Common mistakes to avoid:** Consult `references/constraints.md` for:
- Invalid props (containerStyle, style, className)
- Invalid styling approaches (CSS files, style tags)
- What files NOT to edit (implementation files)
## Common Issues
If component doesn't appear or authentication fails, see `references/troubleshooting.md` for:
- Agent activation and deployment
- Localhost trusted domains
- Cookie restriction settings
## Prerequisites
Before the component will work, the following Salesforce settings must be configured by the user:
**Cookie settings:**
- Setup → My Domain → Disable "Require first party use of Salesforce cookies"
**Trusted domains (required only for local development):**
- Setup → Session Settings → Trusted Domains for Inline Frames → Add your domain
- Local development: `localhost:<PORT>` (e.g., `localhost:3000`)

View File

@ -0,0 +1,134 @@
# Constraints and Anti-Patterns
This document lists all invalid approaches and patterns to avoid when working with AgentforceConversationClient.
## Never Edit Implementation Files
**CRITICAL: Only edit files where the component is USED, never the component implementation itself.**
- ✅ **DO edit**: Any React files that import and use `<AgentforceConversationClient />` (for example, shared shells, route components, or feature pages)
- ❌ **DO NOT edit**: AgentforceConversationClient.tsx, AgentforceConversationClient.jsx, index.tsx, index.jsx, or any files inside:
- `node_modules/@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental/src/`
- `packages/template/feature/feature-react-agentforce-conversation-client/src/`
- `src/components/AgentforceConversationClient.tsx` (patched templates)
- Any path containing `/components/AgentforceConversationClient.`
**If you're reading a file named `AgentforceConversationClient.tsx`, you're in the wrong place. Stop and search for the USAGE instead.**
## Invalid Props
AgentforceConversationClient uses a flat prop API and does NOT accept these props:
- ❌ `containerStyle` - Use `width` and `height` props directly instead
- ❌ `style` - Use `styleTokens` for theming
- ❌ `className` - Not supported
- ❌ Any standard React div props - This wraps an embedded iframe, not a div
**Why:** The component is a wrapper around an embedded iframe using Lightning Out 2.0. Standard React styling props don't apply.
## Invalid Styling Approaches
**CRITICAL: For ALL styling, theming, branding, or color changes - ONLY use `styleTokens` prop.**
Never use these approaches:
- ❌ Creating CSS files (e.g., `agent-styles.css`, `theme.css`)
- ❌ Creating `<style>` tags or internal stylesheets
- ❌ Using `style` attribute on the component
- ❌ Using `className` prop
- ❌ Inline styles
- ❌ CSS modules
- ❌ Styled-components or any CSS-in-JS libraries
**Why:** The component controls its own internal styling through the `styleTokens` API. External CSS cannot reach into the embedded iframe.
## Invalid Implementation Approaches
Never do these:
- ❌ Create custom chat UIs from scratch
- ❌ Use third-party chat libraries (socket.io, WebSocket libraries, etc.)
- ❌ Call `embedAgentforceClient` directly from `@salesforce/agentforce-conversation-client`
- ❌ Build custom WebSocket or REST API chat implementations
**Why:** The AgentforceConversationClient component is the official wrapper that handles authentication, Lightning Out 2.0 initialization, and all communication with Salesforce agents. Custom implementations will not work.
## Invalid Update Patterns
When updating an existing component:
- ❌ Delete and recreate the component
- ❌ Remove all props and start over
- ❌ Copy the entire component to a new file
**Why:** This loses configuration, introduces errors, and creates unnecessary diffs. Always update props in place.
## Examples
### ❌ Wrong - Using containerStyle
```tsx
<AgentforceConversationClient agentId="0Xx..." containerStyle={{ width: 420, height: 600 }} />
```
### ✅ Correct - Using width/height directly
```tsx
<AgentforceConversationClient agentId="0Xx..." width="420px" height="600px" />
```
### ❌ Wrong - Creating CSS file
```css
/* agent-styles.css */
.agentforce-chat {
background: red;
color: white;
}
```
```tsx
import "./agent-styles.css";
<AgentforceConversationClient className="agentforce-chat" />;
```
### ✅ Correct - Using styleTokens
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "red",
headerBlockTextColor: "white",
}}
/>
```
### ❌ Wrong - Creating style tag
```tsx
<>
<style>{`.agent-chat { background: blue; }`}</style>
<AgentforceConversationClient agentId="0Xx..." />
</>
```
### ✅ Correct - Using styleTokens
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "blue",
}}
/>
```
### ❌ Wrong - Editing implementation file
Reading or editing: `node_modules/@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental/src/AgentforceConversationClient.tsx`
### ✅ Correct - Editing usage file
Reading and editing: usage files where the component is imported and used (for example, `src/app.tsx`, a route component, or a feature page)

View File

@ -0,0 +1,132 @@
# Additional Examples
Essential examples for common patterns and combinations. All use flat props API.
---
## Layout Patterns
### Sidebar Chat
```tsx
export default function DashboardWithChat() {
return (
<div style={{ display: "flex", height: "100vh" }}>
<main style={{ flex: 1 }}>{/* Main content */}</main>
<aside style={{ width: 400 }}>
<AgentforceConversationClient agentId="0Xx..." inline width="100%" height="100%" />
</aside>
</div>
);
}
```
### Full Page Chat
```tsx
export default function SupportPage() {
return (
<div>
<h1>Customer Support</h1>
<AgentforceConversationClient agentId="0Xx..." inline width="100%" height="600px" />
</div>
);
}
```
---
## Size Variations
### Responsive sizing
```tsx
<AgentforceConversationClient agentId="0Xx..." inline width="100%" height="80vh" />
```
### Calculated dimensions
```tsx
<AgentforceConversationClient agentId="0Xx..." inline width="500px" height="calc(100vh - 100px)" />
```
---
## Theming Combinations
### Brand theme with custom sizing
```tsx
<AgentforceConversationClient
agentId="0Xx..."
inline
width="500px"
height="700px"
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
messageBlockInboundBackgroundColor: "#0176d3",
messageBlockInboundTextColor: "#ffffff",
messageInputFooterSendButton: "#0176d3",
}}
/>
```
### Dark theme
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "#1a1a1a",
headerBlockTextColor: "#ffffff",
messageBlockInboundBackgroundColor: "#2d2d2d",
messageBlockInboundTextColor: "#ffffff",
messageBlockOutboundBackgroundColor: "#3a3a3a",
messageBlockOutboundTextColor: "#f0f0f0",
}}
/>
```
### Inline without header
```tsx
<AgentforceConversationClient
agentId="0Xx..."
inline
width="100%"
height="600px"
headerEnabled={false}
styleTokens={{
messageBlockBorderRadius: "12px",
}}
/>
```
---
## Complete Host Component Example
```tsx
import { Outlet } from "react-router";
import { AgentforceConversationClient } from "@salesforce/webapp-template-feature-react-agentforce-conversation-client-experimental";
export default function AgentChatHost() {
return (
<>
<Outlet />
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
}}
/>
</>
);
}
```
---
For complete style token reference, see `references/style-tokens.md` or `node_modules/@salesforce/agentforce-conversation-client/README.md`.

View File

@ -0,0 +1,101 @@
# Style Tokens Reference
This document explains how to use `styleTokens` for theming and styling the AgentforceConversationClient.
## Overview
The `styleTokens` prop is the **ONLY** way to customize the appearance of the Agentforce conversation client. It accepts an object with style token keys and CSS values.
## Source of Truth
For the complete and always up-to-date list of all 60+ style tokens, see:
**[@salesforce/agentforce-conversation-client on npm](https://www.npmjs.com/package/@salesforce/agentforce-conversation-client)**
The npm package README contains the definitive documentation with all available style tokens.
## Token Categories
Style tokens are organized by UI area:
- **Header** (7 tokens): background, text color, hover, active, focus, border, font family
- **Messages** (10 tokens): colors, padding, margins, border radius, fonts, body width
- **Inbound messages** (5 tokens): background, text color, width, alignment, hover
- **Outbound messages** (5 tokens): background, text color, width, alignment, margin
- **Input** (33 tokens): colors, borders, fonts, padding, buttons, scrollbar, textarea, actions
## Common Use Cases
### Change header color
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "#0176d3",
headerBlockTextColor: "#ffffff",
}}
/>
```
### Change message colors
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
messageBlockInboundBackgroundColor: "#4CAF50",
messageBlockInboundTextColor: "#ffffff",
messageBlockOutboundBackgroundColor: "#f5f5f5",
messageBlockOutboundTextColor: "#333333",
}}
/>
```
### Apply brand colors
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
headerBlockBackground: "#1a73e8",
headerBlockTextColor: "#ffffff",
messageBlockInboundBackgroundColor: "#1a73e8",
messageBlockInboundTextColor: "#ffffff",
messageInputFooterSendButton: "#1a73e8",
messageInputFooterSendButtonHoverColor: "#1557b0",
}}
/>
```
### Adjust spacing and fonts
```tsx
<AgentforceConversationClient
agentId="0Xx..."
styleTokens={{
messageInputFontSize: "16px",
messageBlockBorderRadius: "12px",
messageBlockPadding: "16px",
messageInputPadding: "12px",
}}
/>
```
## How to Find Token Names
1. Check the [@salesforce/agentforce-conversation-client npm package](https://www.npmjs.com/package/@salesforce/agentforce-conversation-client) for the complete list of all tokens
2. Token names follow a pattern:
- `headerBlock*` - Header area
- `messageBlock*` - Message bubbles
- `messageBlockInbound*` - Messages from customer to agent
- `messageBlockOutbound*` - Messages from agent to customer
- `messageInput*` - Input field and send button
## Important Notes
- You do NOT need to provide all tokens - only override the ones you want to change
- Token values are CSS strings (e.g., `"#FF0000"`, `"16px"`, `"bold"`)
- Invalid token names are silently ignored
- The component uses default values for any tokens you don't specify

View File

@ -23,7 +23,7 @@ Common issues when using the Agentforce Conversation Client.
**Solution:**
1. Confirm the id is correct (18-char Salesforce id, starts with `0Xx`).
2. Ensure the agent is Active in **Setup → Agents**.
2. Ensure the agent is Active in **Setup → Agentforce Agents**.
3. Verify the agent is deployed to the target channel.
---
@ -36,25 +36,22 @@ Common issues when using the Agentforce Conversation Client.
1. Go to **Setup → Session Settings → Trusted Domains for Inline Frames**.
2. Add `localhost:<PORT>` (example: `localhost:3000`).
3. Restart the dev server.
**Important:**
- This setting should be **temporary for local development only**.
- **Remove `localhost:<PORT>` from trusted domains after development**.
- **Recommended:** Test the Agentforce conversation client in a deployed app instead of relying on localhost trusted domains for extended periods.
---
### Blank iframe / auth session issues
**Cause:** First-party Salesforce cookie restriction is enabled.
**Possible cause:** First-party Salesforce cookie restriction may block embedded auth flow in some environments.
**Solution:**
1. Go to **Setup → Session Settings**.
2. Find **Require first party use of Salesforce cookies**.
3. Disable it.
3. Disable it **only if needed and approved by your security/admin team**.
4. Save and reload.
---
### Multiple chat widgets appear
**Cause:** Component rendered more than once.
**Solution:** Render one instance in app layout only.