@seclai/react 0.0.5 → 0.0.6

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
@@ -33,6 +33,31 @@ export function App() {
33
33
  - **`AgentChat`** sends each message as a run with a shared session id and streams the reply.
34
34
  - **`SeclaiAgent`** renders one of the two based on `mode`.
35
35
 
36
+ ### Files in `AgentChat`
37
+
38
+ When the agent accepts attachments, `AgentChat` shows an **Attach** button. Files can also be dropped on the composer or pasted into the message box. Each file uploads as soon as it's added and shows as a chip, with a thumbnail for images, and its upload id goes with the next message. Send stays disabled while a file is uploading. The files a user sent show in their turn. Agents that take no files get the text-only chat, with no attach button.
39
+
40
+ The chat applies the agent's attachment slots to each message as a whole: it accepts the content types of all the slots, and up to the sum of their `max` (no limit if any slot has none). A file that doesn't fit is refused with a message under the box. A file the browser reports no type for (such as HEIC on Windows, or `.md`) isn't refused for its type: the server decides. A run takes one flat list of upload ids, so the chat can't fill slots separately.
41
+
42
+ To tell files apart, add named buttons with tags, then use the tags in `onBeforeSend` to describe the files to the agent. Whatever it returns is sent as the run's input, and the transcript keeps what the user typed:
43
+
44
+ ```tsx
45
+ <AgentChat
46
+ attachButtons={[
47
+ { label: "+ Headshot", tag: "headshot" },
48
+ { label: "+ Style reference", tag: "style" },
49
+ ]}
50
+ onBeforeSend={({ input, files }) =>
51
+ [...files.map((f, i) => `Image ${i + 1} (${f.name}) is the ${f.tag ?? "image"}.`), input].join("\n")
52
+ }
53
+ />
54
+ ```
55
+
56
+ | Prop | |
57
+ |---|---|
58
+ | `attachButtons` | `{ label: string; tag?: string }[]`. Replaces the single Attach button. Dropped and pasted files have no tag |
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
+
36
61
  ### `useAgentRun`
37
62
 
38
63
  Build your own UI on the hook:
@@ -51,7 +76,7 @@ await start({ input: "Hello", uploadIds: ["..."], sessionId: "..." });
51
76
 
52
77
  ### Building your own UI
53
78
 
54
- `AgentChat` doesn't upload files. To send files from your own UI, use the helpers the components are built on:
79
+ To upload files and run the agent from your own UI, use the helpers the components are built on:
55
80
 
56
81
  - **`createEndpoints({ basePath, agentId })`** returns the handler URLs (`AgentEndpoints`): `attachmentReferences`, `upload`, `run`, and `download(runId, attachmentId, name?)`. Pass it the same options as `useAgentRun`.
57
82
  - **`uploadFile(endpoints, file, { signal }?)`** uploads one file and resolves with its `id`.
package/dist/index.cjs CHANGED
@@ -35,25 +35,9 @@ __export(index_exports, {
35
35
  module.exports = __toCommonJS(index_exports);
36
36
 
37
37
  // src/AgentChat.tsx
38
- var import_react2 = require("react");
39
-
40
- // src/placeholders/MarkdownContent.tsx
41
- var import_jsx_runtime = require("react/jsx-runtime");
42
- function MarkdownContent({ content }) {
43
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "seclai-markdown", children: content });
44
- }
45
-
46
- // src/placeholders/MediaPreview.tsx
47
- var import_jsx_runtime2 = require("react/jsx-runtime");
48
- function MediaPreview({ attachment }) {
49
- const name = attachment.name ?? attachment.id;
50
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("figure", { className: "seclai-media", children: [
51
- attachment.mime.startsWith("image/") && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("img", { src: attachment.url, alt: name }),
52
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("figcaption", { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("a", { href: attachment.url, download: name, children: name }) })
53
- ] });
54
- }
38
+ var import_react3 = require("react");
55
39
 
56
- // src/useAgentRun.ts
40
+ // src/attachments.ts
57
41
  var import_react = require("react");
58
42
 
59
43
  // src/endpoints.ts
@@ -96,6 +80,67 @@ async function uploadFile(endpoints, file, { signal } = {}) {
96
80
  return readJson(await fetch(endpoints.upload, { method: "POST", body: form, signal }));
97
81
  }
98
82
 
83
+ // src/attachments.ts
84
+ function useAcceptedAttachments(endpoints) {
85
+ const [state, setState] = (0, import_react.useState)({ slots: null, error: null });
86
+ (0, import_react.useEffect)(() => {
87
+ const controller = new AbortController();
88
+ setState({ slots: null, error: null });
89
+ fetchAttachmentReferences(endpoints, { signal: controller.signal }).then((refs) => setState({ slots: refs.accepted_attachments ?? [], error: null })).catch((err) => {
90
+ if (controller.signal.aborted) return;
91
+ setState({
92
+ slots: null,
93
+ error: err instanceof Error ? err.message : "Could not load this agent."
94
+ });
95
+ });
96
+ return () => controller.abort();
97
+ }, [endpoints]);
98
+ return state;
99
+ }
100
+ function acceptAttribute(contentTypes) {
101
+ return contentTypes?.length ? contentTypes.join(",") : void 0;
102
+ }
103
+ function acceptsType(contentTypes, type) {
104
+ if (!contentTypes?.length || !type) return true;
105
+ const [major] = type.toLowerCase().split("/");
106
+ return contentTypes.some((pattern) => {
107
+ const p = pattern.trim().toLowerCase();
108
+ if (p === "*/*" || p === "*") return true;
109
+ if (p.endsWith("/*")) return major === p.slice(0, -2);
110
+ return p === type.toLowerCase();
111
+ });
112
+ }
113
+ function messageFileLimits(slots) {
114
+ let max = 0;
115
+ let anyType = false;
116
+ const types = /* @__PURE__ */ new Set();
117
+ for (const slot of slots) {
118
+ max = max == null || slot.max == null ? null : max + slot.max;
119
+ if (slot.content_types?.length) slot.content_types.forEach((t) => types.add(t));
120
+ else anyType = true;
121
+ }
122
+ return { max, contentTypes: anyType ? [] : [...types] };
123
+ }
124
+
125
+ // src/placeholders/MarkdownContent.tsx
126
+ var import_jsx_runtime = require("react/jsx-runtime");
127
+ function MarkdownContent({ content }) {
128
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "seclai-markdown", children: content });
129
+ }
130
+
131
+ // src/placeholders/MediaPreview.tsx
132
+ var import_jsx_runtime2 = require("react/jsx-runtime");
133
+ function MediaPreview({ attachment }) {
134
+ const name = attachment.name ?? attachment.id;
135
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("figure", { className: "seclai-media", children: [
136
+ attachment.mime.startsWith("image/") && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("img", { src: attachment.url, alt: name }),
137
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("figcaption", { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("a", { href: attachment.url, download: name, children: name }) })
138
+ ] });
139
+ }
140
+
141
+ // src/useAgentRun.ts
142
+ var import_react2 = require("react");
143
+
99
144
  // src/sse.ts
100
145
  function parseData(data) {
101
146
  try {
@@ -239,11 +284,11 @@ function applyEvent(state, { event, data }, endpoints) {
239
284
  }
240
285
  function useAgentRun(options = {}) {
241
286
  const { basePath, agentId } = options;
242
- const endpoints = (0, import_react.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
243
- const [state, setState] = (0, import_react.useState)(IDLE);
244
- const active = (0, import_react.useRef)(null);
245
- (0, import_react.useEffect)(() => () => active.current?.abort(), []);
246
- const start = (0, import_react.useCallback)(
287
+ const endpoints = (0, import_react2.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
288
+ const [state, setState] = (0, import_react2.useState)(IDLE);
289
+ const active = (0, import_react2.useRef)(null);
290
+ (0, import_react2.useEffect)(() => () => active.current?.abort(), []);
291
+ const start = (0, import_react2.useCallback)(
247
292
  async ({ input, uploadIds, sessionId }) => {
248
293
  active.current?.abort();
249
294
  const controller = new AbortController();
@@ -295,7 +340,7 @@ function useAgentRun(options = {}) {
295
340
  },
296
341
  [endpoints]
297
342
  );
298
- const cancel = (0, import_react.useCallback)(() => active.current?.abort(), []);
343
+ const cancel = (0, import_react2.useCallback)(() => active.current?.abort(), []);
299
344
  return { ...state, start, cancel };
300
345
  }
301
346
 
@@ -308,28 +353,203 @@ function createSessionId() {
308
353
  (byte) => byte.toString(16).padStart(2, "0")
309
354
  ).join("");
310
355
  }
311
- function Turn({ turn }) {
356
+ var nextLocalId = 0;
357
+ function createPreview(file) {
358
+ if (!file.type.startsWith("image/") || typeof URL.createObjectURL !== "function") return null;
359
+ return URL.createObjectURL(file);
360
+ }
361
+ function revoke(url) {
362
+ if (url && typeof URL.revokeObjectURL === "function") URL.revokeObjectURL(url);
363
+ }
364
+ function hasFiles(dataTransfer) {
365
+ return !!dataTransfer && Array.from(dataTransfer.types ?? []).includes("Files");
366
+ }
367
+ function plural(count, word) {
368
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
369
+ }
370
+ function FileChip({ name, tag, preview, status, error, onRemove }) {
371
+ const meta = status === "uploading" ? "Uploading\u2026" : status === "error" ? error : tag;
372
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { className: "seclai-file", "data-status": status, children: [
373
+ preview && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("img", { className: "seclai-file-thumb", src: preview, alt: "" }),
374
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { className: "seclai-file-text", children: [
375
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "seclai-file-name", title: name, children: name }),
376
+ meta && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "seclai-file-meta", children: meta })
377
+ ] }),
378
+ onRemove && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
379
+ "button",
380
+ {
381
+ type: "button",
382
+ className: "seclai-file-remove",
383
+ "aria-label": `Remove ${name}`,
384
+ onClick: onRemove,
385
+ children: "\xD7"
386
+ }
387
+ )
388
+ ] });
389
+ }
390
+ function Turn({ turn, previews }) {
312
391
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { className: `seclai-turn seclai-turn-${turn.role}`, children: [
392
+ turn.files && turn.files.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ul", { className: "seclai-files", "aria-label": "Attached files", children: turn.files.map((file) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
393
+ FileChip,
394
+ {
395
+ name: file.name,
396
+ tag: file.tag,
397
+ preview: previews.get(file.uploadId)
398
+ },
399
+ file.uploadId
400
+ )) }),
313
401
  turn.text && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(MarkdownContent, { content: turn.text }),
314
402
  turn.attachments?.map((attachment) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(MediaPreview, { attachment }, attachment.id)),
315
403
  turn.error && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "seclai-error", role: "alert", children: turn.error }),
316
404
  turn.cancelled && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "seclai-notice", children: "Stopped." })
317
405
  ] });
318
406
  }
319
- function AgentChat({ basePath, agentId, placeholder = "Send a message" }) {
407
+ function AttachControl({
408
+ label,
409
+ accept,
410
+ multiple,
411
+ disabled,
412
+ onFiles
413
+ }) {
414
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("label", { className: "seclai-button seclai-attach", "aria-disabled": disabled || void 0, children: [
415
+ label,
416
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
417
+ "input",
418
+ {
419
+ type: "file",
420
+ className: "seclai-sr-only",
421
+ accept,
422
+ multiple,
423
+ disabled,
424
+ onChange: (e) => {
425
+ const picked = Array.from(e.target.files ?? []);
426
+ e.target.value = "";
427
+ if (picked.length) onFiles(picked);
428
+ }
429
+ }
430
+ )
431
+ ] });
432
+ }
433
+ function AgentChat({
434
+ basePath,
435
+ agentId,
436
+ placeholder = "Send a message",
437
+ attachButtons,
438
+ onBeforeSend
439
+ }) {
440
+ const endpoints = (0, import_react3.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
320
441
  const run = useAgentRun({ basePath, agentId });
321
- const [turns, setTurns] = (0, import_react2.useState)([]);
322
- const [message, setMessage] = (0, import_react2.useState)("");
323
- const sessionId = (0, import_react2.useRef)(null);
324
- const nextTurnId = (0, import_react2.useRef)(0);
442
+ const { slots } = useAcceptedAttachments(endpoints);
443
+ const [turns, setTurns] = (0, import_react3.useState)([]);
444
+ const [message, setMessage] = (0, import_react3.useState)("");
445
+ const [files, setFiles] = (0, import_react3.useState)([]);
446
+ const [notice, setNotice] = (0, import_react3.useState)(null);
447
+ const [dragging, setDragging] = (0, import_react3.useState)(false);
448
+ const sessionId = (0, import_react3.useRef)(null);
449
+ const nextTurnId = (0, import_react3.useRef)(0);
450
+ const sentPreviews = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
451
+ const pendingPreviews = (0, import_react3.useRef)(/* @__PURE__ */ new Set());
452
+ (0, import_react3.useEffect)(
453
+ () => () => {
454
+ pendingPreviews.current.forEach(revoke);
455
+ sentPreviews.current.forEach(revoke);
456
+ },
457
+ []
458
+ );
459
+ const limits = slots?.length ? messageFileLimits(slots) : null;
460
+ const acceptsFiles = !!limits && (limits.max == null || limits.max > 0);
325
461
  const running = run.status === "running";
462
+ const uploading = files.some((f) => f.status === "uploading");
463
+ const ready = files.filter((f) => f.status === "ready" && f.uploadId);
464
+ const room = limits?.max == null ? Infinity : limits.max - files.filter((f) => f.status !== "error").length;
465
+ const canSend = !running && !uploading && (!!message.trim() || ready.length > 0);
466
+ function setFile(localId, patch) {
467
+ setFiles((prev) => prev.map((f) => f.localId === localId ? { ...f, ...patch } : f));
468
+ }
469
+ function upload(item, file) {
470
+ uploadFile(endpoints, file).then(
471
+ (result) => setFile(item.localId, { status: "ready", uploadId: result.id }),
472
+ (err) => setFile(item.localId, {
473
+ status: "error",
474
+ error: err instanceof Error ? err.message : "The upload failed."
475
+ })
476
+ );
477
+ }
478
+ function addFiles(incoming, tag) {
479
+ if (!acceptsFiles || !limits || incoming.length === 0) return;
480
+ const problems = [];
481
+ const added = [];
482
+ let left = room;
483
+ let tooMany = false;
484
+ for (const file of incoming) {
485
+ if (!acceptsType(limits.contentTypes, file.type)) {
486
+ problems.push(`${file.name} isn't a type of file this agent accepts.`);
487
+ continue;
488
+ }
489
+ if (left <= 0) {
490
+ tooMany = true;
491
+ continue;
492
+ }
493
+ left--;
494
+ const preview = createPreview(file);
495
+ if (preview) pendingPreviews.current.add(preview);
496
+ added.push([
497
+ {
498
+ localId: `file-${++nextLocalId}`,
499
+ name: file.name,
500
+ contentType: file.type,
501
+ tag,
502
+ preview,
503
+ status: "uploading"
504
+ },
505
+ file
506
+ ]);
507
+ }
508
+ if (tooMany) problems.push(`You can attach up to ${plural(limits.max, "file")} per message.`);
509
+ setNotice(problems.length ? problems.join(" ") : null);
510
+ if (added.length === 0) return;
511
+ setFiles((prev) => [...prev, ...added.map(([item]) => item)]);
512
+ for (const [item, file] of added) upload(item, file);
513
+ }
514
+ function remove(localId) {
515
+ const gone = files.find((f) => f.localId === localId);
516
+ if (gone?.preview) {
517
+ revoke(gone.preview);
518
+ pendingPreviews.current.delete(gone.preview);
519
+ }
520
+ setFiles((prev) => prev.filter((f) => f.localId !== localId));
521
+ setNotice(null);
522
+ }
326
523
  async function send() {
524
+ if (!canSend) return;
327
525
  const text = message.trim();
328
- if (!text || running) return;
526
+ const sent = ready.map((f) => ({
527
+ uploadId: f.uploadId,
528
+ name: f.name,
529
+ contentType: f.contentType,
530
+ ...f.tag ? { tag: f.tag } : {}
531
+ }));
532
+ const override = onBeforeSend?.({ input: text, files: sent });
533
+ const input = (typeof override === "string" ? override : text) || void 0;
534
+ for (const f of files) {
535
+ if (!f.preview) continue;
536
+ pendingPreviews.current.delete(f.preview);
537
+ if (f.status === "ready" && f.uploadId) sentPreviews.current.set(f.uploadId, f.preview);
538
+ else revoke(f.preview);
539
+ }
329
540
  sessionId.current ??= createSessionId();
330
541
  setMessage("");
331
- setTurns((prev) => [...prev, { id: nextTurnId.current++, role: "user", text }]);
332
- const result = await run.start({ input: text, sessionId: sessionId.current });
542
+ setFiles([]);
543
+ setNotice(null);
544
+ setTurns((prev) => [
545
+ ...prev,
546
+ { id: nextTurnId.current++, role: "user", text, ...sent.length ? { files: sent } : {} }
547
+ ]);
548
+ const result = await run.start({
549
+ input,
550
+ uploadIds: sent.length ? sent.map((f) => f.uploadId) : void 0,
551
+ sessionId: sessionId.current
552
+ });
333
553
  setTurns((prev) => [
334
554
  ...prev,
335
555
  {
@@ -352,41 +572,91 @@ function AgentChat({ basePath, agentId, placeholder = "Send a message" }) {
352
572
  void send();
353
573
  }
354
574
  }
575
+ function onPaste(event) {
576
+ const data = event.clipboardData;
577
+ const pasted = Array.from(data?.files ?? []);
578
+ if (pasted.length === 0) return;
579
+ if (data.getData("text/plain")) return;
580
+ event.preventDefault();
581
+ addFiles(pasted);
582
+ }
583
+ const dropHandlers = acceptsFiles ? {
584
+ onDragOver(event) {
585
+ if (!hasFiles(event.dataTransfer)) return;
586
+ event.preventDefault();
587
+ setDragging(true);
588
+ },
589
+ onDragLeave(event) {
590
+ if (!event.currentTarget.contains(event.relatedTarget)) setDragging(false);
591
+ },
592
+ onDrop(event) {
593
+ if (!hasFiles(event.dataTransfer)) return;
594
+ event.preventDefault();
595
+ setDragging(false);
596
+ addFiles(Array.from(event.dataTransfer.files));
597
+ }
598
+ } : {};
599
+ const buttons = attachButtons?.length ? attachButtons : [{ label: "Attach" }];
355
600
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "seclai-agent seclai-chat", children: [
356
601
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": running, children: [
357
- turns.map((turn) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Turn, { turn }, turn.id)),
602
+ turns.map((turn) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(Turn, { turn, previews: sentPreviews.current }, turn.id)),
358
603
  running && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(MarkdownContent, { content: run.text }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
359
604
  ] }),
360
- /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("form", { className: "seclai-form", onSubmit, children: [
361
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
362
- "textarea",
363
- {
364
- rows: 2,
365
- "aria-label": "Message",
366
- placeholder,
367
- value: message,
368
- onChange: (e) => setMessage(e.target.value),
369
- onKeyDown
370
- }
371
- ),
372
- /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "seclai-actions", children: [
373
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
374
- "button",
375
- {
376
- type: "submit",
377
- className: "seclai-button seclai-button-primary",
378
- disabled: running || !message.trim(),
379
- children: "Send"
380
- }
381
- ),
382
- running && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
383
- ] })
384
- ] })
605
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
606
+ "form",
607
+ {
608
+ className: dragging ? "seclai-form seclai-dropping" : "seclai-form",
609
+ onSubmit,
610
+ ...dropHandlers,
611
+ children: [
612
+ files.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ul", { className: "seclai-files", "aria-label": "Files to send", children: files.map((f) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
613
+ FileChip,
614
+ {
615
+ name: f.name,
616
+ tag: f.tag,
617
+ preview: f.preview,
618
+ status: f.status,
619
+ error: f.error,
620
+ onRemove: () => remove(f.localId)
621
+ },
622
+ f.localId
623
+ )) }),
624
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
625
+ "textarea",
626
+ {
627
+ rows: 2,
628
+ "aria-label": "Message",
629
+ placeholder,
630
+ value: message,
631
+ onChange: (e) => setMessage(e.target.value),
632
+ onKeyDown,
633
+ onPaste: acceptsFiles ? onPaste : void 0
634
+ }
635
+ ),
636
+ notice && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("p", { className: "seclai-error", role: "alert", children: notice }),
637
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "seclai-actions", children: [
638
+ acceptsFiles && buttons.map((button) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
639
+ AttachControl,
640
+ {
641
+ label: button.label,
642
+ accept: acceptAttribute(limits.contentTypes),
643
+ multiple: room > 1,
644
+ disabled: room <= 0,
645
+ onFiles: (picked) => addFiles(picked, button.tag)
646
+ },
647
+ `${button.label}\0${button.tag ?? ""}`
648
+ )),
649
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "submit", className: "seclai-button seclai-button-primary", disabled: !canSend, children: "Send" }),
650
+ running && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
651
+ ] })
652
+ ]
653
+ }
654
+ )
385
655
  ] });
386
656
  }
387
657
 
388
658
  // src/AgentRunForm.tsx
389
- var import_react3 = require("react");
659
+ var import_react4 = require("react");
390
660
  var import_jsx_runtime4 = require("react/jsx-runtime");
391
661
  function slotProblem(slot, count) {
392
662
  const label = slot.label ?? slot.name;
@@ -398,24 +668,13 @@ function slotProblem(slot, count) {
398
668
  return null;
399
669
  }
400
670
  function AgentRunForm({ basePath, agentId, inputLabel = "Input", onFinish }) {
401
- const endpoints = (0, import_react3.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
671
+ const endpoints = (0, import_react4.useMemo)(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
402
672
  const run = useAgentRun({ basePath, agentId });
403
- const [slots, setSlots] = (0, import_react3.useState)(null);
404
- const [loadError, setLoadError] = (0, import_react3.useState)(null);
405
- const [input, setInput] = (0, import_react3.useState)("");
406
- const [files, setFiles] = (0, import_react3.useState)({});
407
- const [uploading, setUploading] = (0, import_react3.useState)(false);
408
- const [formError, setFormError] = (0, import_react3.useState)(null);
409
- (0, import_react3.useEffect)(() => {
410
- const controller = new AbortController();
411
- setSlots(null);
412
- setLoadError(null);
413
- fetchAttachmentReferences(endpoints, { signal: controller.signal }).then((refs) => setSlots(refs.accepted_attachments ?? [])).catch((err) => {
414
- if (controller.signal.aborted) return;
415
- setLoadError(err instanceof Error ? err.message : "Could not load this agent.");
416
- });
417
- return () => controller.abort();
418
- }, [endpoints]);
673
+ const { slots, error: loadError } = useAcceptedAttachments(endpoints);
674
+ const [input, setInput] = (0, import_react4.useState)("");
675
+ const [files, setFiles] = (0, import_react4.useState)({});
676
+ const [uploading, setUploading] = (0, import_react4.useState)(false);
677
+ const [formError, setFormError] = (0, import_react4.useState)(null);
419
678
  const selected = Object.values(files).flat();
420
679
  const busy = uploading || run.status === "running";
421
680
  async function submit(event) {
@@ -477,7 +736,7 @@ function AgentRunForm({ basePath, agentId, inputLabel = "Input", onFinish }) {
477
736
  {
478
737
  type: "file",
479
738
  name: slot.name,
480
- accept: slot.content_types?.length ? slot.content_types.join(",") : void 0,
739
+ accept: acceptAttribute(slot.content_types),
481
740
  multiple: slot.max == null || slot.max > 1,
482
741
  onChange: (e) => setFiles((prev) => ({ ...prev, [slot.name]: Array.from(e.target.files ?? []) }))
483
742
  }
package/dist/index.d.cts CHANGED
@@ -56,15 +56,47 @@ interface AgentEndpointOptions {
56
56
  agentId?: string;
57
57
  }
58
58
 
59
+ /** A named attach button, such as "+ Headshot". */
60
+ interface AgentChatAttachButton {
61
+ label: string;
62
+ /** Stays with every file added through this button. See `onBeforeSend`. */
63
+ tag?: string;
64
+ }
65
+ /** A file the user sent with a message. */
66
+ interface AgentChatFile {
67
+ uploadId: string;
68
+ name: string;
69
+ contentType: string;
70
+ /** The tag of the attach button it was added with. Dropped and pasted files have none. */
71
+ tag?: string;
72
+ }
73
+ /** What `onBeforeSend` gets: the typed text and the files going with it. */
74
+ interface AgentChatMessage {
75
+ input: string;
76
+ files: AgentChatFile[];
77
+ }
59
78
  interface AgentChatProps extends AgentEndpointOptions {
60
79
  /** Placeholder for the message box. */
61
80
  placeholder?: string;
81
+ /**
82
+ * Named attach buttons, for agents that take files. Without them the chat shows
83
+ * one "Attach" button, and only when the agent accepts files.
84
+ */
85
+ attachButtons?: AgentChatAttachButton[];
86
+ /**
87
+ * Called as a message is sent. Return a string to send that as the run's input
88
+ * in place of the typed text, for example to tell the agent which file is which
89
+ * from their tags. The transcript still shows what the user typed.
90
+ */
91
+ onBeforeSend?(message: AgentChatMessage): string | void;
62
92
  }
63
93
  /**
64
94
  * A multi-turn chat. Each message is its own run, and the agent ties them into a
65
- * conversation through the session id in the run's metadata.
95
+ * conversation through the session id in the run's metadata. When the agent
96
+ * accepts files they can be attached, dropped or pasted, and each one uploads
97
+ * as soon as it's added.
66
98
  */
67
- declare function AgentChat({ basePath, agentId, placeholder }: AgentChatProps): react.JSX.Element;
99
+ declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
68
100
 
69
101
  interface AgentRunState {
70
102
  status: AgentRunStatus;
@@ -193,4 +225,4 @@ interface MediaPreviewProps {
193
225
  */
194
226
  declare function MediaPreview({ attachment }: MediaPreviewProps): react.JSX.Element;
195
227
 
196
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, 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 };
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 };
package/dist/index.d.ts CHANGED
@@ -56,15 +56,47 @@ interface AgentEndpointOptions {
56
56
  agentId?: string;
57
57
  }
58
58
 
59
+ /** A named attach button, such as "+ Headshot". */
60
+ interface AgentChatAttachButton {
61
+ label: string;
62
+ /** Stays with every file added through this button. See `onBeforeSend`. */
63
+ tag?: string;
64
+ }
65
+ /** A file the user sent with a message. */
66
+ interface AgentChatFile {
67
+ uploadId: string;
68
+ name: string;
69
+ contentType: string;
70
+ /** The tag of the attach button it was added with. Dropped and pasted files have none. */
71
+ tag?: string;
72
+ }
73
+ /** What `onBeforeSend` gets: the typed text and the files going with it. */
74
+ interface AgentChatMessage {
75
+ input: string;
76
+ files: AgentChatFile[];
77
+ }
59
78
  interface AgentChatProps extends AgentEndpointOptions {
60
79
  /** Placeholder for the message box. */
61
80
  placeholder?: string;
81
+ /**
82
+ * Named attach buttons, for agents that take files. Without them the chat shows
83
+ * one "Attach" button, and only when the agent accepts files.
84
+ */
85
+ attachButtons?: AgentChatAttachButton[];
86
+ /**
87
+ * Called as a message is sent. Return a string to send that as the run's input
88
+ * in place of the typed text, for example to tell the agent which file is which
89
+ * from their tags. The transcript still shows what the user typed.
90
+ */
91
+ onBeforeSend?(message: AgentChatMessage): string | void;
62
92
  }
63
93
  /**
64
94
  * A multi-turn chat. Each message is its own run, and the agent ties them into a
65
- * conversation through the session id in the run's metadata.
95
+ * conversation through the session id in the run's metadata. When the agent
96
+ * accepts files they can be attached, dropped or pasted, and each one uploads
97
+ * as soon as it's added.
66
98
  */
67
- declare function AgentChat({ basePath, agentId, placeholder }: AgentChatProps): react.JSX.Element;
99
+ declare function AgentChat({ basePath, agentId, placeholder, attachButtons, onBeforeSend, }: AgentChatProps): react.JSX.Element;
68
100
 
69
101
  interface AgentRunState {
70
102
  status: AgentRunStatus;
@@ -193,4 +225,4 @@ interface MediaPreviewProps {
193
225
  */
194
226
  declare function MediaPreview({ attachment }: MediaPreviewProps): react.JSX.Element;
195
227
 
196
- export { type AcceptedAttachmentSlot, type AgentAttachment, AgentChat, 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 };
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 };
package/dist/index.js CHANGED
@@ -1,26 +1,15 @@
1
1
  "use client";
2
2
 
3
3
  // src/AgentChat.tsx
4
- import { useRef as useRef2, useState as useState2 } from "react";
4
+ import {
5
+ useEffect as useEffect3,
6
+ useMemo as useMemo2,
7
+ useRef as useRef2,
8
+ useState as useState3
9
+ } from "react";
5
10
 
6
- // src/placeholders/MarkdownContent.tsx
7
- import { jsx } from "react/jsx-runtime";
8
- function MarkdownContent({ content }) {
9
- return /* @__PURE__ */ jsx("div", { className: "seclai-markdown", children: content });
10
- }
11
-
12
- // src/placeholders/MediaPreview.tsx
13
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
14
- function MediaPreview({ attachment }) {
15
- const name = attachment.name ?? attachment.id;
16
- return /* @__PURE__ */ jsxs("figure", { className: "seclai-media", children: [
17
- attachment.mime.startsWith("image/") && /* @__PURE__ */ jsx2("img", { src: attachment.url, alt: name }),
18
- /* @__PURE__ */ jsx2("figcaption", { children: /* @__PURE__ */ jsx2("a", { href: attachment.url, download: name, children: name }) })
19
- ] });
20
- }
21
-
22
- // src/useAgentRun.ts
23
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
11
+ // src/attachments.ts
12
+ import { useEffect, useState } from "react";
24
13
 
25
14
  // src/endpoints.ts
26
15
  var DEFAULT_BASE_PATH = "/api/seclai";
@@ -62,6 +51,67 @@ async function uploadFile(endpoints, file, { signal } = {}) {
62
51
  return readJson(await fetch(endpoints.upload, { method: "POST", body: form, signal }));
63
52
  }
64
53
 
54
+ // src/attachments.ts
55
+ function useAcceptedAttachments(endpoints) {
56
+ const [state, setState] = useState({ slots: null, error: null });
57
+ useEffect(() => {
58
+ const controller = new AbortController();
59
+ setState({ slots: null, error: null });
60
+ fetchAttachmentReferences(endpoints, { signal: controller.signal }).then((refs) => setState({ slots: refs.accepted_attachments ?? [], error: null })).catch((err) => {
61
+ if (controller.signal.aborted) return;
62
+ setState({
63
+ slots: null,
64
+ error: err instanceof Error ? err.message : "Could not load this agent."
65
+ });
66
+ });
67
+ return () => controller.abort();
68
+ }, [endpoints]);
69
+ return state;
70
+ }
71
+ function acceptAttribute(contentTypes) {
72
+ return contentTypes?.length ? contentTypes.join(",") : void 0;
73
+ }
74
+ function acceptsType(contentTypes, type) {
75
+ if (!contentTypes?.length || !type) return true;
76
+ const [major] = type.toLowerCase().split("/");
77
+ return contentTypes.some((pattern) => {
78
+ const p = pattern.trim().toLowerCase();
79
+ if (p === "*/*" || p === "*") return true;
80
+ if (p.endsWith("/*")) return major === p.slice(0, -2);
81
+ return p === type.toLowerCase();
82
+ });
83
+ }
84
+ function messageFileLimits(slots) {
85
+ let max = 0;
86
+ let anyType = false;
87
+ const types = /* @__PURE__ */ new Set();
88
+ for (const slot of slots) {
89
+ max = max == null || slot.max == null ? null : max + slot.max;
90
+ if (slot.content_types?.length) slot.content_types.forEach((t) => types.add(t));
91
+ else anyType = true;
92
+ }
93
+ return { max, contentTypes: anyType ? [] : [...types] };
94
+ }
95
+
96
+ // src/placeholders/MarkdownContent.tsx
97
+ import { jsx } from "react/jsx-runtime";
98
+ function MarkdownContent({ content }) {
99
+ return /* @__PURE__ */ jsx("div", { className: "seclai-markdown", children: content });
100
+ }
101
+
102
+ // src/placeholders/MediaPreview.tsx
103
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
104
+ function MediaPreview({ attachment }) {
105
+ const name = attachment.name ?? attachment.id;
106
+ return /* @__PURE__ */ jsxs("figure", { className: "seclai-media", children: [
107
+ attachment.mime.startsWith("image/") && /* @__PURE__ */ jsx2("img", { src: attachment.url, alt: name }),
108
+ /* @__PURE__ */ jsx2("figcaption", { children: /* @__PURE__ */ jsx2("a", { href: attachment.url, download: name, children: name }) })
109
+ ] });
110
+ }
111
+
112
+ // src/useAgentRun.ts
113
+ import { useCallback, useEffect as useEffect2, useMemo, useRef, useState as useState2 } from "react";
114
+
65
115
  // src/sse.ts
66
116
  function parseData(data) {
67
117
  try {
@@ -206,9 +256,9 @@ function applyEvent(state, { event, data }, endpoints) {
206
256
  function useAgentRun(options = {}) {
207
257
  const { basePath, agentId } = options;
208
258
  const endpoints = useMemo(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
209
- const [state, setState] = useState(IDLE);
259
+ const [state, setState] = useState2(IDLE);
210
260
  const active = useRef(null);
211
- useEffect(() => () => active.current?.abort(), []);
261
+ useEffect2(() => () => active.current?.abort(), []);
212
262
  const start = useCallback(
213
263
  async ({ input, uploadIds, sessionId }) => {
214
264
  active.current?.abort();
@@ -274,28 +324,203 @@ function createSessionId() {
274
324
  (byte) => byte.toString(16).padStart(2, "0")
275
325
  ).join("");
276
326
  }
277
- function Turn({ turn }) {
327
+ var nextLocalId = 0;
328
+ function createPreview(file) {
329
+ if (!file.type.startsWith("image/") || typeof URL.createObjectURL !== "function") return null;
330
+ return URL.createObjectURL(file);
331
+ }
332
+ function revoke(url) {
333
+ if (url && typeof URL.revokeObjectURL === "function") URL.revokeObjectURL(url);
334
+ }
335
+ function hasFiles(dataTransfer) {
336
+ return !!dataTransfer && Array.from(dataTransfer.types ?? []).includes("Files");
337
+ }
338
+ function plural(count, word) {
339
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
340
+ }
341
+ function FileChip({ name, tag, preview, status, error, onRemove }) {
342
+ const meta = status === "uploading" ? "Uploading\u2026" : status === "error" ? error : tag;
343
+ return /* @__PURE__ */ jsxs2("li", { className: "seclai-file", "data-status": status, children: [
344
+ preview && /* @__PURE__ */ jsx3("img", { className: "seclai-file-thumb", src: preview, alt: "" }),
345
+ /* @__PURE__ */ jsxs2("span", { className: "seclai-file-text", children: [
346
+ /* @__PURE__ */ jsx3("span", { className: "seclai-file-name", title: name, children: name }),
347
+ meta && /* @__PURE__ */ jsx3("span", { className: "seclai-file-meta", children: meta })
348
+ ] }),
349
+ onRemove && /* @__PURE__ */ jsx3(
350
+ "button",
351
+ {
352
+ type: "button",
353
+ className: "seclai-file-remove",
354
+ "aria-label": `Remove ${name}`,
355
+ onClick: onRemove,
356
+ children: "\xD7"
357
+ }
358
+ )
359
+ ] });
360
+ }
361
+ function Turn({ turn, previews }) {
278
362
  return /* @__PURE__ */ jsxs2("li", { className: `seclai-turn seclai-turn-${turn.role}`, children: [
363
+ turn.files && turn.files.length > 0 && /* @__PURE__ */ jsx3("ul", { className: "seclai-files", "aria-label": "Attached files", children: turn.files.map((file) => /* @__PURE__ */ jsx3(
364
+ FileChip,
365
+ {
366
+ name: file.name,
367
+ tag: file.tag,
368
+ preview: previews.get(file.uploadId)
369
+ },
370
+ file.uploadId
371
+ )) }),
279
372
  turn.text && /* @__PURE__ */ jsx3(MarkdownContent, { content: turn.text }),
280
373
  turn.attachments?.map((attachment) => /* @__PURE__ */ jsx3(MediaPreview, { attachment }, attachment.id)),
281
374
  turn.error && /* @__PURE__ */ jsx3("p", { className: "seclai-error", role: "alert", children: turn.error }),
282
375
  turn.cancelled && /* @__PURE__ */ jsx3("p", { className: "seclai-notice", children: "Stopped." })
283
376
  ] });
284
377
  }
285
- function AgentChat({ basePath, agentId, placeholder = "Send a message" }) {
378
+ function AttachControl({
379
+ label,
380
+ accept,
381
+ multiple,
382
+ disabled,
383
+ onFiles
384
+ }) {
385
+ return /* @__PURE__ */ jsxs2("label", { className: "seclai-button seclai-attach", "aria-disabled": disabled || void 0, children: [
386
+ label,
387
+ /* @__PURE__ */ jsx3(
388
+ "input",
389
+ {
390
+ type: "file",
391
+ className: "seclai-sr-only",
392
+ accept,
393
+ multiple,
394
+ disabled,
395
+ onChange: (e) => {
396
+ const picked = Array.from(e.target.files ?? []);
397
+ e.target.value = "";
398
+ if (picked.length) onFiles(picked);
399
+ }
400
+ }
401
+ )
402
+ ] });
403
+ }
404
+ function AgentChat({
405
+ basePath,
406
+ agentId,
407
+ placeholder = "Send a message",
408
+ attachButtons,
409
+ onBeforeSend
410
+ }) {
411
+ const endpoints = useMemo2(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
286
412
  const run = useAgentRun({ basePath, agentId });
287
- const [turns, setTurns] = useState2([]);
288
- const [message, setMessage] = useState2("");
413
+ const { slots } = useAcceptedAttachments(endpoints);
414
+ const [turns, setTurns] = useState3([]);
415
+ const [message, setMessage] = useState3("");
416
+ const [files, setFiles] = useState3([]);
417
+ const [notice, setNotice] = useState3(null);
418
+ const [dragging, setDragging] = useState3(false);
289
419
  const sessionId = useRef2(null);
290
420
  const nextTurnId = useRef2(0);
421
+ const sentPreviews = useRef2(/* @__PURE__ */ new Map());
422
+ const pendingPreviews = useRef2(/* @__PURE__ */ new Set());
423
+ useEffect3(
424
+ () => () => {
425
+ pendingPreviews.current.forEach(revoke);
426
+ sentPreviews.current.forEach(revoke);
427
+ },
428
+ []
429
+ );
430
+ const limits = slots?.length ? messageFileLimits(slots) : null;
431
+ const acceptsFiles = !!limits && (limits.max == null || limits.max > 0);
291
432
  const running = run.status === "running";
433
+ const uploading = files.some((f) => f.status === "uploading");
434
+ const ready = files.filter((f) => f.status === "ready" && f.uploadId);
435
+ const room = limits?.max == null ? Infinity : limits.max - files.filter((f) => f.status !== "error").length;
436
+ const canSend = !running && !uploading && (!!message.trim() || ready.length > 0);
437
+ function setFile(localId, patch) {
438
+ setFiles((prev) => prev.map((f) => f.localId === localId ? { ...f, ...patch } : f));
439
+ }
440
+ function upload(item, file) {
441
+ uploadFile(endpoints, file).then(
442
+ (result) => setFile(item.localId, { status: "ready", uploadId: result.id }),
443
+ (err) => setFile(item.localId, {
444
+ status: "error",
445
+ error: err instanceof Error ? err.message : "The upload failed."
446
+ })
447
+ );
448
+ }
449
+ function addFiles(incoming, tag) {
450
+ if (!acceptsFiles || !limits || incoming.length === 0) return;
451
+ const problems = [];
452
+ const added = [];
453
+ let left = room;
454
+ let tooMany = false;
455
+ for (const file of incoming) {
456
+ if (!acceptsType(limits.contentTypes, file.type)) {
457
+ problems.push(`${file.name} isn't a type of file this agent accepts.`);
458
+ continue;
459
+ }
460
+ if (left <= 0) {
461
+ tooMany = true;
462
+ continue;
463
+ }
464
+ left--;
465
+ const preview = createPreview(file);
466
+ if (preview) pendingPreviews.current.add(preview);
467
+ added.push([
468
+ {
469
+ localId: `file-${++nextLocalId}`,
470
+ name: file.name,
471
+ contentType: file.type,
472
+ tag,
473
+ preview,
474
+ status: "uploading"
475
+ },
476
+ file
477
+ ]);
478
+ }
479
+ if (tooMany) problems.push(`You can attach up to ${plural(limits.max, "file")} per message.`);
480
+ setNotice(problems.length ? problems.join(" ") : null);
481
+ if (added.length === 0) return;
482
+ setFiles((prev) => [...prev, ...added.map(([item]) => item)]);
483
+ for (const [item, file] of added) upload(item, file);
484
+ }
485
+ function remove(localId) {
486
+ const gone = files.find((f) => f.localId === localId);
487
+ if (gone?.preview) {
488
+ revoke(gone.preview);
489
+ pendingPreviews.current.delete(gone.preview);
490
+ }
491
+ setFiles((prev) => prev.filter((f) => f.localId !== localId));
492
+ setNotice(null);
493
+ }
292
494
  async function send() {
495
+ if (!canSend) return;
293
496
  const text = message.trim();
294
- if (!text || running) return;
497
+ const sent = ready.map((f) => ({
498
+ uploadId: f.uploadId,
499
+ name: f.name,
500
+ contentType: f.contentType,
501
+ ...f.tag ? { tag: f.tag } : {}
502
+ }));
503
+ const override = onBeforeSend?.({ input: text, files: sent });
504
+ const input = (typeof override === "string" ? override : text) || void 0;
505
+ for (const f of files) {
506
+ if (!f.preview) continue;
507
+ pendingPreviews.current.delete(f.preview);
508
+ if (f.status === "ready" && f.uploadId) sentPreviews.current.set(f.uploadId, f.preview);
509
+ else revoke(f.preview);
510
+ }
295
511
  sessionId.current ??= createSessionId();
296
512
  setMessage("");
297
- setTurns((prev) => [...prev, { id: nextTurnId.current++, role: "user", text }]);
298
- const result = await run.start({ input: text, sessionId: sessionId.current });
513
+ setFiles([]);
514
+ setNotice(null);
515
+ setTurns((prev) => [
516
+ ...prev,
517
+ { id: nextTurnId.current++, role: "user", text, ...sent.length ? { files: sent } : {} }
518
+ ]);
519
+ const result = await run.start({
520
+ input,
521
+ uploadIds: sent.length ? sent.map((f) => f.uploadId) : void 0,
522
+ sessionId: sessionId.current
523
+ });
299
524
  setTurns((prev) => [
300
525
  ...prev,
301
526
  {
@@ -318,41 +543,91 @@ function AgentChat({ basePath, agentId, placeholder = "Send a message" }) {
318
543
  void send();
319
544
  }
320
545
  }
546
+ function onPaste(event) {
547
+ const data = event.clipboardData;
548
+ const pasted = Array.from(data?.files ?? []);
549
+ if (pasted.length === 0) return;
550
+ if (data.getData("text/plain")) return;
551
+ event.preventDefault();
552
+ addFiles(pasted);
553
+ }
554
+ const dropHandlers = acceptsFiles ? {
555
+ onDragOver(event) {
556
+ if (!hasFiles(event.dataTransfer)) return;
557
+ event.preventDefault();
558
+ setDragging(true);
559
+ },
560
+ onDragLeave(event) {
561
+ if (!event.currentTarget.contains(event.relatedTarget)) setDragging(false);
562
+ },
563
+ onDrop(event) {
564
+ if (!hasFiles(event.dataTransfer)) return;
565
+ event.preventDefault();
566
+ setDragging(false);
567
+ addFiles(Array.from(event.dataTransfer.files));
568
+ }
569
+ } : {};
570
+ const buttons = attachButtons?.length ? attachButtons : [{ label: "Attach" }];
321
571
  return /* @__PURE__ */ jsxs2("div", { className: "seclai-agent seclai-chat", children: [
322
572
  /* @__PURE__ */ jsxs2("ul", { className: "seclai-turns", "aria-live": "polite", "aria-busy": running, children: [
323
- turns.map((turn) => /* @__PURE__ */ jsx3(Turn, { turn }, turn.id)),
573
+ turns.map((turn) => /* @__PURE__ */ jsx3(Turn, { turn, previews: sentPreviews.current }, turn.id)),
324
574
  running && /* @__PURE__ */ jsx3("li", { className: "seclai-turn seclai-turn-assistant", children: run.text ? /* @__PURE__ */ jsx3(MarkdownContent, { content: run.text }) : /* @__PURE__ */ jsx3("p", { className: "seclai-notice", children: "Thinking\u2026" }) })
325
575
  ] }),
326
- /* @__PURE__ */ jsxs2("form", { className: "seclai-form", onSubmit, children: [
327
- /* @__PURE__ */ jsx3(
328
- "textarea",
329
- {
330
- rows: 2,
331
- "aria-label": "Message",
332
- placeholder,
333
- value: message,
334
- onChange: (e) => setMessage(e.target.value),
335
- onKeyDown
336
- }
337
- ),
338
- /* @__PURE__ */ jsxs2("div", { className: "seclai-actions", children: [
339
- /* @__PURE__ */ jsx3(
340
- "button",
341
- {
342
- type: "submit",
343
- className: "seclai-button seclai-button-primary",
344
- disabled: running || !message.trim(),
345
- children: "Send"
346
- }
347
- ),
348
- running && /* @__PURE__ */ jsx3("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
349
- ] })
350
- ] })
576
+ /* @__PURE__ */ jsxs2(
577
+ "form",
578
+ {
579
+ className: dragging ? "seclai-form seclai-dropping" : "seclai-form",
580
+ onSubmit,
581
+ ...dropHandlers,
582
+ children: [
583
+ files.length > 0 && /* @__PURE__ */ jsx3("ul", { className: "seclai-files", "aria-label": "Files to send", children: files.map((f) => /* @__PURE__ */ jsx3(
584
+ FileChip,
585
+ {
586
+ name: f.name,
587
+ tag: f.tag,
588
+ preview: f.preview,
589
+ status: f.status,
590
+ error: f.error,
591
+ onRemove: () => remove(f.localId)
592
+ },
593
+ f.localId
594
+ )) }),
595
+ /* @__PURE__ */ jsx3(
596
+ "textarea",
597
+ {
598
+ rows: 2,
599
+ "aria-label": "Message",
600
+ placeholder,
601
+ value: message,
602
+ onChange: (e) => setMessage(e.target.value),
603
+ onKeyDown,
604
+ onPaste: acceptsFiles ? onPaste : void 0
605
+ }
606
+ ),
607
+ notice && /* @__PURE__ */ jsx3("p", { className: "seclai-error", role: "alert", children: notice }),
608
+ /* @__PURE__ */ jsxs2("div", { className: "seclai-actions", children: [
609
+ acceptsFiles && buttons.map((button) => /* @__PURE__ */ jsx3(
610
+ AttachControl,
611
+ {
612
+ label: button.label,
613
+ accept: acceptAttribute(limits.contentTypes),
614
+ multiple: room > 1,
615
+ disabled: room <= 0,
616
+ onFiles: (picked) => addFiles(picked, button.tag)
617
+ },
618
+ `${button.label}\0${button.tag ?? ""}`
619
+ )),
620
+ /* @__PURE__ */ jsx3("button", { type: "submit", className: "seclai-button seclai-button-primary", disabled: !canSend, children: "Send" }),
621
+ running && /* @__PURE__ */ jsx3("button", { type: "button", className: "seclai-button", onClick: run.cancel, children: "Stop" })
622
+ ] })
623
+ ]
624
+ }
625
+ )
351
626
  ] });
352
627
  }
353
628
 
354
629
  // src/AgentRunForm.tsx
355
- import { useEffect as useEffect2, useMemo as useMemo2, useState as useState3 } from "react";
630
+ import { useMemo as useMemo3, useState as useState4 } from "react";
356
631
  import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
357
632
  function slotProblem(slot, count) {
358
633
  const label = slot.label ?? slot.name;
@@ -364,24 +639,13 @@ function slotProblem(slot, count) {
364
639
  return null;
365
640
  }
366
641
  function AgentRunForm({ basePath, agentId, inputLabel = "Input", onFinish }) {
367
- const endpoints = useMemo2(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
642
+ const endpoints = useMemo3(() => createEndpoints({ basePath, agentId }), [basePath, agentId]);
368
643
  const run = useAgentRun({ basePath, agentId });
369
- const [slots, setSlots] = useState3(null);
370
- const [loadError, setLoadError] = useState3(null);
371
- const [input, setInput] = useState3("");
372
- const [files, setFiles] = useState3({});
373
- const [uploading, setUploading] = useState3(false);
374
- const [formError, setFormError] = useState3(null);
375
- useEffect2(() => {
376
- const controller = new AbortController();
377
- setSlots(null);
378
- setLoadError(null);
379
- fetchAttachmentReferences(endpoints, { signal: controller.signal }).then((refs) => setSlots(refs.accepted_attachments ?? [])).catch((err) => {
380
- if (controller.signal.aborted) return;
381
- setLoadError(err instanceof Error ? err.message : "Could not load this agent.");
382
- });
383
- return () => controller.abort();
384
- }, [endpoints]);
644
+ const { slots, error: loadError } = useAcceptedAttachments(endpoints);
645
+ const [input, setInput] = useState4("");
646
+ const [files, setFiles] = useState4({});
647
+ const [uploading, setUploading] = useState4(false);
648
+ const [formError, setFormError] = useState4(null);
385
649
  const selected = Object.values(files).flat();
386
650
  const busy = uploading || run.status === "running";
387
651
  async function submit(event) {
@@ -443,7 +707,7 @@ function AgentRunForm({ basePath, agentId, inputLabel = "Input", onFinish }) {
443
707
  {
444
708
  type: "file",
445
709
  name: slot.name,
446
- accept: slot.content_types?.length ? slot.content_types.join(",") : void 0,
710
+ accept: acceptAttribute(slot.content_types),
447
711
  multiple: slot.max == null || slot.max > 1,
448
712
  onChange: (e) => setFiles((prev) => ({ ...prev, [slot.name]: Array.from(e.target.files ?? []) }))
449
713
  }
package/dist/styles.css CHANGED
@@ -170,6 +170,15 @@
170
170
  .seclai-agent input[type="file"]:hover::file-selector-button {
171
171
  background: var(--seclai-surface-hover);
172
172
  }
173
+
174
+ .seclai-attach[aria-disabled="true"]:hover {
175
+ background: transparent;
176
+ }
177
+
178
+ .seclai-file-remove:hover {
179
+ color: var(--seclai-text);
180
+ background: var(--seclai-surface-hover);
181
+ }
173
182
  }
174
183
 
175
184
  @media (pointer: coarse) {
@@ -236,6 +245,131 @@
236
245
  border-radius: var(--seclai-radius);
237
246
  }
238
247
 
248
+ /* Attachments in the chat composer */
249
+ .seclai-form.seclai-dropping {
250
+ outline: 2px dashed var(--seclai-accent);
251
+ outline-offset: 4px;
252
+ border-radius: var(--seclai-radius);
253
+ }
254
+
255
+ /* Hidden from view but not from the browser, so a wrapping label opens the picker. */
256
+ .seclai-agent .seclai-sr-only {
257
+ position: absolute;
258
+ width: 1px;
259
+ height: 1px;
260
+ min-height: 0;
261
+ margin: -1px;
262
+ padding: 0;
263
+ overflow: hidden;
264
+ clip: rect(0, 0, 0, 0);
265
+ white-space: nowrap;
266
+ border: 0;
267
+ }
268
+
269
+ .seclai-attach:focus-within {
270
+ outline: 2px solid var(--seclai-focus);
271
+ outline-offset: 2px;
272
+ }
273
+
274
+ /* A mouse click on the label focuses the input too; ring keyboard focus only. */
275
+ @supports selector(:has(*)) {
276
+ .seclai-attach:focus-within:not(:has(:focus-visible)) {
277
+ outline: none;
278
+ }
279
+ }
280
+
281
+ .seclai-attach[aria-disabled="true"] {
282
+ cursor: not-allowed;
283
+ opacity: 0.55;
284
+ }
285
+
286
+ .seclai-files {
287
+ display: flex;
288
+ flex-wrap: wrap;
289
+ gap: 8px;
290
+ margin: 0;
291
+ padding: 0;
292
+ list-style: none;
293
+ }
294
+
295
+ .seclai-file {
296
+ display: inline-flex;
297
+ align-items: center;
298
+ gap: 8px;
299
+ max-width: 240px;
300
+ min-height: 40px;
301
+ padding: 4px 4px 4px 8px;
302
+ font-size: 0.8125em;
303
+ background: var(--seclai-surface);
304
+ border: 1px solid var(--seclai-border);
305
+ border-radius: var(--seclai-radius);
306
+ }
307
+
308
+ .seclai-file:has(.seclai-file-thumb) {
309
+ padding-inline-start: 4px;
310
+ }
311
+
312
+ .seclai-file-thumb {
313
+ flex: none;
314
+ width: 32px;
315
+ height: 32px;
316
+ object-fit: cover;
317
+ border-radius: calc(var(--seclai-radius) - 3px);
318
+ }
319
+
320
+ .seclai-file-text {
321
+ display: flex;
322
+ flex-direction: column;
323
+ min-width: 0;
324
+ line-height: 1.3;
325
+ }
326
+
327
+ .seclai-file-name {
328
+ overflow: hidden;
329
+ text-overflow: ellipsis;
330
+ white-space: nowrap;
331
+ }
332
+
333
+ .seclai-file-meta {
334
+ color: var(--seclai-muted);
335
+ }
336
+
337
+ .seclai-file[data-status="uploading"] .seclai-file-thumb {
338
+ opacity: 0.5;
339
+ }
340
+
341
+ .seclai-file[data-status="error"] {
342
+ border-color: var(--seclai-error);
343
+ background: var(--seclai-error-surface);
344
+ }
345
+
346
+ .seclai-file[data-status="error"] .seclai-file-meta {
347
+ color: var(--seclai-error);
348
+ }
349
+
350
+ .seclai-file-remove {
351
+ position: relative;
352
+ flex: none;
353
+ width: 28px;
354
+ height: 28px;
355
+ padding: 0;
356
+ font: inherit;
357
+ font-size: 1.25em;
358
+ line-height: 1;
359
+ color: var(--seclai-muted);
360
+ cursor: pointer;
361
+ background: transparent;
362
+ border: 0;
363
+ border-radius: calc(var(--seclai-radius) - 3px);
364
+ }
365
+
366
+ /* A 44px hit target around the small button. */
367
+ .seclai-file-remove::before {
368
+ content: "";
369
+ position: absolute;
370
+ inset: -8px;
371
+ }
372
+
239
373
  .seclai-markdown {
240
374
  white-space: pre-wrap;
241
375
  overflow-wrap: anywhere;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seclai/react",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
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",