@adminforth/agent 3.2.0 → 3.4.0
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/dist/application/runTurnUseCase.d.ts +5 -1
- package/dist/application/runTurnUseCase.js +41 -57
- package/dist/custom/ChatFooter.vue +76 -36
- package/dist/custom/ChatSurface.vue +89 -19
- package/dist/custom/ComposerAttachments.vue +36 -0
- package/dist/custom/composables/agentStore/constants.ts +13 -0
- package/dist/custom/composables/agentStore/useAgentAttachments.ts +163 -0
- package/dist/custom/composables/agentStore/useAgentChat.ts +19 -4
- package/dist/custom/composables/agentStore/useAgentSessions.ts +84 -20
- package/dist/custom/composables/useAgentStore.ts +67 -31
- package/dist/custom/composables/useAgentTransitions.ts +13 -37
- package/dist/custom/conversation_area/MessageAttachments.vue +22 -0
- package/dist/custom/conversation_area/MessageRenderer.vue +15 -2
- package/dist/custom/types.ts +39 -0
- package/dist/custom/utils.ts +15 -0
- package/dist/domain/imageAttachments.d.ts +73 -0
- package/dist/domain/imageAttachments.js +63 -0
- package/dist/domain/turnTypes.d.ts +16 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +30 -2
- package/dist/llm/agentRuntime.d.ts +11 -1
- package/dist/llm/agentRuntime.js +6 -1
- package/dist/llm/langGraphLlm.js +7 -1
- package/dist/llm/middleware/attachmentsMiddleware.d.ts +16 -0
- package/dist/llm/middleware/attachmentsMiddleware.js +139 -0
- package/dist/persistence/sessionStore.d.ts +11 -2
- package/dist/persistence/sessionStore.js +44 -9
- package/dist/persistence/turnAttachments.d.ts +41 -0
- package/dist/persistence/turnAttachments.js +112 -0
- package/dist/tools/navigateUser.d.ts +3 -3
- package/dist/tools/toolLabels.js +1 -0
- package/dist/tools/viewImage.d.ts +13 -0
- package/dist/tools/viewImage.js +57 -0
- package/dist/transport/http/context.d.ts +22 -3
- package/dist/transport/http/coreEndpoints.d.ts +36 -1
- package/dist/transport/http/coreEndpoints.js +104 -35
- package/dist/transport/http/sessionEndpoints.js +3 -4
- package/dist/types.d.ts +29 -0
- package/package.json +3 -3
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { ref } from 'vue';
|
|
2
|
+
import { callAdminForthApi } from '@/utils';
|
|
3
|
+
import { getErrorMessage, t } from '../../utils';
|
|
4
|
+
import type { IAttachmentRef, IAttachmentsConfig, IComposerAttachment, IMessageAttachment } from '../../types';
|
|
5
|
+
import {
|
|
6
|
+
IMAGE_ENCODE_QUALITY,
|
|
7
|
+
IMAGE_UPLOAD_FALLBACK_BACKGROUND,
|
|
8
|
+
IMAGE_UPLOAD_FALLBACK_FORMAT,
|
|
9
|
+
IMAGE_UPLOAD_FORMAT,
|
|
10
|
+
MAX_IMAGE_LONG_SIDE,
|
|
11
|
+
MAX_IMAGE_SHORT_SIDE,
|
|
12
|
+
} from './constants';
|
|
13
|
+
|
|
14
|
+
type CreateAgentAttachmentsOptions = {
|
|
15
|
+
alert(options: { message: string; variant: 'warning' | 'danger' }): void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// a new file is shown from memory until it is uploaded or dropped
|
|
19
|
+
function freeOriginal(attachment: IComposerAttachment) {
|
|
20
|
+
if (attachment.file) {
|
|
21
|
+
URL.revokeObjectURL(attachment.url);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function encodeCanvas(canvas: HTMLCanvasElement, type: string) {
|
|
26
|
+
return new Promise<Blob>((resolve) => {
|
|
27
|
+
canvas.toBlob((result) => resolve(result!), type, IMAGE_ENCODE_QUALITY);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Prepares an image for the model: scaled down to fit Full HD and encoded as WebP, so it stays in
|
|
33
|
+
* the size limit and costs fewer tokens. A browser which can not encode WebP (Safari gives PNG
|
|
34
|
+
* instead) encodes JPEG.
|
|
35
|
+
*/
|
|
36
|
+
async function toFullHdWebp(file: File): Promise<File> {
|
|
37
|
+
const bitmap = await createImageBitmap(file);
|
|
38
|
+
const scale = Math.min(
|
|
39
|
+
1,
|
|
40
|
+
MAX_IMAGE_LONG_SIDE / Math.max(bitmap.width, bitmap.height),
|
|
41
|
+
MAX_IMAGE_SHORT_SIDE / Math.min(bitmap.width, bitmap.height),
|
|
42
|
+
);
|
|
43
|
+
const canvas = document.createElement('canvas');
|
|
44
|
+
canvas.width = Math.round(bitmap.width * scale);
|
|
45
|
+
canvas.height = Math.round(bitmap.height * scale);
|
|
46
|
+
const context = canvas.getContext('2d')!;
|
|
47
|
+
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
48
|
+
bitmap.close();
|
|
49
|
+
|
|
50
|
+
let format = IMAGE_UPLOAD_FORMAT;
|
|
51
|
+
let blob = await encodeCanvas(canvas, format.type);
|
|
52
|
+
if (blob.type !== format.type) {
|
|
53
|
+
format = IMAGE_UPLOAD_FALLBACK_FORMAT;
|
|
54
|
+
// the background goes under the image
|
|
55
|
+
context.globalCompositeOperation = 'destination-over';
|
|
56
|
+
context.fillStyle = IMAGE_UPLOAD_FALLBACK_BACKGROUND;
|
|
57
|
+
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
58
|
+
blob = await encodeCanvas(canvas, format.type);
|
|
59
|
+
}
|
|
60
|
+
const baseName = file.name.slice(0, file.name.lastIndexOf('.'));
|
|
61
|
+
return new File([blob], `${baseName}.${format.extension}`, { type: format.type });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function uploadToSession(sessionId: string, file: File): Promise<{ ref: IAttachmentRef; url: string }> {
|
|
65
|
+
const res = await callAdminForthApi({
|
|
66
|
+
method: 'POST',
|
|
67
|
+
path: '/agent/attachment-upload-url',
|
|
68
|
+
body: { sessionId, filename: file.name, contentType: file.type, size: file.size },
|
|
69
|
+
});
|
|
70
|
+
if (res.error) {
|
|
71
|
+
throw new Error(res.error);
|
|
72
|
+
}
|
|
73
|
+
const upload = await fetch(res.uploadUrl, {
|
|
74
|
+
method: 'PUT',
|
|
75
|
+
headers: { 'Content-Type': res.contentType, ...res.uploadExtraParams },
|
|
76
|
+
body: file,
|
|
77
|
+
});
|
|
78
|
+
if (!upload.ok) {
|
|
79
|
+
throw new Error(`Image upload failed with status ${upload.status}`);
|
|
80
|
+
}
|
|
81
|
+
return { ref: { filePath: res.filePath, token: res.token }, url: res.previewUrl };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function createAgentAttachments({ alert }: CreateAgentAttachmentsOptions) {
|
|
85
|
+
const attachments = ref<IComposerAttachment[]>([]);
|
|
86
|
+
const isUploading = ref(false);
|
|
87
|
+
const config = ref<IAttachmentsConfig | null>(null);
|
|
88
|
+
|
|
89
|
+
function setConfig(attachmentsConfig: IAttachmentsConfig | null) {
|
|
90
|
+
config.value = attachmentsConfig;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function addFiles(files: File[]) {
|
|
94
|
+
const { maxPerMessage, mimeTypes } = config.value!;
|
|
95
|
+
const images = files.filter((file) => mimeTypes.includes(file.type));
|
|
96
|
+
if (images.length < files.length) {
|
|
97
|
+
alert({ message: t('Only images can be attached'), variant: 'warning' });
|
|
98
|
+
}
|
|
99
|
+
const free = maxPerMessage - attachments.value.length;
|
|
100
|
+
if (images.length > free) {
|
|
101
|
+
alert({ message: t('You can attach up to {count} images to a message', { count: maxPerMessage }), variant: 'warning' });
|
|
102
|
+
}
|
|
103
|
+
attachments.value = [
|
|
104
|
+
...attachments.value,
|
|
105
|
+
...images.slice(0, free).map((file) => ({ id: crypto.randomUUID(), url: URL.createObjectURL(file), file })),
|
|
106
|
+
];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function removeAttachment(id: string) {
|
|
110
|
+
freeOriginal(attachments.value.find((candidate) => candidate.id === id)!);
|
|
111
|
+
attachments.value = attachments.value.filter((candidate) => candidate.id !== id);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Frees the files added to the composer which will not be sent. */
|
|
115
|
+
function discardNewFiles() {
|
|
116
|
+
attachments.value.forEach(freeOriginal);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Shows the images of an edited message in the composer. */
|
|
120
|
+
function setFromMessage(messageAttachments: IMessageAttachment[]) {
|
|
121
|
+
attachments.value = messageAttachments.map((attachment) => ({ id: crypto.randomUUID(), ...attachment }));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Uploads the new images of the composer to the session. Returns the refs for the request and
|
|
126
|
+
* the attachments to show in the sent message, or null when an upload failed; the reason is
|
|
127
|
+
* shown to the user. The message shows the stored files, the ones the model gets, so the
|
|
128
|
+
* originals of the composer previews are freed.
|
|
129
|
+
*/
|
|
130
|
+
async function upload(sessionId: string, composerAttachments: IComposerAttachment[]) {
|
|
131
|
+
isUploading.value = true;
|
|
132
|
+
try {
|
|
133
|
+
const uploaded = await Promise.all(composerAttachments.map(async (attachment) => {
|
|
134
|
+
const { ref, url } = attachment.file
|
|
135
|
+
? await uploadToSession(sessionId, await toFullHdWebp(attachment.file))
|
|
136
|
+
: { ref: { filePath: attachment.filePath! }, url: attachment.url };
|
|
137
|
+
return { ref, shown: { filePath: ref.filePath, url } };
|
|
138
|
+
}));
|
|
139
|
+
composerAttachments.forEach(freeOriginal);
|
|
140
|
+
return {
|
|
141
|
+
refs: uploaded.map(({ ref }) => ref),
|
|
142
|
+
shown: uploaded.map(({ shown }) => shown),
|
|
143
|
+
};
|
|
144
|
+
} catch (error) {
|
|
145
|
+
alert({ message: t('Failed to upload the image: {reason}', { reason: getErrorMessage(error) }), variant: 'danger' });
|
|
146
|
+
return null;
|
|
147
|
+
} finally {
|
|
148
|
+
isUploading.value = false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
attachments,
|
|
154
|
+
isUploading,
|
|
155
|
+
config,
|
|
156
|
+
setConfig,
|
|
157
|
+
addFiles,
|
|
158
|
+
discardNewFiles,
|
|
159
|
+
removeAttachment,
|
|
160
|
+
setFromMessage,
|
|
161
|
+
upload,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
@@ -2,7 +2,8 @@ import { DefaultChatTransport } from 'ai';
|
|
|
2
2
|
import { ref, shallowRef, watch, type Ref } from 'vue';
|
|
3
3
|
import { Chat } from '../../chat';
|
|
4
4
|
import { getCurrentPageContext } from './pageContext';
|
|
5
|
-
import
|
|
5
|
+
import { getErrorMessage } from '../../utils';
|
|
6
|
+
import type { IApprovalDescription, IAttachmentRef, IMessageAttachment } from '../../types';
|
|
6
7
|
// const { DefaultChatTransport } = await import('ai');
|
|
7
8
|
|
|
8
9
|
type AgentImportMeta = ImportMeta & {
|
|
@@ -13,6 +14,7 @@ type AgentImportMeta = ImportMeta & {
|
|
|
13
14
|
|
|
14
15
|
type CreateAgentChatManagerOptions = {
|
|
15
16
|
lastMessage: Ref<string>;
|
|
17
|
+
lastAttachments: Ref<IAttachmentRef[]>;
|
|
16
18
|
activeModeName: Ref<string | null>;
|
|
17
19
|
onOpenPage: (targetPath: string) => void;
|
|
18
20
|
onToolApprovalRequest: (sessionId: string, approvals: IApprovalDescription[]) => void;
|
|
@@ -20,6 +22,7 @@ type CreateAgentChatManagerOptions = {
|
|
|
20
22
|
|
|
21
23
|
export function createAgentChatManager({
|
|
22
24
|
lastMessage,
|
|
25
|
+
lastAttachments,
|
|
23
26
|
activeModeName,
|
|
24
27
|
onOpenPage,
|
|
25
28
|
onToolApprovalRequest,
|
|
@@ -235,6 +238,7 @@ export function createAgentChatManager({
|
|
|
235
238
|
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
236
239
|
mode: activeModeName.value,
|
|
237
240
|
currentPage: getCurrentPageContext(),
|
|
241
|
+
attachments: lastAttachments.value,
|
|
238
242
|
};
|
|
239
243
|
|
|
240
244
|
// Editing an existing message branches from its turn: hit /edit, which
|
|
@@ -256,7 +260,7 @@ export function createAgentChatManager({
|
|
|
256
260
|
}),
|
|
257
261
|
onError(error: unknown) {
|
|
258
262
|
console.error('Chat error:', error);
|
|
259
|
-
appendTextDelta(`Error: ${
|
|
263
|
+
appendTextDelta(`Error: ${getErrorMessage(error)}`);
|
|
260
264
|
},
|
|
261
265
|
onData: handleRealtimeChatData,
|
|
262
266
|
});
|
|
@@ -265,6 +269,10 @@ export function createAgentChatManager({
|
|
|
265
269
|
}
|
|
266
270
|
}
|
|
267
271
|
|
|
272
|
+
function dropChat(sessionId: string) {
|
|
273
|
+
chats.delete(sessionId);
|
|
274
|
+
}
|
|
275
|
+
|
|
268
276
|
function abortCurrentChatRequest() {
|
|
269
277
|
currentChat.value?.stop();
|
|
270
278
|
}
|
|
@@ -313,7 +321,12 @@ export function createAgentChatManager({
|
|
|
313
321
|
// (mirroring the server-side truncate), and `editingTurnId` routes the request
|
|
314
322
|
// to /edit for the matching turn. If a turn is still generating it is stopped
|
|
315
323
|
// first so the edit supersedes it.
|
|
316
|
-
async function sendEditMessage({ messageId, turnId, text }: {
|
|
324
|
+
async function sendEditMessage({ messageId, turnId, text, attachments }: {
|
|
325
|
+
messageId: string;
|
|
326
|
+
turnId: string;
|
|
327
|
+
text: string;
|
|
328
|
+
attachments: { refs: IAttachmentRef[]; shown: IMessageAttachment[] };
|
|
329
|
+
}) {
|
|
317
330
|
const chat = currentChat.value;
|
|
318
331
|
if (!chat) {
|
|
319
332
|
return;
|
|
@@ -331,8 +344,9 @@ export function createAgentChatManager({
|
|
|
331
344
|
}
|
|
332
345
|
editingTurnId.value = turnId;
|
|
333
346
|
lastMessage.value = text;
|
|
347
|
+
lastAttachments.value = attachments.refs;
|
|
334
348
|
try {
|
|
335
|
-
await chat.sendMessage({ text, messageId, metadata: { turnId } });
|
|
349
|
+
await chat.sendMessage({ text, messageId, metadata: { turnId, attachments: attachments.shown } });
|
|
336
350
|
} finally {
|
|
337
351
|
editingTurnId.value = null;
|
|
338
352
|
}
|
|
@@ -367,5 +381,6 @@ export function createAgentChatManager({
|
|
|
367
381
|
abortCurrentChatRequest,
|
|
368
382
|
submitToolApproval,
|
|
369
383
|
sendEditMessage,
|
|
384
|
+
dropChat,
|
|
370
385
|
};
|
|
371
386
|
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type { ComputedRef, Ref, ShallowRef } from 'vue';
|
|
2
2
|
import { callAdminForthApi } from '@/utils';
|
|
3
3
|
import type { Chat } from '../../chat';
|
|
4
|
-
import type { IAgentSession, IApprovalDescription, ISessionsListItem, IPart } from '../../types';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
4
|
+
import type { IAgentSession, IApprovalDescription, IAttachmentRef, IMessageAttachment, ISessionsListItem, IPart } from '../../types';
|
|
5
|
+
import type { createAgentAttachments } from './useAgentAttachments';
|
|
6
|
+
import { ATTACHMENT_URLS_REFRESH_INTERVAL_MS, PRE_SESSION_ID, STEER_PERSIST_PREFIX } from './constants';
|
|
7
|
+
import { t } from '../../utils';
|
|
7
8
|
|
|
8
9
|
type AdminforthLike = {
|
|
9
10
|
confirm(options: { title?: string; message?: string; yes?: string; no?: string; dangerous?: boolean }): Promise<boolean>;
|
|
11
|
+
alert(options: { message: string; variant: 'danger' }): void;
|
|
10
12
|
};
|
|
11
13
|
|
|
12
14
|
type CreateAgentSessionManagerOptions = {
|
|
@@ -20,9 +22,12 @@ type CreateAgentSessionManagerOptions = {
|
|
|
20
22
|
isMessageInputBlocked: ComputedRef<boolean>;
|
|
21
23
|
userMessageInput: Ref<any>;
|
|
22
24
|
lastMessage: Ref<string>;
|
|
25
|
+
lastAttachments: Ref<IAttachmentRef[]>;
|
|
26
|
+
composerAttachments: ReturnType<typeof createAgentAttachments>;
|
|
23
27
|
blockCloseOfChat: Ref<boolean>;
|
|
24
28
|
adminforth: AdminforthLike;
|
|
25
29
|
setCurrentChat: (sessionId: string) => void;
|
|
30
|
+
dropChat: (sessionId: string) => void;
|
|
26
31
|
restorePendingToolApproval: (sessionId: string, approvals: IApprovalDescription[]) => void;
|
|
27
32
|
};
|
|
28
33
|
|
|
@@ -37,19 +42,18 @@ export function createAgentSessionManager({
|
|
|
37
42
|
isMessageInputBlocked,
|
|
38
43
|
userMessageInput,
|
|
39
44
|
lastMessage,
|
|
45
|
+
lastAttachments,
|
|
46
|
+
composerAttachments,
|
|
40
47
|
blockCloseOfChat,
|
|
41
48
|
adminforth,
|
|
42
49
|
setCurrentChat,
|
|
50
|
+
dropChat,
|
|
43
51
|
restorePendingToolApproval,
|
|
44
52
|
}: CreateAgentSessionManagerOptions) {
|
|
45
53
|
function sortSessionsListByTimestamp(sessionsListToSort: ISessionsListItem[]) {
|
|
46
54
|
return [...sessionsListToSort].sort((a: ISessionsListItem, b: ISessionsListItem) => b.timestamp.localeCompare(a.timestamp));
|
|
47
55
|
}
|
|
48
56
|
|
|
49
|
-
function t(key: string) {
|
|
50
|
-
return i18nInstance?.global.t(key) ?? key;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
57
|
function saveCurrentSessionInCache() {
|
|
54
58
|
if (currentSession.value) {
|
|
55
59
|
currentSession.value.messages = currentChat.value?.messages.map((m: any) => {
|
|
@@ -58,7 +62,7 @@ export function createAgentSessionManager({
|
|
|
58
62
|
if (m.role === 'user' && m.metadata?.steer) {
|
|
59
63
|
return { role: 'user', text: `${STEER_PERSIST_PREFIX}${text}`, turnId };
|
|
60
64
|
}
|
|
61
|
-
return { role: m.role, text, turnId };
|
|
65
|
+
return { role: m.role, text, turnId, attachments: m.metadata?.attachments };
|
|
62
66
|
}) || [];
|
|
63
67
|
sessions.value[currentSession.value.sessionId] = currentSession.value;
|
|
64
68
|
}
|
|
@@ -66,11 +70,12 @@ export function createAgentSessionManager({
|
|
|
66
70
|
|
|
67
71
|
function mapStoredMessage(m: any): any[] {
|
|
68
72
|
const turnId = m.turnId;
|
|
73
|
+
const attachments = m.attachments;
|
|
69
74
|
if (m.role === 'user' && typeof m.text === 'string' && m.text.includes(STEER_PERSIST_PREFIX)) {
|
|
70
75
|
const [prompt, ...steers] = m.text.split(STEER_PERSIST_PREFIX);
|
|
71
76
|
const mapped: any[] = [];
|
|
72
|
-
if (prompt) {
|
|
73
|
-
mapped.push({ id: crypto.randomUUID(), role: 'user', metadata: { turnId }, parts: [{ type: 'text', text: prompt, state: 'done' }] });
|
|
77
|
+
if (prompt || attachments?.length) {
|
|
78
|
+
mapped.push({ id: crypto.randomUUID(), role: 'user', metadata: { turnId, attachments }, parts: [{ type: 'text', text: prompt, state: 'done' }] });
|
|
74
79
|
}
|
|
75
80
|
for (const steer of steers) {
|
|
76
81
|
mapped.push({
|
|
@@ -82,17 +87,51 @@ export function createAgentSessionManager({
|
|
|
82
87
|
}
|
|
83
88
|
return mapped;
|
|
84
89
|
}
|
|
85
|
-
return [{ id: crypto.randomUUID(), role: m.role, metadata: { turnId }, parts: [{ type: 'text', text: m.text, state: 'done' }] }];
|
|
90
|
+
return [{ id: crypto.randomUUID(), role: m.role, metadata: { turnId, attachments }, parts: [{ type: 'text', text: m.text, state: 'done' }] }];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function requestSessionInfo(sessionId: string) {
|
|
94
|
+
return callAdminForthApi({
|
|
95
|
+
method: 'POST',
|
|
96
|
+
path: '/agent/get-session-info',
|
|
97
|
+
body: { sessionId },
|
|
98
|
+
silentError: true,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Image urls of private storages are signed for a while, but a loaded session stays in the
|
|
103
|
+
// tab. A thumbnail which failed to load asks for fresh urls; not too often, so a file which is
|
|
104
|
+
// really gone does not make it ask again and again.
|
|
105
|
+
const attachmentUrlsRefreshedAt = new Map<string, number>();
|
|
106
|
+
|
|
107
|
+
async function refreshAttachmentUrls(sessionId: string) {
|
|
108
|
+
const refreshedAt = attachmentUrlsRefreshedAt.get(sessionId) ?? 0;
|
|
109
|
+
if (Date.now() - refreshedAt < ATTACHMENT_URLS_REFRESH_INTERVAL_MS) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
attachmentUrlsRefreshedAt.set(sessionId, Date.now());
|
|
113
|
+
const res = await requestSessionInfo(sessionId);
|
|
114
|
+
if (res.error || activeSessionId.value !== sessionId) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const urls = new Map<string, string>(res.session.messages
|
|
118
|
+
.flatMap((m: any) => m.attachments ?? [])
|
|
119
|
+
.map((attachment: IMessageAttachment) => [attachment.filePath, attachment.url]));
|
|
120
|
+
currentChat.value!.messages = currentChat.value!.messages.map((m: any) => (m.metadata?.attachments ? {
|
|
121
|
+
...m,
|
|
122
|
+
metadata: {
|
|
123
|
+
...m.metadata,
|
|
124
|
+
attachments: m.metadata.attachments.map((attachment: IMessageAttachment) => ({
|
|
125
|
+
...attachment,
|
|
126
|
+
url: urls.get(attachment.filePath) ?? attachment.url,
|
|
127
|
+
})),
|
|
128
|
+
},
|
|
129
|
+
} : m));
|
|
86
130
|
}
|
|
87
131
|
|
|
88
132
|
async function fetchSession(sessionId: string) {
|
|
89
133
|
try {
|
|
90
|
-
const res = await
|
|
91
|
-
method: 'POST',
|
|
92
|
-
path: '/agent/get-session-info',
|
|
93
|
-
body: { sessionId },
|
|
94
|
-
silentError: true,
|
|
95
|
-
});
|
|
134
|
+
const res = await requestSessionInfo(sessionId);
|
|
96
135
|
if (res.error) {
|
|
97
136
|
return;
|
|
98
137
|
}
|
|
@@ -124,6 +163,15 @@ export function createAgentSessionManager({
|
|
|
124
163
|
}
|
|
125
164
|
}
|
|
126
165
|
|
|
166
|
+
/** Shows the session as the server has it, dropping what the tab keeps (e.g. after a failed edit). */
|
|
167
|
+
async function reloadSession(sessionId: string) {
|
|
168
|
+
// without the current session, switching does not save the stale chat back to the cache
|
|
169
|
+
currentSession.value = null;
|
|
170
|
+
delete sessions.value[sessionId];
|
|
171
|
+
dropChat(sessionId);
|
|
172
|
+
await setActiveSession(sessionId);
|
|
173
|
+
}
|
|
174
|
+
|
|
127
175
|
async function deletePreSession() {
|
|
128
176
|
sessionList.value = sessionList.value.filter((s: ISessionsListItem) => s.sessionId !== PRE_SESSION_ID);
|
|
129
177
|
if (activeSessionId.value === PRE_SESSION_ID) {
|
|
@@ -143,6 +191,7 @@ export function createAgentSessionManager({
|
|
|
143
191
|
});
|
|
144
192
|
if (res.error) {
|
|
145
193
|
console.error('Error creating new session:', res.error);
|
|
194
|
+
adminforth.alert({ message: res.error, variant: 'danger' });
|
|
146
195
|
return;
|
|
147
196
|
}
|
|
148
197
|
deletePreSession();
|
|
@@ -160,13 +209,23 @@ export function createAgentSessionManager({
|
|
|
160
209
|
|
|
161
210
|
async function sendMessage(explicitMessage?: string) {
|
|
162
211
|
// `explicitMessage` is used to drain a buffered (queued) message; without it we send
|
|
163
|
-
// whatever is currently typed in the input.
|
|
212
|
+
// whatever is currently typed in the input, with the images attached in the composer.
|
|
164
213
|
const message = (explicitMessage ?? trimmedUserMessage.value).trim();
|
|
165
|
-
|
|
214
|
+
const attachments = explicitMessage === undefined ? composerAttachments.attachments.value : [];
|
|
215
|
+
if ((!message && attachments.length === 0) || isMessageInputBlocked.value || composerAttachments.isUploading.value) {
|
|
166
216
|
return;
|
|
167
217
|
}
|
|
168
218
|
if (!currentSession.value || currentSession.value.sessionId === PRE_SESSION_ID) {
|
|
169
|
-
await createNewSession(message);
|
|
219
|
+
await createNewSession(message || t('Image'));
|
|
220
|
+
// the reason is already shown, the message stays in the input to send again
|
|
221
|
+
if (!currentSession.value || currentSession.value.sessionId === PRE_SESSION_ID) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// Images are uploaded only now: the upload URL is issued for an existing session.
|
|
226
|
+
const uploaded = await composerAttachments.upload(currentSession.value!.sessionId, attachments);
|
|
227
|
+
if (!uploaded) {
|
|
228
|
+
return;
|
|
170
229
|
}
|
|
171
230
|
currentSession.value!.timestamp = new Date().toISOString();
|
|
172
231
|
sessionList.value = sortSessionsListByTimestamp(sessionList.value.map((s: ISessionsListItem) => s.sessionId === currentSession.value?.sessionId ? {
|
|
@@ -174,11 +233,14 @@ export function createAgentSessionManager({
|
|
|
174
233
|
timestamp: currentSession.value?.timestamp || s.timestamp,
|
|
175
234
|
} : s));
|
|
176
235
|
lastMessage.value = message;
|
|
236
|
+
lastAttachments.value = uploaded.refs;
|
|
177
237
|
currentChat.value?.sendMessage({
|
|
178
238
|
text: message,
|
|
239
|
+
metadata: { attachments: uploaded.shown },
|
|
179
240
|
});
|
|
180
241
|
if (explicitMessage === undefined) {
|
|
181
242
|
userMessageInput.value = '';
|
|
243
|
+
composerAttachments.attachments.value = [];
|
|
182
244
|
}
|
|
183
245
|
}
|
|
184
246
|
|
|
@@ -387,6 +449,8 @@ export function createAgentSessionManager({
|
|
|
387
449
|
|
|
388
450
|
return {
|
|
389
451
|
sendMessage,
|
|
452
|
+
refreshAttachmentUrls,
|
|
453
|
+
reloadSession,
|
|
390
454
|
createPreSession,
|
|
391
455
|
setActiveSession,
|
|
392
456
|
fetchSessionsList,
|