@adminforth/agent 3.3.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 +64 -11
- 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 -11
- 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 +10 -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,
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { defineStore } from 'pinia';
|
|
2
|
-
import { IAgentSession, IApprovalDescription, ISessionsListItem } from '../types';
|
|
2
|
+
import { IAgentSession, IApprovalDescription, IAttachmentRef, IComposerAttachment, ISessionsListItem } from '../types';
|
|
3
3
|
import { ref, nextTick, computed, watch, onMounted } from 'vue';
|
|
4
4
|
import { useRouter } from 'vue-router';
|
|
5
5
|
import { useAdminforth } from '@/adminforth';
|
|
6
6
|
import { useCoreStore } from '@/stores/core';
|
|
7
7
|
import { useAgentTransitions } from './useAgentTransitions';
|
|
8
8
|
import { useWindowSize } from '@vueuse/core';
|
|
9
|
-
import { remToPx, pxToRem } from '../utils';
|
|
9
|
+
import { remToPx, pxToRem, getErrorMessage, t } from '../utils';
|
|
10
10
|
import {
|
|
11
11
|
type AgentMode,
|
|
12
12
|
DEFAULT_CHAT_WIDTH,
|
|
@@ -19,6 +19,7 @@ import { createAgentChatManager } from './agentStore/useAgentChat';
|
|
|
19
19
|
import { createAgentPlaceholderController } from './agentStore/useAgentPlaceholder';
|
|
20
20
|
import { createAgentSessionManager } from './agentStore/useAgentSessions';
|
|
21
21
|
import { createAgentSteerQueue } from './agentStore/useAgentSteerQueue';
|
|
22
|
+
import { createAgentAttachments } from './agentStore/useAgentAttachments';
|
|
22
23
|
import { STEER_PERSIST_PREFIX } from './agentStore/constants';
|
|
23
24
|
|
|
24
25
|
export const useAgentStore = defineStore('agent', () => {
|
|
@@ -42,8 +43,12 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
42
43
|
const editingMessageId = ref<string | null>(null);
|
|
43
44
|
const editingMessageTurnId = ref<string | null>(null);
|
|
44
45
|
const savedUserInput = ref('');
|
|
46
|
+
const savedAttachments = ref<IComposerAttachment[]>([]);
|
|
45
47
|
const isEditingMessage = computed(() => editingMessageId.value !== null);
|
|
46
48
|
const lastMessage = ref('');
|
|
49
|
+
const lastAttachments = ref<IAttachmentRef[]>([]);
|
|
50
|
+
const composerAttachments = createAgentAttachments({ alert: adminforth.alert });
|
|
51
|
+
const hasAttachments = computed(() => composerAttachments.attachments.value.length > 0);
|
|
47
52
|
const isTeleportedToBody = ref(false);
|
|
48
53
|
const setIsTeleportedToBody = (isTeleported: boolean) => {
|
|
49
54
|
isTeleportedToBody.value = isTeleported;
|
|
@@ -63,8 +68,10 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
63
68
|
abortCurrentChatRequest,
|
|
64
69
|
submitToolApproval: submitToolApprovalResponse,
|
|
65
70
|
sendEditMessage,
|
|
71
|
+
dropChat,
|
|
66
72
|
} = createAgentChatManager({
|
|
67
73
|
lastMessage,
|
|
74
|
+
lastAttachments,
|
|
68
75
|
activeModeName,
|
|
69
76
|
onOpenPage: openAgentPage,
|
|
70
77
|
onToolApprovalRequest: addToolApprovalPart,
|
|
@@ -160,7 +167,7 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
160
167
|
} catch (error) {
|
|
161
168
|
if (approvalPart?.data) {
|
|
162
169
|
approvalPart.data.status = 'pending';
|
|
163
|
-
approvalPart.data.error =
|
|
170
|
+
approvalPart.data.error = getErrorMessage(error);
|
|
164
171
|
}
|
|
165
172
|
console.error('Error submitting tool approval', error);
|
|
166
173
|
}
|
|
@@ -193,6 +200,8 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
193
200
|
const blockCloseOfChat = ref(false);
|
|
194
201
|
const {
|
|
195
202
|
sendMessage,
|
|
203
|
+
refreshAttachmentUrls,
|
|
204
|
+
reloadSession,
|
|
196
205
|
createPreSession,
|
|
197
206
|
setActiveSession,
|
|
198
207
|
fetchSessionsList,
|
|
@@ -216,9 +225,12 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
216
225
|
isMessageInputBlocked,
|
|
217
226
|
userMessageInput,
|
|
218
227
|
lastMessage,
|
|
228
|
+
lastAttachments,
|
|
229
|
+
composerAttachments,
|
|
219
230
|
blockCloseOfChat,
|
|
220
231
|
adminforth,
|
|
221
232
|
setCurrentChat,
|
|
233
|
+
dropChat,
|
|
222
234
|
restorePendingToolApproval: addToolApprovalPart,
|
|
223
235
|
});
|
|
224
236
|
|
|
@@ -250,13 +262,22 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
250
262
|
|
|
251
263
|
// Submitting while a turn is active buffers the message (it shows up in the steer
|
|
252
264
|
// queue, where the user can steer it or let it send); otherwise it sends right away.
|
|
265
|
+
// The queue keeps text only, so a message with images waits for the turn to end.
|
|
266
|
+
// images go with the text chat only, the voice chat has no composer to show them
|
|
267
|
+
const canAttachImages = computed(() => Boolean(composerAttachments.config.value) && !isAudioChatMode.value);
|
|
268
|
+
|
|
269
|
+
const canSubmitUserMessage = computed(() =>
|
|
270
|
+
Boolean(trimmedUserMessage.value || hasAttachments.value)
|
|
271
|
+
&& !(isTurnActive.value && hasAttachments.value)
|
|
272
|
+
&& !composerAttachments.isUploading.value
|
|
273
|
+
);
|
|
274
|
+
|
|
253
275
|
function submitUserMessage() {
|
|
254
|
-
|
|
255
|
-
if (!message) {
|
|
276
|
+
if (!canSubmitUserMessage.value) {
|
|
256
277
|
return;
|
|
257
278
|
}
|
|
258
279
|
if (isTurnActive.value) {
|
|
259
|
-
steerBuffer.enqueue(
|
|
280
|
+
steerBuffer.enqueue(trimmedUserMessage.value);
|
|
260
281
|
userMessageInput.value = '';
|
|
261
282
|
return;
|
|
262
283
|
}
|
|
@@ -291,6 +312,7 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
291
312
|
watch(activeSessionId, (newVal: string | null) => {
|
|
292
313
|
// The edited message lives in the outgoing session's chat, so drop edit mode.
|
|
293
314
|
if (editingMessageId.value !== null) {
|
|
315
|
+
composerAttachments.discardNewFiles();
|
|
294
316
|
exitEditMode();
|
|
295
317
|
}
|
|
296
318
|
if (newVal) {
|
|
@@ -479,11 +501,13 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
479
501
|
}
|
|
480
502
|
if (editingMessageId.value === null) {
|
|
481
503
|
savedUserInput.value = userMessageInput.value ?? '';
|
|
504
|
+
savedAttachments.value = composerAttachments.attachments.value;
|
|
482
505
|
}
|
|
483
506
|
const text = getCompiledMessageTextWithSteeredParts(message);
|
|
484
507
|
editingMessageId.value = messageId;
|
|
485
508
|
editingMessageTurnId.value = turnId;
|
|
486
509
|
userMessageInput.value = text;
|
|
510
|
+
composerAttachments.setFromMessage(message.metadata?.attachments ?? []);
|
|
487
511
|
nextTick(() => focusTextInput());
|
|
488
512
|
}
|
|
489
513
|
|
|
@@ -491,6 +515,8 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
491
515
|
function exitEditMode() {
|
|
492
516
|
userMessageInput.value = savedUserInput.value;
|
|
493
517
|
savedUserInput.value = '';
|
|
518
|
+
composerAttachments.attachments.value = savedAttachments.value;
|
|
519
|
+
savedAttachments.value = [];
|
|
494
520
|
editingMessageId.value = null;
|
|
495
521
|
editingMessageTurnId.value = null;
|
|
496
522
|
}
|
|
@@ -499,6 +525,7 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
499
525
|
if (editingMessageId.value === null) {
|
|
500
526
|
return;
|
|
501
527
|
}
|
|
528
|
+
composerAttachments.discardNewFiles();
|
|
502
529
|
exitEditMode();
|
|
503
530
|
nextTick(() => focusTextInput());
|
|
504
531
|
}
|
|
@@ -508,19 +535,37 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
508
535
|
return false;
|
|
509
536
|
}
|
|
510
537
|
const text = trimmedUserMessage.value;
|
|
511
|
-
|
|
538
|
+
const attachments = composerAttachments.attachments.value;
|
|
539
|
+
if ((!text && attachments.length === 0) || composerAttachments.isUploading.value) {
|
|
512
540
|
return false;
|
|
513
541
|
}
|
|
514
542
|
const messageId = editingMessageId.value;
|
|
515
543
|
const turnId = editingMessageTurnId.value!;
|
|
544
|
+
const editedMessage = currentChat.value?.messages.find((m: any) => m.id === messageId);
|
|
545
|
+
const lastMessageText = getCompiledMessageTextWithSteeredParts(editedMessage);
|
|
546
|
+
const lastFilePaths = (editedMessage?.metadata?.attachments ?? []).map((attachment: any) => attachment.filePath);
|
|
547
|
+
const isUnchanged = lastMessageText.trim() === text
|
|
548
|
+
&& attachments.length === lastFilePaths.length
|
|
549
|
+
&& attachments.every((attachment, index) => attachment.filePath === lastFilePaths[index]);
|
|
550
|
+
if (isUnchanged) {
|
|
551
|
+
exitEditMode();
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
// Upload before leaving edit mode, so a failed upload keeps the edit to retry.
|
|
555
|
+
const uploaded = await composerAttachments.upload(activeSessionId.value!, attachments);
|
|
556
|
+
if (!uploaded) {
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
516
559
|
steerBuffer.clear();
|
|
517
560
|
// Restore the stashed input and leave edit mode before the regeneration streams in.
|
|
518
561
|
exitEditMode();
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
562
|
+
await sendEditMessage({ messageId, turnId, text, attachments: uploaded });
|
|
563
|
+
// the edit failed (e.g. the message was changed in another tab): the chat in the tab is out
|
|
564
|
+
// of date, so it is replaced with the one the server has
|
|
565
|
+
if (currentChat.value?.status === 'error') {
|
|
566
|
+
adminforth.alert({ message: t('The message could not be edited, the chat is reloaded'), variant: 'warning' });
|
|
567
|
+
await reloadSession(activeSessionId.value!);
|
|
522
568
|
}
|
|
523
|
-
await sendEditMessage({ messageId, turnId, text });
|
|
524
569
|
return true;
|
|
525
570
|
}
|
|
526
571
|
|
|
@@ -631,7 +676,18 @@ export const useAgentStore = defineStore('agent', () => {
|
|
|
631
676
|
openAgentPage,
|
|
632
677
|
setCurrentChatStatus,
|
|
633
678
|
updateLastAgentMessage,
|
|
679
|
+
//_________-Attachments-_____________
|
|
680
|
+
attachments: composerAttachments.attachments,
|
|
681
|
+
refreshAttachmentUrls: () => refreshAttachmentUrls(activeSessionId.value!),
|
|
682
|
+
attachmentsConfig: composerAttachments.config,
|
|
683
|
+
canAttachImages,
|
|
684
|
+
setAttachmentsConfig: composerAttachments.setConfig,
|
|
685
|
+
isUploadingAttachments: composerAttachments.isUploading,
|
|
686
|
+
addAttachmentFiles: composerAttachments.addFiles,
|
|
687
|
+
removeAttachment: composerAttachments.removeAttachment,
|
|
688
|
+
//___________________________________
|
|
634
689
|
//_________-Steer queue-_____________
|
|
690
|
+
canSubmitUserMessage,
|
|
635
691
|
submitUserMessage,
|
|
636
692
|
isTurnActive,
|
|
637
693
|
isFinalResponseStreaming,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
<template>
|
|
2
|
+
<div class="af-agent-message-attachments self-end flex flex-wrap justify-end gap-2 mr-4 mb-1">
|
|
3
|
+
<ZoomableImage
|
|
4
|
+
v-for="attachment in attachments"
|
|
5
|
+
:key="attachment.url"
|
|
6
|
+
:src="attachment.url"
|
|
7
|
+
class="max-w-48 max-h-24 rounded-default border border-lightInputBorder dark:border-darkInputBorder"
|
|
8
|
+
@error="agentStore.refreshAttachmentUrls()"
|
|
9
|
+
/>
|
|
10
|
+
</div>
|
|
11
|
+
</template>
|
|
12
|
+
|
|
13
|
+
<script setup lang="ts">
|
|
14
|
+
import { ZoomableImage } from '@/afcl';
|
|
15
|
+
import { useAgentStore } from '../composables/useAgentStore';
|
|
16
|
+
|
|
17
|
+
defineProps<{
|
|
18
|
+
attachments: Array<{ url: string }>;
|
|
19
|
+
}>();
|
|
20
|
+
|
|
21
|
+
const agentStore = useAgentStore();
|
|
22
|
+
</script>
|