@seclai/react 0.0.9 → 0.0.11

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
@@ -58,6 +58,58 @@ To tell files apart, add named buttons with tags, then use the tags in `onBefore
58
58
  | `attachButtons` | `{ label: string; tag?: string }[]`. Replaces the single Attach button. Dropped and pasted files have no tag |
59
59
  | `onBeforeSend` | `({ input, files }) => string \| void`, where `files` are `{ uploadId, name, contentType, tag? }`. Return a string to send it in place of the typed text |
60
60
 
61
+ ### Saved sessions
62
+
63
+ By default `AgentChat` makes up a session id on the first message and keeps the transcript in memory, so a reload starts over. To let users go back to a conversation, give it the session id and the turns you saved, and save each new turn as it finishes:
64
+
65
+ ```tsx
66
+ import { AgentChat, type AgentChatTurn } from "@seclai/react";
67
+
68
+ function SavedChat({ sessionId, turns }: { sessionId: string; turns: AgentChatTurn[] }) {
69
+ return (
70
+ <AgentChat
71
+ sessionId={sessionId}
72
+ initialTurns={turns}
73
+ onTurnComplete={(turn, { sessionId }) =>
74
+ fetch(`/api/chats/${sessionId}/turns`, { method: "POST", body: JSON.stringify(turn) })
75
+ }
76
+ />
77
+ );
78
+ }
79
+
80
+ // Load the turns from your API first, e.g. GET /api/chats/:id/turns, then:
81
+ <SavedChat sessionId={id} turns={turns} />;
82
+ ```
83
+
84
+ Each `AgentChatTurn` is one exchange, a message and its reply, as plain JSON:
85
+
86
+ ```ts
87
+ {
88
+ input: string; // what the user typed
89
+ sentInput?: string; // what was sent, when onBeforeSend changed it
90
+ files?: { uploadId, name, contentType, tag? }[];
91
+ output: string; // for a failed or cancelled run, whatever had streamed
92
+ attachments?: { id, name, mime, bytes }[];
93
+ runId?: string | null;
94
+ status: "completed" | "failed" | "cancelled";
95
+ error?: string | null;
96
+ }
97
+ ```
98
+
99
+ - `onTurnComplete` is called once per run, when it completes, fails or is cancelled. Store what it gives you as is, and pass the list back as `initialTurns`. Its second argument has the run's `sessionId`, which is the generated one when you don't pass `sessionId`. Always save under that `context.sessionId`, not a session id captured from the surrounding scope: a run cut short by a switch reports through the latest `onTurnComplete`, after your app has moved on to the next conversation.
100
+ - Attachments are stored without URLs. The chat rebuilds them from `runId` and the attachment id through your download handler, so they don't go stale, and restored images show as they did live. Restored user files show as name chips, without thumbnails.
101
+ - `initialTurns` is read when the chat mounts and when `sessionId` changes. Later changes to it are ignored, as with an input's `defaultValue`.
102
+ - Changing `sessionId` switches conversations: the transcript resets to `initialTurns`, the composer clears, and a reply still streaming stops. That run is still reported to `onTurnComplete`, as cancelled, with the old session id. Remounting with a `key` works too.
103
+ - The one exception: a chat started without `sessionId` can be handed the id it generated (the `context.sessionId` you saved under), and it keeps its transcript, composer and any reply still streaming. For a new chat, though, prefer generating the id up front (for example with `crypto.randomUUID()`) and passing it from the first message, so the id you save under and the one you pass never differ.
104
+
105
+ Saving from the browser misses turns when the user closes the tab mid-run. If your server uses the `onRunEnd` hook of `@seclai/handlers`, saving there is more reliable, and the chat then only needs `sessionId` and `initialTurns`.
106
+
107
+ | Prop | |
108
+ |---|---|
109
+ | `sessionId` | Sent with every run. Generated on the first message when left out |
110
+ | `initialTurns` | `AgentChatTurn[]` to show on mount, or when `sessionId` changes |
111
+ | `onTurnComplete` | `(turn: AgentChatTurn, { sessionId }) => void`, once per finished run |
112
+
61
113
  ### `useAgentRun`
62
114
 
63
115
  Build your own UI on the hook:
package/dist/index.cjs CHANGED
@@ -745,9 +745,9 @@ function FileChip({ name, tag, preview, status, error, onRemove }) {
745
745
  )
746
746
  ] });
747
747
  }
748
- function Turn({ turn, previews }) {
749
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: `seclai-turn seclai-turn-${turn.role}`, children: [
750
- turn.files && turn.files.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ul", { className: "seclai-files", "aria-label": "Attached files", children: turn.files.map((file) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
748
+ function UserTurn({ message, previews }) {
749
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: "seclai-turn seclai-turn-user", children: [
750
+ message.files.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("ul", { className: "seclai-files", "aria-label": "Attached files", children: message.files.map((file) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
751
751
  FileChip,
752
752
  {
753
753
  name: file.name,
@@ -756,12 +756,32 @@ function Turn({ turn, previews }) {
756
756
  },
757
757
  file.uploadId
758
758
  )) }),
759
- turn.text && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MarkdownContent, { content: turn.text }),
760
- turn.attachments && turn.attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MediaGallery, { attachments: turn.attachments }),
759
+ message.input && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MarkdownContent, { content: message.input })
760
+ ] });
761
+ }
762
+ function AssistantTurn({ turn, endpoints }) {
763
+ const { runId } = turn;
764
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("li", { className: "seclai-turn seclai-turn-assistant", children: [
765
+ turn.output && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MarkdownContent, { content: turn.output }),
766
+ runId && turn.attachments && turn.attachments.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
767
+ MediaGallery,
768
+ {
769
+ attachments: turn.attachments.map(({ id, name, mime, bytes }) => ({
770
+ id,
771
+ name,
772
+ mime,
773
+ bytes,
774
+ url: endpoints.download(runId, id, name)
775
+ }))
776
+ }
777
+ ),
761
778
  turn.error && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "seclai-error", role: "alert", children: turn.error }),
762
- turn.cancelled && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "seclai-notice", children: "Stopped." })
779
+ turn.status === "cancelled" && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "seclai-notice", children: "Stopped." })
763
780
  ] });
764
781
  }
782
+ function toTurnAttachment({ id, name, mime, bytes }) {
783
+ return { id, name, mime, bytes };
784
+ }
765
785
  function AttachControl({
766
786
  label,
767
787
  accept,
@@ -793,20 +813,60 @@ function AgentChat({
793
813
  agentId,
794
814
  placeholder = "Send a message",
795
815
  attachButtons,
796
- onBeforeSend
816
+ onBeforeSend,
817
+ sessionId,
818
+ initialTurns,
819
+ onTurnComplete
797
820
  }) {
798
821
  const endpoints = (0, import_react6.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
799
822
  const run = useAgentRun({ basePath, agentId });
800
823
  const { slots } = useAcceptedAttachments(endpoints);
801
- const [turns, setTurns] = (0, import_react6.useState)([]);
824
+ const [transcript, setTranscript] = (0, import_react6.useState)(() => ({
825
+ sessionId,
826
+ epoch: 0,
827
+ turns: initialTurns ?? [],
828
+ pending: null,
829
+ generatedSessionId: null,
830
+ runEpoch: null
831
+ }));
802
832
  const [message, setMessage] = (0, import_react6.useState)("");
803
833
  const [files, setFiles] = (0, import_react6.useState)([]);
804
834
  const [notice, setNotice] = (0, import_react6.useState)(null);
805
835
  const [dragging, setDragging] = (0, import_react6.useState)(false);
806
- const sessionId = (0, import_react6.useRef)(null);
807
- const nextTurnId = (0, import_react6.useRef)(0);
836
+ const generatedSessionId = (0, import_react6.useRef)(null);
837
+ const shownEpoch = (0, import_react6.useRef)(transcript.epoch);
838
+ const turnComplete = (0, import_react6.useRef)(onTurnComplete);
808
839
  const sentPreviews = (0, import_react6.useRef)(/* @__PURE__ */ new Map());
809
840
  const pendingPreviews = (0, import_react6.useRef)(/* @__PURE__ */ new Set());
841
+ if (transcript.sessionId !== sessionId) {
842
+ const adopting = transcript.sessionId === void 0 && sessionId !== void 0 && sessionId === transcript.generatedSessionId;
843
+ setTranscript(
844
+ adopting ? { ...transcript, sessionId } : {
845
+ sessionId,
846
+ epoch: transcript.epoch + 1,
847
+ turns: initialTurns ?? [],
848
+ pending: null,
849
+ generatedSessionId: null,
850
+ runEpoch: null
851
+ }
852
+ );
853
+ }
854
+ (0, import_react6.useEffect)(() => {
855
+ turnComplete.current = onTurnComplete;
856
+ });
857
+ (0, import_react6.useEffect)(() => {
858
+ if (shownEpoch.current === transcript.epoch) return;
859
+ shownEpoch.current = transcript.epoch;
860
+ run.cancel();
861
+ generatedSessionId.current = null;
862
+ pendingPreviews.current.forEach(revoke);
863
+ pendingPreviews.current.clear();
864
+ sentPreviews.current.forEach(revoke);
865
+ sentPreviews.current.clear();
866
+ setMessage("");
867
+ setFiles([]);
868
+ setNotice(null);
869
+ }, [transcript.epoch, run.cancel]);
810
870
  (0, import_react6.useEffect)(
811
871
  () => () => {
812
872
  pendingPreviews.current.forEach(revoke);
@@ -817,6 +877,7 @@ function AgentChat({
817
877
  const limits = slots?.length ? messageFileLimits(slots) : null;
818
878
  const acceptsFiles = !!limits && (limits.max == null || limits.max > 0);
819
879
  const running = run.status === "running";
880
+ const streaming = running && transcript.runEpoch === transcript.epoch;
820
881
  const uploading = files.some((f) => f.status === "uploading");
821
882
  const ready = files.filter((f) => f.status === "ready" && f.uploadId);
822
883
  const room = limits?.max == null ? Infinity : limits.max - files.filter((f) => f.status !== "error").length;
@@ -895,30 +956,37 @@ function AgentChat({
895
956
  if (f.status === "ready" && f.uploadId) sentPreviews.current.set(f.uploadId, f.preview);
896
957
  else revoke(f.preview);
897
958
  }
898
- sessionId.current ??= createSessionId();
959
+ const runSessionId = sessionId ?? (generatedSessionId.current ??= createSessionId());
960
+ const { epoch } = transcript;
899
961
  setMessage("");
900
962
  setFiles([]);
901
963
  setNotice(null);
902
- setTurns((prev) => [
964
+ setTranscript((prev) => ({
903
965
  ...prev,
904
- { id: nextTurnId.current++, role: "user", text, ...sent.length ? { files: sent } : {} }
905
- ]);
966
+ pending: { input: text, files: sent },
967
+ runEpoch: epoch,
968
+ ...sessionId === void 0 ? { generatedSessionId: runSessionId } : {}
969
+ }));
906
970
  const result = await run.start({
907
971
  input,
908
972
  uploadIds: sent.length ? sent.map((f) => f.uploadId) : void 0,
909
- sessionId: sessionId.current
973
+ sessionId: runSessionId
910
974
  });
911
- setTurns((prev) => [
912
- ...prev,
913
- {
914
- id: nextTurnId.current++,
915
- role: "assistant",
916
- text: result.text,
917
- attachments: result.attachments,
918
- error: result.error,
919
- cancelled: result.status === "cancelled"
920
- }
921
- ]);
975
+ const turn = {
976
+ input: text,
977
+ ...typeof override === "string" && override !== text ? { sentInput: override } : {},
978
+ files: sent,
979
+ output: result.text,
980
+ attachments: result.attachments.map(toTurnAttachment),
981
+ runId: result.runId,
982
+ // `start` always settles, so the run is over.
983
+ status: result.status,
984
+ error: result.error
985
+ };
986
+ setTranscript(
987
+ (prev) => prev.epoch === epoch ? { ...prev, turns: [...prev.turns, turn], pending: null, runEpoch: null } : prev
988
+ );
989
+ turnComplete.current?.(turn, { sessionId: runSessionId });
922
990
  }
923
991
  function onSubmit(event) {
924
992
  event.preventDefault();
@@ -956,9 +1024,19 @@ function AgentChat({
956
1024
  } : {};
957
1025
  const buttons = attachButtons?.length ? attachButtons : [{ label: "Attach" }];
958
1026
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "seclai-agent seclai-chat", children: [
959
- /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": running, children: [
960
- turns.map((turn) => /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Turn, { turn, previews: sentPreviews.current }, turn.id)),
961
- running && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MarkdownContent, { content: run.text }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
1027
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": streaming, children: [
1028
+ transcript.turns.map((turn, i) => /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_react6.Fragment, { children: [
1029
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1030
+ UserTurn,
1031
+ {
1032
+ message: { input: turn.input, files: turn.files ?? [] },
1033
+ previews: sentPreviews.current
1034
+ }
1035
+ ),
1036
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(AssistantTurn, { turn, endpoints })
1037
+ ] }, `${transcript.epoch}:${i}`)),
1038
+ transcript.pending && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(UserTurn, { message: transcript.pending, previews: sentPreviews.current }),
1039
+ streaming && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(MarkdownContent, { content: run.text }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
962
1040
  ] }),
963
1041
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
964
1042
  "form",
package/dist/index.d.cts CHANGED
@@ -90,14 +90,70 @@ interface AgentChatProps extends AgentEndpointOptions {
90
90
  * from their tags. The transcript still shows what the user typed.
91
91
  */
92
92
  onBeforeSend?(message: AgentChatMessage): string | void;
93
+ /**
94
+ * The session id sent with every run, which keys the agent's conversation
95
+ * memory. Leave it out and the chat makes one up on the first message.
96
+ *
97
+ * Changing it switches to another conversation: the transcript resets to
98
+ * `initialTurns`, the composer clears, and a reply still streaming stops.
99
+ * Remounting with a `key` does the same. Passing the id the chat generated,
100
+ * after starting without one, adopts it and resets nothing. For a new chat,
101
+ * prefer generating the id up front and passing it from the start.
102
+ */
103
+ sessionId?: string;
104
+ /**
105
+ * Exchanges to show when the chat mounts, or when `sessionId` changes, such as
106
+ * the ones `onTurnComplete` gave you. Read only then: later changes are
107
+ * ignored, as with an input's `defaultValue`.
108
+ */
109
+ initialTurns?: AgentChatTurn[];
110
+ /**
111
+ * Called once per run, when it completes, fails or is cancelled, with the
112
+ * exchange as plain data to save and pass back as `initialTurns`. A run cut
113
+ * short by a `sessionId` change or an unmount still reports, as cancelled,
114
+ * through the latest callback: save under `context.sessionId`, not a session
115
+ * id captured from the surrounding scope.
116
+ */
117
+ onTurnComplete?(turn: AgentChatTurn, context: {
118
+ sessionId: string;
119
+ }): void;
120
+ }
121
+ /** A file an agent produced, without its URL, which is rebuilt from `runId` and `id`. */
122
+ interface AgentChatAttachment {
123
+ id: string;
124
+ name: string | null;
125
+ mime: string;
126
+ bytes: number | null;
127
+ }
128
+ /**
129
+ * One exchange: a message and the agent's reply. It's plain, serializable data,
130
+ * so `onTurnComplete` output can be stored and passed back as `initialTurns`.
131
+ */
132
+ interface AgentChatTurn {
133
+ /** What the user typed. */
134
+ input: string;
135
+ /** What was sent as the run's input, when `onBeforeSend` changed it. */
136
+ sentInput?: string;
137
+ /** Files sent with the message. Restored ones show without thumbnails. */
138
+ files?: AgentChatFile[];
139
+ /** The reply. For a failed or cancelled run, whatever had streamed. */
140
+ output: string;
141
+ /** Files the agent produced. Shown only when `runId` is set. */
142
+ attachments?: AgentChatAttachment[];
143
+ runId?: string | null;
144
+ status: "completed" | "failed" | "cancelled";
145
+ error?: string | null;
93
146
  }
94
147
  /**
95
148
  * A multi-turn chat. Each message is its own run, and the agent ties them into a
96
149
  * conversation through the session id in the run's metadata. When the agent
97
150
  * accepts files they can be attached, dropped or pasted, and each one uploads
98
151
  * as soon as it's added.
152
+ *
153
+ * Pass `sessionId` and `initialTurns` to reopen a saved conversation, and save
154
+ * each exchange from `onTurnComplete`.
99
155
  */
100
- declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
156
+ declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, sessionId, initialTurns, onTurnComplete, }: AgentChatProps): react.JSX.Element;
101
157
 
102
158
  interface SseEvent {
103
159
  event: string;
@@ -330,4 +386,4 @@ interface MarkdownContentProps {
330
386
  */
331
387
  declare function MarkdownContent({ content }: MarkdownContentProps): react.JSX.Element;
332
388
 
333
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
389
+ export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatAttachment, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentChatTurn, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
package/dist/index.d.ts CHANGED
@@ -90,14 +90,70 @@ interface AgentChatProps extends AgentEndpointOptions {
90
90
  * from their tags. The transcript still shows what the user typed.
91
91
  */
92
92
  onBeforeSend?(message: AgentChatMessage): string | void;
93
+ /**
94
+ * The session id sent with every run, which keys the agent's conversation
95
+ * memory. Leave it out and the chat makes one up on the first message.
96
+ *
97
+ * Changing it switches to another conversation: the transcript resets to
98
+ * `initialTurns`, the composer clears, and a reply still streaming stops.
99
+ * Remounting with a `key` does the same. Passing the id the chat generated,
100
+ * after starting without one, adopts it and resets nothing. For a new chat,
101
+ * prefer generating the id up front and passing it from the start.
102
+ */
103
+ sessionId?: string;
104
+ /**
105
+ * Exchanges to show when the chat mounts, or when `sessionId` changes, such as
106
+ * the ones `onTurnComplete` gave you. Read only then: later changes are
107
+ * ignored, as with an input's `defaultValue`.
108
+ */
109
+ initialTurns?: AgentChatTurn[];
110
+ /**
111
+ * Called once per run, when it completes, fails or is cancelled, with the
112
+ * exchange as plain data to save and pass back as `initialTurns`. A run cut
113
+ * short by a `sessionId` change or an unmount still reports, as cancelled,
114
+ * through the latest callback: save under `context.sessionId`, not a session
115
+ * id captured from the surrounding scope.
116
+ */
117
+ onTurnComplete?(turn: AgentChatTurn, context: {
118
+ sessionId: string;
119
+ }): void;
120
+ }
121
+ /** A file an agent produced, without its URL, which is rebuilt from `runId` and `id`. */
122
+ interface AgentChatAttachment {
123
+ id: string;
124
+ name: string | null;
125
+ mime: string;
126
+ bytes: number | null;
127
+ }
128
+ /**
129
+ * One exchange: a message and the agent's reply. It's plain, serializable data,
130
+ * so `onTurnComplete` output can be stored and passed back as `initialTurns`.
131
+ */
132
+ interface AgentChatTurn {
133
+ /** What the user typed. */
134
+ input: string;
135
+ /** What was sent as the run's input, when `onBeforeSend` changed it. */
136
+ sentInput?: string;
137
+ /** Files sent with the message. Restored ones show without thumbnails. */
138
+ files?: AgentChatFile[];
139
+ /** The reply. For a failed or cancelled run, whatever had streamed. */
140
+ output: string;
141
+ /** Files the agent produced. Shown only when `runId` is set. */
142
+ attachments?: AgentChatAttachment[];
143
+ runId?: string | null;
144
+ status: "completed" | "failed" | "cancelled";
145
+ error?: string | null;
93
146
  }
94
147
  /**
95
148
  * A multi-turn chat. Each message is its own run, and the agent ties them into a
96
149
  * conversation through the session id in the run's metadata. When the agent
97
150
  * accepts files they can be attached, dropped or pasted, and each one uploads
98
151
  * as soon as it's added.
152
+ *
153
+ * Pass `sessionId` and `initialTurns` to reopen a saved conversation, and save
154
+ * each exchange from `onTurnComplete`.
99
155
  */
100
- declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
156
+ declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, sessionId, initialTurns, onTurnComplete, }: AgentChatProps): react.JSX.Element;
101
157
 
102
158
  interface SseEvent {
103
159
  event: string;
@@ -330,4 +386,4 @@ interface MarkdownContentProps {
330
386
  */
331
387
  declare function MarkdownContent({ content }: MarkdownContentProps): react.JSX.Element;
332
388
 
333
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
389
+ export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatAttachment, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentChatTurn, type AgentEndpointOptions, type AgentEndpoints, type AgentRunEvent, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, type MediaAspectRatio, MediaGallery, type MediaGalleryProps, MediaPreview, type MediaPreviewProps, MediaSkeleton, type MediaSkeletonProps, MediaViewer, type MediaViewerProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, attachmentFileName, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  // src/AgentChat.tsx
4
4
  import {
5
+ Fragment as Fragment3,
5
6
  useEffect as useEffect6,
6
7
  useMemo as useMemo2,
7
8
  useRef as useRef5,
@@ -712,9 +713,9 @@ function FileChip({ name, tag, preview, status, error, onRemove }) {
712
713
  )
713
714
  ] });
714
715
  }
715
- function Turn({ turn, previews }) {
716
- return /* @__PURE__ */ jsxs5("li", { className: `seclai-turn seclai-turn-${turn.role}`, children: [
717
- turn.files && turn.files.length > 0 && /* @__PURE__ */ jsx6("ul", { className: "seclai-files", "aria-label": "Attached files", children: turn.files.map((file) => /* @__PURE__ */ jsx6(
716
+ function UserTurn({ message, previews }) {
717
+ return /* @__PURE__ */ jsxs5("li", { className: "seclai-turn seclai-turn-user", children: [
718
+ message.files.length > 0 && /* @__PURE__ */ jsx6("ul", { className: "seclai-files", "aria-label": "Attached files", children: message.files.map((file) => /* @__PURE__ */ jsx6(
718
719
  FileChip,
719
720
  {
720
721
  name: file.name,
@@ -723,12 +724,32 @@ function Turn({ turn, previews }) {
723
724
  },
724
725
  file.uploadId
725
726
  )) }),
726
- turn.text && /* @__PURE__ */ jsx6(MarkdownContent, { content: turn.text }),
727
- turn.attachments && turn.attachments.length > 0 && /* @__PURE__ */ jsx6(MediaGallery, { attachments: turn.attachments }),
727
+ message.input && /* @__PURE__ */ jsx6(MarkdownContent, { content: message.input })
728
+ ] });
729
+ }
730
+ function AssistantTurn({ turn, endpoints }) {
731
+ const { runId } = turn;
732
+ return /* @__PURE__ */ jsxs5("li", { className: "seclai-turn seclai-turn-assistant", children: [
733
+ turn.output && /* @__PURE__ */ jsx6(MarkdownContent, { content: turn.output }),
734
+ runId && turn.attachments && turn.attachments.length > 0 && /* @__PURE__ */ jsx6(
735
+ MediaGallery,
736
+ {
737
+ attachments: turn.attachments.map(({ id, name, mime, bytes }) => ({
738
+ id,
739
+ name,
740
+ mime,
741
+ bytes,
742
+ url: endpoints.download(runId, id, name)
743
+ }))
744
+ }
745
+ ),
728
746
  turn.error && /* @__PURE__ */ jsx6("p", { className: "seclai-error", role: "alert", children: turn.error }),
729
- turn.cancelled && /* @__PURE__ */ jsx6("p", { className: "seclai-notice", children: "Stopped." })
747
+ turn.status === "cancelled" && /* @__PURE__ */ jsx6("p", { className: "seclai-notice", children: "Stopped." })
730
748
  ] });
731
749
  }
750
+ function toTurnAttachment({ id, name, mime, bytes }) {
751
+ return { id, name, mime, bytes };
752
+ }
732
753
  function AttachControl({
733
754
  label,
734
755
  accept,
@@ -760,20 +781,60 @@ function AgentChat({
760
781
  agentId,
761
782
  placeholder = "Send a message",
762
783
  attachButtons,
763
- onBeforeSend
784
+ onBeforeSend,
785
+ sessionId,
786
+ initialTurns,
787
+ onTurnComplete
764
788
  }) {
765
789
  const endpoints = useMemo2(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
766
790
  const run = useAgentRun({ basePath, agentId });
767
791
  const { slots } = useAcceptedAttachments(endpoints);
768
- const [turns, setTurns] = useState5([]);
792
+ const [transcript, setTranscript] = useState5(() => ({
793
+ sessionId,
794
+ epoch: 0,
795
+ turns: initialTurns ?? [],
796
+ pending: null,
797
+ generatedSessionId: null,
798
+ runEpoch: null
799
+ }));
769
800
  const [message, setMessage] = useState5("");
770
801
  const [files, setFiles] = useState5([]);
771
802
  const [notice, setNotice] = useState5(null);
772
803
  const [dragging, setDragging] = useState5(false);
773
- const sessionId = useRef5(null);
774
- const nextTurnId = useRef5(0);
804
+ const generatedSessionId = useRef5(null);
805
+ const shownEpoch = useRef5(transcript.epoch);
806
+ const turnComplete = useRef5(onTurnComplete);
775
807
  const sentPreviews = useRef5(/* @__PURE__ */ new Map());
776
808
  const pendingPreviews = useRef5(/* @__PURE__ */ new Set());
809
+ if (transcript.sessionId !== sessionId) {
810
+ const adopting = transcript.sessionId === void 0 && sessionId !== void 0 && sessionId === transcript.generatedSessionId;
811
+ setTranscript(
812
+ adopting ? { ...transcript, sessionId } : {
813
+ sessionId,
814
+ epoch: transcript.epoch + 1,
815
+ turns: initialTurns ?? [],
816
+ pending: null,
817
+ generatedSessionId: null,
818
+ runEpoch: null
819
+ }
820
+ );
821
+ }
822
+ useEffect6(() => {
823
+ turnComplete.current = onTurnComplete;
824
+ });
825
+ useEffect6(() => {
826
+ if (shownEpoch.current === transcript.epoch) return;
827
+ shownEpoch.current = transcript.epoch;
828
+ run.cancel();
829
+ generatedSessionId.current = null;
830
+ pendingPreviews.current.forEach(revoke);
831
+ pendingPreviews.current.clear();
832
+ sentPreviews.current.forEach(revoke);
833
+ sentPreviews.current.clear();
834
+ setMessage("");
835
+ setFiles([]);
836
+ setNotice(null);
837
+ }, [transcript.epoch, run.cancel]);
777
838
  useEffect6(
778
839
  () => () => {
779
840
  pendingPreviews.current.forEach(revoke);
@@ -784,6 +845,7 @@ function AgentChat({
784
845
  const limits = slots?.length ? messageFileLimits(slots) : null;
785
846
  const acceptsFiles = !!limits && (limits.max == null || limits.max > 0);
786
847
  const running = run.status === "running";
848
+ const streaming = running && transcript.runEpoch === transcript.epoch;
787
849
  const uploading = files.some((f) => f.status === "uploading");
788
850
  const ready = files.filter((f) => f.status === "ready" && f.uploadId);
789
851
  const room = limits?.max == null ? Infinity : limits.max - files.filter((f) => f.status !== "error").length;
@@ -862,30 +924,37 @@ function AgentChat({
862
924
  if (f.status === "ready" && f.uploadId) sentPreviews.current.set(f.uploadId, f.preview);
863
925
  else revoke(f.preview);
864
926
  }
865
- sessionId.current ??= createSessionId();
927
+ const runSessionId = sessionId ?? (generatedSessionId.current ??= createSessionId());
928
+ const { epoch } = transcript;
866
929
  setMessage("");
867
930
  setFiles([]);
868
931
  setNotice(null);
869
- setTurns((prev) => [
932
+ setTranscript((prev) => ({
870
933
  ...prev,
871
- { id: nextTurnId.current++, role: "user", text, ...sent.length ? { files: sent } : {} }
872
- ]);
934
+ pending: { input: text, files: sent },
935
+ runEpoch: epoch,
936
+ ...sessionId === void 0 ? { generatedSessionId: runSessionId } : {}
937
+ }));
873
938
  const result = await run.start({
874
939
  input,
875
940
  uploadIds: sent.length ? sent.map((f) => f.uploadId) : void 0,
876
- sessionId: sessionId.current
941
+ sessionId: runSessionId
877
942
  });
878
- setTurns((prev) => [
879
- ...prev,
880
- {
881
- id: nextTurnId.current++,
882
- role: "assistant",
883
- text: result.text,
884
- attachments: result.attachments,
885
- error: result.error,
886
- cancelled: result.status === "cancelled"
887
- }
888
- ]);
943
+ const turn = {
944
+ input: text,
945
+ ...typeof override === "string" && override !== text ? { sentInput: override } : {},
946
+ files: sent,
947
+ output: result.text,
948
+ attachments: result.attachments.map(toTurnAttachment),
949
+ runId: result.runId,
950
+ // `start` always settles, so the run is over.
951
+ status: result.status,
952
+ error: result.error
953
+ };
954
+ setTranscript(
955
+ (prev) => prev.epoch === epoch ? { ...prev, turns: [...prev.turns, turn], pending: null, runEpoch: null } : prev
956
+ );
957
+ turnComplete.current?.(turn, { sessionId: runSessionId });
889
958
  }
890
959
  function onSubmit(event) {
891
960
  event.preventDefault();
@@ -923,9 +992,19 @@ function AgentChat({
923
992
  } : {};
924
993
  const buttons = attachButtons?.length ? attachButtons : [{ label: "Attach" }];
925
994
  return /* @__PURE__ */ jsxs5("div", { className: "seclai-agent seclai-chat", children: [
926
- /* @__PURE__ */ jsxs5("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": running, children: [
927
- turns.map((turn) => /* @__PURE__ */ jsx6(Turn, { turn, previews: sentPreviews.current }, turn.id)),
928
- running && /* @__PURE__ */ jsx6("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ jsx6(MarkdownContent, { content: run.text }) : /* @__PURE__ */ jsx6("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
995
+ /* @__PURE__ */ jsxs5("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": streaming, children: [
996
+ transcript.turns.map((turn, i) => /* @__PURE__ */ jsxs5(Fragment3, { children: [
997
+ /* @__PURE__ */ jsx6(
998
+ UserTurn,
999
+ {
1000
+ message: { input: turn.input, files: turn.files ?? [] },
1001
+ previews: sentPreviews.current
1002
+ }
1003
+ ),
1004
+ /* @__PURE__ */ jsx6(AssistantTurn, { turn, endpoints })
1005
+ ] }, `${transcript.epoch}:${i}`)),
1006
+ transcript.pending && /* @__PURE__ */ jsx6(UserTurn, { message: transcript.pending, previews: sentPreviews.current }),
1007
+ streaming && /* @__PURE__ */ jsx6("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ jsx6(MarkdownContent, { content: run.text }) : /* @__PURE__ */ jsx6("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
929
1008
  ] }),
930
1009
  /* @__PURE__ */ jsxs5(
931
1010
  "form",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/react",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "React components and hooks for running Seclai agents: run form, chat, and streaming output.",
5
5
  "license": "MIT",
6
6
  "type": "module",