@seclai/react 0.0.6 → 0.0.7

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
@@ -63,7 +63,9 @@ To tell files apart, add named buttons with tags, then use the tags in `onBefore
63
63
  Build your own UI on the hook:
64
64
 
65
65
  ```tsx
66
- const { status, text, steps, attachments, error, start, cancel } = useAgentRun();
66
+ const { status, text, steps, attachments, error, startedAt, start, cancel, reset } = useAgentRun({
67
+ onEvent: (event) => console.debug(event.event, event.data),
68
+ });
67
69
 
68
70
  await start({ input: "Hello", uploadIds: ["..."], sessionId: "..." });
69
71
  ```
@@ -71,8 +73,35 @@ await start({ input: "Hello", uploadIds: ["..."], sessionId: "..." });
71
73
  - `status` is `idle`, `running`, `completed`, `failed` or `cancelled`.
72
74
  - `text` holds streamed tokens while running, then the run's final output.
73
75
  - `attachments` have a `url` that goes through your download handler.
74
- - `start` resolves with the final state and doesn't reject. Failures appear in `status` and `error`.
76
+ - `startedAt` is when `start` began, from `Date.now()`. It's kept after the run ends and is `null` before the first run and after `reset`.
77
+ - `start` resolves with the final state and doesn't reject. Failures appear in `status` and `error`. A run stopped by `cancel()` or `reset()` resolves as `cancelled`.
75
78
  - `cancel` stops streaming, but the run carries on at Seclai.
79
+ - `reset` returns to `idle` and clears `text`, `steps`, `attachments`, `error`, `runId` and `startedAt`. During a run it stops streaming as `cancel` does, so the run also carries on at Seclai.
80
+ - `onEvent` is called with each event from the run stream, `{ event, data }`, in order, as the hook updates its state. Events from a stopped run aren't passed on. The latest callback is always used, so an inline function is fine. If it throws, the error goes to `console.error` and the run carries on.
81
+
82
+ Options also take `basePath` and `agentId`, as the components do.
83
+
84
+ Runs that generate images can take a minute or two, so show the time elapsed:
85
+
86
+ ```tsx
87
+ function Elapsed({ startedAt }: { startedAt: number }) {
88
+ const [now, setNow] = useState(Date.now());
89
+ useEffect(() => {
90
+ const timer = setInterval(() => setNow(Date.now()), 1000);
91
+ return () => clearInterval(timer);
92
+ }, []);
93
+ const seconds = Math.max(0, Math.floor((now - startedAt) / 1000));
94
+ return <>{Math.floor(seconds / 60)}:{String(seconds % 60).padStart(2, "0")}</>;
95
+ }
96
+
97
+ const run = useAgentRun();
98
+
99
+ {run.status === "running" && run.startedAt !== null && (
100
+ <p>
101
+ Usually takes a minute or two · <Elapsed startedAt={run.startedAt} />
102
+ </p>
103
+ )}
104
+ ```
76
105
 
77
106
  ### Building your own UI
78
107
 
package/dist/index.cjs CHANGED
@@ -205,7 +205,8 @@ var IDLE = {
205
205
  steps: [],
206
206
  attachments: [],
207
207
  error: null,
208
- runId: null
208
+ runId: null,
209
+ startedAt: null
209
210
  };
210
211
  function toAttachments(files, runId, endpoints) {
211
212
  if (!files || !runId) return [];
@@ -283,17 +284,21 @@ function applyEvent(state, { event, data }, endpoints) {
283
284
  }
284
285
  }
285
286
  function useAgentRun(options = {}) {
286
- const { basePath, agentId } = options;
287
+ const { basePath, agentId, onEvent } = options;
287
288
  const endpoints = (0, import_react2.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
288
289
  const [state, setState] = (0, import_react2.useState)(IDLE);
289
290
  const active = (0, import_react2.useRef)(null);
291
+ const onEventRef = (0, import_react2.useRef)(onEvent);
292
+ (0, import_react2.useEffect)(() => {
293
+ onEventRef.current = onEvent;
294
+ });
290
295
  (0, import_react2.useEffect)(() => () => active.current?.abort(), []);
291
296
  const start = (0, import_react2.useCallback)(
292
297
  async ({ input, uploadIds, sessionId }) => {
293
298
  active.current?.abort();
294
299
  const controller = new AbortController();
295
300
  active.current = controller;
296
- let current = { ...IDLE, status: "running" };
301
+ let current = { ...IDLE, status: "running", startedAt: Date.now() };
297
302
  const update = (next) => {
298
303
  current = next;
299
304
  if (active.current === controller) setState(next);
@@ -315,10 +320,18 @@ function useAgentRun(options = {}) {
315
320
  return current;
316
321
  }
317
322
  for await (const event of readSseStream(res.body)) {
323
+ if (controller.signal.aborted) break;
318
324
  update(applyEvent(current, event, endpoints));
325
+ try {
326
+ onEventRef.current?.(event);
327
+ } catch (err) {
328
+ console.error("useAgentRun: onEvent threw", err);
329
+ }
319
330
  if (current.status !== "running") break;
320
331
  }
321
- if (current.status === "running") {
332
+ if (controller.signal.aborted) {
333
+ if (current.status === "running") update({ ...current, status: "cancelled" });
334
+ } else if (current.status === "running") {
322
335
  update({
323
336
  ...current,
324
337
  status: "failed",
@@ -341,7 +354,13 @@ function useAgentRun(options = {}) {
341
354
  [endpoints]
342
355
  );
343
356
  const cancel = (0, import_react2.useCallback)(() => active.current?.abort(), []);
344
- return { ...state, start, cancel };
357
+ const reset = (0, import_react2.useCallback)(() => {
358
+ const controller = active.current;
359
+ active.current = null;
360
+ controller?.abort();
361
+ setState(IDLE);
362
+ }, []);
363
+ return { ...state, start, cancel, reset };
345
364
  }
346
365
 
347
366
  // src/AgentChat.tsx
package/dist/index.d.cts CHANGED
@@ -98,6 +98,11 @@ interface AgentChatProps extends AgentEndpointOptions {
98
98
  */
99
99
  declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
100
100
 
101
+ interface SseEvent {
102
+ event: string;
103
+ data: unknown;
104
+ }
105
+
101
106
  interface AgentRunState {
102
107
  status: AgentRunStatus;
103
108
  /** Streamed tokens while running; the run's final `output` once it completes. */
@@ -107,6 +112,24 @@ interface AgentRunState {
107
112
  attachments: AgentAttachment[];
108
113
  error: string | null;
109
114
  runId: string | null;
115
+ /**
116
+ * When the current run started, from `Date.now()`. Kept once the run ends, so
117
+ * a UI can show how long it took. `null` until `start` is called, and again
118
+ * after `reset`.
119
+ */
120
+ startedAt: number | null;
121
+ }
122
+ /** One event from the run stream: the SSE event name and its parsed JSON data. */
123
+ type AgentRunEvent = SseEvent;
124
+ interface UseAgentRunOptions extends AgentEndpointOptions {
125
+ /**
126
+ * Called with each event read from the run stream, in order, as the hook
127
+ * applies it to the state. The latest callback is always used, so it can be
128
+ * an inline function. Events from a cancelled, reset or superseded run are
129
+ * not passed on. If it throws, the error is logged with `console.error` and
130
+ * the run carries on.
131
+ */
132
+ onEvent?(event: AgentRunEvent): void;
110
133
  }
111
134
  interface StartRunOptions {
112
135
  input?: string;
@@ -125,9 +148,16 @@ interface UseAgentRunResult extends AgentRunState {
125
148
  * run on Seclai, which may carry on and use credits.
126
149
  */
127
150
  cancel(): void;
151
+ /**
152
+ * Return to `idle` and clear the state, stopping any stream in progress as
153
+ * `cancel` does. Like `cancel`, it doesn't stop the run on Seclai. A pending
154
+ * `start` still resolves, with `status: "cancelled"` and the run's last
155
+ * `text`, `runId` and `startedAt`, while the hook itself shows `idle`.
156
+ */
157
+ reset(): void;
128
158
  }
129
159
  /** Run an agent through the handlers' `run` endpoint and track the event stream. */
130
- declare function useAgentRun(options?: AgentEndpointOptions): UseAgentRunResult;
160
+ declare function useAgentRun(options?: UseAgentRunOptions): UseAgentRunResult;
131
161
 
132
162
  interface AgentRunFormProps extends AgentEndpointOptions {
133
163
  /** Label for the text input. */
@@ -225,4 +255,4 @@ interface MediaPreviewProps {
225
255
  */
226
256
  declare function MediaPreview({ attachment }: MediaPreviewProps): react.JSX.Element;
227
257
 
228
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentEndpointOptions, type AgentEndpoints, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, MediaPreview, type MediaPreviewProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunResult, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
258
+ 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, MediaPreview, type MediaPreviewProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
package/dist/index.d.ts CHANGED
@@ -98,6 +98,11 @@ interface AgentChatProps extends AgentEndpointOptions {
98
98
  */
99
99
  declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
100
100
 
101
+ interface SseEvent {
102
+ event: string;
103
+ data: unknown;
104
+ }
105
+
101
106
  interface AgentRunState {
102
107
  status: AgentRunStatus;
103
108
  /** Streamed tokens while running; the run's final `output` once it completes. */
@@ -107,6 +112,24 @@ interface AgentRunState {
107
112
  attachments: AgentAttachment[];
108
113
  error: string | null;
109
114
  runId: string | null;
115
+ /**
116
+ * When the current run started, from `Date.now()`. Kept once the run ends, so
117
+ * a UI can show how long it took. `null` until `start` is called, and again
118
+ * after `reset`.
119
+ */
120
+ startedAt: number | null;
121
+ }
122
+ /** One event from the run stream: the SSE event name and its parsed JSON data. */
123
+ type AgentRunEvent = SseEvent;
124
+ interface UseAgentRunOptions extends AgentEndpointOptions {
125
+ /**
126
+ * Called with each event read from the run stream, in order, as the hook
127
+ * applies it to the state. The latest callback is always used, so it can be
128
+ * an inline function. Events from a cancelled, reset or superseded run are
129
+ * not passed on. If it throws, the error is logged with `console.error` and
130
+ * the run carries on.
131
+ */
132
+ onEvent?(event: AgentRunEvent): void;
110
133
  }
111
134
  interface StartRunOptions {
112
135
  input?: string;
@@ -125,9 +148,16 @@ interface UseAgentRunResult extends AgentRunState {
125
148
  * run on Seclai, which may carry on and use credits.
126
149
  */
127
150
  cancel(): void;
151
+ /**
152
+ * Return to `idle` and clear the state, stopping any stream in progress as
153
+ * `cancel` does. Like `cancel`, it doesn't stop the run on Seclai. A pending
154
+ * `start` still resolves, with `status: "cancelled"` and the run's last
155
+ * `text`, `runId` and `startedAt`, while the hook itself shows `idle`.
156
+ */
157
+ reset(): void;
128
158
  }
129
159
  /** Run an agent through the handlers' `run` endpoint and track the event stream. */
130
- declare function useAgentRun(options?: AgentEndpointOptions): UseAgentRunResult;
160
+ declare function useAgentRun(options?: UseAgentRunOptions): UseAgentRunResult;
131
161
 
132
162
  interface AgentRunFormProps extends AgentEndpointOptions {
133
163
  /** Label for the text input. */
@@ -225,4 +255,4 @@ interface MediaPreviewProps {
225
255
  */
226
256
  declare function MediaPreview({ attachment }: MediaPreviewProps): react.JSX.Element;
227
257
 
228
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, type AgentChatAttachButton, type AgentChatFile, type AgentChatMessage, type AgentChatProps, type AgentEndpointOptions, type AgentEndpoints, AgentRunForm, type AgentRunFormProps, type AgentRunState, type AgentRunStatus, type AgentRunStep, type AgentUiMode, type AttachmentReferences, DEFAULT_BASE_PATH, type EndpointRequestOptions, MarkdownContent, type MarkdownContentProps, MediaPreview, type MediaPreviewProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunResult, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
258
+ 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, MediaPreview, type MediaPreviewProps, SeclaiAgent, type SeclaiAgentProps, type StartRunOptions, type UploadResult, type UseAgentRunOptions, type UseAgentRunResult, createEndpoints, fetchAttachmentReferences, uploadFile, useAgentRun };
package/dist/index.js CHANGED
@@ -176,7 +176,8 @@ var IDLE = {
176
176
  steps: [],
177
177
  attachments: [],
178
178
  error: null,
179
- runId: null
179
+ runId: null,
180
+ startedAt: null
180
181
  };
181
182
  function toAttachments(files, runId, endpoints) {
182
183
  if (!files || !runId) return [];
@@ -254,17 +255,21 @@ function applyEvent(state, { event, data }, endpoints) {
254
255
  }
255
256
  }
256
257
  function useAgentRun(options = {}) {
257
- const { basePath, agentId } = options;
258
+ const { basePath, agentId, onEvent } = options;
258
259
  const endpoints = useMemo(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
259
260
  const [state, setState] = useState2(IDLE);
260
261
  const active = useRef(null);
262
+ const onEventRef = useRef(onEvent);
263
+ useEffect2(() => {
264
+ onEventRef.current = onEvent;
265
+ });
261
266
  useEffect2(() => () => active.current?.abort(), []);
262
267
  const start = useCallback(
263
268
  async ({ input, uploadIds, sessionId }) => {
264
269
  active.current?.abort();
265
270
  const controller = new AbortController();
266
271
  active.current = controller;
267
- let current = { ...IDLE, status: "running" };
272
+ let current = { ...IDLE, status: "running", startedAt: Date.now() };
268
273
  const update = (next) => {
269
274
  current = next;
270
275
  if (active.current === controller) setState(next);
@@ -286,10 +291,18 @@ function useAgentRun(options = {}) {
286
291
  return current;
287
292
  }
288
293
  for await (const event of readSseStream(res.body)) {
294
+ if (controller.signal.aborted) break;
289
295
  update(applyEvent(current, event, endpoints));
296
+ try {
297
+ onEventRef.current?.(event);
298
+ } catch (err) {
299
+ console.error("useAgentRun: onEvent threw", err);
300
+ }
290
301
  if (current.status !== "running") break;
291
302
  }
292
- if (current.status === "running") {
303
+ if (controller.signal.aborted) {
304
+ if (current.status === "running") update({ ...current, status: "cancelled" });
305
+ } else if (current.status === "running") {
293
306
  update({
294
307
  ...current,
295
308
  status: "failed",
@@ -312,7 +325,13 @@ function useAgentRun(options = {}) {
312
325
  [endpoints]
313
326
  );
314
327
  const cancel = useCallback(() => active.current?.abort(), []);
315
- return { ...state, start, cancel };
328
+ const reset = useCallback(() => {
329
+ const controller = active.current;
330
+ active.current = null;
331
+ controller?.abort();
332
+ setState(IDLE);
333
+ }, []);
334
+ return { ...state, start, cancel, reset };
316
335
  }
317
336
 
318
337
  // src/AgentChat.tsx
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/react",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
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",