@sgflabs/storefront-core 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,3 +82,7 @@ single callback, with no Google Console change.
82
82
  - `NEXT_PUBLIC_BASE_URL` must be the exact public https origin of the app, and its proxy must send
83
83
  `x-forwarded-proto: https`. In this mode the handoff redeems for that configured host, never the `Host` header, so it works only for the
84
84
  exact host of `NEXT_PUBLIC_BASE_URL`: an alternate hostname that is also enabled as an SSO hub return origin will not work.
85
+
86
+ ## AI assistant (`AiChatWidget`)
87
+
88
+ Mount `AiChatWidget` from `components/organisms/AiChatWidget/AiChatWidget` in the app's root layout. It renders nothing unless the ai-interface base URL is set: `AI_INTERFACE_URL` at container runtime (mirrored to the browser through the root layout's `window.__STOREFRONT_ENV__` snapshot, like the other runtime keys) or `NEXT_PUBLIC_AI_INTERFACE_URL` at build. Guests get an anonymous per-tab identity; the ai-interface must allow the storefront's origin (its `CORS_ORIGIN`, or the vendor-storefront host lookup). Pass `className` to move the launcher clear of an app's own fixed bottom bars. The empty panel carries the DPDP notice (messages go to an AI service) with a link to `/<locale>/legal/privacy`, so the storefront must serve that legal page.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgflabs/storefront-core",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "Shared storefront library consumed as raw TypeScript source by the brand apps.",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "sideEffects": [
@@ -54,10 +54,10 @@
54
54
  },
55
55
  "devDependencies": {
56
56
  "@sentry/nextjs": "^10.63.0",
57
- "@sgflabs/artha-go-sdk": "^0.2.0",
58
- "@sgflabs/gstin": "^0.1.9",
59
- "@sgflabs/page-spec": "^0.1.9",
60
- "@sgflabs/storefront-core-common": "^0.1.9",
57
+ "@sgflabs/artha-go-sdk": "^0.3.0",
58
+ "@sgflabs/gstin": "^0.1.10",
59
+ "@sgflabs/page-spec": "^0.1.10",
60
+ "@sgflabs/storefront-core-common": "^0.1.10",
61
61
  "@testing-library/dom": "^10.4.1",
62
62
  "@testing-library/jest-dom": "^7.0.0",
63
63
  "@testing-library/react": "^16.3.2",
@@ -72,10 +72,10 @@
72
72
  },
73
73
  "peerDependencies": {
74
74
  "@sentry/nextjs": "^10.63.0",
75
- "@sgflabs/artha-go-sdk": "^0.2.0",
76
- "@sgflabs/gstin": "^0.1.9",
77
- "@sgflabs/page-spec": "^0.1.9",
78
- "@sgflabs/storefront-core-common": "^0.1.9",
75
+ "@sgflabs/artha-go-sdk": "^0.3.0",
76
+ "@sgflabs/gstin": "^0.1.10",
77
+ "@sgflabs/page-spec": "^0.1.10",
78
+ "@sgflabs/storefront-core-common": "^0.1.10",
79
79
  "next": "15.5.27",
80
80
  "react": "^19.2.3",
81
81
  "react-dom": "^19.2.3"
@@ -0,0 +1,256 @@
1
+ "use client"
2
+
3
+ import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react"
4
+ import Link from "next/link"
5
+ import { usePathname } from "next/navigation"
6
+ import { useEffect, useRef, useState } from "react"
7
+ import ReactMarkdown, { type Components } from "react-markdown"
8
+
9
+ import { CloseIcon, MessageIcon } from "../../../icons"
10
+ import { CHAT_MESSAGE_MAX_LENGTH, resolveAiInterfaceUrl } from "../../../lib/ai-chat/ai-chat-api"
11
+ import { type ChatMessage, useAiChat } from "../../../lib/ai-chat/use-ai-chat"
12
+ import { cn } from "../../../lib/utils"
13
+
14
+ const SUGGESTIONS = [
15
+ "What products do you have?",
16
+ "Help me find a product for my application",
17
+ "What are your best sellers?",
18
+ ]
19
+
20
+ // react-markdown already drops unsafe URL schemes (javascript:, data:) and
21
+ // never emits raw HTML; this only hardens how the allowed links open and
22
+ // keeps remote images out of the transcript.
23
+ const markdownComponents: Components = {
24
+ a: ({ href, children }) => (
25
+ <a href={href} target="_blank" rel="noopener noreferrer" className="underline">
26
+ {children}
27
+ </a>
28
+ ),
29
+ img: () => null,
30
+ }
31
+
32
+ function MessageBubble({ message }: { message: ChatMessage }) {
33
+ if (message.role === "notice") {
34
+ return (
35
+ <p className="mx-auto max-w-[90%] rounded-sm border px-3 py-2 text-center text-xs text-secondary">
36
+ {message.content}
37
+ </p>
38
+ )
39
+ }
40
+ const isUser = message.role === "user"
41
+ return (
42
+ <div className={cn("flex", isUser ? "justify-end" : "justify-start")}>
43
+ <div
44
+ className={cn(
45
+ "max-w-[85%] rounded-sm px-3 py-2 text-sm leading-relaxed break-words",
46
+ isUser
47
+ ? "bg-action text-action-on-primary whitespace-pre-wrap"
48
+ : "border bg-primary text-primary [&_ol]:list-decimal [&_ol]:pl-5 [&_p]:my-1 [&_ul]:list-disc [&_ul]:pl-5"
49
+ )}
50
+ data-testid={`ai-chat-message-${message.role}`}
51
+ >
52
+ {isUser ? (
53
+ message.content
54
+ ) : (
55
+ <ReactMarkdown components={markdownComponents}>{message.content}</ReactMarkdown>
56
+ )}
57
+ </div>
58
+ </div>
59
+ )
60
+ }
61
+
62
+ /**
63
+ * Headless UI's Dialog supplies the dialog basics (focus trap and initial
64
+ * focus, Escape and outside-click close, aria-modal, scroll lock, focus
65
+ * return to the launcher), same as the package's other modals.
66
+ */
67
+ function ChatPanel({ baseUrl, onClose }: { baseUrl: string; onClose: () => void }) {
68
+ const { messages, isLoading, error, sendMessage, cancelMessage, startNewChat, clearError } =
69
+ useAiChat(baseUrl)
70
+ const [input, setInput] = useState("")
71
+ const listRef = useRef<HTMLDivElement>(null)
72
+ const pathname = usePathname()
73
+ const locale = pathname?.split("/").filter(Boolean)[0] ?? "in"
74
+
75
+ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll to the newest line on every transcript change
76
+ useEffect(() => {
77
+ const list = listRef.current
78
+ if (list) {
79
+ list.scrollTop = list.scrollHeight
80
+ }
81
+ }, [messages, isLoading])
82
+
83
+ const handleSend = () => {
84
+ const text = input.trim()
85
+ if (!text || isLoading) {
86
+ return
87
+ }
88
+ setInput("")
89
+ clearError()
90
+ void sendMessage(text)
91
+ }
92
+
93
+ return (
94
+ <Dialog open onClose={onClose} className="relative z-[60]">
95
+ <DialogPanel
96
+ data-testid="ai-chat-panel"
97
+ className="fixed inset-0 flex flex-col bg-primary text-primary shadow-lg md:inset-auto md:bottom-6 md:right-6 md:h-[600px] md:max-h-[calc(100vh-3rem)] md:w-[400px] md:rounded-sm md:border"
98
+ >
99
+ <div className="flex items-center justify-between gap-2 border-b px-4 py-3">
100
+ <DialogTitle className="label-md uppercase">Assistant</DialogTitle>
101
+ <div className="flex items-center gap-3">
102
+ <button
103
+ type="button"
104
+ onClick={startNewChat}
105
+ className="text-xs text-secondary underline"
106
+ data-testid="ai-chat-new"
107
+ >
108
+ New chat
109
+ </button>
110
+ <button
111
+ type="button"
112
+ onClick={onClose}
113
+ aria-label="Close assistant"
114
+ data-testid="ai-chat-close"
115
+ >
116
+ <CloseIcon size={20} color="currentColor" />
117
+ </button>
118
+ </div>
119
+ </div>
120
+
121
+ <div
122
+ ref={listRef}
123
+ role="log"
124
+ aria-live="polite"
125
+ className="flex flex-1 flex-col gap-3 overflow-y-auto px-4 py-3"
126
+ >
127
+ {messages.length === 0 ? (
128
+ <div className="my-auto flex flex-col items-center gap-3 text-center">
129
+ <MessageIcon size={32} color="currentColor" />
130
+ <p className="text-sm text-secondary">
131
+ Ask about products, pricing, availability or anything in our catalogue.
132
+ </p>
133
+ <p className="text-xs text-secondary" data-testid="ai-chat-data-notice">
134
+ Messages are processed by an AI service. Please don&apos;t share personal details.{" "}
135
+ <Link href={`/${locale}/legal/privacy`} className="underline">
136
+ Privacy policy
137
+ </Link>
138
+ </p>
139
+ <div className="flex w-full flex-col gap-2">
140
+ {SUGGESTIONS.map((s) => (
141
+ <button
142
+ key={s}
143
+ type="button"
144
+ onClick={() => setInput(s)}
145
+ className="rounded-sm border px-3 py-2 text-left text-sm hover:bg-action-secondary-hover"
146
+ >
147
+ {s}
148
+ </button>
149
+ ))}
150
+ </div>
151
+ </div>
152
+ ) : (
153
+ messages.map((m) => <MessageBubble key={m.id} message={m} />)
154
+ )}
155
+ {isLoading && (
156
+ <p className="text-xs text-secondary" data-testid="ai-chat-typing">
157
+ Assistant is typing…
158
+ </p>
159
+ )}
160
+ </div>
161
+
162
+ {error && (
163
+ <div
164
+ role="alert"
165
+ className="mx-4 mb-2 flex items-start justify-between gap-2 rounded-sm border border-negative bg-negative-secondary px-3 py-2 text-xs text-negative"
166
+ >
167
+ <span>{error}</span>
168
+ <button type="button" onClick={clearError} aria-label="Dismiss error">
169
+ <CloseIcon size={14} color="currentColor" />
170
+ </button>
171
+ </div>
172
+ )}
173
+
174
+ <form
175
+ className="flex items-end gap-2 border-t px-3 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom,0px))]"
176
+ onSubmit={(e) => {
177
+ e.preventDefault()
178
+ handleSend()
179
+ }}
180
+ >
181
+ <textarea
182
+ autoFocus
183
+ value={input}
184
+ onChange={(e) => setInput(e.target.value)}
185
+ onKeyDown={(e) => {
186
+ if (e.key === "Enter" && !e.shiftKey) {
187
+ e.preventDefault()
188
+ handleSend()
189
+ }
190
+ }}
191
+ placeholder="Ask about products..."
192
+ aria-label="Message"
193
+ rows={1}
194
+ maxLength={CHAT_MESSAGE_MAX_LENGTH}
195
+ disabled={isLoading}
196
+ className="max-h-28 min-h-[40px] flex-1 resize-none rounded-sm border px-3 py-2 text-sm"
197
+ />
198
+ {isLoading ? (
199
+ <button
200
+ type="button"
201
+ onClick={cancelMessage}
202
+ className="rounded-sm border px-3 py-2 text-sm"
203
+ data-testid="ai-chat-stop"
204
+ >
205
+ Stop
206
+ </button>
207
+ ) : (
208
+ <button
209
+ type="submit"
210
+ disabled={!input.trim()}
211
+ className="rounded-sm bg-action px-3 py-2 text-sm text-action-on-primary disabled:bg-disabled disabled:text-disabled"
212
+ data-testid="ai-chat-send"
213
+ >
214
+ Send
215
+ </button>
216
+ )}
217
+ </form>
218
+ </DialogPanel>
219
+ </Dialog>
220
+ )
221
+ }
222
+
223
+ /**
224
+ * Floating AI assistant. Renders nothing unless AI_INTERFACE_URL (runtime) or
225
+ * NEXT_PUBLIC_AI_INTERFACE_URL (build) points at the artha-go ai-interface
226
+ * service; guests are allowed (anonymous per-tab identity).
227
+ *
228
+ * `className` positions the launcher: apps with their own fixed bottom bars
229
+ * (a sticky PDP action bar, a mini player) pass an offset for the pages that
230
+ * need it; the default sits in the bottom-right corner above page chrome.
231
+ */
232
+ export function AiChatWidget({ className }: { className?: string }) {
233
+ const [open, setOpen] = useState(false)
234
+ const baseUrl = resolveAiInterfaceUrl()
235
+ if (!baseUrl) {
236
+ return null
237
+ }
238
+
239
+ return (
240
+ <>
241
+ {open && <ChatPanel baseUrl={baseUrl} onClose={() => setOpen(false)} />}
242
+ <button
243
+ type="button"
244
+ onClick={() => setOpen(true)}
245
+ aria-label="Open assistant"
246
+ data-testid="ai-chat-launcher"
247
+ className={cn(
248
+ "fixed right-4 bottom-[calc(1.5rem+env(safe-area-inset-bottom,0px))] z-[60] flex h-14 w-14 items-center justify-center rounded-full bg-action text-action-on-primary shadow-lg hover:bg-action-hover md:right-6",
249
+ className
250
+ )}
251
+ >
252
+ <MessageIcon size={24} color="currentColor" />
253
+ </button>
254
+ </>
255
+ )
256
+ }
@@ -0,0 +1,305 @@
1
+ // Web port of apps/opticomm-mobile/lib/chat-api.ts. Transport is the SDK's
2
+ // `chat` namespace (artha-go `packages/artha-sdk/src/chat.ts`); this module
3
+ // owns only the client policy on top of it: retries, request timeout and the
4
+ // acknowledged poll loop.
5
+
6
+ import { AiInterfaceError, createChat } from "@sgflabs/artha-go-sdk"
7
+
8
+ import { readStorefrontRuntimePublic } from "../runtime/public-storefront-runtime-env"
9
+
10
+ /** Composer cap, the mobile app's convention; the service itself caps nothing shorter than the model context. */
11
+ export const CHAT_MESSAGE_MAX_LENGTH = 500
12
+ const REQUEST_TIMEOUT_MS = 15_000
13
+ const ENQUEUE_MAX_ATTEMPTS = 3
14
+ const ENQUEUE_BACKOFF_MS = 300
15
+ const DEFAULT_POLL_TIMEOUT_MS = 90_000
16
+ const DEFAULT_POLL_INTERVAL_MS = 1_000
17
+ const HTTP_FORBIDDEN = 403
18
+ const HTTP_REQUEST_TIMEOUT = 408
19
+ const HTTP_TOO_MANY_REQUESTS = 429
20
+ const HTTP_SERVER_ERROR_MIN = 500
21
+
22
+ export type { ChatReply } from "@sgflabs/artha-go-sdk"
23
+
24
+ import type { ChatReply } from "@sgflabs/artha-go-sdk"
25
+
26
+ export class ChatAbortedError extends Error {
27
+ constructor() {
28
+ super("Aborted")
29
+ this.name = "ChatAbortedError"
30
+ }
31
+ }
32
+
33
+ /**
34
+ * /api/chat/poll answered 403: the poll token is no longer known server-side.
35
+ * The message was already queued, and its tools (cart, order) may have run,
36
+ * so the turn is not resent: the buyer decides after checking.
37
+ */
38
+ export class ChatPollTokenInvalidError extends Error {
39
+ constructor() {
40
+ super(
41
+ "Your session expired before the reply arrived. Anything you asked for may still have gone through, so please check your cart before sending again."
42
+ )
43
+ this.name = "ChatPollTokenInvalidError"
44
+ }
45
+ }
46
+
47
+ /** Opaque 32-hex id. `randomUUID` exists only in secure contexts, so plain-http dev hosts take the second path. */
48
+ export function newMessageId() {
49
+ if (typeof crypto.randomUUID === "function") {
50
+ return crypto.randomUUID().replace(/-/g, "")
51
+ }
52
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) =>
53
+ b.toString(16).padStart(2, "0")
54
+ ).join("")
55
+ }
56
+
57
+ /**
58
+ * Base URL of the ai-interface service, or undefined when the widget must stay
59
+ * off. Fails closed on anything that is not an absolute http(s) URL so a
60
+ * mis-set variable cannot turn into a request to a relative path or a
61
+ * `javascript:` scheme.
62
+ */
63
+ export function resolveAiInterfaceUrl() {
64
+ const raw = readStorefrontRuntimePublic("NEXT_PUBLIC_AI_INTERFACE_URL")
65
+ if (!raw) {
66
+ return undefined
67
+ }
68
+ try {
69
+ const url = new URL(raw)
70
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
71
+ return undefined
72
+ }
73
+ return raw.replace(/\/+$/, "")
74
+ } catch {
75
+ return undefined
76
+ }
77
+ }
78
+
79
+ const chatClients = new Map<string, ReturnType<typeof createChat>>()
80
+
81
+ /** The SDK chat namespace for an ai-interface URL (runtime config, so not the shared `opticommSdk`). */
82
+ export function chatFor(aiInterfaceUrl: string) {
83
+ let chat = chatClients.get(aiInterfaceUrl)
84
+ if (!chat) {
85
+ chat = createChat(aiInterfaceUrl)
86
+ chatClients.set(aiInterfaceUrl, chat)
87
+ }
88
+ return chat
89
+ }
90
+
91
+ function isTransientStatus(status: number | undefined) {
92
+ return (
93
+ status === HTTP_REQUEST_TIMEOUT ||
94
+ status === HTTP_TOO_MANY_REQUESTS ||
95
+ (status !== undefined && status >= HTTP_SERVER_ERROR_MIN)
96
+ )
97
+ }
98
+
99
+ /** Network failure (fetch rejects with a TypeError), our own timeout (an AbortError), or a transient status. */
100
+ function isTransientError(err: unknown) {
101
+ if (err instanceof AiInterfaceError) {
102
+ return isTransientStatus(err.status)
103
+ }
104
+ return err instanceof TypeError || (err instanceof DOMException && err.name === "AbortError")
105
+ }
106
+
107
+ /** Waits `ms`, or less if `signal` aborts first. */
108
+ const sleep = (ms: number, signal?: AbortSignal) =>
109
+ new Promise<void>((resolve) => {
110
+ const timer = setTimeout(() => {
111
+ signal?.removeEventListener("abort", onAbort)
112
+ resolve()
113
+ }, ms)
114
+ function onAbort() {
115
+ clearTimeout(timer)
116
+ resolve()
117
+ }
118
+ signal?.addEventListener("abort", onAbort, { once: true })
119
+ })
120
+
121
+ /** Runs one SDK call with the request timeout, mapping the caller's abort to ChatAbortedError. */
122
+ async function withTimeout<T>(call: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal) {
123
+ if (signal?.aborted) {
124
+ throw new ChatAbortedError()
125
+ }
126
+ const controller = new AbortController()
127
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
128
+ const onAbort = () => controller.abort()
129
+ signal?.addEventListener("abort", onAbort)
130
+ try {
131
+ return await call(controller.signal)
132
+ } catch (err) {
133
+ if (signal?.aborted) {
134
+ throw new ChatAbortedError()
135
+ }
136
+ throw err
137
+ } finally {
138
+ clearTimeout(timer)
139
+ signal?.removeEventListener("abort", onAbort)
140
+ }
141
+ }
142
+
143
+ export async function enqueueChat(
144
+ baseUrl: string,
145
+ userId: string,
146
+ message: string,
147
+ messageId: string,
148
+ previousPollToken: string | undefined,
149
+ signal?: AbortSignal
150
+ ) {
151
+ const body = {
152
+ user_id: userId,
153
+ message,
154
+ provider: "web" as const,
155
+ time: Date.now(),
156
+ // ai-interface round-trips `extra.messageId`, which lets the poll reject
157
+ // replies to earlier turns. (It strips any client-sent conversation sid.)
158
+ extra: { messageId },
159
+ // Proves this caller owns the active session for userId.
160
+ poll_token: previousPollToken,
161
+ }
162
+ const chat = chatFor(baseUrl)
163
+ let lastError: unknown
164
+ for (let attempt = 0; attempt < ENQUEUE_MAX_ATTEMPTS; attempt += 1) {
165
+ try {
166
+ const { poll_token } = await withTimeout((s) => chat.enqueue(body, { signal: s }), signal)
167
+ return { pollToken: poll_token }
168
+ } catch (err) {
169
+ if (!isTransientError(err)) {
170
+ throw err
171
+ }
172
+ lastError = err
173
+ // Back off so three attempts do not re-hit the enqueue throttle at once.
174
+ await sleep(ENQUEUE_BACKOFF_MS * 2 ** attempt, signal)
175
+ }
176
+ }
177
+ throw lastError
178
+ }
179
+
180
+ /**
181
+ * `lastMessageId` is the reply this caller already holds: the cursor that makes
182
+ * delivery acknowledged rather than destructive. Sending it keeps the reply in
183
+ * the server's inbox until it is named, so a response lost in flight is
184
+ * re-delivered on the next poll instead of dropped with the turn.
185
+ */
186
+ export async function pollForReply(
187
+ baseUrl: string,
188
+ userId: string,
189
+ pollToken: string,
190
+ expectedMessageId: string,
191
+ {
192
+ timeoutMs = DEFAULT_POLL_TIMEOUT_MS,
193
+ intervalMs = DEFAULT_POLL_INTERVAL_MS,
194
+ signal,
195
+ lastMessageId = "",
196
+ }: {
197
+ timeoutMs?: number
198
+ intervalMs?: number
199
+ signal?: AbortSignal
200
+ lastMessageId?: string
201
+ } = {}
202
+ ) {
203
+ const chat = chatFor(baseUrl)
204
+ const pollOnce = (cursor: string) =>
205
+ withTimeout(
206
+ (s) =>
207
+ chat.poll(
208
+ { user_id: userId, poll_token: pollToken, last_message_id: cursor },
209
+ { signal: s }
210
+ ),
211
+ signal
212
+ )
213
+ let cursor = lastMessageId
214
+ // The cursor the most recent request actually carried; see the flush below.
215
+ let sentCursor = lastMessageId
216
+ const deadline = Date.now() + timeoutMs
217
+ while (Date.now() < deadline) {
218
+ if (signal?.aborted) {
219
+ throw new ChatAbortedError()
220
+ }
221
+ await sleep(intervalMs, signal)
222
+ if (signal?.aborted) {
223
+ throw new ChatAbortedError()
224
+ }
225
+ sentCursor = cursor
226
+ let body: ChatReply | null
227
+ try {
228
+ body = await pollOnce(cursor)
229
+ } catch (err) {
230
+ if (err instanceof AiInterfaceError && err.status === HTTP_FORBIDDEN) {
231
+ throw new ChatPollTokenInvalidError()
232
+ }
233
+ if (isTransientError(err)) {
234
+ continue
235
+ }
236
+ throw err
237
+ }
238
+ if (!body || body.message === undefined) {
239
+ continue
240
+ }
241
+ if (typeof body.message !== "string") {
242
+ throw new Error("Chat returned non-string message")
243
+ }
244
+ if (body.extra?.messageId !== expectedMessageId) {
245
+ // A reply to an earlier turn. Acknowledge it so it stops heading the
246
+ // inbox, otherwise every later poll returns it again.
247
+ if (typeof body.message_id === "string" && body.message_id !== "") {
248
+ cursor = body.message_id
249
+ }
250
+ continue
251
+ }
252
+ return body
253
+ }
254
+ // A stale reply learned on the last pass advanced the cursor with no request
255
+ // left to carry it. Flush it once, best effort, so it does not stall the
256
+ // next turn too.
257
+ if (cursor !== sentCursor && !signal?.aborted) {
258
+ try {
259
+ await pollOnce(cursor)
260
+ } catch {
261
+ // The next turn re-acknowledges what this missed.
262
+ }
263
+ }
264
+ throw new Error("Chat timed out — please try again")
265
+ }
266
+
267
+ /**
268
+ * `onEnqueued` fires with each poll token the service mints, before polling
269
+ * starts. Every enqueue rotates the token and the service accepts only the
270
+ * current or previous one, so a caller that persists the token only after the
271
+ * reply loses the session after two stopped turns in a row.
272
+ */
273
+ export async function completeChatTurn(
274
+ baseUrl: string,
275
+ userId: string,
276
+ message: string,
277
+ messageId: string,
278
+ previousPollToken: string | undefined,
279
+ signal?: AbortSignal,
280
+ pollOptions?: {
281
+ timeoutMs?: number
282
+ intervalMs?: number
283
+ lastMessageId?: string
284
+ onEnqueued?: (pollToken: string) => void
285
+ }
286
+ ) {
287
+ const { pollToken } = await enqueueChat(
288
+ baseUrl,
289
+ userId,
290
+ message,
291
+ messageId,
292
+ previousPollToken,
293
+ signal
294
+ )
295
+ pollOptions?.onEnqueued?.(pollToken)
296
+ // A poll 403 is not retried by re-enqueueing: the queued turn may already
297
+ // have run its tools, and the state that would let the service replay it
298
+ // (replay key, BullMQ job id) lives in the same store whose loss causes
299
+ // the 403. ChatPollTokenInvalidError tells the buyer to check first.
300
+ const reply = await pollForReply(baseUrl, userId, pollToken, messageId, {
301
+ ...pollOptions,
302
+ signal,
303
+ })
304
+ return { pollToken, reply }
305
+ }
@@ -0,0 +1,194 @@
1
+ "use client"
2
+
3
+ // Web port of apps/opticomm-mobile/context/chat-context.tsx. One hook instead
4
+ // of a provider: the widget is mounted once per page. Identity lives in
5
+ // sessionStorage (per tab, gone when the tab closes), so a guest's
6
+ // conversation never outlives their visit and never follows another person
7
+ // using the same browser profile.
8
+
9
+ import { AiInterfaceError } from "@sgflabs/artha-go-sdk"
10
+ import { useCallback, useRef, useState } from "react"
11
+
12
+ import * as chatApi from "./ai-chat-api"
13
+
14
+ export type ChatMessage = {
15
+ // 'notice' is a client-side system line (the identity reset below), never a
16
+ // turn sent to or from the model.
17
+ role: "user" | "assistant" | "notice"
18
+ content: string
19
+ id: string
20
+ }
21
+
22
+ /**
23
+ * `lastReplyId` is the reply this tab already took delivery of: the cursor the
24
+ * poll acknowledges with. It belongs with the identity because it is scoped to
25
+ * `userId`'s inbox; a reset identity starts with an empty one.
26
+ */
27
+ type ChatIdentity = {
28
+ userId: string
29
+ pollToken?: string
30
+ lastReplyId?: string
31
+ }
32
+
33
+ export const CHAT_IDENTITY_KEY = "ai_chat_identity"
34
+
35
+ export const IDENTITY_RESET_NOTICE =
36
+ "Your session expired, so the conversation context was reset. Earlier messages are still shown, but the assistant no longer remembers them."
37
+
38
+ // sessionStorage can throw (private mode, blocked storage). Fall back to this
39
+ // tab's memory so the chat still works for the page's lifetime.
40
+ let memoryIdentity: ChatIdentity | undefined
41
+
42
+ function readIdentity(): ChatIdentity | undefined {
43
+ try {
44
+ const stored = window.sessionStorage.getItem(CHAT_IDENTITY_KEY)
45
+ if (!stored) {
46
+ return memoryIdentity
47
+ }
48
+ const parsed: unknown = JSON.parse(stored)
49
+ if (
50
+ parsed &&
51
+ typeof parsed === "object" &&
52
+ typeof (parsed as ChatIdentity).userId === "string"
53
+ ) {
54
+ return parsed as ChatIdentity
55
+ }
56
+ } catch {
57
+ // Unreadable or unparsable: treat as absent.
58
+ }
59
+ return memoryIdentity
60
+ }
61
+
62
+ function writeIdentity(identity: ChatIdentity | undefined): void {
63
+ memoryIdentity = identity
64
+ try {
65
+ if (identity) {
66
+ window.sessionStorage.setItem(CHAT_IDENTITY_KEY, JSON.stringify(identity))
67
+ } else {
68
+ window.sessionStorage.removeItem(CHAT_IDENTITY_KEY)
69
+ }
70
+ } catch {
71
+ // Memory copy above is the fallback.
72
+ }
73
+ }
74
+
75
+ function getOrCreateIdentity(): ChatIdentity {
76
+ const existing = readIdentity()
77
+ if (existing) {
78
+ return existing
79
+ }
80
+ const identity = { userId: chatApi.newMessageId() }
81
+ writeIdentity(identity)
82
+ return identity
83
+ }
84
+
85
+ export function useAiChat(baseUrl: string) {
86
+ const [messages, setMessages] = useState<ChatMessage[]>([])
87
+ const [isLoading, setIsLoading] = useState(false)
88
+ const [error, setError] = useState<string | null>(null)
89
+ const sendAbortRef = useRef<AbortController | null>(null)
90
+
91
+ const sendMessage = useCallback(
92
+ async (content: string) => {
93
+ sendAbortRef.current?.abort()
94
+ const controller = new AbortController()
95
+ sendAbortRef.current = controller
96
+ const messageId = chatApi.newMessageId()
97
+ const dropOptimistic = () => setMessages((prev) => prev.filter((m) => m.id !== messageId))
98
+
99
+ try {
100
+ setIsLoading(true)
101
+ setError(null)
102
+ setMessages((prev) => [...prev, { role: "user", content, id: messageId }])
103
+
104
+ let identity = getOrCreateIdentity()
105
+ // Persist each minted token at once: see completeChatTurn's onEnqueued.
106
+ const keepToken = (pollToken: string) => {
107
+ // New chat mid-enqueue already dropped this identity; do not write it back.
108
+ if (controller.signal.aborted) {
109
+ return
110
+ }
111
+ identity = { ...identity, pollToken }
112
+ writeIdentity(identity)
113
+ }
114
+ let turn: Awaited<ReturnType<typeof chatApi.completeChatTurn>>
115
+ try {
116
+ turn = await chatApi.completeChatTurn(
117
+ baseUrl,
118
+ identity.userId,
119
+ content,
120
+ messageId,
121
+ identity.pollToken,
122
+ controller.signal,
123
+ { lastMessageId: identity.lastReplyId ?? "", onEnqueued: keepToken }
124
+ )
125
+ } catch (err) {
126
+ if (!(err instanceof AiInterfaceError) || err.status !== 403) {
127
+ throw err
128
+ }
129
+ // Neither the current nor the previous poll token matches: the
130
+ // service no longer knows this identity. Re-enqueueing it would 403
131
+ // forever, so mint a fresh one and say so in the transcript.
132
+ writeIdentity(undefined)
133
+ identity = getOrCreateIdentity()
134
+ setMessages((prev) => [
135
+ ...prev,
136
+ { role: "notice", content: IDENTITY_RESET_NOTICE, id: `${messageId}:identity-reset` },
137
+ ])
138
+ turn = await chatApi.completeChatTurn(
139
+ baseUrl,
140
+ identity.userId,
141
+ content,
142
+ messageId,
143
+ undefined,
144
+ controller.signal,
145
+ { lastMessageId: "", onEnqueued: keepToken }
146
+ )
147
+ }
148
+ writeIdentity({
149
+ ...identity,
150
+ pollToken: turn.pollToken,
151
+ lastReplyId: turn.reply.message_id,
152
+ })
153
+ if (controller.signal.aborted) {
154
+ return
155
+ }
156
+ setMessages((prev) => [
157
+ ...prev,
158
+ { role: "assistant", content: turn.reply.message, id: turn.reply.message_id },
159
+ ])
160
+ } catch (err) {
161
+ dropOptimistic()
162
+ if (controller.signal.aborted) {
163
+ return
164
+ }
165
+ setError(err instanceof Error ? err.message : "Failed to send message")
166
+ } finally {
167
+ if (sendAbortRef.current === controller) {
168
+ sendAbortRef.current = null
169
+ setIsLoading(false)
170
+ }
171
+ }
172
+ },
173
+ [baseUrl]
174
+ )
175
+
176
+ const cancelMessage = useCallback(() => {
177
+ sendAbortRef.current?.abort()
178
+ }, [])
179
+
180
+ // Drops the persisted identity too, so the service starts a fresh thread
181
+ // instead of resuming the one tied to the old userId.
182
+ const startNewChat = useCallback(() => {
183
+ sendAbortRef.current?.abort()
184
+ sendAbortRef.current = null
185
+ writeIdentity(undefined)
186
+ setMessages([])
187
+ setError(null)
188
+ setIsLoading(false)
189
+ }, [])
190
+
191
+ const clearError = useCallback(() => setError(null), [])
192
+
193
+ return { messages, isLoading, error, sendMessage, cancelMessage, startNewChat, clearError }
194
+ }
@@ -16,6 +16,8 @@ export type StorefrontPublicRuntimeSnapshot = {
16
16
  NEXT_PUBLIC_ENABLE_COOKIE_CONSENT?: string
17
17
  /** Browse panel vocabulary: `applications` (default) or `categories-collections` (Davison). */
18
18
  NEXT_PUBLIC_BROWSE_NAV_MODE?: string
19
+ /** artha-go ai-interface base URL; the AI chat widget renders nothing when unset. */
20
+ NEXT_PUBLIC_AI_INTERFACE_URL?: string
19
21
  }
20
22
 
21
23
  declare global {
@@ -78,6 +80,12 @@ export function buildStorefrontRuntimeEnvSnapshot(): StorefrontPublicRuntimeSnap
78
80
  if (browseNavMode !== undefined) {
79
81
  snapshot.NEXT_PUBLIC_BROWSE_NAV_MODE = browseNavMode
80
82
  }
83
+ const aiInterfaceUrl =
84
+ optionalTrim(process.env.AI_INTERFACE_URL) ??
85
+ optionalTrim(process.env.NEXT_PUBLIC_AI_INTERFACE_URL)
86
+ if (aiInterfaceUrl !== undefined) {
87
+ snapshot.NEXT_PUBLIC_AI_INTERFACE_URL = aiInterfaceUrl
88
+ }
81
89
  return snapshot
82
90
  }
83
91
 
@@ -143,6 +151,12 @@ export function readStorefrontRuntimePublic(
143
151
  optionalTrim(process.env.NEXT_PUBLIC_BROWSE_NAV_MODE)
144
152
  )
145
153
  }
154
+ if (publicKey === "NEXT_PUBLIC_AI_INTERFACE_URL") {
155
+ return (
156
+ optionalTrim(process.env.AI_INTERFACE_URL) ??
157
+ optionalTrim(process.env.NEXT_PUBLIC_AI_INTERFACE_URL)
158
+ )
159
+ }
146
160
  return optionalTrim(
147
161
  process.env[publicKey as keyof NodeJS.ProcessEnv] as string | undefined
148
162
  )