diff --git a/CHANGELOG.md b/CHANGELOG.md index b18d708..9645508 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ The release version comes from `package.json`. Keep the newest dated entry first. +## 0.4.0 — 2026-11-17 + +- Add PLP and SRP page type support for commerce_agent_context in both inline and handoff modes. +- Send category name in handoff event detail for SRP-based context. + ## 0.3.0 — 2026-11-13 - Unify hybrid mode shopper-agent redirect with shopper-agent mode, replacing direct Cimulate DOM manipulation with the shared handoff CustomEvent. diff --git a/package-lock.json b/package-lock.json index bbcfe10..12bb38d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "inline-agent-widget", - "version": "0.3.0", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "inline-agent-widget", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "devDependencies": { "@testing-library/jest-dom": "^6.9.1", diff --git a/package.json b/package.json index 6af4955..f6bcacf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "inline-agent-widget", - "version": "0.3.0", + "version": "0.4.0", "description": "A bare-minimum, embeddable inline chat widget for Salesforce Agentforce (SCRT2 Messaging for In-App and Web). Renders agent replies as sanitized markdown inside a Shadow DOM.", "type": "module", "main": "./dist/inline-agent-widget.umd.js", diff --git a/src/ShopperAgentShim.tsx b/src/ShopperAgentShim.tsx index 1bd6e88..90fad96 100644 --- a/src/ShopperAgentShim.tsx +++ b/src/ShopperAgentShim.tsx @@ -8,13 +8,18 @@ import { } from "react"; import { SparkleIcon, SendIcon } from "./components/icons"; import type { WidgetConfig } from "./provider/types"; +import { resolveProductId } from "./provider/product-context"; export const HANDOFF_EVENT = "inline-agent-widget:handoff"; +export type PageContextType = "pdp_inline" | "plp_inline" | "srp_inline"; + export interface HandoffEventDetail { question: string; productName?: string; source: "pill" | "input"; + pageContextType?: PageContextType; + pageContextData?: Record; } /** @@ -33,16 +38,19 @@ export function ShopperAgentShim({ }) { const [text, setText] = useState(""); const textareaRef = useRef(null); - const pills = config.pdpQuestions ?? []; + const pageType = config.pageType ?? "pdp"; + const pills = resolvePills(config, pageType); const dispatchHandoff = (question: string, source: "pill" | "input") => { const trimmed = question.trim(); if (trimmed.length === 0) return; const target: EventTarget = hostElement ?? window; + const context = buildHandoffContext(config, pageType); const detail: HandoffEventDetail = { question: trimmed, productName: config.productName, source, + ...context, }; target.dispatchEvent( new CustomEvent(HANDOFF_EVENT, { @@ -81,10 +89,7 @@ export function ShopperAgentShim({ }, [text]); const placeholder = - config.placeholder ?? - (config.productName - ? `Ask me anything about ${config.productName}` - : "Ask me anything"); + config.placeholder ?? defaultPlaceholder(config, pageType); return (
@@ -137,3 +142,65 @@ export function ShopperAgentShim({
); } + +function resolvePills( + config: WidgetConfig, + pageType: "pdp" | "plp" | "srp", +): string[] { + switch (pageType) { + case "plp": + return config.categoryQuestions ?? []; + case "srp": + return []; + case "pdp": + default: + return config.pdpQuestions ?? []; + } +} + +function buildHandoffContext( + config: WidgetConfig, + pageType: "pdp" | "plp" | "srp", +): Pick { + switch (pageType) { + case "plp": { + const name = config.categoryName || config.categoryId; + if (!name) return {}; + return { + pageContextType: "plp_inline", + pageContextData: { categoryName: name }, + }; + } + case "srp": { + if (!config.searchQuery) return {}; + return { + pageContextType: "srp_inline", + pageContextData: { query: config.searchQuery }, + }; + } + case "pdp": + default: { + const productId = resolveProductId(window.location, config); + if (!productId) return {}; + return { + pageContextType: "pdp_inline", + pageContextData: { id: productId }, + }; + } + } +} + +function defaultPlaceholder( + config: WidgetConfig, + pageType: "pdp" | "plp" | "srp", +): string { + if (config.productName) return `Ask me anything about ${config.productName}`; + switch (pageType) { + case "plp": + return "Ask me about this category"; + case "srp": + return "Ask me about these results"; + default: + return "Ask me anything"; + } +} diff --git a/src/custom-element.ts b/src/custom-element.ts index aa738ca..d42f2ba 100644 --- a/src/custom-element.ts +++ b/src/custom-element.ts @@ -18,6 +18,11 @@ const OBSERVED = [ "persist-session", "pre-warm", "mode", + "page-type", + "category-id", + "category-name", + "category-questions", + "search-query", ] as const; function readMode(value: string | undefined): WidgetConfig["mode"] { @@ -27,6 +32,13 @@ function readMode(value: string | undefined): WidgetConfig["mode"] { return undefined; } +function readPageType(value: string | undefined): WidgetConfig["pageType"] { + if (value === "pdp" || value === "plp" || value === "srp") { + return value; + } + return undefined; +} + function readConfig(el: HTMLElement): WidgetConfig { const attr = (name: string) => el.getAttribute(name)?.trim() || undefined; return { @@ -43,6 +55,11 @@ function readConfig(el: HTMLElement): WidgetConfig { persistSession: el.hasAttribute("persist-session"), preWarm: el.hasAttribute("pre-warm"), mode: readMode(attr("mode")), + pageType: readPageType(attr("page-type")), + categoryId: attr("category-id"), + categoryName: attr("category-name"), + categoryQuestions: parsePdpQuestions(attr("category-questions")), + searchQuery: attr("search-query"), }; } diff --git a/src/provider/WidgetProvider.tsx b/src/provider/WidgetProvider.tsx index 176bff9..abe904b 100644 --- a/src/provider/WidgetProvider.tsx +++ b/src/provider/WidgetProvider.tsx @@ -7,7 +7,12 @@ import type { SessionPersistence } from "./ensure-connected"; import { initialWidgetState, widgetReducer } from "./reducer"; import { buildSessionKey, clearSession, loadSession, saveSession } from "./session-store"; import type { WidgetConfig } from "./types"; -import { buildPdpInlineContext, resolveProductId } from "./product-context"; +import { + buildPdpInlineContext, + buildPlpInlineContext, + buildSrpInlineContext, + resolveProductId, +} from "./product-context"; import { classifyMessage, shouldAppendStreamingToken } from "./welcome-tracker"; function isMessageTooLong(err: unknown): boolean { @@ -30,6 +35,45 @@ function toUserMessage(err: unknown): string { return "Something went wrong. Please try again."; } +import type { SessionContextVariable } from "../sdk"; + +interface PageContextSnapshot { + productIdParam?: string; + productIdPattern?: string; + pageType?: "pdp" | "plp" | "srp"; + categoryId?: string; + searchQuery?: string; + mode?: string; +} + +function resolveInlineContext( + snapshot: PageContextSnapshot, +): SessionContextVariable[] | undefined { + const pageType = snapshot.pageType ?? "pdp"; + switch (pageType) { + case "plp": { + const categoryId = snapshot.categoryId?.trim(); + return categoryId ? buildPlpInlineContext(categoryId) : undefined; + } + case "srp": { + const query = snapshot.searchQuery?.trim(); + return query ? buildSrpInlineContext(query) : undefined; + } + case "pdp": + default: { + const productId = + typeof window !== "undefined" + ? resolveProductId(window.location, snapshot) + : null; + return productId + ? buildPdpInlineContext(productId, { + suggestionRouting: snapshot.mode === "hybrid", + }) + : undefined; + } + } +} + /** Buffered pre-echo Chatbot entry: we don't yet know the echo cutoff, * so we stash the message content + its server timestamp and replay * them through the classifier once user_echo lands. */ @@ -93,12 +137,20 @@ export function WidgetProvider({ dispatch({ type: "SET_PDP_QUESTIONS", questions: pdpQuestions ?? [] }); }, [pdpQuestionsKey]); - // The URL-based product-context config, held in a ref so the dependency-stable - // sendMessage callback (deps: []) reads the latest without being recreated. - const productContextRef = useRef({ productIdParam, productIdPattern }); + // Page-context config held in a ref so the dependency-stable sendMessage + // callback (deps: []) reads the latest values without being recreated. + const pageContextRef = useRef({ + productIdParam, productIdPattern, + pageType: config.pageType, categoryId: config.categoryId, + searchQuery: config.searchQuery, mode: config.mode, + }); useEffect(() => { - productContextRef.current = { productIdParam, productIdPattern }; - }, [productIdParam, productIdPattern]); + pageContextRef.current = { + productIdParam, productIdPattern, + pageType: config.pageType, categoryId: config.categoryId, + searchQuery: config.searchQuery, mode: config.mode, + }; + }, [productIdParam, productIdPattern, config.pageType, config.categoryId, config.searchQuery, config.mode]); // Clear stale question/answer when the user navigates between PDPs via SPA // routing. SPA frameworks use pushState/replaceState (no popstate event) and @@ -366,14 +418,10 @@ export function WidgetProvider({ // every error-return path below. dispatch({ type: "SET_AGENT_TYPING", typing: true }); - // Resolve the product id from the current URL immediately before each send. - // The agent resets these external variables after every turn, so PDP context - // must be attached to every applicable message. Off a PDP, context is - // omitted and the widget retains its general-chat behavior. - const productId = - typeof window !== "undefined" - ? resolveProductId(window.location, productContextRef.current) - : null; + // Build commerce_agent_context based on the page the widget is on. + // The agent resets these external variables after every turn, so context + // must be attached to every applicable message. + const contextVars = resolveInlineContext(pageContextRef.current); // SCRT2 only forwards commerce_agent_context after the bot joins; posting // earlier means SCRT2 falls back to the Flow handler and drops the @@ -384,14 +432,7 @@ export function WidgetProvider({ if (clientRef.current !== client) throw new Error("unmounted"); await manager.waitForWelcome(6000); if (clientRef.current !== client) throw new Error("unmounted"); - await client.sendMessage( - trimmed, - productId - ? buildPdpInlineContext(productId, { - suggestionRouting: config.mode === "hybrid", - }) - : undefined, - ); + await client.sendMessage(trimmed, contextVars); }; try { diff --git a/src/provider/product-context.ts b/src/provider/product-context.ts index 902309d..80ad9eb 100644 --- a/src/provider/product-context.ts +++ b/src/provider/product-context.ts @@ -21,7 +21,7 @@ export interface CommerceAgentContext { [key: string]: unknown; version: string; page_context_type: string; - page_context_data: { id: string }; + page_context_data: Record; suggestion_routing?: boolean; } @@ -124,3 +124,39 @@ export function buildPdpInlineContext( }, ]; } + +/** Build commerce_agent_context for a category / product listing page. */ +export function buildPlpInlineContext( + categoryId: string, +): SessionContextVariable[] { + const context: CommerceAgentContext = { + version: COMMERCE_AGENT_CONTEXT_VERSION, + page_context_type: "plp_inline", + page_context_data: { categoryId }, + }; + + return [ + { + name: "commerce_agent_context", + value: { valueType: "StructuredValue", value: context }, + }, + ]; +} + +/** Build commerce_agent_context for a search results page. */ +export function buildSrpInlineContext( + query: string, +): SessionContextVariable[] { + const context: CommerceAgentContext = { + version: COMMERCE_AGENT_CONTEXT_VERSION, + page_context_type: "srp_inline", + page_context_data: { query }, + }; + + return [ + { + name: "commerce_agent_context", + value: { valueType: "StructuredValue", value: context }, + }, + ]; +} diff --git a/src/provider/types.ts b/src/provider/types.ts index 91b0826..2bd0b8f 100644 --- a/src/provider/types.ts +++ b/src/provider/types.ts @@ -30,6 +30,31 @@ export interface WidgetConfig { */ mode?: "inline" | "shopper-agent" | "hybrid"; + /** + * Storefront page type the widget is placed on. Determines which context + * is included in handoff events and which pill source is used. + * - `"pdp"` (default) — product detail page + * - `"plp"` — product listing / category page + * - `"srp"` — search results page + */ + pageType?: "pdp" | "plp" | "srp"; + + /** Category ID for PLP pages (e.g. "mens-clothing-jackets"). */ + categoryId?: string; + + /** Category display name for PLP pages (e.g. "Men's Jackets"). */ + categoryName?: string; + + /** + * Pre-generated opener questions for a category page, analogous to + * `pdpQuestions` for PDP. Stored on the category object's custom attribute + * (`c_categoryQuestions`) and passed through by the storefront. + */ + categoryQuestions?: string[]; + + /** Search query string for SRP pages (e.g. "waterproof jackets"). */ + searchQuery?: string; + /** * Current PDP product name, used to template the InputBar placeholder as * `"Ask me anything about "`. When unset, the InputBar falls diff --git a/tests/provider/product-context.test.ts b/tests/provider/product-context.test.ts index 30fd608..51710fa 100644 --- a/tests/provider/product-context.test.ts +++ b/tests/provider/product-context.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; import { buildPdpInlineContext, + buildPlpInlineContext, + buildSrpInlineContext, resolveProductId, } from "../../src/provider/product-context"; @@ -145,3 +147,35 @@ describe("buildPdpInlineContext", () => { expect((valB.value.page_context_data as { id: string }).id).toBe("PRODUCT-B"); }); }); + +describe("buildPlpInlineContext", () => { + it("builds a plp_inline StructuredValue with the category id", () => { + const context = buildPlpInlineContext("mens-clothing-jackets"); + expect(context).toHaveLength(1); + expect(context[0].name).toBe("commerce_agent_context"); + expect(context[0].value).toEqual({ + valueType: "StructuredValue", + value: { + version: "1.0.0", + page_context_type: "plp_inline", + page_context_data: { categoryId: "mens-clothing-jackets" }, + }, + }); + }); +}); + +describe("buildSrpInlineContext", () => { + it("builds a srp_inline StructuredValue with the search query", () => { + const context = buildSrpInlineContext("waterproof jackets"); + expect(context).toHaveLength(1); + expect(context[0].name).toBe("commerce_agent_context"); + expect(context[0].value).toEqual({ + valueType: "StructuredValue", + value: { + version: "1.0.0", + page_context_type: "srp_inline", + page_context_data: { query: "waterproof jackets" }, + }, + }); + }); +}); diff --git a/tests/shopper-agent-shim.test.tsx b/tests/shopper-agent-shim.test.tsx index 19cc533..c32489f 100644 --- a/tests/shopper-agent-shim.test.tsx +++ b/tests/shopper-agent-shim.test.tsx @@ -203,6 +203,131 @@ describe("ShopperAgentShim", () => { } }); + it("renders categoryQuestions as pills on a PLP page", () => { + render( + , + ); + expect(screen.getByRole("button", { name: "What's on sale?" })).toBeDefined(); + expect(screen.getByRole("button", { name: "Most popular?" })).toBeDefined(); + expect(screen.queryByRole("button", { name: "Should not appear" })).toBeNull(); + }); + + it("renders no pills on SRP page", () => { + render( + , + ); + expect(screen.queryByRole("list", { name: "Suggested questions" })).toBeNull(); + }); + + it("uses PLP placeholder when no productName", () => { + render( + , + ); + const textarea = screen.getByRole("textbox", { name: "Ask a question" }) as HTMLTextAreaElement; + expect(textarea.placeholder).toBe("Ask me about this category"); + }); + + it("uses SRP placeholder when no productName", () => { + render( + , + ); + const textarea = screen.getByRole("textbox", { name: "Ask a question" }) as HTMLTextAreaElement; + expect(textarea.placeholder).toBe("Ask me about these results"); + }); + + it("includes pageContextType and pageContextData in handoff event for PLP", () => { + const host = document.createElement("div"); + document.body.appendChild(host); + const handler = vi.fn(); + host.addEventListener(HANDOFF_EVENT, handler as EventListener); + + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: "What's on sale?" })); + + const detail = (handler.mock.calls[0][0] as CustomEvent).detail; + expect(detail.pageContextType).toBe("plp_inline"); + expect(detail.pageContextData).toEqual({ categoryName: "Men's Jackets" }); + }); + + it("includes pageContextType and pageContextData in handoff event for SRP", () => { + const host = document.createElement("div"); + document.body.appendChild(host); + const handler = vi.fn(); + host.addEventListener(HANDOFF_EVENT, handler as EventListener); + + render( + , + ); + const textarea = screen.getByRole("textbox", { name: "Ask a question" }); + fireEvent.change(textarea, { target: { value: "Any deals?" } }); + fireEvent.click(screen.getByRole("button", { name: "Send question" })); + + const detail = (handler.mock.calls[0][0] as CustomEvent).detail; + expect(detail.pageContextType).toBe("srp_inline"); + expect(detail.pageContextData).toEqual({ query: "waterproof jackets" }); + }); + + it("omits pageContext fields when PLP has no categoryId or categoryName", () => { + const host = document.createElement("div"); + document.body.appendChild(host); + const handler = vi.fn(); + host.addEventListener(HANDOFF_EVENT, handler as EventListener); + + render( + , + ); + fireEvent.click(screen.getByRole("button", { name: "Question?" })); + + const detail = (handler.mock.calls[0][0] as CustomEvent).detail; + expect(detail.pageContextType).toBeUndefined(); + expect(detail.pageContextData).toBeUndefined(); + }); + it("renderInto skips SCRT2 config validation in shopper-agent mode", async () => { // SCRT2 fields deliberately blank — the old guard would render a // "missing required config" error. With mode="shopper-agent" the shim