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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
77 changes: 72 additions & 5 deletions src/ShopperAgentShim.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
}

/**
Expand All @@ -33,16 +38,19 @@ export function ShopperAgentShim({
}) {
const [text, setText] = useState("");
const textareaRef = useRef<HTMLTextAreaElement>(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<HandoffEventDetail>(HANDOFF_EVENT, {
Expand Down Expand Up @@ -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 (
<div className="widget">
Expand Down Expand Up @@ -137,3 +142,65 @@ export function ShopperAgentShim({
</div>
);
}

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<HandoffEventDetail, "pageContextType" | "pageContextData"> {
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";
}
}
17 changes: 17 additions & 0 deletions src/custom-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"] {
Expand All @@ -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 {
Expand All @@ -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"),
};
}

Expand Down
85 changes: 63 additions & 22 deletions src/provider/WidgetProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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. */
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
38 changes: 37 additions & 1 deletion src/provider/product-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>;
suggestion_routing?: boolean;
}

Expand Down Expand Up @@ -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 },
},
];
}
25 changes: 25 additions & 0 deletions src/provider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <productName>"`. When unset, the InputBar falls
Expand Down
Loading
Loading