optio-chat-participation-ui 0.1.0 → 0.1.1

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
@@ -15,6 +15,12 @@ app's users take part in optio's agent chat as themselves, beside the agents.
15
15
  quiet lines. "Load earlier messages" pages back through the history. "Leave" stands in the
16
16
  channel's header; typing `/leave` in the input does the same (it is not sent). Leaving a
17
17
  channel you are the only member of ends the channel, so the widget asks first then.
18
+ - Files in channels: attach files with the paperclip, by dropping them on the channel or by
19
+ pasting (a screenshot, say); each uploads at once as a chip with its progress, Remove, and on
20
+ failure its reason with Retry; a message may be files only. Pictures (PNG, JPEG, WebP, GIF) show
21
+ as thumbnails that open in full size, other files as download cards. The hub's limits apply
22
+ (10 MB per file by default, 10 files per message); with an older chat hub there is no attach
23
+ control.
18
24
  - Each button with a short label is named by it for screen readers; its long text is the
19
25
  tooltip and the button's description.
20
26
  - Mobile first, on vultus' list-and-detail page: from 720 px wide the channel list in a column
@@ -89,6 +95,8 @@ Your server must tell optio who the person is, through optio-api's `inputAuthor`
89
95
  client's own beside the task's events: `{type: 'stream', connected}` (the event stream lost, and
90
96
  open again) and `{type: 'replaced', resume}` (a newer tab of the person's took the stream over;
91
97
  `resume()` opens it again now). An exhaustive `switch` over its `type`, or a `ParticipationClient`
92
- of your own, needs both.
98
+ of your own, needs both. A `ParticipationClient` of your own also needs `upload(file, onProgress,
99
+ signal)` and `fileUrl` (chat attachments), and its `send` takes the uploads' references as a
100
+ third argument.
93
101
 
94
102
  Design: `docs/2026-11-25-chat-participation-design.md` in the optio repository.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "optio-chat-participation-ui",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The widget of optio's chat participation task: people take part in the agent chat as themselves",
6
6
  "repository": {
@@ -27,8 +27,8 @@
27
27
  "README.md"
28
28
  ],
29
29
  "dependencies": {
30
- "optio-conversation-ui": "0.12.0",
31
- "optio-ui": "0.12.3"
30
+ "optio-conversation-ui": "0.13.0",
31
+ "optio-ui": "0.12.4"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "@ant-design/icons": ">=6",
@@ -1,10 +1,12 @@
1
1
  import { LogoutOutlined } from '@ant-design/icons';
2
2
  import { Alert, Button, Spin, theme, Tooltip } from 'antd';
3
- import { ChatLogView, type ChatLogViewTexts } from 'optio-conversation-ui';
3
+ import {
4
+ ChatLogView, sizeText, type ChatAttachment, type ChatFileUrl, type ChatLogAttachments, type ChatLogViewTexts, type SizeWords,
5
+ } from 'optio-conversation-ui';
4
6
  import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, type ReactNode } from 'react';
5
7
  // vultus-core's, through vultus-antd's re-export, as the widget's other vultus pieces.
6
8
  import { ActionButton, useAction, useConfirm } from 'vultus-antd';
7
- import { pageInFocus, type UiState } from './api.js';
9
+ import { pageInFocus, type ParticipationClient, type UiAttachmentLimits, type UiState } from './api.js';
8
10
  import { NO_AVATARS, withCurrentAvatars, type AvatarMap } from './avatars.js';
9
11
  import { errorText, sameChannel } from './errors.js';
10
12
  import { useChatT } from './i18n.js';
@@ -67,7 +69,21 @@ export interface ChannelViewProps {
67
69
  log: ChannelLog;
68
70
  /** The narrow layout (one screen at a time; the layout draws the back control above the view). */
69
71
  narrow: boolean;
70
- onSend: (text: string) => Promise<boolean | { error: string }>;
72
+ /**
73
+ * Sends a message: its text (empty for a files-only message) and the uploaded files it carries
74
+ * (`[]` for none), as ChatLogView gives them.
75
+ */
76
+ onSend: (text: string, attachments: ChatAttachment[]) => Promise<boolean | { error: string }>;
77
+ /**
78
+ * What the hub takes as files (the state's `attachments`): with `upload`, the message box takes
79
+ * files (the paperclip, drop and paste). Null or absent (an older hub, the hub not reached yet,
80
+ * a task from before attachments): no attach control.
81
+ */
82
+ attachments?: UiAttachmentLimits | null;
83
+ /** Uploads one file (the client's `upload`). */
84
+ upload?: ParticipationClient['upload'];
85
+ /** A message's file URLs (the client's `fileUrl`); absent: cards that download nothing. */
86
+ fileUrl?: ChatFileUrl;
71
87
  /** Marks the channel read up to a message; rejects when that failed. */
72
88
  onRead: (upTo: string) => Promise<void>;
73
89
  /** Leaves the channel (`POST leave`); a refusal is the widget's to show (`error`). */
@@ -105,11 +121,16 @@ export interface ChannelViewProps {
105
121
  * other members it leaves at once; as the sole member (leaving ends the channel)
106
122
  * or with a count it cannot read, it asks first (vultus' cascade modal through
107
123
  * `useConfirm`, a danger OK "Leave"), and leaves on OK.
124
+ *
125
+ * Chat attachments (`docs/2026-11-27-chat-attachments-design.md`, section 3): with the hub's
126
+ * `attachments` limits and `upload`, ChatLogView's uploads (each file goes up at once as a chip;
127
+ * a chip's failure says why in the widget's words, `errorText` with `{file: true}`); every
128
+ * message's files from `fileUrl`.
108
129
  */
109
130
  export function ChannelView(props: ChannelViewProps): ReactNode {
110
131
  const {
111
132
  channel, description, unread, hub, onResume, log, narrow, onSend, onRead, onLeave, memberCount, error, onDismissError,
112
- chatAvatarUrl, avatars = NO_AVATARS,
133
+ chatAvatarUrl, avatars = NO_AVATARS, attachments, upload, fileUrl,
113
134
  } = props;
114
135
  const { token } = theme.useToken();
115
136
  const t = useChatT();
@@ -247,26 +268,62 @@ export function ChannelView(props: ChannelViewProps): ReactNode {
247
268
 
248
269
  // `/leave` (owner, 2026-11-27: "submitting /leave in the input box should trigger the same action
249
270
  // (and not actually send this message)"): the same action, its confirmation included; resolved as
250
- // sent, so the input is cleared. Anything else goes to the widget's send.
251
- const send = useCallback(async (text: string): Promise<boolean | { error: string }> => {
252
- if (!isLeaveCommand(text)) return onSend(text);
271
+ // sent, so the input is cleared. Anything else goes to the widget's send, with its files.
272
+ const send = useCallback(async (text: string, files: ChatAttachment[]): Promise<boolean | { error: string }> => {
273
+ if (!isLeaveCommand(text)) return onSend(text, files);
253
274
  askLeaveRef.current.fire();
254
275
  return true;
255
276
  }, [onSend]);
256
277
 
257
- // ChatLogView's own texts (owner, 2026-11-26: "i18n OK"), from the same i18n.
258
- const texts = useMemo<ChatLogViewTexts>(() => ({
259
- loadEarlier: t('chatParticipation.loadEarlier'),
260
- placeholder: t('chatParticipation.messagePlaceholder'),
261
- send: t('chatParticipation.send'),
262
- sendFailed: t('chatParticipation.sendFailed'),
263
- agentSender: t('chatParticipation.agentSender'),
264
- avatarFullSize: t('chatParticipation.avatarFullSize'),
265
- avatarLabel: (name) => (name === undefined
266
- ? t('chatParticipation.avatarLabelUnnamed')
267
- : t('chatParticipation.avatarLabel', { name })),
268
- wide: t('chatParticipation.wide'),
269
- }), [t]);
278
+ // The message box's uploads (ChatLogView's `attachments`): only with the hub's limits. A chip's
279
+ // reason is the rejection's message, so a refusal is rejected as the widget's text for it (an
280
+ // upload's: `{file: true}`); an aborted upload's rejection is ChatLogView's to ignore.
281
+ const maxBytes = attachments?.maxBytes;
282
+ const maxFiles = attachments?.maxFiles;
283
+ const uploads = useMemo<ChatLogAttachments | undefined>(() => {
284
+ if (maxBytes === undefined || maxFiles === undefined || upload === undefined) return undefined;
285
+ return {
286
+ maxBytes,
287
+ maxFiles,
288
+ upload: (file, onProgress, signal) => upload(file, onProgress, signal).catch((err: unknown) => {
289
+ throw signal.aborted ? err : new Error(errorText(err, t, { file: true }));
290
+ }),
291
+ };
292
+ }, [maxBytes, maxFiles, upload, t]);
293
+
294
+ // ChatLogView's own texts (owner, 2026-11-26: "i18n OK"), from the same i18n; the attachments'
295
+ // too (Retry the widget's `retry`). A file's size: conversation-ui's sizeText (the rounding, the
296
+ // units) with the language's decimal separator and byte words.
297
+ const texts = useMemo<ChatLogViewTexts>(() => {
298
+ const sizeWords: SizeWords = {
299
+ decimal: t('chatParticipation.decimalSeparator'),
300
+ bytes: (n) => (n === 1 ? t('chatParticipation.sizeByte') : t('chatParticipation.sizeBytes', { count: n })),
301
+ };
302
+ return {
303
+ loadEarlier: t('chatParticipation.loadEarlier'),
304
+ placeholder: t('chatParticipation.messagePlaceholder'),
305
+ send: t('chatParticipation.send'),
306
+ sendFailed: t('chatParticipation.sendFailed'),
307
+ agentSender: t('chatParticipation.agentSender'),
308
+ avatarFullSize: t('chatParticipation.avatarFullSize'),
309
+ avatarLabel: (name) => (name === undefined
310
+ ? t('chatParticipation.avatarLabelUnnamed')
311
+ : t('chatParticipation.avatarLabel', { name })),
312
+ wide: t('chatParticipation.wide'),
313
+ attach: t('chatParticipation.attach'),
314
+ dropFiles: t('chatParticipation.dropFiles'),
315
+ attachTooLarge: (limit) => t('chatParticipation.attachTooLarge', { limit }),
316
+ attachTooMany: (max) => t('chatParticipation.attachTooMany', { max }),
317
+ uploadFailed: (reason) => t('chatParticipation.uploadFailed', { reason }),
318
+ retry: t('chatParticipation.retry'),
319
+ remove: t('chatParticipation.remove'),
320
+ fileNotAvailable: t('chatParticipation.fileNotAvailable'),
321
+ fileNotAvailableNow: t('chatParticipation.fileNotAvailableNow'),
322
+ download: t('chatParticipation.download'),
323
+ fileCount: (n) => (n === 1 ? t('chatParticipation.fileCountOne') : t('chatParticipation.fileCount', { count: n })),
324
+ fileSize: (bytes) => sizeText(bytes, sizeWords),
325
+ };
326
+ }, [t]);
270
327
 
271
328
  let notice: ReactNode = null;
272
329
  if (error !== null) {
@@ -347,6 +404,8 @@ export function ChannelView(props: ChannelViewProps): ReactNode {
347
404
  hasEarlier={log.hasEarlier}
348
405
  loadingEarlier={log.loadingEarlier}
349
406
  chatAvatarUrl={chatAvatarUrl}
407
+ attachments={uploads}
408
+ fileUrl={fileUrl}
350
409
  wideness={narrow ? 'wide' : undefined}
351
410
  notice={notice}
352
411
  texts={texts}
@@ -1,4 +1,5 @@
1
1
  import { Alert, Button, Spin, theme, Tooltip } from 'antd';
2
+ import type { ChatFileUrl } from 'optio-conversation-ui';
2
3
  import type { WidgetProps } from 'optio-ui';
3
4
  import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
4
5
  import { flushSync } from 'react-dom';
@@ -13,6 +14,7 @@ import {
13
14
  ParticipationError,
14
15
  type ParticipationClient,
15
16
  type ParticipationServerEvent,
17
+ type UiAttachment,
16
18
  type UiChannel,
17
19
  type UiChannelDescription,
18
20
  type UiJoinResult,
@@ -124,6 +126,10 @@ function withChannels(state: UiState | null, map: (channels: UiChannel[]) => UiC
124
126
  * While the stream is lost the hub line says "Connecting…"; while it is paused
125
127
  * (another tab of the person's replaced it, and the client waits for the page
126
128
  * to be in use again) it says so, and a click on it resumes the stream.
129
+ * Chat attachments: while the state has the hub's `attachments` limits, the
130
+ * open channel's message box takes files (each uploaded at once through the
131
+ * client, the send carrying their references); every message draws its files
132
+ * from the client's `fileUrl`.
127
133
  * Calls `onReady` once the person's state (or why it failed) shows.
128
134
  *
129
135
  * The open channel lives in the host's ArgStore (an ArgStoreProvider above the
@@ -417,17 +423,27 @@ function ParticipationWidget(props: ChatParticipationWidgetProps): ReactNode {
417
423
  }
418
424
  }, [client]);
419
425
 
420
- const send = useCallback(async (text: string): Promise<boolean | { error: string }> => {
426
+ // A message with the files the channel's chips uploaded (their references; none: the request as
427
+ // before attachments).
428
+ const send = useCallback(async (text: string, attachments: UiAttachment[]): Promise<boolean | { error: string }> => {
421
429
  const channel = openRef.current;
422
430
  if (channel === null) return false;
423
431
  try {
424
- handleMessage(await client.send(channel, text));
432
+ handleMessage(await (attachments.length > 0 ? client.send(channel, text, attachments) : client.send(channel, text)));
425
433
  return true;
426
434
  } catch (err) {
427
435
  return { error: errorText(err, t) };
428
436
  }
429
437
  }, [client, t, handleMessage]);
430
438
 
439
+ // The channel's uploads and file URLs, called on the client (a host's client, a class say, may
440
+ // keep `upload` and `fileUrl` as methods that use `this`).
441
+ const upload = useCallback(
442
+ (file: File, onProgress: (fraction: number) => void, signal: AbortSignal) => client.upload(file, onProgress, signal),
443
+ [client],
444
+ );
445
+ const fileUrl = useCallback<ChatFileUrl>((a, opts) => client.fileUrl(a, opts), [client]);
446
+
431
447
  const markRead = useCallback(async (upTo: string) => {
432
448
  const channel = openRef.current;
433
449
  if (channel === null) return;
@@ -560,6 +576,9 @@ function ParticipationWidget(props: ChatParticipationWidgetProps): ReactNode {
560
576
  onDismissError={() => setChannelError(null)}
561
577
  chatAvatarUrl={chatAvatarUrl}
562
578
  avatars={avatars}
579
+ attachments={ui.attachments ?? null}
580
+ upload={upload}
581
+ fileUrl={fileUrl}
563
582
  />
564
583
  );
565
584
  };
package/src/api.ts CHANGED
@@ -5,10 +5,14 @@
5
5
  *
6
6
  * Every path is relative to the widget proxy URL (`WidgetProps.widgetProxyUrl`,
7
7
  * which ends in `/`): `GET state`, `GET channels`, `POST join` `{channel}`,
8
- * `POST leave` `{channel}`, `POST send` `{channel, text}`,
8
+ * `POST leave` `{channel}`, `POST send` `{channel, text, attachments?}`,
9
9
  * `GET history?channel=&before=<id>&limit=50`, `POST read` `{channel, upTo}`,
10
- * `POST channel-description` `{channel, description}`, `GET events` (SSE).
11
- * optio-api stamps each request with who the person is.
10
+ * `POST channel-description` `{channel, description}`, `GET events` (SSE);
11
+ * chat attachments (`docs/2026-11-27-chat-attachments-design.md`, section 2):
12
+ * `POST upload?name=<the file's name>` (the raw bytes; the uploaded file's
13
+ * `{id, name, type, size}`) and `GET file?id=&name=[&size=thumb][&download=1]`
14
+ * (the file, streamed through from the hub; only the browser asks it, through
15
+ * the URLs `fileUrl` gives). optio-api stamps each request with who the person is.
12
16
  *
13
17
  * The SSE stream sends five events, each one JSON value: `message` (a stored
14
18
  * message, `UiMessage`; the person's own sends too), `channels` (the person's
@@ -19,8 +23,9 @@
19
23
  *
20
24
  * An error answer is a non-2xx status with `{reason, message}` (`UiError`):
21
25
  * 401 `no-author`, 400 for a request that breaks a rule (`bad-request`, or the
22
- * hub's `channel-invalid`, `too-large`, `not-member`, `not-sole-member`), 503
23
- * `hub-unreachable`. The client
26
+ * hub's `channel-invalid`, `too-large`, `not-member`, `not-sole-member`,
27
+ * `refused`; for files `too-many-files`, `file-not-found`, and `no-name` for an
28
+ * upload before the person's first join), 503 `hub-unreachable`. The client
24
29
  * rejects with a `ParticipationError` carrying them. An answer without that
25
30
  * body (optio-api's widget proxy's own, e.g. 404 `Widget upstream not found`
26
31
  * while the task does not run) gets the reason `http-<status>` and the body's
@@ -28,6 +33,25 @@
28
33
  * at all, status 0 and the reason `network`.
29
34
  */
30
35
 
36
+ import type { ChatAttachment, ChatFileUrl } from 'optio-conversation-ui';
37
+
38
+ /**
39
+ * A file a message carries, `{id, name, type, size}` as the hub stamped it (optio-chat's
40
+ * `wire.parse_attachments`): conversation-ui's `ChatAttachment`, which the views draw. `id` the
41
+ * file's content hash, `name` the name the message shows, `type` the type the hub found in the
42
+ * bytes, `size` in bytes. `POST upload` answers one.
43
+ */
44
+ export type UiAttachment = ChatAttachment;
45
+
46
+ /**
47
+ * `GET state`'s `attachments`: the hub's limit per file in bytes (the deployment's) and the most
48
+ * files a message carries.
49
+ */
50
+ export interface UiAttachmentLimits {
51
+ maxBytes: number;
52
+ maxFiles: number;
53
+ }
54
+
31
55
  /** A message for the UI. `description`: the sender's (English; the UI decides when to show it). */
32
56
  export interface UiMessage {
33
57
  id: string;
@@ -48,6 +72,8 @@ export interface UiMessage {
48
72
  event: 'joined' | 'left' | null;
49
73
  /** Sent by this person (their name, or another identity of theirs by a shared claim). */
50
74
  mine: boolean;
75
+ /** Its files, in order (`[]` for none; absent from a task from before attachments). */
76
+ attachments?: UiAttachment[];
51
77
  }
52
78
 
53
79
  /** One of the person's channels. */
@@ -70,6 +96,12 @@ export interface UiState {
70
96
  me: UiMe | null;
71
97
  hub: 'connected' | 'connecting' | 'unreachable';
72
98
  channels: UiChannel[];
99
+ /**
100
+ * What the hub takes as files; null while the task knows no limit (the hub not reached yet, or
101
+ * an older hub, which takes none); absent from a task from before attachments. Without it the
102
+ * widget offers no attach control.
103
+ */
104
+ attachments?: UiAttachmentLimits | null;
73
105
  }
74
106
 
75
107
  /** One channel of `GET channels` (the hub's listing). */
@@ -150,13 +182,33 @@ export const HISTORY_PAGE_SIZE = 50;
150
182
  /** The longest channel description the hub takes, in bytes of UTF-8 (optio-chat's `wire.MAX_DESCRIPTION_BYTES`). */
151
183
  export const MAX_DESCRIPTION_BYTES = 2048;
152
184
 
185
+ /** The most files a message carries (optio-chat's `wire.MAX_ATTACHMENTS`; the `too-many-files` text names it). */
186
+ export const MAX_ATTACHMENTS = 10;
187
+
153
188
  export interface ParticipationClient {
154
189
  state(): Promise<UiState>;
155
190
  channels(): Promise<UiChannelListing[]>;
156
191
  join(channel: string): Promise<UiJoinResult>;
157
192
  leave(channel: string): Promise<void>;
158
- /** The stored own message. */
159
- send(channel: string, text: string): Promise<UiMessage>;
193
+ /**
194
+ * The stored own message. `attachments`: the references of earlier uploads (up to
195
+ * `MAX_ATTACHMENTS`; only their `id` and `name` are sent), the text then may be empty (a
196
+ * files-only message); none or empty: the body as before attachments.
197
+ */
198
+ send(channel: string, text: string, attachments?: ReadonlyArray<{ id: string; name: string }>): Promise<UiMessage>;
199
+ /**
200
+ * Uploads one file (`POST upload?name=`, the raw bytes, over XMLHttpRequest for its
201
+ * progress) and resolves the uploaded file as the hub took it (`{id, name, type, size}`; a 2xx
202
+ * without them is refused as `http-<status>`). `onProgress`: the part sent, a fraction from
203
+ * 0 to 1. `signal` aborts it (an `AbortError`). A refusal rejects with a `ParticipationError`,
204
+ * as every request's.
205
+ */
206
+ upload(file: File, onProgress: (fraction: number) => void, signal: AbortSignal): Promise<UiAttachment>;
207
+ /**
208
+ * A message's file as the task's file route serves it: the full file, its thumbnail
209
+ * (`thumb`), or a download (`download`). Relative to the widget proxy URL; the browser asks it.
210
+ */
211
+ fileUrl: ChatFileUrl;
160
212
  /** A page of the channel's history, oldest first, before the message `before` (none: the newest). */
161
213
  history(channel: string, before?: string, limit?: number): Promise<UiHistory>;
162
214
  /** The read mark: every message up to the one `upTo` is read. */
@@ -197,9 +249,45 @@ export function pageInFocus(): boolean {
197
249
  return typeof document.hasFocus !== 'function' || document.hasFocus();
198
250
  }
199
251
 
252
+ // An answer's body: its JSON value, or null for an empty body or one that is not JSON.
253
+ function bodyOf(text: string): unknown {
254
+ if (text === '') return null;
255
+ try {
256
+ return JSON.parse(text);
257
+ } catch {
258
+ return null;
259
+ }
260
+ }
261
+
262
+ // A non-2xx answer as the client rejects it: the task's `{reason, message}`, else (optio-api's
263
+ // proxy's own answer) the reason `http-<status>` and the body's `message` or `HTTP <status>`.
264
+ function refusalOf(status: number, body: unknown): ParticipationError {
265
+ const fields = body !== null && typeof body === 'object' ? (body as Record<string, unknown>) : {};
266
+ const reason = typeof fields.reason === 'string' && fields.reason !== '' ? fields.reason : `http-${status}`;
267
+ const message = typeof fields.message === 'string' && fields.message !== '' ? fields.message : `HTTP ${status}`;
268
+ return new ParticipationError(status, reason, message);
269
+ }
270
+
271
+ // An upload's answer as the reference a message carries, `{id, name, type, size}` (those four
272
+ // fields only), or null when the body is no such thing (a proxy's page, a broken answer).
273
+ function attachmentOf(body: unknown): UiAttachment | null {
274
+ if (body === null || typeof body !== 'object') return null;
275
+ const { id, name, type, size } = body as Record<string, unknown>;
276
+ if (typeof id !== 'string' || id === '' || typeof name !== 'string' || typeof type !== 'string') return null;
277
+ if (typeof size !== 'number' || !Number.isSafeInteger(size) || size < 0) return null;
278
+ return { id, name, type, size };
279
+ }
280
+
281
+ // What an aborted upload rejects with (as `fetch` does when its signal aborts).
282
+ function aborted(): DOMException {
283
+ return new DOMException('The upload was aborted.', 'AbortError');
284
+ }
285
+
200
286
  /**
201
287
  * The widget API's client: `fetch` relative to `widgetProxyUrl` (credentials
202
- * same-origin), `events` over `EventSource(widgetProxyUrl + 'events')`.
288
+ * same-origin), `events` over `EventSource(widgetProxyUrl + 'events')`,
289
+ * `upload` over XMLHttpRequest (for its progress; a refusal read as every
290
+ * request's), `fileUrl` the file route's URLs (relative to `widgetProxyUrl`).
203
291
  *
204
292
  * `events`: each SSE event's data is one JSON value; one that does not parse
205
293
  * is dropped. At every (re)connection of the stream (its `open`, the first one
@@ -238,24 +326,59 @@ export function createParticipationClient(widgetProxyUrl: string): Participation
238
326
  } catch (err) {
239
327
  throw new ParticipationError(0, REASON_NETWORK, err instanceof Error ? err.message : String(err));
240
328
  }
241
- const text = await res.text().catch(() => '');
242
- let body: unknown = null;
243
- if (text !== '') {
244
- try {
245
- body = JSON.parse(text);
246
- } catch {
247
- body = null;
248
- }
249
- }
250
- if (!res.ok) {
251
- const fields = body !== null && typeof body === 'object' ? (body as Record<string, unknown>) : {};
252
- const reason = typeof fields.reason === 'string' && fields.reason !== '' ? fields.reason : `http-${res.status}`;
253
- const message = typeof fields.message === 'string' && fields.message !== '' ? fields.message : `HTTP ${res.status}`;
254
- throw new ParticipationError(res.status, reason, message);
255
- }
329
+ const body = bodyOf(await res.text().catch(() => ''));
330
+ if (!res.ok) throw refusalOf(res.status, body);
256
331
  return body as T;
257
332
  }
258
333
 
334
+ // `POST upload?name=`: the File itself as the body (its bytes as they are; the hub finds the
335
+ // type in them, so the request claims none), over XMLHttpRequest, which reports the upload's
336
+ // progress (fetch does not). Same-origin, so the browser sends the cookies as for fetch.
337
+ const upload = (file: File, onProgress: (fraction: number) => void, signal: AbortSignal) => (
338
+ new Promise<UiAttachment>((resolve, reject) => {
339
+ if (signal.aborted) {
340
+ reject(aborted());
341
+ return;
342
+ }
343
+ const xhr = new XMLHttpRequest();
344
+ const onAbort = () => xhr.abort();
345
+ signal.addEventListener('abort', onAbort);
346
+ const settle = () => signal.removeEventListener('abort', onAbort);
347
+ xhr.open('POST', url(`upload?name=${encodeURIComponent(file.name)}`));
348
+ xhr.setRequestHeader('content-type', 'application/octet-stream');
349
+ xhr.upload.onprogress = (ev) => {
350
+ const total = ev.lengthComputable && ev.total > 0 ? ev.total : file.size;
351
+ if (total > 0) onProgress(Math.min(1, ev.loaded / total));
352
+ };
353
+ xhr.onload = () => {
354
+ settle();
355
+ const body = bodyOf(xhr.responseText);
356
+ const ok = xhr.status >= 200 && xhr.status < 300;
357
+ const attachment = ok ? attachmentOf(body) : null;
358
+ // A 2xx that is no uploaded file is refused as an answer without the task's body.
359
+ if (attachment !== null) resolve(attachment);
360
+ else reject(refusalOf(xhr.status, ok ? null : body));
361
+ };
362
+ xhr.onerror = () => {
363
+ settle();
364
+ reject(new ParticipationError(0, REASON_NETWORK, 'The upload could not reach the server.'));
365
+ };
366
+ xhr.onabort = () => {
367
+ settle();
368
+ reject(aborted());
369
+ };
370
+ xhr.send(file);
371
+ })
372
+ );
373
+
374
+ // The file route's URL: `id` and `name` always (the route serves the file under its cleaned
375
+ // name), `size=thumb` for a thumbnail (absent: the full file), `download=1` for a download;
376
+ // each value encoded, a space as %20.
377
+ const fileUrl: ChatFileUrl = (a, opts) => url(
378
+ `file?id=${encodeURIComponent(a.id)}&name=${encodeURIComponent(a.name)}`
379
+ + (opts?.thumb ? '&size=thumb' : '') + (opts?.download ? '&download=1' : ''),
380
+ );
381
+
259
382
  const post = <T>(path: string, body: unknown) => request<T>(path, {
260
383
  method: 'POST',
261
384
  headers: { 'content-type': 'application/json' },
@@ -269,7 +392,11 @@ export function createParticipationClient(widgetProxyUrl: string): Participation
269
392
  leave: async (channel) => {
270
393
  await post<unknown>('leave', { channel });
271
394
  },
272
- send: (channel, text) => post<UiMessage>('send', { channel, text }),
395
+ send: (channel, text, attachments) => post<UiMessage>('send', attachments !== undefined && attachments.length > 0
396
+ ? { channel, text, attachments: attachments.map(({ id, name }) => ({ id, name })) }
397
+ : { channel, text }),
398
+ upload,
399
+ fileUrl,
273
400
  history: (channel, before, limit = HISTORY_PAGE_SIZE) => {
274
401
  const query = new URLSearchParams({ channel });
275
402
  if (before !== undefined) query.set('before', before);
package/src/errors.ts CHANGED
@@ -1,18 +1,40 @@
1
- import { ParticipationError } from './api.js';
1
+ import { MAX_ATTACHMENTS, ParticipationError, REASON_NETWORK } from './api.js';
2
2
  import type { ChatT } from './i18n.js';
3
3
 
4
- /** The texts the widget has for the widget API's reasons; any other shows the answer's message. */
5
- export function errorText(err: unknown, t: ChatT): string {
4
+ /**
5
+ * The texts the widget has for the widget API's reasons; any other shows the answer's message.
6
+ * A request that got no answer (`network`: the connection dropped, the browser offline) and an
7
+ * answer of optio-api's proxy's own with a 5xx (`http-5xx`, no task body: a deploy, the task not
8
+ * running) say the chat cannot be reached now (`unreachable`). `file`: the refusal of an upload
9
+ * (a chip's reason): `too-large` is then the file's (over the hub's limit), not the message's,
10
+ * `refused` the file's (the hub did not take it), and `too-many-files` the open-upload cap (too
11
+ * many uploads at once: on an upload it can mean nothing else); without it `refused`, which the
12
+ * hub answers any request with (a join's, a profile's), shows the answer's message, and
13
+ * `too-many-files` is a send's (more files than a message carries). `file-not-found` and
14
+ * `no-name` have their own texts either way.
15
+ */
16
+ export function errorText(err: unknown, t: ChatT, opts: { file?: boolean } = {}): string {
6
17
  if (err instanceof ParticipationError) {
18
+ if (err.reason === REASON_NETWORK || (err.status >= 500 && err.reason === `http-${err.status}`)) {
19
+ return t('chatParticipation.unreachable');
20
+ }
7
21
  switch (err.reason) {
8
22
  case 'hub-unreachable':
9
23
  return t('chatParticipation.hubUnreachable');
10
24
  case 'channel-invalid':
11
25
  return t('chatParticipation.channelInvalid');
12
26
  case 'too-large':
13
- return t('chatParticipation.tooLarge');
27
+ return t(opts.file ? 'chatParticipation.fileTooLarge' : 'chatParticipation.tooLarge');
14
28
  case 'not-sole-member':
15
29
  return t('chatParticipation.notSoleMember');
30
+ case 'too-many-files':
31
+ return opts.file ? t('chatParticipation.tooManyUploads') : t('chatParticipation.tooManyFiles', { max: MAX_ATTACHMENTS });
32
+ case 'file-not-found':
33
+ return t('chatParticipation.fileNotFound');
34
+ case 'no-name':
35
+ return t('chatParticipation.noName');
36
+ case 'refused':
37
+ return opts.file ? t('chatParticipation.filesRefused') : err.message;
16
38
  default:
17
39
  return err.message;
18
40
  }
package/src/i18n.ts CHANGED
@@ -72,6 +72,18 @@ const en = {
72
72
  'chatParticipation.earlierFailed': 'Earlier messages could not be loaded: {{message}}',
73
73
  'chatParticipation.retry': 'Retry',
74
74
  'chatParticipation.tooLarge': 'The message is too large.',
75
+ // The widget API's reasons for files (errors.errorText): an upload's too-large is the file's;
76
+ // `{{max}}` the most files a message carries.
77
+ 'chatParticipation.fileTooLarge': "The file is larger than the chat's limit.",
78
+ 'chatParticipation.tooManyFiles': 'A message can carry at most {{max}} files.',
79
+ 'chatParticipation.fileNotFound': 'An attached file is not available any more. Remove it and attach it again.',
80
+ 'chatParticipation.filesRefused': 'The chat hub refused the file.',
81
+ 'chatParticipation.noName': 'You have no chat name yet: join a channel first.',
82
+ // An upload's too-many-files: the hub's cap on uploads at once.
83
+ 'chatParticipation.tooManyUploads': 'Too many files are uploading at once. Wait for one to finish, then retry.',
84
+ // No answer at all (the connection dropped, the browser offline), or a 5xx of optio-api's
85
+ // proxy's own (a deploy, the task not running): any request's.
86
+ 'chatParticipation.unreachable': 'The chat cannot be reached right now. Check your connection, or try again in a moment.',
75
87
  'chatParticipation.joined': '{{name}} joined the channel',
76
88
  'chatParticipation.left': '{{name}} left the channel',
77
89
  // ChatLogView's own texts (its `texts`; the same English as its defaults).
@@ -84,6 +96,28 @@ const en = {
84
96
  'chatParticipation.avatarLabel': "Show {{name}}'s avatar in full size",
85
97
  'chatParticipation.avatarLabelUnnamed': 'Show the avatar in full size',
86
98
  'chatParticipation.wide': 'Wide',
99
+ // ChatLogView's attachment texts (chat attachments; its Retry is `retry` above): the paperclip,
100
+ // the drop area, a chip's refusal (`{{limit}}` the limit as conversation-ui's sizeText gives
101
+ // it) or failure (`{{reason}}` errorText's), the failed chips' Remove, a file that cannot be
102
+ // opened (for good, or now), the download button, a collapsed chat row's count (one, and more:
103
+ // `{{count}}` two or more).
104
+ 'chatParticipation.attach': 'Attach files',
105
+ 'chatParticipation.dropFiles': 'Drop files here',
106
+ 'chatParticipation.attachTooLarge': "Larger than the chat's limit of {{limit}}",
107
+ 'chatParticipation.attachTooMany': 'A message can carry at most {{max}} files',
108
+ 'chatParticipation.uploadFailed': 'Upload failed: {{reason}}',
109
+ 'chatParticipation.remove': 'Remove',
110
+ 'chatParticipation.fileNotAvailable': 'Not available',
111
+ 'chatParticipation.fileNotAvailableNow': 'Not available right now',
112
+ 'chatParticipation.download': 'Download',
113
+ 'chatParticipation.fileCountOne': ' · 1 file',
114
+ 'chatParticipation.fileCount': ' · {{count}} files',
115
+ // A file's size (ChatLogView's fileSize, through conversation-ui's sizeText, which keeps the
116
+ // rounding and the units KB and MB): the decimal separator, and a size under 1024 bytes
117
+ // (`{{count}}` 0 or 2 to 1023).
118
+ 'chatParticipation.decimalSeparator': '.',
119
+ 'chatParticipation.sizeByte': '1 byte',
120
+ 'chatParticipation.sizeBytes': '{{count}} bytes',
87
121
  } as const;
88
122
 
89
123
  /** A key of the widget's texts. */
@@ -133,6 +167,13 @@ const hu: Record<ChatParticipationKey, string> = {
133
167
  'chatParticipation.earlierFailed': 'A korábbi üzenetek nem tölthetők be: {{message}}',
134
168
  'chatParticipation.retry': 'Újra',
135
169
  'chatParticipation.tooLarge': 'Az üzenet túl nagy.',
170
+ 'chatParticipation.fileTooLarge': 'A fájl nagyobb a csevegés méretkorlátjánál.',
171
+ 'chatParticipation.tooManyFiles': 'Egy üzenethez legfeljebb {{max}} fájl csatolható.',
172
+ 'chatParticipation.fileNotFound': 'Egy csatolt fájl már nem érhető el. Távolítsa el, és csatolja újra.',
173
+ 'chatParticipation.filesRefused': 'A csevegőközpont nem fogadta el a fájlt.',
174
+ 'chatParticipation.noName': 'Még nincs csevegőneve: előbb csatlakozzon egy csatornához.',
175
+ 'chatParticipation.tooManyUploads': 'Egyszerre túl sok fájl töltődik fel. Várja meg, amíg valamelyik befejeződik, majd próbálja újra.',
176
+ 'chatParticipation.unreachable': 'A csevegés most nem érhető el. Ellenőrizze a kapcsolatát, vagy próbálja újra egy kis idő múlva.',
136
177
  'chatParticipation.joined': '{{name}} csatlakozott a csatornához',
137
178
  'chatParticipation.left': '{{name}} kilépett a csatornából',
138
179
  'chatParticipation.loadEarlier': 'Korábbi üzenetek betöltése',
@@ -144,6 +185,20 @@ const hu: Record<ChatParticipationKey, string> = {
144
185
  'chatParticipation.avatarLabel': '{{name}} profilképének megjelenítése teljes méretben',
145
186
  'chatParticipation.avatarLabelUnnamed': 'Profilkép megjelenítése teljes méretben',
146
187
  'chatParticipation.wide': 'Széles',
188
+ 'chatParticipation.attach': 'Fájlok csatolása',
189
+ 'chatParticipation.dropFiles': 'Húzza ide a fájlokat',
190
+ 'chatParticipation.attachTooLarge': 'Nagyobb a csevegés méretkorlátjánál ({{limit}})',
191
+ 'chatParticipation.attachTooMany': 'Egy üzenethez legfeljebb {{max}} fájl csatolható',
192
+ 'chatParticipation.uploadFailed': 'A feltöltés nem sikerült: {{reason}}',
193
+ 'chatParticipation.remove': 'Eltávolítás',
194
+ 'chatParticipation.fileNotAvailable': 'Nem érhető el',
195
+ 'chatParticipation.fileNotAvailableNow': 'Most nem érhető el',
196
+ 'chatParticipation.download': 'Letöltés',
197
+ 'chatParticipation.fileCountOne': ' · 1 fájl',
198
+ 'chatParticipation.fileCount': ' · {{count}} fájl',
199
+ 'chatParticipation.decimalSeparator': ',',
200
+ 'chatParticipation.sizeByte': '1 bájt',
201
+ 'chatParticipation.sizeBytes': '{{count}} bájt',
147
202
  };
148
203
 
149
204
  const de: Record<ChatParticipationKey, string> = {
@@ -190,6 +245,13 @@ const de: Record<ChatParticipationKey, string> = {
190
245
  'chatParticipation.earlierFailed': 'Frühere Nachrichten konnten nicht geladen werden: {{message}}',
191
246
  'chatParticipation.retry': 'Erneut versuchen',
192
247
  'chatParticipation.tooLarge': 'Die Nachricht ist zu groß.',
248
+ 'chatParticipation.fileTooLarge': 'Die Datei ist größer als das Chat-Limit.',
249
+ 'chatParticipation.tooManyFiles': 'Eine Nachricht kann höchstens {{max}} Dateien enthalten.',
250
+ 'chatParticipation.fileNotFound': 'Eine angehängte Datei ist nicht mehr verfügbar. Entfernen Sie sie und hängen Sie sie erneut an.',
251
+ 'chatParticipation.filesRefused': 'Der Chat-Hub hat die Datei nicht angenommen.',
252
+ 'chatParticipation.noName': 'Sie haben noch keinen Chat-Namen: Treten Sie zuerst einem Kanal bei.',
253
+ 'chatParticipation.tooManyUploads': 'Es werden zu viele Dateien gleichzeitig hochgeladen. Warten Sie, bis eine fertig ist, und versuchen Sie es dann erneut.',
254
+ 'chatParticipation.unreachable': 'Der Chat ist derzeit nicht erreichbar. Prüfen Sie Ihre Verbindung oder versuchen Sie es gleich noch einmal.',
193
255
  'chatParticipation.joined': '{{name}} ist dem Kanal beigetreten',
194
256
  'chatParticipation.left': '{{name}} hat den Kanal verlassen',
195
257
  'chatParticipation.loadEarlier': 'Frühere Nachrichten laden',
@@ -201,6 +263,20 @@ const de: Record<ChatParticipationKey, string> = {
201
263
  'chatParticipation.avatarLabel': 'Profilbild von {{name}} in voller Größe anzeigen',
202
264
  'chatParticipation.avatarLabelUnnamed': 'Profilbild in voller Größe anzeigen',
203
265
  'chatParticipation.wide': 'Breit',
266
+ 'chatParticipation.attach': 'Dateien anhängen',
267
+ 'chatParticipation.dropFiles': 'Legen Sie die Dateien hier ab',
268
+ 'chatParticipation.attachTooLarge': 'Größer als das Chat-Limit von {{limit}}',
269
+ 'chatParticipation.attachTooMany': 'Eine Nachricht kann höchstens {{max}} Dateien enthalten',
270
+ 'chatParticipation.uploadFailed': 'Das Hochladen ist fehlgeschlagen: {{reason}}',
271
+ 'chatParticipation.remove': 'Entfernen',
272
+ 'chatParticipation.fileNotAvailable': 'Nicht verfügbar',
273
+ 'chatParticipation.fileNotAvailableNow': 'Derzeit nicht verfügbar',
274
+ 'chatParticipation.download': 'Herunterladen',
275
+ 'chatParticipation.fileCountOne': ' · 1 Datei',
276
+ 'chatParticipation.fileCount': ' · {{count}} Dateien',
277
+ 'chatParticipation.decimalSeparator': ',',
278
+ 'chatParticipation.sizeByte': '1 Byte',
279
+ 'chatParticipation.sizeBytes': '{{count}} Byte',
204
280
  };
205
281
 
206
282
  /** The widget's texts in English, Hungarian and German: one flat bundle per language. */
package/src/index.ts CHANGED
@@ -31,6 +31,8 @@ export {
31
31
  createParticipationClient,
32
32
  type ParticipationClient,
33
33
  type ParticipationServerEvent,
34
+ type UiAttachment,
35
+ type UiAttachmentLimits,
34
36
  type UiAvatar,
35
37
  type UiChannel,
36
38
  type UiChannelDescription,
package/src/reducer.ts CHANGED
@@ -65,10 +65,12 @@ function itemOf(message: UiMessage, seq: number): ChatItem {
65
65
  // muted row shows none.
66
66
  return { kind: 'activity', text: `${message.sender} ${ANNOUNCEMENT_TEXT[message.event]}`, seq, muted: true, ...timestamp };
67
67
  }
68
- if (message.mine) return { kind: 'user', text: message.text, seq, queueId: message.id, ...timestamp };
68
+ // Its files stand under its text in its bubble (chat attachments); none: no field.
69
+ const files = Array.isArray(message.attachments) && message.attachments.length > 0 ? { attachments: message.attachments } : {};
70
+ if (message.mine) return { kind: 'user', text: message.text, seq, queueId: message.id, ...timestamp, ...files };
69
71
  return {
70
72
  kind: 'assistant', text: message.text, pending: false, seq, msgId: message.id,
71
- author: authorOf(message), ...timestamp,
73
+ author: authorOf(message), ...timestamp, ...files,
72
74
  };
73
75
  }
74
76
 
@@ -116,7 +118,8 @@ function build(state: ChatState, items: ChatItem[], authors: Record<string, Auth
116
118
  * item keyed by the message id (`queueId`), its `chat` author in the authors
117
119
  * record (end side); others -> an `assistant` item with `author`
118
120
  * (`{ns: 'chat', id: sender, label, avatarId, kind, description}`, start
119
- * side); announcements -> a muted `activity` row (`<name> joined the
121
+ * side); both carry the message's `attachments` (none: no field);
122
+ * announcements -> a muted `activity` row (`<name> joined the
120
123
  * channel`, English: `localizeAnnouncements` gives other texts). One item per
121
124
  * message id: a message already shown changes nothing (the same state comes
122
125
  * back). A live message takes its place by its `sentAt` (after the shown ones