@surfaces-ui/chat 0.0.0-stage → 0.3.0

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.
Files changed (61) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +43 -2
  4. package/dist/AnalyticsChat.d.ts +82 -0
  5. package/dist/AnalyticsChat.js +168 -0
  6. package/dist/AnalyticsChat.js.map +1 -0
  7. package/dist/Approval.d.ts +18 -0
  8. package/dist/Approval.js +116 -0
  9. package/dist/Approval.js.map +1 -0
  10. package/dist/Chat.d.ts +112 -0
  11. package/dist/Chat.js +119 -0
  12. package/dist/Chat.js.map +1 -0
  13. package/dist/ChatComposer.d.ts +117 -0
  14. package/dist/ChatComposer.js +186 -0
  15. package/dist/ChatComposer.js.map +1 -0
  16. package/dist/ChatPanels.d.ts +34 -0
  17. package/dist/ChatPanels.js +75 -0
  18. package/dist/ChatPanels.js.map +1 -0
  19. package/dist/DataPanel.d.ts +19 -0
  20. package/dist/DataPanel.js +20 -0
  21. package/dist/DataPanel.js.map +1 -0
  22. package/dist/Menu.d.ts +37 -0
  23. package/dist/Menu.js +85 -0
  24. package/dist/Menu.js.map +1 -0
  25. package/dist/PageStudio.d.ts +103 -0
  26. package/dist/PageStudio.js +166 -0
  27. package/dist/PageStudio.js.map +1 -0
  28. package/dist/SessionList.d.ts +64 -0
  29. package/dist/SessionList.js +225 -0
  30. package/dist/SessionList.js.map +1 -0
  31. package/dist/appComponents.d.ts +6 -0
  32. package/dist/appComponents.js +100 -0
  33. package/dist/appComponents.js.map +1 -0
  34. package/dist/conversation.d.ts +66 -0
  35. package/dist/conversation.js +119 -0
  36. package/dist/conversation.js.map +1 -0
  37. package/dist/icons.d.ts +33 -0
  38. package/dist/icons.js +34 -0
  39. package/dist/icons.js.map +1 -0
  40. package/dist/index.d.ts +18 -0
  41. package/dist/index.js +19 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/selectors.d.ts +106 -0
  44. package/dist/selectors.js +160 -0
  45. package/dist/selectors.js.map +1 -0
  46. package/dist/sessions.d.ts +71 -0
  47. package/dist/sessions.js +194 -0
  48. package/dist/sessions.js.map +1 -0
  49. package/dist/speech.d.ts +43 -0
  50. package/dist/speech.js +89 -0
  51. package/dist/speech.js.map +1 -0
  52. package/dist/thread.d.ts +199 -0
  53. package/dist/thread.js +225 -0
  54. package/dist/thread.js.map +1 -0
  55. package/dist/useChat.d.ts +121 -0
  56. package/dist/useChat.js +293 -0
  57. package/dist/useChat.js.map +1 -0
  58. package/dist/voice.d.ts +41 -0
  59. package/dist/voice.js +128 -0
  60. package/dist/voice.js.map +1 -0
  61. package/package.json +72 -3
@@ -0,0 +1,116 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { CONFIRM_WORD, approvalDigest } from "@surfaces-ui/agent";
3
+ import { CodeBlock, SqlEditor } from "@surfaces-ui/components";
4
+ import { useEffect, useId, useState } from "react";
5
+ const RISK_WORD = { low: "Low risk", high: "High risk", irreversible: "Cannot be undone", "": "" };
6
+ const when = (iso) => {
7
+ const time = Date.parse(iso);
8
+ return Number.isNaN(time) ? iso : new Date(time).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
9
+ };
10
+ const decision = (d) => `${d.allow ? "Allowed" : "Declined"} by ${d.by?.name || d.by?.id || "you"}${d.at ? `, ${when(d.at)}` : ""}${d.reason ? `: “${d.reason}”` : ""}`;
11
+ /** Checks that the request's digest matches the SQL and subject the card shows. */
12
+ function useDigestCheck(approval) {
13
+ const [state, setState] = useState(approval.digest ? "checking" : "ok");
14
+ useEffect(() => {
15
+ if (!approval.digest)
16
+ return setState("ok");
17
+ let live = true;
18
+ void approvalDigest({ sql: approval.sql, subject: approval.subject }).then((digest) => live && setState(digest === approval.digest ? "ok" : "mismatch"));
19
+ return () => {
20
+ live = false;
21
+ };
22
+ }, [approval.digest, approval.sql, approval.subject]);
23
+ return state;
24
+ }
25
+ /** Whether `expiresAt` has passed, updating when it does. */
26
+ function useExpired(expiresAt, now) {
27
+ const deadline = expiresAt ? Date.parse(expiresAt) : Number.NaN;
28
+ const [expired, setExpired] = useState(() => !Number.isNaN(deadline) && deadline <= now());
29
+ useEffect(() => {
30
+ if (Number.isNaN(deadline))
31
+ return;
32
+ const left = deadline - now();
33
+ if (left <= 0)
34
+ return setExpired(true);
35
+ setExpired(false);
36
+ // Timers longer than this overflow; a page open that long checks again on the next render.
37
+ const timer = setTimeout(() => setExpired(true), Math.min(left, 2 ** 31 - 1));
38
+ return () => clearTimeout(timer);
39
+ }, [deadline, now]);
40
+ return expired;
41
+ }
42
+ /**
43
+ * A question the agent is waiting on: allow or deny, pick an option, or type
44
+ * an answer. For a permission it shows what exactly is asked (SQL and a
45
+ * structured subject), what it was based on, how risky it is and when it
46
+ * expires; it can take a reason, let the person edit before approving,
47
+ * require typing "confirm" for what cannot be undone, and show who has
48
+ * already decided when several people must. It refuses to offer approval
49
+ * when the request does not match its own digest, and once it has expired.
50
+ */
51
+ export function ApprovalCard({ approval, onAnswer, now = Date.now }) {
52
+ const id = useId();
53
+ const digest = useDigestCheck(approval);
54
+ const expired = useExpired(approval.expiresAt, now);
55
+ const [text, setText] = useState("");
56
+ const [reason, setReason] = useState("");
57
+ const [confirm, setConfirm] = useState("");
58
+ const [editing, setEditing] = useState(false);
59
+ const [sql, setSql] = useState(approval.sql);
60
+ const [subject, setSubject] = useState(approval.subject ? JSON.stringify(approval.subject, null, 2) : "");
61
+ const [error, setError] = useState("");
62
+ const answered = approval.answer;
63
+ const irreversible = approval.risk === "irreversible";
64
+ const needed = approval.approvalsRequired;
65
+ const reply = (allow, answer = "") => {
66
+ if (approval.reasonRequired && !reason.trim()) {
67
+ setError("Give a reason first.");
68
+ return undefined;
69
+ }
70
+ const base = { allow, text: answer, reason };
71
+ if (!allow || !editing)
72
+ return base;
73
+ let editedSubject;
74
+ if (approval.subject) {
75
+ try {
76
+ const parsed = JSON.parse(subject);
77
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
78
+ throw new Error("not an object");
79
+ editedSubject = parsed;
80
+ }
81
+ catch {
82
+ setError("The edited details are not a JSON object.");
83
+ return undefined;
84
+ }
85
+ }
86
+ return {
87
+ ...base,
88
+ ...(sql !== approval.sql ? { editedSql: sql } : {}),
89
+ ...(editedSubject && JSON.stringify(editedSubject) !== JSON.stringify(approval.subject) ? { editedSubject } : {}),
90
+ };
91
+ };
92
+ const submit = (allow, answer = "") => {
93
+ setError("");
94
+ if (allow && irreversible && confirm.trim().toLowerCase() !== CONFIRM_WORD) {
95
+ setError(`Type “${CONFIRM_WORD}” to allow something that cannot be undone.`);
96
+ return;
97
+ }
98
+ const r = reply(allow, answer);
99
+ if (r)
100
+ onAnswer(approval.id, r);
101
+ };
102
+ const onSubmitInput = (event) => {
103
+ event.preventDefault();
104
+ if (text.trim())
105
+ submit(true, text.trim());
106
+ };
107
+ const blocked = digest === "mismatch" || expired;
108
+ return (_jsxs("section", { className: "sf-chat-approval", "aria-label": approval.title, "data-answered": answered ? "" : undefined, "data-risk": approval.risk || undefined, children: [_jsx("p", { className: "sf-chat-approval-title", children: approval.title }), (approval.risk || needed > 1) && (_jsxs("p", { className: "sf-chat-approval-tags", children: [approval.risk && (_jsx("span", { className: "sf-a2-badge", "data-tone": approval.risk === "low" ? "neutral" : approval.risk === "high" ? "warning" : "danger", children: RISK_WORD[approval.risk] })), needed > 1 && _jsx("span", { className: "sf-a2-badge", "data-tone": "neutral", children: `Needs ${needed} people` })] })), approval.detail && _jsx("p", { className: "sf-chat-approval-detail", children: approval.detail }), approval.basis && _jsxs("p", { className: "sf-chat-approval-detail", children: ["Based on: ", approval.basis] }), editing && !answered ? (_jsxs(_Fragment, { children: [approval.sql && (_jsxs("div", { className: "sf-chat-approval-field", children: [_jsx("span", { "aria-hidden": "true", children: "SQL" }), _jsx(SqlEditor, { value: sql, onChange: setSql, label: "SQL", minHeight: 80, maxHeight: 320 })] })), approval.subject && (_jsxs("label", { className: "sf-chat-approval-field", children: [_jsx("span", { children: "Details (JSON)" }), _jsx("textarea", { className: "sf-input", value: subject, spellCheck: false, rows: Math.min(14, subject.split("\n").length + 1), onChange: (e) => setSubject(e.target.value) })] }))] })) : (_jsxs(_Fragment, { children: [(answered?.editedSql ?? approval.sql) && _jsx(CodeBlock, { code: answered?.editedSql ?? approval.sql, language: "sql", label: answered?.editedSql !== undefined ? "SQL, as edited" : "SQL" }), (answered?.editedSubject ?? approval.subject) && (_jsx(CodeBlock, { code: JSON.stringify(answered?.editedSubject ?? approval.subject, null, 2), language: "json", label: answered?.editedSubject ? "Details, as edited" : "Details" }))] })), approval.approvals.length > 0 && (_jsx("ul", { className: "sf-chat-approval-record", "aria-label": "Decisions so far", children: approval.approvals.map((d, i) => (_jsx("li", { children: decision(d) }, `${d.by?.id ?? ""}-${i}`))) })), answered ? (_jsxs("p", { className: "sf-chat-approval-detail", role: "status", children: [approval.kind === "permission" ? decision(answered) : `${answered.by?.name ? `${answered.by.name} answered` : "You answered"}: ${answered.text}`, answered.editedSql !== undefined || answered.editedSubject ? " (edited before approving)" : ""] })) : digest === "mismatch" ? (_jsx("p", { className: "sf-chat-error", role: "alert", children: "This request does not match its own contents, so it cannot be approved. Ask the agent to send it again." })) : expired ? (_jsxs("p", { className: "sf-chat-error", role: "alert", children: ["This request expired ", when(approval.expiresAt), ". Ask the agent again so it is checked against the data as it is now."] })) : (_jsxs(_Fragment, { children: [approval.expiresAt && _jsxs("p", { className: "sf-chat-approval-detail", children: ["Expires ", when(approval.expiresAt), "."] }), (approval.kind === "permission" || approval.reasonRequired) && (_jsxs("label", { className: "sf-chat-approval-field", children: [_jsx("span", { children: approval.reasonRequired ? "Reason (required)" : "Reason (optional)" }), _jsx("input", { className: "sf-input", value: reason, onChange: (e) => setReason(e.target.value), "aria-required": approval.reasonRequired || undefined })] })), approval.kind === "permission" && irreversible && (_jsxs("label", { className: "sf-chat-approval-field", children: [_jsx("span", { children: `Type “${CONFIRM_WORD}” to allow` }), _jsx("input", { className: "sf-input", value: confirm, onChange: (e) => setConfirm(e.target.value), autoComplete: "off" })] })), error && (_jsx("p", { className: "sf-chat-error", role: "alert", children: error })), approval.kind === "permission" ? (_jsxs("div", { className: "sf-chat-approval-actions", children: [_jsx("button", { type: "button", className: "sf-button", "data-variant": "primary", disabled: blocked || digest === "checking", onClick: () => submit(true), children: editing ? "Allow my version" : "Allow" }), _jsx("button", { type: "button", className: "sf-button", onClick: () => submit(false), children: "Deny" }), approval.editable && (_jsx("button", { type: "button", className: "sf-button", "aria-pressed": editing, onClick: () => {
109
+ if (editing) {
110
+ setSql(approval.sql);
111
+ setSubject(approval.subject ? JSON.stringify(approval.subject, null, 2) : "");
112
+ }
113
+ setEditing(!editing);
114
+ }, children: editing ? "Undo my edits" : "Edit before allowing" }))] })) : approval.kind === "choice" ? (_jsx("div", { className: "sf-chat-approval-actions", children: approval.options.map((option) => (_jsx("button", { type: "button", className: "sf-button", onClick: () => submit(true, option), children: option }, option))) })) : (_jsxs("form", { className: "sf-chat-approval-actions", onSubmit: onSubmitInput, children: [_jsx("label", { className: "sf-a2-visually-hidden", htmlFor: id, children: "Your answer" }), _jsx("input", { id: id, className: "sf-input", value: text, onChange: (e) => setText(e.target.value) }), _jsx("button", { type: "submit", className: "sf-button", "data-variant": "primary", children: "Send" })] }))] }))] }));
115
+ }
116
+ //# sourceMappingURL=Approval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Approval.js","sourceRoot":"","sources":["../src/Approval.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAkB,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAWnE,MAAM,SAAS,GAAyC,EAAE,GAAG,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW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K,SAAS,EAAC,0BAA0B,YACtC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAChC,iBAAqB,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,WAAW,EAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,YACzF,MAAM,IADI,MAAM,CAEV,CACV,CAAC,GACE,CACP,CAAC,CAAC,CAAC,CACF,gBAAM,SAAS,EAAC,0BAA0B,EAAC,QAAQ,EAAE,aAAa,aAChE,gBAAO,SAAS,EAAC,uBAAuB,EAAC,OAAO,EAAE,EAAE,4BAE5C,EACR,gBAAO,EAAE,EAAE,EAAE,EAAE,SAAS,EAAC,UAAU,EAAC,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAI,EAC7F,iBAAQ,IAAI,EAAC,QAAQ,EAAC,SAAS,EAAC,WAAW,kBAAc,SAAS,qBAEzD,IACJ,CACR,IACA,CACJ,IACO,CACX,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonObject } from \"@bufbuild/protobuf\";\nimport { CONFIRM_WORD, approvalDigest } from \"@surfaces-ui/agent\";\nimport { CodeBlock, SqlEditor } from \"@surfaces-ui/components\";\nimport { type FormEvent, useEffect, useId, useState } from \"react\";\nimport type { ChatApproval, ChatDecision } from \"./thread.js\";\nimport type { ApprovalReply } from \"./useChat.js\";\n\nexport interface ApprovalCardProps {\n approval: ChatApproval;\n onAnswer(id: string, reply: ApprovalReply): void;\n /** The time to check expiry against; for tests. Defaults to the clock. */\n now?: () => number;\n}\n\nconst RISK_WORD: Record<ChatApproval[\"risk\"], string> = { low: \"Low risk\", high: \"High risk\", irreversible: \"Cannot be undone\", \"\": \"\" };\n\nconst when = (iso: string) => {\n const time = Date.parse(iso);\n return Number.isNaN(time) ? iso : new Date(time).toLocaleString(undefined, { dateStyle: \"medium\", timeStyle: \"short\" });\n};\n\nconst decision = (d: ChatDecision) => `${d.allow ? \"Allowed\" : \"Declined\"} by ${d.by?.name || d.by?.id || \"you\"}${d.at ? `, ${when(d.at)}` : \"\"}${d.reason ? `: “${d.reason}”` : \"\"}`;\n\n/** Checks that the request's digest matches the SQL and subject the card shows. */\nfunction useDigestCheck(approval: ChatApproval): \"checking\" | \"ok\" | \"mismatch\" {\n const [state, setState] = useState<\"checking\" | \"ok\" | \"mismatch\">(approval.digest ? \"checking\" : \"ok\");\n useEffect(() => {\n if (!approval.digest) return setState(\"ok\");\n let live = true;\n void approvalDigest({ sql: approval.sql, subject: approval.subject }).then((digest) => live && setState(digest === approval.digest ? \"ok\" : \"mismatch\"));\n return () => {\n live = false;\n };\n }, [approval.digest, approval.sql, approval.subject]);\n return state;\n}\n\n/** Whether `expiresAt` has passed, updating when it does. */\nfunction useExpired(expiresAt: string, now: () => number): boolean {\n const deadline = expiresAt ? Date.parse(expiresAt) : Number.NaN;\n const [expired, setExpired] = useState(() => !Number.isNaN(deadline) && deadline <= now());\n useEffect(() => {\n if (Number.isNaN(deadline)) return;\n const left = deadline - now();\n if (left <= 0) return setExpired(true);\n setExpired(false);\n // Timers longer than this overflow; a page open that long checks again on the next render.\n const timer = setTimeout(() => setExpired(true), Math.min(left, 2 ** 31 - 1));\n return () => clearTimeout(timer);\n }, [deadline, now]);\n return expired;\n}\n\n/**\n * A question the agent is waiting on: allow or deny, pick an option, or type\n * an answer. For a permission it shows what exactly is asked (SQL and a\n * structured subject), what it was based on, how risky it is and when it\n * expires; it can take a reason, let the person edit before approving,\n * require typing \"confirm\" for what cannot be undone, and show who has\n * already decided when several people must. It refuses to offer approval\n * when the request does not match its own digest, and once it has expired.\n */\nexport function ApprovalCard({ approval, onAnswer, now = Date.now }: ApprovalCardProps) {\n const id = useId();\n const digest = useDigestCheck(approval);\n const expired = useExpired(approval.expiresAt, now);\n const [text, setText] = useState(\"\");\n const [reason, setReason] = useState(\"\");\n const [confirm, setConfirm] = useState(\"\");\n const [editing, setEditing] = useState(false);\n const [sql, setSql] = useState(approval.sql);\n const [subject, setSubject] = useState(approval.subject ? JSON.stringify(approval.subject, null, 2) : \"\");\n const [error, setError] = useState(\"\");\n const answered = approval.answer;\n const irreversible = approval.risk === \"irreversible\";\n const needed = approval.approvalsRequired;\n\n const reply = (allow: boolean, answer = \"\"): ApprovalReply | undefined => {\n if (approval.reasonRequired && !reason.trim()) {\n setError(\"Give a reason first.\");\n return undefined;\n }\n const base: ApprovalReply = { allow, text: answer, reason };\n if (!allow || !editing) return base;\n let editedSubject: JsonObject | undefined;\n if (approval.subject) {\n try {\n const parsed = JSON.parse(subject) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"not an object\");\n editedSubject = parsed as JsonObject;\n } catch {\n setError(\"The edited details are not a JSON object.\");\n return undefined;\n }\n }\n return {\n ...base,\n ...(sql !== approval.sql ? { editedSql: sql } : {}),\n ...(editedSubject && JSON.stringify(editedSubject) !== JSON.stringify(approval.subject) ? { editedSubject } : {}),\n };\n };\n const submit = (allow: boolean, answer = \"\") => {\n setError(\"\");\n if (allow && irreversible && confirm.trim().toLowerCase() !== CONFIRM_WORD) {\n setError(`Type “${CONFIRM_WORD}” to allow something that cannot be undone.`);\n return;\n }\n const r = reply(allow, answer);\n if (r) onAnswer(approval.id, r);\n };\n const onSubmitInput = (event: FormEvent) => {\n event.preventDefault();\n if (text.trim()) submit(true, text.trim());\n };\n\n const blocked = digest === \"mismatch\" || expired;\n return (\n <section className=\"sf-chat-approval\" aria-label={approval.title} data-answered={answered ? \"\" : undefined} data-risk={approval.risk || undefined}>\n <p className=\"sf-chat-approval-title\">{approval.title}</p>\n {(approval.risk || needed > 1) && (\n <p className=\"sf-chat-approval-tags\">\n {approval.risk && (\n <span className=\"sf-a2-badge\" data-tone={approval.risk === \"low\" ? \"neutral\" : approval.risk === \"high\" ? \"warning\" : \"danger\"}>\n {RISK_WORD[approval.risk]}\n </span>\n )}\n {needed > 1 && <span className=\"sf-a2-badge\" data-tone=\"neutral\">{`Needs ${needed} people`}</span>}\n </p>\n )}\n {approval.detail && <p className=\"sf-chat-approval-detail\">{approval.detail}</p>}\n {approval.basis && <p className=\"sf-chat-approval-detail\">Based on: {approval.basis}</p>}\n\n {editing && !answered ? (\n <>\n {approval.sql && (\n // The SQL editor, so the query a person changes is highlighted as the one they read was.\n <div className=\"sf-chat-approval-field\">\n <span aria-hidden=\"true\">SQL</span>\n <SqlEditor value={sql} onChange={setSql} label=\"SQL\" minHeight={80} maxHeight={320} />\n </div>\n )}\n {approval.subject && (\n <label className=\"sf-chat-approval-field\">\n <span>Details (JSON)</span>\n <textarea className=\"sf-input\" value={subject} spellCheck={false} rows={Math.min(14, subject.split(\"\\n\").length + 1)} onChange={(e) => setSubject(e.target.value)} />\n </label>\n )}\n </>\n ) : (\n <>\n {(answered?.editedSql ?? approval.sql) && <CodeBlock code={answered?.editedSql ?? approval.sql} language=\"sql\" label={answered?.editedSql !== undefined ? \"SQL, as edited\" : \"SQL\"} />}\n {(answered?.editedSubject ?? approval.subject) && (\n <CodeBlock code={JSON.stringify(answered?.editedSubject ?? approval.subject, null, 2)} language=\"json\" label={answered?.editedSubject ? \"Details, as edited\" : \"Details\"} />\n )}\n </>\n )}\n\n {approval.approvals.length > 0 && (\n <ul className=\"sf-chat-approval-record\" aria-label=\"Decisions so far\">\n {approval.approvals.map((d, i) => (\n <li key={`${d.by?.id ?? \"\"}-${i}`}>{decision(d)}</li>\n ))}\n </ul>\n )}\n\n {answered ? (\n <p className=\"sf-chat-approval-detail\" role=\"status\">\n {approval.kind === \"permission\" ? decision(answered) : `${answered.by?.name ? `${answered.by.name} answered` : \"You answered\"}: ${answered.text}`}\n {answered.editedSql !== undefined || answered.editedSubject ? \" (edited before approving)\" : \"\"}\n </p>\n ) : digest === \"mismatch\" ? (\n <p className=\"sf-chat-error\" role=\"alert\">\n This request does not match its own contents, so it cannot be approved. Ask the agent to send it again.\n </p>\n ) : expired ? (\n <p className=\"sf-chat-error\" role=\"alert\">\n This request expired {when(approval.expiresAt)}. Ask the agent again so it is checked against the data as it is now.\n </p>\n ) : (\n <>\n {approval.expiresAt && <p className=\"sf-chat-approval-detail\">Expires {when(approval.expiresAt)}.</p>}\n {(approval.kind === \"permission\" || approval.reasonRequired) && (\n <label className=\"sf-chat-approval-field\">\n <span>{approval.reasonRequired ? \"Reason (required)\" : \"Reason (optional)\"}</span>\n <input className=\"sf-input\" value={reason} onChange={(e) => setReason(e.target.value)} aria-required={approval.reasonRequired || undefined} />\n </label>\n )}\n {approval.kind === \"permission\" && irreversible && (\n <label className=\"sf-chat-approval-field\">\n <span>{`Type “${CONFIRM_WORD}” to allow`}</span>\n <input className=\"sf-input\" value={confirm} onChange={(e) => setConfirm(e.target.value)} autoComplete=\"off\" />\n </label>\n )}\n {error && (\n <p className=\"sf-chat-error\" role=\"alert\">\n {error}\n </p>\n )}\n {approval.kind === \"permission\" ? (\n <div className=\"sf-chat-approval-actions\">\n <button type=\"button\" className=\"sf-button\" data-variant=\"primary\" disabled={blocked || digest === \"checking\"} onClick={() => submit(true)}>\n {editing ? \"Allow my version\" : \"Allow\"}\n </button>\n <button type=\"button\" className=\"sf-button\" onClick={() => submit(false)}>\n Deny\n </button>\n {approval.editable && (\n <button type=\"button\" className=\"sf-button\" aria-pressed={editing} onClick={() => {\n if (editing) {\n setSql(approval.sql);\n setSubject(approval.subject ? JSON.stringify(approval.subject, null, 2) : \"\");\n }\n setEditing(!editing);\n }}\n >\n {editing ? \"Undo my edits\" : \"Edit before allowing\"}\n </button>\n )}\n </div>\n ) : approval.kind === \"choice\" ? (\n <div className=\"sf-chat-approval-actions\">\n {approval.options.map((option) => (\n <button key={option} type=\"button\" className=\"sf-button\" onClick={() => submit(true, option)}>\n {option}\n </button>\n ))}\n </div>\n ) : (\n <form className=\"sf-chat-approval-actions\" onSubmit={onSubmitInput}>\n <label className=\"sf-a2-visually-hidden\" htmlFor={id}>\n Your answer\n </label>\n <input id={id} className=\"sf-input\" value={text} onChange={(e) => setText(e.target.value)} />\n <button type=\"submit\" className=\"sf-button\" data-variant=\"primary\">\n Send\n </button>\n </form>\n )}\n </>\n )}\n </section>\n );\n}\n"]}
package/dist/Chat.d.ts ADDED
@@ -0,0 +1,112 @@
1
+ import type { AgentBackend } from "@surfaces-ui/agent";
2
+ import type { AgentInfo } from "@surfaces-ui/proto";
3
+ import { type DataRef } from "@surfaces-ui/components";
4
+ import { type Catalog, type SurfaceAction } from "@surfaces-ui/spec";
5
+ import { type ComponentRenderer, type SurfaceNote } from "@surfaces-ui/spec/react";
6
+ import type { ChatActions, ChatActor, ChatStep, ChatThread, ChatUsage } from "./thread.js";
7
+ import type { ChatProvider } from "./selectors.js";
8
+ import { type ChatSettings, type UseChat, type UseChatOptions } from "./useChat.js";
9
+ export interface ToolStepsProps {
10
+ steps: ChatStep[];
11
+ }
12
+ /** The work an agent did for a reply, such as tool calls. Each step opens to show its detail. */
13
+ export declare function ToolSteps({ steps }: ToolStepsProps): import("react").JSX.Element;
14
+ export interface ActionsCardProps {
15
+ actions: ChatActions;
16
+ /** A press: the button's id, and the choice it belongs to when it is in one. Never called for a disabled button. */
17
+ onPress(buttonId: string, choiceId?: string): void;
18
+ }
19
+ /**
20
+ * What a person can do about a reply, under it: a row of buttons, or several
21
+ * alternatives one row each with buttons for the whole set after them. The
22
+ * host decides what a press does and, once it is handled, replaces the
23
+ * buttons with what became of it (`outcome`).
24
+ */
25
+ export declare function ActionsCard({ actions, onPress }: ActionsCardProps): import("react").JSX.Element;
26
+ export interface MessageListProps {
27
+ thread: ChatThread;
28
+ catalog: Catalog;
29
+ renderers: Record<string, ComponentRenderer>;
30
+ onAction(action: SurfaceAction): void;
31
+ onAnswer: UseChat["answer"];
32
+ /** Where each drawn surface stands and what went wrong with it, kept for the agent's next turn (`useChat`'s `report` and `problem`). */
33
+ onReport?: UseChat["report"];
34
+ onProblem?: UseChat["problem"];
35
+ /** Told what a person does in a drawn component as they do it, with where. For a host that keeps its own context for an agent. */
36
+ onContext?(note: SurfaceNote & {
37
+ surfaceId: string;
38
+ componentId: string;
39
+ }): void;
40
+ /** A press on a button in an actions part (`ChatActions`): the part's id, the button's id, and its choice's id when it is in one. */
41
+ onPartAction?(partId: string, actionId: string, choiceId?: string): void;
42
+ /** Shown when the thread is empty. */
43
+ empty?: string;
44
+ }
45
+ /**
46
+ * The conversation so far. Replies can hold text, tool steps, approvals and
47
+ * components the agent drew. The list follows new content while the reader
48
+ * is at the bottom and stays put when they have scrolled up.
49
+ */
50
+ export declare function MessageList(props: MessageListProps): import("react").JSX.Element;
51
+ export interface SuggestionsProps {
52
+ items: string[];
53
+ onPick(text: string): void;
54
+ }
55
+ /** Things the person might say next, one press each. */
56
+ export declare function Suggestions({ items, onPick }: SuggestionsProps): import("react").JSX.Element | null;
57
+ /** How full the agent's context is, and what the conversation has cost when known. */
58
+ export declare function UsageGauge({ usage }: {
59
+ usage: ChatUsage | undefined;
60
+ }): import("react").JSX.Element | null;
61
+ export interface ChatProps {
62
+ /** Any agent runtime behind the AgentBackend interface. */
63
+ agent: AgentBackend;
64
+ /** The catalog agent-drawn components are checked against. Defaults to the analytics catalog. */
65
+ catalog?: Catalog;
66
+ renderers?: Record<string, ComponentRenderer>;
67
+ agentId?: string;
68
+ /** Limit the agent to the data in this saved context pack. */
69
+ contextPackId?: string;
70
+ /** Who is using the chat, from the host's sign-in; recorded on approval answers and surface events. */
71
+ user?: ChatActor;
72
+ /** Where to keep the conversation across reloads (`browserStorage()` from `@surfaces-ui/state`, or your own). */
73
+ storage?: UseChatOptions["storage"];
74
+ storageKey?: string;
75
+ /** Tables and columns attached to the message being written, when the host holds them (see `Composer`). */
76
+ references?: DataRef[];
77
+ onReferencesChange?(references: DataRef[]): void;
78
+ /** The thread to open with: a saved or written conversation. Read once. */
79
+ initialThread?: ChatThread;
80
+ /** Told the thread after every change, so a host can save it or build from what was drawn. */
81
+ onThreadChange?(thread: ChatThread): void;
82
+ /**
83
+ * Told what a person does in a drawn component as they do it (a view
84
+ * added, a field changed, a filter set). The chat already keeps these and
85
+ * gives them to the agent with its next turn; this is for a host that
86
+ * wants them too.
87
+ */
88
+ onContext?: MessageListProps["onContext"];
89
+ /** Offered before the first message. */
90
+ starters?: string[];
91
+ placeholder?: string;
92
+ /** The agent, model, skills and connectors a person chose, sent with each turn; with `onSettingsChange` the composer offers them. */
93
+ settings?: ChatSettings;
94
+ onSettingsChange?(settings: ChatSettings): void;
95
+ /** What the agent offers (`DescribeAgents`), for the composer's menus. */
96
+ agents?: AgentInfo[];
97
+ /** Where models run, when the host can reach several: the Model menu groups models by provider. */
98
+ providers?: ChatProvider[];
99
+ onManageProviders?(): void;
100
+ /** Shown when the thread is empty. */
101
+ empty?: string;
102
+ /** Height of the whole chat. A number is px. Defaults to 640. */
103
+ height?: number | string;
104
+ className?: string;
105
+ }
106
+ /**
107
+ * A complete chat: the conversation, suggestions and the composer. Agent
108
+ * replies stream in as Markdown, with tool steps, approvals and any catalog
109
+ * component (charts, tables, pivots, model diagrams, decision cards) drawn
110
+ * inline. Data components need a DataSourceProvider above the chat.
111
+ */
112
+ export declare function Chat(props: ChatProps): import("react").JSX.Element;
package/dist/Chat.js ADDED
@@ -0,0 +1,119 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, sameDataRef } from "@surfaces-ui/components";
3
+ import { analyticsCatalog } from "@surfaces-ui/spec";
4
+ import { SurfaceView, lazyAnalyticsRenderers } from "@surfaces-ui/spec/react";
5
+ import { useEffect, useId, useRef, useState } from "react";
6
+ import { ApprovalCard } from "./Approval.js";
7
+ import { Composer } from "./ChatComposer.js";
8
+ import { useChat } from "./useChat.js";
9
+ const count = new Intl.NumberFormat("en-US");
10
+ const STEP_MARK = { running: "…", done: "✓", failed: "!" };
11
+ const STEP_WORD = { running: "running", done: "done", failed: "failed" };
12
+ /** The work an agent did for a reply, such as tool calls. Each step opens to show its detail. */
13
+ export function ToolSteps({ steps }) {
14
+ return (_jsx("ul", { className: "sf-chat-steps", "aria-label": "Steps", children: steps.map((step) => (_jsx("li", { "data-status": step.status, children: _jsxs("details", { children: [_jsxs("summary", { children: [_jsx("span", { className: "sf-chat-step-mark", "aria-hidden": "true", children: STEP_MARK[step.status] }), _jsx("span", { className: "sf-chat-step-title", children: step.title || step.tool }), _jsxs("span", { className: "sf-chat-step-meta", children: [STEP_WORD[step.status], step.durationMs > 0 ? ` · ${count.format(step.durationMs)} ms` : ""] })] }), step.tool && _jsxs("p", { className: "sf-chat-step-tool", children: ["Tool: ", step.tool] }), step.detail && _jsx("pre", { tabIndex: 0, children: step.detail })] }) }, step.id))) }));
15
+ }
16
+ function ActionButtons({ buttons, label, onPress }) {
17
+ const uid = useId();
18
+ if (buttons.length === 0)
19
+ return null;
20
+ return (_jsx("div", { className: "sf-chat-actions-row", role: label ? "group" : undefined, "aria-label": label, children: buttons.map((button, i) => {
21
+ const why = button.reason ? `${uid}-${i}` : undefined;
22
+ return (_jsxs("span", { className: "sf-chat-actions-button", children: [_jsx("button", { type: "button", className: "sf-button", "data-variant": button.variant, "aria-disabled": button.disabled || undefined, "aria-label": button.ariaLabel, "aria-describedby": why, title: button.reason, onClick: () => {
23
+ if (!button.disabled)
24
+ onPress(button.id);
25
+ }, children: button.label }), why && (_jsx("span", { id: why, className: "sf-a2-visually-hidden", children: button.reason }))] }, button.id));
26
+ }) }));
27
+ }
28
+ /**
29
+ * What a person can do about a reply, under it: a row of buttons, or several
30
+ * alternatives one row each with buttons for the whole set after them. The
31
+ * host decides what a press does and, once it is handled, replaces the
32
+ * buttons with what became of it (`outcome`).
33
+ */
34
+ export function ActionsCard({ actions, onPress }) {
35
+ const choices = actions.choices ?? [];
36
+ return (_jsxs("div", { className: "sf-chat-actions", role: "group", "aria-label": actions.title || "Actions", "data-handled": actions.outcome !== undefined || undefined, children: [actions.title && _jsx("p", { className: "sf-chat-actions-title", children: actions.title }), actions.detail && _jsx("p", { className: "sf-chat-actions-detail", children: actions.detail }), actions.outcome !== undefined ? (_jsx("p", { className: "sf-chat-actions-outcome", role: "status", children: actions.outcome })) : (_jsxs(_Fragment, { children: [choices.length > 0 && (_jsx("ul", { className: "sf-chat-actions-choices", "aria-label": "Choices", children: choices.map((choice) => (_jsxs("li", { children: [_jsxs("p", { className: "sf-chat-actions-choice", children: [_jsx("span", { className: "sf-chat-actions-title", children: choice.title }), choice.detail && _jsxs("span", { className: "sf-chat-actions-detail", children: [" \u00B7 ", choice.detail] })] }), _jsx(ActionButtons, { buttons: choice.buttons, label: choice.title, onPress: (id) => onPress(id, choice.id) })] }, choice.id))) })), _jsx(ActionButtons, { buttons: actions.buttons ?? [], label: choices.length > 0 ? "All choices" : undefined, onPress: (id) => onPress(id) })] }))] }));
37
+ }
38
+ function MessageView({ message, thread, catalog, renderers, onAction, onAnswer, onReport, onProblem, onContext, onPartAction }) {
39
+ if (message.role === "user") {
40
+ return (_jsxs("article", { className: "sf-chat-message", "data-role": "user", children: [_jsx("span", { className: "sf-a2-visually-hidden", children: "You said:" }), _jsx("p", { children: message.parts.map((p) => (p.kind === "text" ? p.text : "")).join("") }), message.parts.map((p, i) => p.kind === "references" ? (_jsx("ul", { className: "sf-chat-references", "aria-label": "Attached", children: p.references.map((ref) => (_jsx("li", { className: "sf-chat-reference", "data-kind": ref.kind, children: dataRefLabel(ref) }, `${ref.sourceId}/${dataRefLabel(ref)}`))) }, i)) : null)] }));
41
+ }
42
+ return (_jsxs("article", { className: "sf-chat-message", "data-role": "assistant", "aria-busy": message.streaming, children: [_jsx("span", { className: "sf-a2-visually-hidden", children: "The agent replied:" }), message.parts.map((part, index) => {
43
+ switch (part.kind) {
44
+ case "text":
45
+ return _jsx(Markdown, { text: part.text }, index);
46
+ case "steps":
47
+ return _jsx(ToolSteps, { steps: part.steps }, index);
48
+ case "surface": {
49
+ const surface = thread.surfaces[part.surfaceId];
50
+ // Agent-drawn components are checked against the catalog before they are drawn.
51
+ const key = part.surfaceId;
52
+ return surface ? (_jsx(SurfaceView, { surface: surface, catalog: catalog, renderers: renderers, onAction: onAction, onDataChange: (data) => onReport?.(key, { data }), onControlsChange: (componentId, controls) => onReport?.(key, { componentId, controls }), onContext: (componentId, note) => {
53
+ onReport?.(key, { componentId, note });
54
+ onContext?.({ ...note, surfaceId: key, componentId });
55
+ }, onProblem: (problem) => onProblem?.(key, problem), className: "sf-chat-surface" }, index)) : null;
56
+ }
57
+ case "approval":
58
+ return _jsx(ApprovalCard, { approval: part.approval, onAnswer: onAnswer }, index);
59
+ case "actions":
60
+ return _jsx(ActionsCard, { actions: part.actions, onPress: (actionId, choiceId) => onPartAction?.(part.actions.id, actionId, choiceId) }, index);
61
+ case "references":
62
+ // Attachments belong to what a person sent; a reply has none.
63
+ return null;
64
+ default:
65
+ return (_jsx("p", { className: "sf-chat-error", role: "alert", children: part.code === "CANCELLED" ? "Stopped." : part.message }, index));
66
+ }
67
+ }), message.streaming && message.parts.length === 0 && _jsx("p", { className: "sf-chat-thinking", children: "Working\u2026" }), !message.streaming && message.generatedBy && _jsxs("p", { className: "sf-chat-by", children: ["Answered by ", message.generatedBy] })] }));
68
+ }
69
+ /**
70
+ * The conversation so far. Replies can hold text, tool steps, approvals and
71
+ * components the agent drew. The list follows new content while the reader
72
+ * is at the bottom and stays put when they have scrolled up.
73
+ */
74
+ export function MessageList(props) {
75
+ const { thread } = props;
76
+ const list = useRef(null);
77
+ const pinned = useRef(true);
78
+ useEffect(() => {
79
+ const element = list.current;
80
+ if (element && pinned.current)
81
+ element.scrollTop = element.scrollHeight;
82
+ }, [thread]);
83
+ return (_jsxs("div", { ref: list, className: "sf-chat-list", role: "log", "aria-label": "Conversation", "aria-live": "polite", tabIndex: 0, onScroll: (event) => {
84
+ const element = event.currentTarget;
85
+ pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;
86
+ }, children: [thread.messages.length === 0 && props.empty && _jsx("div", { className: "sf-chat-empty", children: props.empty }), thread.messages.map((message) => (_jsx(MessageView, { ...props, message: message }, message.id)))] }));
87
+ }
88
+ /** Things the person might say next, one press each. */
89
+ export function Suggestions({ items, onPick }) {
90
+ if (items.length === 0)
91
+ return null;
92
+ return (_jsx("div", { className: "sf-chat-suggestions", role: "group", "aria-label": "Suggestions", children: items.map((item) => (_jsx("button", { type: "button", className: "sf-button", onClick: () => onPick(item), children: item }, item))) }));
93
+ }
94
+ /** How full the agent's context is, and what the conversation has cost when known. */
95
+ export function UsageGauge({ usage }) {
96
+ if (!usage || usage.contextLimit <= 0)
97
+ return null;
98
+ const share = Math.min(1, usage.contextTokens / usage.contextLimit);
99
+ return (_jsxs("p", { className: "sf-chat-usage", children: [_jsx("meter", { min: 0, max: 1, high: 0.8, value: share, "aria-label": "Context used" }), _jsxs("span", { children: [Math.round(share * 100), "% of context used", usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : ""] })] }));
100
+ }
101
+ /**
102
+ * A complete chat: the conversation, suggestions and the composer. Agent
103
+ * replies stream in as Markdown, with tool steps, approvals and any catalog
104
+ * component (charts, tables, pivots, model diagrams, decision cards) drawn
105
+ * inline. Data components need a DataSourceProvider above the chat.
106
+ */
107
+ export function Chat(props) {
108
+ const catalog = props.catalog ?? analyticsCatalog;
109
+ const renderers = props.renderers ?? lazyAnalyticsRenderers;
110
+ const chat = useChat(props.agent, { catalog, agentId: props.agentId, contextPackId: props.contextPackId, user: props.user, storage: props.storage, storageKey: props.storageKey, initial: props.initialThread, settings: props.settings });
111
+ const { thread } = chat;
112
+ // Told on a change of thread only: a host passing a new function each render must not be told again (and set state in a loop).
113
+ const onThreadChange = useRef(props.onThreadChange);
114
+ onThreadChange.current = props.onThreadChange;
115
+ useEffect(() => onThreadChange.current?.(thread), [thread]);
116
+ const suggestions = thread.messages.length === 0 ? (props.starters ?? []) : thread.status === "idle" ? thread.suggestions : [];
117
+ return (_jsxs("section", { className: ["sf-chat", props.className].filter(Boolean).join(" "), style: { height: props.height ?? 640 }, "aria-label": "Chat", children: [_jsx(MessageList, { thread: thread, catalog: catalog, renderers: renderers, onAction: chat.act, onAnswer: chat.answer, onReport: chat.report, onProblem: chat.problem, onContext: props.onContext, empty: props.empty }), _jsx(Suggestions, { items: suggestions, onPick: (text) => chat.send(text) }), _jsx(Composer, { agents: props.agents, settings: props.settings, onSettingsChange: props.onSettingsChange, providers: props.providers, onManageProviders: props.onManageProviders, references: props.references, onReferencesChange: props.onReferencesChange, onSend: chat.send, onStop: chat.stop, streaming: thread.status === "streaming", placeholder: thread.status === "waiting" ? "Answer above, or type to say something else" : props.placeholder }), _jsx(UsageGauge, { usage: thread.usage })] }));
118
+ }
119
+ //# sourceMappingURL=Chat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Chat.js","sourceRoot":"","sources":["../src/Chat.tsx"],"names":[],"mappings":";AAEA,OAAO,EAAgB,QAAQ,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACpI,OAAO,EAAoC,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACvF,OAAO,EAA4C,WAAW,EAAE,sBAAsB,EAAE,MAAM,yBAAyB,CAAC;AACxH,OAAO,EAAsD,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC/G,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG7C,OAAO,EAAwD,OAAO,EAAE,MAAM,cAAc,CAAC;AAE7F,MAAM,KAAK,GAAG,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;AAC7C,MAAM,SAAS,GAAuC,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC;AAC/F,MAA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EAAE,KAAK,CAAC,gBAAgB,EACxC,SAAS,EAAE,KAAK,CAAC,SAAS,EAC1B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB,EAC1C,UAAU,EAAE,KAAK,CAAC,UAAU,EAC5B,kBAAkB,EAAE,KAAK,CAAC,kBAAkB,EAC5C,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE,WAAW,EAAE,MAAM,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,6CAA6C,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,GAAI,EAClM,KAAC,UAAU,IAAC,KAAK,EAAE,MAAM,CAAC,KAAK,GAAI,IAC3B,CACX,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentBackend } from \"@surfaces-ui/agent\";\nimport type { AgentInfo } from \"@surfaces-ui/proto\";\nimport { type DataRef, Markdown, addDataRefs, dataRefLabel, hasDataRefs, readDataRefs, sameDataRef } from \"@surfaces-ui/components\";\nimport { type Catalog, type SurfaceAction, analyticsCatalog } from \"@surfaces-ui/spec\";\nimport { type ComponentRenderer, type SurfaceNote, SurfaceView, lazyAnalyticsRenderers } from \"@surfaces-ui/spec/react\";\nimport { type DragEvent, type FormEvent, type KeyboardEvent, useEffect, useId, useRef, useState } from \"react\";\nimport { ApprovalCard } from \"./Approval.js\";\nimport { Composer } from \"./ChatComposer.js\";\nimport type { ChatActions, ChatActor, ChatButton, ChatMessage, ChatStep, ChatThread, ChatUsage } from \"./thread.js\";\nimport type { ChatProvider } from \"./selectors.js\";\nimport { type ChatSettings, type UseChat, type UseChatOptions, useChat } from \"./useChat.js\";\n\nconst count = new Intl.NumberFormat(\"en-US\");\nconst STEP_MARK: Record<ChatStep[\"status\"], string> = { running: \"…\", done: \"✓\", failed: \"!\" };\nconst STEP_WORD: Record<ChatStep[\"status\"], string> = { running: \"running\", done: \"done\", failed: \"failed\" };\n\nexport interface ToolStepsProps {\n steps: ChatStep[];\n}\n\n/** The work an agent did for a reply, such as tool calls. Each step opens to show its detail. */\nexport function ToolSteps({ steps }: ToolStepsProps) {\n return (\n <ul className=\"sf-chat-steps\" aria-label=\"Steps\">\n {steps.map((step) => (\n <li key={step.id} data-status={step.status}>\n <details>\n <summary>\n <span className=\"sf-chat-step-mark\" aria-hidden=\"true\">\n {STEP_MARK[step.status]}\n </span>\n <span className=\"sf-chat-step-title\">{step.title || step.tool}</span>\n <span className=\"sf-chat-step-meta\">\n {STEP_WORD[step.status]}\n {step.durationMs > 0 ? ` · ${count.format(step.durationMs)} ms` : \"\"}\n </span>\n </summary>\n {step.tool && <p className=\"sf-chat-step-tool\">Tool: {step.tool}</p>}\n {step.detail && <pre tabIndex={0}>{step.detail}</pre>}\n </details>\n </li>\n ))}\n </ul>\n );\n}\n\nexport interface ActionsCardProps {\n actions: ChatActions;\n /** A press: the button's id, and the choice it belongs to when it is in one. Never called for a disabled button. */\n onPress(buttonId: string, choiceId?: string): void;\n}\n\nfunction ActionButtons({ buttons, label, onPress }: { buttons: ChatButton[]; label?: string; onPress(id: string): void }) {\n const uid = useId();\n if (buttons.length === 0) return null;\n return (\n <div className=\"sf-chat-actions-row\" role={label ? \"group\" : undefined} aria-label={label}>\n {buttons.map((button, i) => {\n const why = button.reason ? `${uid}-${i}` : undefined;\n return (\n <span key={button.id} className=\"sf-chat-actions-button\">\n <button\n type=\"button\"\n className=\"sf-button\"\n data-variant={button.variant}\n // Not `disabled`: a disabled button cannot be reached by keyboard, and then neither can its reason.\n aria-disabled={button.disabled || undefined}\n aria-label={button.ariaLabel}\n aria-describedby={why}\n title={button.reason}\n onClick={() => {\n if (!button.disabled) onPress(button.id);\n }}\n >\n {button.label}\n </button>\n {why && (\n <span id={why} className=\"sf-a2-visually-hidden\">\n {button.reason}\n </span>\n )}\n </span>\n );\n })}\n </div>\n );\n}\n\n/**\n * What a person can do about a reply, under it: a row of buttons, or several\n * alternatives one row each with buttons for the whole set after them. The\n * host decides what a press does and, once it is handled, replaces the\n * buttons with what became of it (`outcome`).\n */\nexport function ActionsCard({ actions, onPress }: ActionsCardProps) {\n const choices = actions.choices ?? [];\n return (\n <div className=\"sf-chat-actions\" role=\"group\" aria-label={actions.title || \"Actions\"} data-handled={actions.outcome !== undefined || undefined}>\n {actions.title && <p className=\"sf-chat-actions-title\">{actions.title}</p>}\n {actions.detail && <p className=\"sf-chat-actions-detail\">{actions.detail}</p>}\n {actions.outcome !== undefined ? (\n <p className=\"sf-chat-actions-outcome\" role=\"status\">\n {actions.outcome}\n </p>\n ) : (\n <>\n {choices.length > 0 && (\n <ul className=\"sf-chat-actions-choices\" aria-label=\"Choices\">\n {choices.map((choice) => (\n <li key={choice.id}>\n <p className=\"sf-chat-actions-choice\">\n <span className=\"sf-chat-actions-title\">{choice.title}</span>\n {choice.detail && <span className=\"sf-chat-actions-detail\"> · {choice.detail}</span>}\n </p>\n <ActionButtons buttons={choice.buttons} label={choice.title} onPress={(id) => onPress(id, choice.id)} />\n </li>\n ))}\n </ul>\n )}\n <ActionButtons buttons={actions.buttons ?? []} label={choices.length > 0 ? \"All choices\" : undefined} onPress={(id) => onPress(id)} />\n </>\n )}\n </div>\n );\n}\n\nexport interface MessageListProps {\n thread: ChatThread;\n catalog: Catalog;\n renderers: Record<string, ComponentRenderer>;\n onAction(action: SurfaceAction): void;\n onAnswer: UseChat[\"answer\"];\n /** Where each drawn surface stands and what went wrong with it, kept for the agent's next turn (`useChat`'s `report` and `problem`). */\n onReport?: UseChat[\"report\"];\n onProblem?: UseChat[\"problem\"];\n /** Told what a person does in a drawn component as they do it, with where. For a host that keeps its own context for an agent. */\n onContext?(note: SurfaceNote & { surfaceId: string; componentId: string }): void;\n /** A press on a button in an actions part (`ChatActions`): the part's id, the button's id, and its choice's id when it is in one. */\n onPartAction?(partId: string, actionId: string, choiceId?: string): void;\n /** Shown when the thread is empty. */\n empty?: string;\n}\n\nfunction MessageView({ message, thread, catalog, renderers, onAction, onAnswer, onReport, onProblem, onContext, onPartAction }: MessageListProps & { message: ChatMessage }) {\n if (message.role === \"user\") {\n return (\n <article className=\"sf-chat-message\" data-role=\"user\">\n <span className=\"sf-a2-visually-hidden\">You said:</span>\n <p>{message.parts.map((p) => (p.kind === \"text\" ? p.text : \"\")).join(\"\")}</p>\n {message.parts.map((p, i) =>\n p.kind === \"references\" ? (\n // biome-ignore lint/suspicious/noArrayIndexKey: a message's parts do not move.\n <ul key={i} className=\"sf-chat-references\" aria-label=\"Attached\">\n {p.references.map((ref) => (\n <li key={`${ref.sourceId}/${dataRefLabel(ref)}`} className=\"sf-chat-reference\" data-kind={ref.kind}>\n {dataRefLabel(ref)}\n </li>\n ))}\n </ul>\n ) : null,\n )}\n </article>\n );\n }\n return (\n <article className=\"sf-chat-message\" data-role=\"assistant\" aria-busy={message.streaming}>\n <span className=\"sf-a2-visually-hidden\">The agent replied:</span>\n {message.parts.map((part, index) => {\n switch (part.kind) {\n case \"text\":\n return <Markdown key={index} text={part.text} />;\n case \"steps\":\n return <ToolSteps key={index} steps={part.steps} />;\n case \"surface\": {\n const surface = thread.surfaces[part.surfaceId];\n // Agent-drawn components are checked against the catalog before they are drawn.\n const key = part.surfaceId;\n return surface ? (\n <SurfaceView\n key={index}\n surface={surface}\n catalog={catalog}\n renderers={renderers}\n onAction={onAction}\n onDataChange={(data) => onReport?.(key, { data })}\n onControlsChange={(componentId, controls) => onReport?.(key, { componentId, controls })}\n onContext={(componentId, note) => {\n onReport?.(key, { componentId, note });\n onContext?.({ ...note, surfaceId: key, componentId });\n }}\n onProblem={(problem) => onProblem?.(key, problem)}\n className=\"sf-chat-surface\"\n />\n ) : null;\n }\n case \"approval\":\n return <ApprovalCard key={index} approval={part.approval} onAnswer={onAnswer} />;\n case \"actions\":\n return <ActionsCard key={index} actions={part.actions} onPress={(actionId, choiceId) => onPartAction?.(part.actions.id, actionId, choiceId)} />;\n case \"references\":\n // Attachments belong to what a person sent; a reply has none.\n return null;\n default:\n return (\n <p key={index} className=\"sf-chat-error\" role=\"alert\">\n {part.code === \"CANCELLED\" ? \"Stopped.\" : part.message}\n </p>\n );\n }\n })}\n {message.streaming && message.parts.length === 0 && <p className=\"sf-chat-thinking\">Working…</p>}\n {!message.streaming && message.generatedBy && <p className=\"sf-chat-by\">Answered by {message.generatedBy}</p>}\n </article>\n );\n}\n\n/**\n * The conversation so far. Replies can hold text, tool steps, approvals and\n * components the agent drew. The list follows new content while the reader\n * is at the bottom and stays put when they have scrolled up.\n */\nexport function MessageList(props: MessageListProps) {\n const { thread } = props;\n const list = useRef<HTMLDivElement>(null);\n const pinned = useRef(true);\n useEffect(() => {\n const element = list.current;\n if (element && pinned.current) element.scrollTop = element.scrollHeight;\n }, [thread]);\n return (\n <div\n ref={list}\n className=\"sf-chat-list\"\n role=\"log\"\n aria-label=\"Conversation\"\n aria-live=\"polite\"\n tabIndex={0}\n onScroll={(event) => {\n const element = event.currentTarget;\n pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 48;\n }}\n >\n {thread.messages.length === 0 && props.empty && <div className=\"sf-chat-empty\">{props.empty}</div>}\n {thread.messages.map((message) => (\n <MessageView key={message.id} {...props} message={message} />\n ))}\n </div>\n );\n}\n\nexport interface SuggestionsProps {\n items: string[];\n onPick(text: string): void;\n}\n\n/** Things the person might say next, one press each. */\nexport function Suggestions({ items, onPick }: SuggestionsProps) {\n if (items.length === 0) return null;\n return (\n <div className=\"sf-chat-suggestions\" role=\"group\" aria-label=\"Suggestions\">\n {items.map((item) => (\n <button key={item} type=\"button\" className=\"sf-button\" onClick={() => onPick(item)}>\n {item}\n </button>\n ))}\n </div>\n );\n}\n\n/** How full the agent's context is, and what the conversation has cost when known. */\nexport function UsageGauge({ usage }: { usage: ChatUsage | undefined }) {\n if (!usage || usage.contextLimit <= 0) return null;\n const share = Math.min(1, usage.contextTokens / usage.contextLimit);\n return (\n <p className=\"sf-chat-usage\">\n <meter min={0} max={1} high={0.8} value={share} aria-label=\"Context used\" />\n <span>\n {Math.round(share * 100)}% of context used\n {usage.costUsd !== undefined ? ` · $${usage.costUsd.toFixed(2)}` : \"\"}\n </span>\n </p>\n );\n}\n\nexport interface ChatProps {\n /** Any agent runtime behind the AgentBackend interface. */\n agent: AgentBackend;\n /** The catalog agent-drawn components are checked against. Defaults to the analytics catalog. */\n catalog?: Catalog;\n renderers?: Record<string, ComponentRenderer>;\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /** Who is using the chat, from the host's sign-in; recorded on approval answers and surface events. */\n user?: ChatActor;\n /** Where to keep the conversation across reloads (`browserStorage()` from `@surfaces-ui/state`, or your own). */\n storage?: UseChatOptions[\"storage\"];\n storageKey?: string;\n /** Tables and columns attached to the message being written, when the host holds them (see `Composer`). */\n references?: DataRef[];\n onReferencesChange?(references: DataRef[]): void;\n /** The thread to open with: a saved or written conversation. Read once. */\n initialThread?: ChatThread;\n /** Told the thread after every change, so a host can save it or build from what was drawn. */\n onThreadChange?(thread: ChatThread): void;\n /**\n * Told what a person does in a drawn component as they do it (a view\n * added, a field changed, a filter set). The chat already keeps these and\n * gives them to the agent with its next turn; this is for a host that\n * wants them too.\n */\n onContext?: MessageListProps[\"onContext\"];\n /** Offered before the first message. */\n starters?: string[];\n placeholder?: string;\n /** The agent, model, skills and connectors a person chose, sent with each turn; with `onSettingsChange` the composer offers them. */\n settings?: ChatSettings;\n onSettingsChange?(settings: ChatSettings): void;\n /** What the agent offers (`DescribeAgents`), for the composer's menus. */\n agents?: AgentInfo[];\n /** Where models run, when the host can reach several: the Model menu groups models by provider. */\n providers?: ChatProvider[];\n onManageProviders?(): void;\n /** Shown when the thread is empty. */\n empty?: string;\n /** Height of the whole chat. A number is px. Defaults to 640. */\n height?: number | string;\n className?: string;\n}\n\n/**\n * A complete chat: the conversation, suggestions and the composer. Agent\n * replies stream in as Markdown, with tool steps, approvals and any catalog\n * component (charts, tables, pivots, model diagrams, decision cards) drawn\n * inline. Data components need a DataSourceProvider above the chat.\n */\nexport function Chat(props: ChatProps) {\n const catalog = props.catalog ?? analyticsCatalog;\n const renderers = props.renderers ?? lazyAnalyticsRenderers;\n const chat = useChat(props.agent, { catalog, agentId: props.agentId, contextPackId: props.contextPackId, user: props.user, storage: props.storage, storageKey: props.storageKey, initial: props.initialThread, settings: props.settings });\n const { thread } = chat;\n // Told on a change of thread only: a host passing a new function each render must not be told again (and set state in a loop).\n const onThreadChange = useRef(props.onThreadChange);\n onThreadChange.current = props.onThreadChange;\n useEffect(() => onThreadChange.current?.(thread), [thread]);\n const suggestions = thread.messages.length === 0 ? (props.starters ?? []) : thread.status === \"idle\" ? thread.suggestions : [];\n return (\n <section className={[\"sf-chat\", props.className].filter(Boolean).join(\" \")} style={{ height: props.height ?? 640 }} aria-label=\"Chat\">\n <MessageList thread={thread} catalog={catalog} renderers={renderers} onAction={chat.act} onAnswer={chat.answer} onReport={chat.report} onProblem={chat.problem} onContext={props.onContext} empty={props.empty} />\n <Suggestions items={suggestions} onPick={(text) => chat.send(text)} />\n <Composer\n agents={props.agents}\n settings={props.settings}\n onSettingsChange={props.onSettingsChange}\n providers={props.providers}\n onManageProviders={props.onManageProviders}\n references={props.references}\n onReferencesChange={props.onReferencesChange}\n onSend={chat.send} onStop={chat.stop} streaming={thread.status === \"streaming\"} placeholder={thread.status === \"waiting\" ? \"Answer above, or type to say something else\" : props.placeholder} />\n <UsageGauge usage={thread.usage} />\n </section>\n );\n}\n"]}
@@ -0,0 +1,117 @@
1
+ import { type DataRef } from "@surfaces-ui/components";
2
+ import type { AgentInfo, ToolConnector } from "@surfaces-ui/proto";
3
+ import { type DataPanelProps } from "./DataPanel.js";
4
+ import { type ChatPanel, type ChatProvider } from "./selectors.js";
5
+ import type { SpeechAdapter } from "./speech.js";
6
+ import type { ChatSettings } from "./useChat.js";
7
+ import { type VoiceReply } from "./voice.js";
8
+ /** What became of one file a person attached. */
9
+ export interface AttachResult {
10
+ file: File;
11
+ /** The table or file it became, by name. */
12
+ ref?: DataRef;
13
+ /** Why it could not be used. */
14
+ error?: string;
15
+ }
16
+ export interface ComposerProps {
17
+ onSend(text: string, references: DataRef[]): void;
18
+ /** Shown in place of Send while a reply is streaming. */
19
+ onStop?(): void;
20
+ streaming?: boolean;
21
+ disabled?: boolean;
22
+ placeholder?: string;
23
+ /** The box's name for assistive technology. Default "Message". */
24
+ label?: string;
25
+ /**
26
+ * Tables and columns attached to the message being written. Give it with
27
+ * `onReferencesChange` to hold them yourself, so something beside the chat
28
+ * (a browser's "Add to chat") can add to them; otherwise the composer keeps
29
+ * them. Either way they can be dropped onto the composer.
30
+ */
31
+ references?: DataRef[];
32
+ onReferencesChange?(references: DataRef[]): void;
33
+ /** Turns files from the person's computer into data the agent can name. Without it there is no upload. Any file is offered; the host says which it can use. */
34
+ attachFiles?(files: File[]): Promise<AttachResult[]>;
35
+ /** Browsing tables and files from the composer ("Add data"). Without `onManage`, it opens in a popover. */
36
+ browse?: Omit<DataPanelProps, "onAttach">;
37
+ /** Agents with their models, skills and connectors (`DescribeAgents`). Each menu shows only when there is something to choose. */
38
+ agents?: AgentInfo[];
39
+ settings?: ChatSettings;
40
+ onSettingsChange?(settings: ChatSettings): void;
41
+ /** Data connections for the Connectors menu's Data group. */
42
+ sources?: {
43
+ id: string;
44
+ label: string;
45
+ }[];
46
+ onAddConnection?(): void;
47
+ onConnect?(connector: ToolConnector): void;
48
+ /** Opens a panel with the whole list ("View all…", "Manage…", "Add data"). */
49
+ onManage?(panel: ChatPanel): void;
50
+ /** The panels `onManage` can open. Default: all of them. */
51
+ managed?: ChatPanel[];
52
+ /** Items a menu lists before "View all…". Default 5. */
53
+ menuLimit?: number;
54
+ /** Where models run, when the host can reach several: the Model menu groups models by provider. */
55
+ providers?: ChatProvider[];
56
+ /** "Manage providers…" at the foot of the Model menu. */
57
+ onManageProviders?(): void;
58
+ /** Talking instead of typing. The microphone shows only where the adapter is supported. */
59
+ speech?: SpeechAdapter;
60
+ /** The latest reply, for a spoken conversation to read and to know when to listen again. */
61
+ voiceReply?: VoiceReply;
62
+ /**
63
+ * Ask before the microphone is first used. The microphone shows, and its
64
+ * first press says where audio goes (`speech.label`) with "Use voice" and
65
+ * "Not now"; nothing listens until the person agrees. The host keeps the
66
+ * answer (`given`) so it is asked once. Without it, passing `speech` is the consent.
67
+ */
68
+ speechConsent?: SpeechConsent;
69
+ /** What the message is about beyond attached data, as chips before the attached tables and files. */
70
+ context?: ComposerContext[];
71
+ /** Choices for the next message, as checkboxes under the box. */
72
+ toggles?: ComposerToggle[];
73
+ }
74
+ /**
75
+ * A choice that goes with the next message, drawn as a checkbox under the
76
+ * box ("Try three ways"). The host keeps `checked`, and clears it after a send
77
+ * when it holds for one message only.
78
+ */
79
+ export interface ComposerToggle {
80
+ id: string;
81
+ label: string;
82
+ /** More about it, after the label and part of its name. */
83
+ detail?: string;
84
+ checked: boolean;
85
+ onChange(checked: boolean): void;
86
+ disabled?: boolean;
87
+ }
88
+ /**
89
+ * Something the message is about that is not a table or a file: the part of
90
+ * a page a person selected ("About Chart amount-by-region"). Shown as a chip
91
+ * beside the attached data; the host keeps it and says what it means.
92
+ */
93
+ export interface ComposerContext {
94
+ /** Keeps the chip steady across renders; defaults to the label. */
95
+ id?: string;
96
+ label: string;
97
+ /** Shown after the label, smaller. */
98
+ detail?: string;
99
+ /** Given, the chip has a remove button that calls it ("Whole page instead"). */
100
+ onClear?(): void;
101
+ /** The remove button's name. Default "Remove " and the label. */
102
+ clearLabel?: string;
103
+ }
104
+ /** Whether the person agreed to use voice, kept by the host. */
105
+ export interface SpeechConsent {
106
+ given: boolean;
107
+ onGive(): void;
108
+ }
109
+ /**
110
+ * Where the person writes. Enter sends; Shift+Enter starts a new line.
111
+ * Everything beyond the box is optional: files from the computer (the `+`
112
+ * menu, a drop or a paste), tables and files from a browser, the agent,
113
+ * model, skills and connectors, and the microphone. Send is the arrow.
114
+ */
115
+ export declare function ChatComposer(props: ComposerProps): import("react").JSX.Element;
116
+ /** The composer. Kept under its first name; everything added since is optional. */
117
+ export declare const Composer: typeof ChatComposer;