@widgetic/editor 4.1.12 → 4.1.14

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.
@@ -0,0 +1,107 @@
1
+ <!--
2
+ * KnowledgeTextForm
3
+ *
4
+ * The form of the Documents panel (AI Answers) that adds a document made of text a person typed or pasted: a title and the
5
+ * text. It is on the screen only while the person is writing; closing it, by cancelling or by adding the document, throws
6
+ * away what was written, and a document the API refuses keeps the form open with everything in it so it can be fixed.
7
+ *
8
+ * The form sends nothing itself: it hands the title and the text to `onAdd` (the panel's `addText`), which answers `true`
9
+ * when the document was added. What the panel says about a refusal is on the screen in the panel, below its list, not here.
10
+ -->
11
+
12
+ <script module lang="ts">
13
+ /** Declared props contract of the form. */
14
+ export interface KnowledgeTextFormProps {
15
+ /** True while the panel is sending or removing something: nothing can be added meanwhile. */
16
+ busy?: boolean;
17
+ /** Adds the document. Resolves `true` when it was added (the form then closes) and `false` when it was not. */
18
+ onAdd: (input: { title: string; text: string }) => Promise<boolean>;
19
+ /** Takes the form off the screen: the person cancelled, or the document was added. */
20
+ onClose: () => void;
21
+ }
22
+ </script>
23
+
24
+ <script lang="ts">
25
+ import { onMount } from 'svelte';
26
+ import { Button, Input, Textarea } from '@widgetic/design-system/components';
27
+ import { dirForUserText, useTextDirection } from '@widgetic/design-system/components/textDirection';
28
+ import { useEditorLanguage } from '../../i18n/language';
29
+ import { KNOWLEDGE_TITLE_MAX_LENGTH } from '../../composition/knowledgeDocuments';
30
+
31
+ let { busy = false, onAdd, onClose }: KnowledgeTextFormProps = $props();
32
+
33
+ // The words of the editor in the language of the page, and the way the screen is read (what a person typed is read by its
34
+ // own first letter on a right to left screen).
35
+ const { t } = useEditorLanguage();
36
+ const textDirection = useTextDirection();
37
+
38
+ // Ids that stay unique when the panel is on the screen twice.
39
+ const uniqueId = $props.id();
40
+ const titleFieldId = `${uniqueId}-title`;
41
+ const textFieldId = `${uniqueId}-text`;
42
+
43
+ let titleField: HTMLInputElement | null = $state(null);
44
+ let title = $state('');
45
+ let text = $state('');
46
+
47
+ /** Both boxes need words, and nothing else may be going on: the same two things the panel would turn the person back for. */
48
+ const canAdd = $derived(!busy && title.trim() !== '' && text.trim() !== '');
49
+
50
+ // The form was opened by a button: the person goes on typing where the form begins, without searching for it.
51
+ onMount(() => {
52
+ titleField?.focus();
53
+ });
54
+
55
+ async function handleSubmit(event: SubmitEvent): Promise<void> {
56
+ event.preventDefault();
57
+ if (!canAdd) return;
58
+ try {
59
+ const wasAdded = await onAdd({ title, text });
60
+ if (wasAdded) onClose();
61
+ } catch (error) {
62
+ // The panel answers `false` for what it could not do; this is something it did not expect. The form stays as it is.
63
+ console.warn('[KnowledgeDocuments] The text could not be added:', error);
64
+ }
65
+ }
66
+ </script>
67
+
68
+ <form class="flex flex-col gap-2 rounded-large border border-grey2 bg-grey1 p-3" onsubmit={handleSubmit}>
69
+ <label class="caption text-grey5" for={titleFieldId}>{$t('editor.knowledge.titleLabel')}</label>
70
+ <div
71
+ class="rounded-large border border-grey2 bg-white transition-colors duration-200 focus-within:border-forest-green hover:border-forest-green"
72
+ >
73
+ <Input
74
+ id={titleFieldId}
75
+ bind:ref={titleField}
76
+ bind:value={title}
77
+ maxlength={KNOWLEDGE_TITLE_MAX_LENGTH}
78
+ autocomplete="off"
79
+ placeholder={$t('editor.knowledge.titlePlaceholder')}
80
+ dir={title ? dirForUserText($textDirection) : undefined}
81
+ disabled={busy}
82
+ class="subtext h-10 w-full border-none bg-transparent px-4 text-grey7 placeholder:text-grey3 focus-visible:ring-0 focus-visible:ring-offset-0"
83
+ />
84
+ </div>
85
+ <label class="caption text-grey5" for={textFieldId}>{$t('editor.knowledge.textLabel')}</label>
86
+ <div
87
+ class="rounded-large border border-grey2 bg-white transition-colors duration-200 focus-within:border-forest-green hover:border-forest-green"
88
+ >
89
+ <Textarea
90
+ id={textFieldId}
91
+ bind:value={text}
92
+ rows={6}
93
+ placeholder={$t('editor.knowledge.textPlaceholder')}
94
+ dir={text ? dirForUserText($textDirection) : undefined}
95
+ disabled={busy}
96
+ class="subtext w-full resize-y border-none bg-transparent px-4 py-3 text-grey7 placeholder:text-grey3 focus-visible:ring-0 focus-visible:ring-offset-0"
97
+ />
98
+ </div>
99
+ <div class="flex justify-end gap-2">
100
+ <Button type="button" variant="ghost" size="sm" class="text-grey5" onclick={onClose}>
101
+ {$t('editor.knowledge.cancel')}
102
+ </Button>
103
+ <Button type="submit" size="sm" disabled={!canAdd}>
104
+ {$t('editor.knowledge.addDocument')}
105
+ </Button>
106
+ </div>
107
+ </form>
@@ -0,0 +1,15 @@
1
+ /** Declared props contract of the form. */
2
+ export interface KnowledgeTextFormProps {
3
+ /** True while the panel is sending or removing something: nothing can be added meanwhile. */
4
+ busy?: boolean;
5
+ /** Adds the document. Resolves `true` when it was added (the form then closes) and `false` when it was not. */
6
+ onAdd: (input: {
7
+ title: string;
8
+ text: string;
9
+ }) => Promise<boolean>;
10
+ /** Takes the form off the screen: the person cancelled, or the document was added. */
11
+ onClose: () => void;
12
+ }
13
+ declare const KnowledgeTextForm: import("svelte").Component<KnowledgeTextFormProps, {}, "">;
14
+ type KnowledgeTextForm = ReturnType<typeof KnowledgeTextForm>;
15
+ export default KnowledgeTextForm;
@@ -21,6 +21,7 @@ export { default as InputControllerHeader } from './InputControllerHeader.svelte
21
21
  export { default as TimeInputController } from './TimeInputController.svelte';
22
22
  export { default as RoundedCornersInputController } from './RoundedCornersInputController.svelte';
23
23
  export { default as TagsInputController } from './TagsInputController.svelte';
24
+ export { default as KnowledgeDocumentsInputController } from './KnowledgeDocumentsInputController.svelte';
24
25
  export { default as DateFieldInputController } from './DateFieldInputController.svelte';
25
26
  export interface InputControllerConfig {
26
27
  placeholder?: string;
@@ -21,4 +21,5 @@ export { default as InputControllerHeader } from './InputControllerHeader.svelte
21
21
  export { default as TimeInputController } from './TimeInputController.svelte';
22
22
  export { default as RoundedCornersInputController } from './RoundedCornersInputController.svelte';
23
23
  export { default as TagsInputController } from './TagsInputController.svelte';
24
+ export { default as KnowledgeDocumentsInputController } from './KnowledgeDocumentsInputController.svelte';
24
25
  export { default as DateFieldInputController } from './DateFieldInputController.svelte';
@@ -17,9 +17,13 @@
17
17
  * - every failure is a `CompositionApiError` with the API's own code, so the host can tell an ended session
18
18
  * (`EDITOR_SESSION_EXPIRED`...) from a missing composition (`NOT_FOUND`) from a widget that was never
19
19
  * published (`WIDGET_NOT_PUBLISHED`);
20
- * - a request that gets no answer does not hang the editor: it fails with `TIMEOUT` after a set time.
20
+ * - a request that gets no answer does not hang the editor: it fails with `TIMEOUT` after a set time;
21
+ * - the documents of an AI Answers widget (`/compositions/{id}/adapters/ai-answers/knowledge`) are listed, added (as typed
22
+ * text, or as a file sent as a multipart form) and removed through the same four rules above. Adding one waits for the API
23
+ * to read and embed the document, which takes longer than any other call, so it has a limit of its own.
21
24
  */
22
25
  import { type JsonRecord } from './compositionHelpers.js';
26
+ import { type KnowledgeDocument, type KnowledgeFileInput, type KnowledgeListing, type KnowledgeTextInput } from './knowledgeDocuments.js';
23
27
  /** Why the token is being asked for. `expired` means the API just refused the previous one. */
24
28
  export type TokenReason = 'initial' | 'expired';
25
29
  /** The fields of a composition an editor may change. Anything else is refused by the API for an editor session. */
@@ -162,6 +166,22 @@ export interface CompositionApi {
162
166
  peekEditLease(compositionId: string, options?: CompositionRequestOptions): Promise<EditLeaseAnswer>;
163
167
  /** Gives up this tab's claim (nothing happens when it holds none, or somebody else does now). */
164
168
  releaseEditLease(compositionId: string, sessionId: string, options?: ReleaseEditLeaseOptions): Promise<void>;
169
+ /** The documents the widget's AI answers from (AI Answers), and how much of the knowledge base they use. */
170
+ listKnowledgeDocuments(compositionId: string, options?: CompositionRequestOptions): Promise<KnowledgeListing>;
171
+ /**
172
+ * Adds a document made of text. Answers once the AI can use it, which takes a few seconds, longer for a long text.
173
+ * Costs no credits. The same text cannot be added twice (`KNOWLEDGE_DUPLICATE_DOCUMENT`).
174
+ */
175
+ addKnowledgeText(compositionId: string, input: KnowledgeTextInput, options?: CompositionRequestOptions): Promise<KnowledgeDocument>;
176
+ /**
177
+ * Adds a document made of a file: a text, Markdown or CSV file, or a picture of a page (a PDF is refused by the API for
178
+ * now). The file is sent as a multipart form (field `file`, and `title` when one is given) and is read on the API's side,
179
+ * which keeps no copy of it. Answers once the AI can use the document, which can take up to a minute and a half for a
180
+ * long one.
181
+ */
182
+ addKnowledgeFile(compositionId: string, input: KnowledgeFileInput, options?: CompositionRequestOptions): Promise<KnowledgeDocument>;
183
+ /** Takes a document out of the knowledge base, with everything the AI made from it. */
184
+ removeKnowledgeDocument(compositionId: string, documentId: string, options?: CompositionRequestOptions): Promise<void>;
165
185
  }
166
186
  /** A key that is unique, not secret: the page's `crypto.randomUUID`, else random bytes, else the clock and `Math.random`. */
167
187
  export declare function createRandomIdempotencyKey(): string;
@@ -17,9 +17,13 @@
17
17
  * - every failure is a `CompositionApiError` with the API's own code, so the host can tell an ended session
18
18
  * (`EDITOR_SESSION_EXPIRED`...) from a missing composition (`NOT_FOUND`) from a widget that was never
19
19
  * published (`WIDGET_NOT_PUBLISHED`);
20
- * - a request that gets no answer does not hang the editor: it fails with `TIMEOUT` after a set time.
20
+ * - a request that gets no answer does not hang the editor: it fails with `TIMEOUT` after a set time;
21
+ * - the documents of an AI Answers widget (`/compositions/{id}/adapters/ai-answers/knowledge`) are listed, added (as typed
22
+ * text, or as a file sent as a multipart form) and removed through the same four rules above. Adding one waits for the API
23
+ * to read and embed the document, which takes longer than any other call, so it has a limit of its own.
21
24
  */
22
25
  import { unwrapApiData } from './compositionHelpers.js';
26
+ import { KNOWLEDGE_ADD_TIMEOUT_MS, readKnowledgeDocument, readKnowledgeListing } from './knowledgeDocuments.js';
23
27
  export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
24
28
  /** What the API accepts as an idempotency key. */
25
29
  const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9_-]{8,50}$/;
@@ -205,18 +209,22 @@ export function createCompositionApi(options) {
205
209
  const fetchImplementation = options.fetch ?? globalThis.fetch.bind(globalThis);
206
210
  const controller = new AbortController();
207
211
  let timedOut = false;
212
+ const limitMs = extras.timeoutMs ?? requestTimeoutMs;
208
213
  const timer = setTimeout(() => {
209
214
  timedOut = true;
210
215
  controller.abort();
211
- }, requestTimeoutMs);
216
+ }, limitMs);
212
217
  const forwardAbort = () => controller.abort();
213
218
  extras.signal?.addEventListener('abort', forwardAbort, { once: true });
214
219
  const headers = {
215
220
  Accept: 'application/json',
216
221
  Authorization: `Bearer ${token}`
217
222
  };
218
- if (extras.body !== undefined)
223
+ // A form carries its own `Content-Type`, boundary included, which `fetch` writes when it is given one: setting it here
224
+ // would leave the API a form it cannot split into its parts.
225
+ if (extras.form === undefined && extras.body !== undefined) {
219
226
  headers['Content-Type'] = 'application/json';
227
+ }
220
228
  if (extras.idempotencyKey)
221
229
  headers['Idempotency-Key'] = extras.idempotencyKey;
222
230
  if (extras.ifMatch)
@@ -225,7 +233,7 @@ export function createCompositionApi(options) {
225
233
  const response = await fetchImplementation(url, {
226
234
  method,
227
235
  headers,
228
- body: extras.body !== undefined ? JSON.stringify(extras.body) : undefined,
236
+ body: extras.form ?? (extras.body !== undefined ? JSON.stringify(extras.body) : undefined),
229
237
  // The token is the credential; the page's cookies for the API's domain play no part.
230
238
  credentials: 'omit',
231
239
  // What a composition holds changes with every save; never serve it from a cache.
@@ -239,7 +247,7 @@ export function createCompositionApi(options) {
239
247
  }
240
248
  catch (error) {
241
249
  if (timedOut) {
242
- throw new CompositionApiError(`The API did not answer within ${describeWait(requestTimeoutMs)}.`, {
250
+ throw new CompositionApiError(`The API did not answer within ${describeWait(limitMs)}.`, {
243
251
  status: 0,
244
252
  code: 'TIMEOUT'
245
253
  });
@@ -334,6 +342,17 @@ export function createCompositionApi(options) {
334
342
  }
335
343
  return sessionId;
336
344
  }
345
+ /** The address of the documents of a composition's AI Answers widget, with `suffix` after it. */
346
+ function knowledgePath(compositionId, suffix = '') {
347
+ return compositionPath(compositionId, `/adapters/ai-answers/knowledge${suffix}`);
348
+ }
349
+ /** The id of a document, which goes into an address; a missing one is a bug of the caller, never sent. */
350
+ function checkedDocumentId(documentId) {
351
+ if (typeof documentId !== 'string' || documentId.trim() === '') {
352
+ throw new TypeError('A document id is needed');
353
+ }
354
+ return documentId;
355
+ }
337
356
  return {
338
357
  async getComposition(compositionId, requestOptions = {}) {
339
358
  const record = await request('GET', compositionPath(compositionId), requestOptions);
@@ -409,6 +428,46 @@ export function createCompositionApi(options) {
409
428
  },
410
429
  async releaseEditLease(compositionId, sessionId, releaseOptions = {}) {
411
430
  await request('DELETE', leasePath(compositionId, `?sessionId=${encodeURIComponent(checkedSessionId(sessionId))}`), { signal: releaseOptions.signal, keepalive: releaseOptions.keepalive });
431
+ },
432
+ async listKnowledgeDocuments(compositionId, requestOptions = {}) {
433
+ const listing = readKnowledgeListing(await request('GET', knowledgePath(compositionId), requestOptions));
434
+ if (!listing)
435
+ throw invalidResponse('The API gave no list of documents.');
436
+ return listing;
437
+ },
438
+ async addKnowledgeText(compositionId, input, requestOptions = {}) {
439
+ const document = readKnowledgeDocument(await request('POST', knowledgePath(compositionId, '/documents'), {
440
+ body: { title: input.title, text: input.text },
441
+ signal: requestOptions.signal,
442
+ timeoutMs: KNOWLEDGE_ADD_TIMEOUT_MS
443
+ }));
444
+ if (!document)
445
+ throw invalidResponse('The API gave no document.');
446
+ return document;
447
+ },
448
+ async addKnowledgeFile(compositionId, input, requestOptions = {}) {
449
+ if (typeof Blob === 'undefined' || !(input?.file instanceof Blob)) {
450
+ throw new TypeError('A file is needed');
451
+ }
452
+ const form = new FormData();
453
+ if (typeof input.title === 'string' && input.title.trim() !== '') {
454
+ form.append('title', input.title);
455
+ }
456
+ // A `File` carries its own name; a plain `Blob` has none, so the caller names it (or it is just "document").
457
+ const ownName = input.file.name;
458
+ const fileName = input.fileName || (typeof ownName === 'string' ? ownName : '') || 'document';
459
+ form.append('file', input.file, fileName);
460
+ const document = readKnowledgeDocument(await request('POST', knowledgePath(compositionId, '/documents/file'), {
461
+ form,
462
+ signal: requestOptions.signal,
463
+ timeoutMs: KNOWLEDGE_ADD_TIMEOUT_MS
464
+ }));
465
+ if (!document)
466
+ throw invalidResponse('The API gave no document.');
467
+ return document;
468
+ },
469
+ async removeKnowledgeDocument(compositionId, documentId, requestOptions = {}) {
470
+ await request('DELETE', knowledgePath(compositionId, `/documents/${encodeURIComponent(checkedDocumentId(documentId))}`), requestOptions);
412
471
  }
413
472
  };
414
473
  }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The documents of the AI Answers adapter: what an owner gives a widget's AI to write its answers from.
3
+ *
4
+ * This file holds what is true of them whatever draws them: the shape the API answers with (and a reader that checks it,
5
+ * because an answer the editor cannot read must not break the settings panel), the few limits the editor itself knows,
6
+ * and `createKnowledgeDocumentsClient`, which binds the four calls to ONE composition so a control that is given the client
7
+ * never needs to know which composition it is in, or how a request is made.
8
+ *
9
+ * It imports only types from `compositionApi.ts`, which in turn reads its answers with the readers of this file: nothing
10
+ * of `compositionApi.ts` is loaded when this file is, so the two do not wait for each other.
11
+ */
12
+ import type { CompositionApi, CompositionRequestOptions } from './compositionApi.js';
13
+ /** A document is `processing` while its text is being read and turned into numbers, and `ready` once the AI can use it. */
14
+ export type KnowledgeDocumentStatus = 'processing' | 'ready';
15
+ /** One document of a widget's knowledge base, as the API lists it. The text itself is never sent back. */
16
+ export interface KnowledgeDocument {
17
+ id: string;
18
+ /** What the owner called it (a file's own name when none was given). Text typed by a person: shown as written. */
19
+ title: string;
20
+ status: KnowledgeDocumentStatus;
21
+ /** How many characters of text the document holds. */
22
+ charCount: number;
23
+ /** How many passages the text was cut into. */
24
+ chunkCount: number;
25
+ /** When it was added (an ISO date). */
26
+ createdAt: string;
27
+ /** When it became ready, or `null` while it is not. */
28
+ readyAt: string | null;
29
+ }
30
+ /** How much of the knowledge base is used, and how much it can hold. A limit is `null` when the API did not say. */
31
+ export interface KnowledgeTotals {
32
+ documents: number;
33
+ characters: number;
34
+ maxDocuments: number | null;
35
+ maxTotalChars: number | null;
36
+ }
37
+ /** Everything the API says about a widget's knowledge base. */
38
+ export interface KnowledgeListing {
39
+ documents: KnowledgeDocument[];
40
+ totals: KnowledgeTotals;
41
+ }
42
+ /** What goes into a document typed or pasted as text. */
43
+ export interface KnowledgeTextInput {
44
+ title: string;
45
+ text: string;
46
+ }
47
+ /** What goes into a document made from a file. Without a `title` the API uses the file's name. */
48
+ export interface KnowledgeFileInput {
49
+ file: Blob;
50
+ /** The name the file is sent under. A `File` has its own; a plain `Blob` needs one. */
51
+ fileName?: string;
52
+ title?: string;
53
+ }
54
+ /**
55
+ * The four calls of a widget's knowledge base, for one composition. Each one fails with a `CompositionApiError` whose `code`
56
+ * is the API's own (`KNOWLEDGE_DUPLICATE_DOCUMENT`, `KNOWLEDGE_FILE_TOO_LARGE`...), or one of the client's.
57
+ */
58
+ export interface KnowledgeDocumentsClient {
59
+ list(options?: CompositionRequestOptions): Promise<KnowledgeListing>;
60
+ addText(input: KnowledgeTextInput, options?: CompositionRequestOptions): Promise<KnowledgeDocument>;
61
+ addFile(input: KnowledgeFileInput, options?: CompositionRequestOptions): Promise<KnowledgeDocument>;
62
+ remove(documentId: string, options?: CompositionRequestOptions): Promise<void>;
63
+ }
64
+ /** The longest title the API takes, in characters. A hint for the box a title is typed in; the API holds the limit. */
65
+ export declare const KNOWLEDGE_TITLE_MAX_LENGTH = 120;
66
+ /**
67
+ * What the file chooser offers: a text file (plain, Markdown or CSV) or a picture of a page. Only a hint to the person
68
+ * choosing: what a file IS comes from its bytes, on the API's side, and the API says so when it is not one of these.
69
+ *
70
+ * A PDF is NOT offered: the API does not read PDFs yet (28 Oct 2026; its `PDF_READING_ENABLED` is off, because reading one in
71
+ * a process of its own can take more memory than the instance has). A PDF that is dropped on the panel or chosen anyway is
72
+ * refused by the API (`KNOWLEDGE_FILE_TYPE_UNSUPPORTED`) and the person is told so in words (`fileTypeUnsupported`). When the
73
+ * API reads PDFs, `.pdf` and `application/pdf` come back to this list in the release that goes with it.
74
+ */
75
+ export declare const KNOWLEDGE_FILE_ACCEPT: string;
76
+ /**
77
+ * How long a document may take to add before the editor gives up, in milliseconds. The API ends an add by itself after 90
78
+ * seconds (a long document is read, cut up and embedded in that time); the editor waits a little longer so that the API's own
79
+ * answer, not the editor's timeout, tells the person what happened.
80
+ */
81
+ export declare const KNOWLEDGE_ADD_TIMEOUT_MS = 120000;
82
+ /** One document as the API wrote it, or `null` when what came is no document (no id, no title). */
83
+ export declare function readKnowledgeDocument(value: unknown): KnowledgeDocument | null;
84
+ /**
85
+ * What the API listed, or `null` when it is no list. A document that cannot be read is left out rather than failing the list:
86
+ * the rest are still the owner's, and still usable. When the API gives no totals they are worked out from the documents.
87
+ */
88
+ export declare function readKnowledgeListing(value: unknown): KnowledgeListing | null;
89
+ /** Binds the four calls to one composition. */
90
+ export declare function createKnowledgeDocumentsClient(api: Pick<CompositionApi, 'listKnowledgeDocuments' | 'addKnowledgeText' | 'addKnowledgeFile' | 'removeKnowledgeDocument'>, compositionId: string): KnowledgeDocumentsClient;
@@ -0,0 +1,94 @@
1
+ /** The longest title the API takes, in characters. A hint for the box a title is typed in; the API holds the limit. */
2
+ export const KNOWLEDGE_TITLE_MAX_LENGTH = 120;
3
+ /**
4
+ * What the file chooser offers: a text file (plain, Markdown or CSV) or a picture of a page. Only a hint to the person
5
+ * choosing: what a file IS comes from its bytes, on the API's side, and the API says so when it is not one of these.
6
+ *
7
+ * A PDF is NOT offered: the API does not read PDFs yet (28 Oct 2026; its `PDF_READING_ENABLED` is off, because reading one in
8
+ * a process of its own can take more memory than the instance has). A PDF that is dropped on the panel or chosen anyway is
9
+ * refused by the API (`KNOWLEDGE_FILE_TYPE_UNSUPPORTED`) and the person is told so in words (`fileTypeUnsupported`). When the
10
+ * API reads PDFs, `.pdf` and `application/pdf` come back to this list in the release that goes with it.
11
+ */
12
+ export const KNOWLEDGE_FILE_ACCEPT = [
13
+ '.txt',
14
+ '.text',
15
+ '.md',
16
+ '.markdown',
17
+ '.csv',
18
+ '.png',
19
+ '.jpg',
20
+ '.jpeg',
21
+ '.webp',
22
+ 'text/plain',
23
+ 'text/markdown',
24
+ 'text/csv',
25
+ 'image/png',
26
+ 'image/jpeg',
27
+ 'image/webp'
28
+ ].join(',');
29
+ /**
30
+ * How long a document may take to add before the editor gives up, in milliseconds. The API ends an add by itself after 90
31
+ * seconds (a long document is read, cut up and embedded in that time); the editor waits a little longer so that the API's own
32
+ * answer, not the editor's timeout, tells the person what happened.
33
+ */
34
+ export const KNOWLEDGE_ADD_TIMEOUT_MS = 120_000;
35
+ function isRecord(value) {
36
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
37
+ }
38
+ /** A count worth believing: a finite number of zero or more. Anything else is `null`. */
39
+ function readCount(value) {
40
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
41
+ }
42
+ /** One document as the API wrote it, or `null` when what came is no document (no id, no title). */
43
+ export function readKnowledgeDocument(value) {
44
+ if (!isRecord(value))
45
+ return null;
46
+ if (typeof value.id !== 'string' || value.id === '' || typeof value.title !== 'string')
47
+ return null;
48
+ return {
49
+ id: value.id,
50
+ title: value.title,
51
+ // Any status but `ready` is a document the AI cannot use yet, so it is shown as still being read.
52
+ status: value.status === 'ready' ? 'ready' : 'processing',
53
+ charCount: readCount(value.charCount) ?? 0,
54
+ chunkCount: readCount(value.chunkCount) ?? 0,
55
+ createdAt: typeof value.createdAt === 'string' ? value.createdAt : '',
56
+ readyAt: typeof value.readyAt === 'string' ? value.readyAt : null
57
+ };
58
+ }
59
+ /**
60
+ * What the API listed, or `null` when it is no list. A document that cannot be read is left out rather than failing the list:
61
+ * the rest are still the owner's, and still usable. When the API gives no totals they are worked out from the documents.
62
+ */
63
+ export function readKnowledgeListing(value) {
64
+ if (!isRecord(value) || !Array.isArray(value.documents))
65
+ return null;
66
+ const documents = [];
67
+ for (const entry of value.documents) {
68
+ const document = readKnowledgeDocument(entry);
69
+ if (document)
70
+ documents.push(document);
71
+ else
72
+ console.warn('[knowledgeDocuments] A document the API listed could not be read and was left out');
73
+ }
74
+ const totals = isRecord(value.totals) ? value.totals : {};
75
+ return {
76
+ documents,
77
+ totals: {
78
+ documents: readCount(totals.documents) ?? documents.length,
79
+ characters: readCount(totals.characters) ??
80
+ documents.reduce((sum, document) => sum + document.charCount, 0),
81
+ maxDocuments: readCount(totals.maxDocuments),
82
+ maxTotalChars: readCount(totals.maxTotalChars)
83
+ }
84
+ };
85
+ }
86
+ /** Binds the four calls to one composition. */
87
+ export function createKnowledgeDocumentsClient(api, compositionId) {
88
+ return {
89
+ list: (options) => api.listKnowledgeDocuments(compositionId, options),
90
+ addText: (input, options) => api.addKnowledgeText(compositionId, input, options),
91
+ addFile: (input, options) => api.addKnowledgeFile(compositionId, input, options),
92
+ remove: (documentId, options) => api.removeKnowledgeDocument(compositionId, documentId, options)
93
+ };
94
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * What happens in the Documents panel of AI Answers, without anything to look at: loading the list, adding files and text,
3
+ * taking a document out, and telling the person what went wrong in words they can act on.
4
+ *
5
+ * The panel (`KnowledgeDocumentsInputController.svelte`) only draws this state and forwards what the person presses. The logic
6
+ * is here so that it can be tested in Node, with a fake client and a fake clock, where a component cannot be pressed:
7
+ *
8
+ * - the list is loaded once when the panel starts, and again on "try again". A document that is still being read (another
9
+ * tab of the same owner added it a moment ago) is looked at again every few seconds, a limited number of times;
10
+ * - files are sent one after the other, never together: each one is read and embedded on the API's side, and the API allows
11
+ * a few adds in a few minutes, so sending five at once would only make four of them wait or fail. One that fails is
12
+ * reported by name and the next one is tried, unless the failure would be the same for all of them (the session ended,
13
+ * the connection is down, the knowledge base is full, too many adds): then the rest are not sent and the person is told;
14
+ * - removing a document takes two presses, so a slip of the hand does not lose a document that took a minute to add. The
15
+ * first press asks, the second one removes; leaving it alone for a few seconds takes the question back;
16
+ * - whatever is in flight is cancelled when the panel goes away, and its answer is ignored.
17
+ *
18
+ * The state it keeps is a Svelte store (`subscribe` calls the listener at once with the state, then at every change), so the
19
+ * panel can read it as `$panel`.
20
+ */
21
+ import type { EditorMessageKey } from '../i18n/messages.js';
22
+ import { type EditorFailure } from './compositionEditorController.js';
23
+ import { type KnowledgeDocument, type KnowledgeDocumentsClient, type KnowledgeTotals } from './knowledgeDocuments.js';
24
+ /**
25
+ * A sentence for the person, as the catalog's key and the values that go into it, so the panel says it in the language of
26
+ * the page. `verbatim` is what the API itself said, kept for a failure the editor has no sentence of its own for.
27
+ */
28
+ export interface PanelMessage {
29
+ messageKey: EditorMessageKey;
30
+ messageValues?: Record<string, string | number>;
31
+ verbatim?: string;
32
+ }
33
+ /** A problem to show below the list, next to the buttons that were pressed, until the person dismisses it or starts something else. */
34
+ export interface PanelNotice {
35
+ /** Tells one notice from another, so a list of them can be drawn by key. */
36
+ id: number;
37
+ message: PanelMessage;
38
+ }
39
+ /** `unavailable`: no client (the control is not inside a composition editor). */
40
+ export type KnowledgePanelPhase = 'unavailable' | 'loading' | 'ready' | 'failed';
41
+ /** What is being sent right now: the name of the file (or the title of the text), and where it is in the batch. */
42
+ export interface PanelSending {
43
+ name: string;
44
+ /** 1-based place of this one in the batch. */
45
+ position: number;
46
+ count: number;
47
+ }
48
+ export interface KnowledgePanelState {
49
+ phase: KnowledgePanelPhase;
50
+ /** The documents, oldest first. */
51
+ documents: readonly KnowledgeDocument[];
52
+ /** How much of the knowledge base is used, or `null` before the first list. */
53
+ totals: KnowledgeTotals | null;
54
+ /** Why the list could not be loaded (`phase` is `failed`). */
55
+ loadFailure: PanelMessage | null;
56
+ sending: PanelSending | null;
57
+ /** The ids of the documents being removed. */
58
+ removing: readonly string[];
59
+ /** The document whose removal was asked once: pressing remove again takes it out. */
60
+ confirmingRemoval: string | null;
61
+ notices: readonly PanelNotice[];
62
+ }
63
+ export interface PanelTimers {
64
+ set(callback: () => void, delayMs: number): unknown;
65
+ clear(handle: unknown): void;
66
+ }
67
+ export interface KnowledgePanelOptions {
68
+ /** The four calls for this composition; `undefined` when the control is used outside a composition editor. */
69
+ client: KnowledgeDocumentsClient | undefined;
70
+ /** How long to wait before looking again at a list that has a document still being read. Default: 4 seconds. */
71
+ pollDelayMs?: number;
72
+ /** How many times to look again before giving up on a document that never becomes ready. Default: 15 (a minute). */
73
+ maxPolls?: number;
74
+ /** How long a first press on "remove" waits for the second one. Default: 6 seconds. */
75
+ removalConfirmationMs?: number;
76
+ /** The clock to wait with. Default: the page's `setTimeout`. Tests give one they can wind forward. */
77
+ timers?: PanelTimers;
78
+ }
79
+ /**
80
+ * The sentence for a failure of a call about the knowledge base. `about` names what was being added (a file's name, a
81
+ * document's title), for the sentences that say which one it was. The API's own sentence is kept only when the editor has
82
+ * none of its own for the code: those are written for the owner and say what to do, but only in English.
83
+ */
84
+ export declare function describeKnowledgeFailure(failure: EditorFailure, about?: {
85
+ name?: string;
86
+ }): PanelMessage;
87
+ export declare class KnowledgeDocumentsPanel {
88
+ private readonly client;
89
+ private readonly pollDelayMs;
90
+ private readonly maxPolls;
91
+ private readonly removalConfirmationMs;
92
+ private readonly timers;
93
+ private readonly listeners;
94
+ /** Cancels every request that is on its way when the panel goes away. */
95
+ private readonly cancellation;
96
+ private state;
97
+ private started;
98
+ private destroyed;
99
+ private loading;
100
+ private pollsSoFar;
101
+ private latestRefresh;
102
+ private pollHandle;
103
+ private confirmationHandle;
104
+ private nextNoticeId;
105
+ constructor(options: KnowledgePanelOptions);
106
+ getState(): KnowledgePanelState;
107
+ /** The store contract: the listener hears the state now and at every change; the returned function stops it. */
108
+ subscribe(listener: (state: KnowledgePanelState) => void): () => void;
109
+ private setState;
110
+ /** Loads the list. Called once, when the panel is on the screen; calling it again does nothing. */
111
+ start(): Promise<void>;
112
+ /** Loads the list again after it failed ("try again"). */
113
+ retry(): Promise<void>;
114
+ private load;
115
+ private loadList;
116
+ /**
117
+ * Looks at the list again, without any sign of it on the screen, to bring the totals up to date after a change, or to see
118
+ * a document become ready. A failure is only logged: the list that is on the screen is still the best the panel has.
119
+ */
120
+ private refresh;
121
+ /** While a document is being read, look again every few seconds (a limited number of times), so it turns ready on its own. */
122
+ private watchDocumentsBeingRead;
123
+ private stopWatching;
124
+ /** True while the panel is busy with something that must end before the next thing starts. */
125
+ private isBusy;
126
+ /** Sends the files one after the other (see the top of this file). Resolves when the last one is done. */
127
+ addFiles(files: readonly File[]): Promise<void>;
128
+ /**
129
+ * Adds a document made of text the person typed or pasted. Resolves `true` when it was added, so the form can close, and
130
+ * `false` when it was not (the reason is in `notices`) or the panel was busy.
131
+ */
132
+ addText(input: {
133
+ title: string;
134
+ text: string;
135
+ }): Promise<boolean>;
136
+ /** Ends a batch: the problems become notices (a few, and a line for the rest), and nothing is being sent any more. */
137
+ private finishSending;
138
+ private noticeFor;
139
+ /** Takes the problems off the screen. */
140
+ dismissNotices(): void;
141
+ /** The first press on "remove": asks the person to press it again. */
142
+ askToRemove(documentId: string): void;
143
+ /** Takes the question back (the person chose to keep the document, or went on to something else). */
144
+ cancelRemoval(): void;
145
+ private clearConfirmationTimer;
146
+ /** The second press: takes the document out. Does nothing unless the first press came for this very document. */
147
+ confirmRemoval(documentId: string): Promise<void>;
148
+ /** Takes a document off the list and its share off the totals, so the screen is right before the API is asked again. */
149
+ private dropDocument;
150
+ /** Cancels what is on its way and stops every timer. The panel says nothing more after this. */
151
+ destroy(): void;
152
+ }