@myrialabs/clopen 0.4.44 → 0.4.45
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/backend/artifacts/project/bridge.ts +218 -0
- package/backend/artifacts/project/edit.ts +243 -0
- package/backend/artifacts/project/index.ts +38 -0
- package/backend/artifacts/project/project.test.ts +181 -0
- package/backend/artifacts/project/scan.ts +368 -0
- package/backend/artifacts/project/sources.ts +100 -0
- package/backend/artifacts/sync.ts +1 -1
- package/backend/auth/permissions.ts +15 -0
- package/backend/chat/stream-manager.ts +20 -3
- package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
- package/backend/engine/adapters/claude/stream.ts +27 -1
- package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
- package/backend/engine/adapters/cline/stream.ts +20 -6
- package/backend/engine/adapters/codex/stream.ts +21 -4
- package/backend/engine/adapters/copilot/stream.ts +6 -3
- package/backend/engine/adapters/cursor/stream.ts +19 -8
- package/backend/engine/adapters/opencode/server.ts +14 -4
- package/backend/engine/adapters/opencode/stream.ts +18 -3
- package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
- package/backend/engine/adapters/pi/stream.ts +35 -3
- package/backend/engine/adapters/qwen/stream.ts +8 -0
- package/backend/engine/artifact-sync.ts +12 -5
- package/backend/files/file-watcher.test.ts +77 -0
- package/backend/files/file-watcher.ts +92 -60
- package/backend/files/watch-ignore.test.ts +182 -0
- package/backend/files/watch-ignore.ts +244 -0
- package/backend/git/git-executor.ts +14 -4
- package/backend/index.ts +11 -1
- package/backend/instructions/service.ts +5 -3
- package/backend/instructions/sync.ts +10 -27
- package/backend/mcp/external/config.ts +65 -23
- package/backend/mcp/external/project.ts +124 -0
- package/backend/mcp/external/proxy.ts +65 -11
- package/backend/mcp/index.ts +14 -9
- package/backend/mcp/internal/remote-server.ts +11 -1
- package/backend/skills/marketplace.ts +1 -1
- package/backend/snapshot/blob-store.ts +9 -5
- package/backend/snapshot/git-attribution.test.ts +42 -0
- package/backend/snapshot/git-attribution.ts +306 -0
- package/backend/snapshot/gitignore.test.ts +62 -0
- package/backend/snapshot/gitignore.ts +158 -78
- package/backend/snapshot/snapshot-service.test.ts +270 -0
- package/backend/snapshot/snapshot-service.ts +412 -136
- package/backend/snapshot/turn-activity.test.ts +52 -0
- package/backend/snapshot/turn-activity.ts +83 -0
- package/backend/snapshot/turn-changes.test.ts +58 -1
- package/backend/snapshot/turn-changes.ts +66 -0
- package/backend/worktrees/tree.ts +1 -1
- package/backend/ws/chat/composer.ts +504 -0
- package/backend/ws/chat/index.ts +3 -1
- package/backend/ws/chat/stream.ts +252 -440
- package/backend/ws/index.ts +4 -0
- package/backend/ws/project-artifacts/index.ts +236 -0
- package/backend/ws/snapshot/changes.ts +66 -31
- package/dist/assets/{index-BWyhqUi5.js → index-Am-rJRxA.js} +1 -1
- package/dist/assets/{index-DX5OwLOc.js → index-D-Ad1N96.js} +1 -1
- package/dist/assets/main--PLCDxSy.css +1 -0
- package/dist/assets/main-DelPm2Xt.js +1239 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +5 -0
- package/shared/types/unified/message.ts +2 -0
- package/dist/assets/main-DOkwqXRU.js +0 -1215
- package/dist/assets/main-DzCY0n-j.css +0 -1
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chat Composer State
|
|
3
|
+
*
|
|
4
|
+
* Everything about the message box that outlives a page load, per chat session:
|
|
5
|
+
*
|
|
6
|
+
* - Drafts are per USER. Text and attachments typed in a session wait for the
|
|
7
|
+
* same person on any device, but never land in a collaborator's box — a
|
|
8
|
+
* shared box let two people overwrite each other keystroke by keystroke.
|
|
9
|
+
* - Edit mode is per user too. Collaborators only learn THAT someone is
|
|
10
|
+
* editing; they never enter (or cancel, or submit) another person's edit.
|
|
11
|
+
* - The message queue holds what was sent while the AI was still working, and
|
|
12
|
+
* the server starts the next one when a turn completes — so a queued message
|
|
13
|
+
* is sent even if every tab that queued it has been closed.
|
|
14
|
+
*
|
|
15
|
+
* All state is in memory, like the rest of the live chat state: a restart
|
|
16
|
+
* drops drafts and the queue, not conversations.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { t } from 'elysia';
|
|
20
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
21
|
+
import type { StreamRequest } from '$shared/types/unified';
|
|
22
|
+
import { debug } from '$shared/utils/logger';
|
|
23
|
+
import { ws } from '$backend/utils/ws';
|
|
24
|
+
import { streamManager } from '../../chat/stream-manager';
|
|
25
|
+
import { messageQueries } from '../../database/queries';
|
|
26
|
+
import { INITIAL_NODE_ID } from '../../snapshot/helpers';
|
|
27
|
+
import { requireSessionAccess } from '../access';
|
|
28
|
+
import { bridgeStreamToRoom, startChatStream } from './stream';
|
|
29
|
+
|
|
30
|
+
// ============================================================================
|
|
31
|
+
// State
|
|
32
|
+
// ============================================================================
|
|
33
|
+
|
|
34
|
+
interface DraftAttachment {
|
|
35
|
+
id: string;
|
|
36
|
+
fileName: string;
|
|
37
|
+
type: string;
|
|
38
|
+
mediaType: string;
|
|
39
|
+
base64: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A draft carries the revision of each part's latest write. Writes reach the
|
|
44
|
+
* server in an order nobody controls — a save debounced while typing, the
|
|
45
|
+
* clear that follows a send, a composer remounting mid-flight — so an older
|
|
46
|
+
* write must never overwrite a newer one. An emptied draft is kept as a
|
|
47
|
+
* tombstone for the same reason: a late save of the text that was just sent
|
|
48
|
+
* would otherwise bring it back.
|
|
49
|
+
*/
|
|
50
|
+
interface Draft {
|
|
51
|
+
text: string;
|
|
52
|
+
attachments: DraftAttachment[];
|
|
53
|
+
textRevision: number;
|
|
54
|
+
attachmentsRevision: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface EditState {
|
|
58
|
+
messageId: string;
|
|
59
|
+
messageTimestamp: string | null;
|
|
60
|
+
userName: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface QueuedMessage {
|
|
64
|
+
id: string;
|
|
65
|
+
userId: string;
|
|
66
|
+
userName: string;
|
|
67
|
+
createdAt: string;
|
|
68
|
+
text: string;
|
|
69
|
+
attachmentCount: number;
|
|
70
|
+
request: StreamRequest;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Keyed by `draftKey(sessionId, userId)`. */
|
|
74
|
+
const drafts = new Map<string, Draft>();
|
|
75
|
+
/** chatSessionId → userId → that user's edit. */
|
|
76
|
+
const edits = new Map<string, Map<string, EditState>>();
|
|
77
|
+
/** chatSessionId → messages waiting for the current turn to finish, in order. */
|
|
78
|
+
const queues = new Map<string, QueuedMessage[]>();
|
|
79
|
+
/** Sessions whose next queued message is being started right now. */
|
|
80
|
+
const draining = new Set<string>();
|
|
81
|
+
|
|
82
|
+
function draftKey(chatSessionId: string, userId: string): string {
|
|
83
|
+
return `${chatSessionId}\u0000${userId}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function isSessionBusy(chatSessionId: string, projectId: string): boolean {
|
|
87
|
+
if (draining.has(chatSessionId)) return true;
|
|
88
|
+
return streamManager.getSessionStream(chatSessionId, projectId)?.status === 'active';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function promptText(prompt: any): string {
|
|
92
|
+
const content = Array.isArray(prompt?.content) ? prompt.content : [];
|
|
93
|
+
return content
|
|
94
|
+
.filter((block: any) => block?.type === 'text' && typeof block.text === 'string')
|
|
95
|
+
.map((block: any) => block.text as string)
|
|
96
|
+
.join('\n');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function promptAttachmentCount(prompt: any): number {
|
|
100
|
+
const content = Array.isArray(prompt?.content) ? prompt.content : [];
|
|
101
|
+
return content.filter((block: any) => block?.type === 'image' || block?.type === 'document').length;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function editorsFor(chatSessionId: string, exceptUserId?: string) {
|
|
105
|
+
const sessionEdits = edits.get(chatSessionId);
|
|
106
|
+
if (!sessionEdits) return [];
|
|
107
|
+
return [...sessionEdits.entries()]
|
|
108
|
+
.filter(([userId]) => userId !== exceptUserId)
|
|
109
|
+
.map(([userId, edit]) => ({ userId, userName: edit.userName, messageId: edit.messageId }));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function queueView(chatSessionId: string) {
|
|
113
|
+
return (queues.get(chatSessionId) ?? []).map((item) => ({
|
|
114
|
+
id: item.id,
|
|
115
|
+
userId: item.userId,
|
|
116
|
+
userName: item.userName,
|
|
117
|
+
createdAt: item.createdAt,
|
|
118
|
+
text: item.text,
|
|
119
|
+
attachmentCount: item.attachmentCount
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function broadcastQueue(chatSessionId: string): void {
|
|
124
|
+
ws.emit.chatSession(chatSessionId, 'chat:queue', {
|
|
125
|
+
chatSessionId,
|
|
126
|
+
items: queueView(chatSessionId)
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Start a queued message as a turn of its own. It gets a fresh timestamp (it
|
|
132
|
+
* was written before the turn it waited on, but belongs after it) and no
|
|
133
|
+
* client-side resume id: by now the branch has moved, so the stream resolves
|
|
134
|
+
* the resume target from HEAD itself.
|
|
135
|
+
*/
|
|
136
|
+
async function startQueued(item: QueuedMessage): Promise<void> {
|
|
137
|
+
const { chatSessionId } = item.request;
|
|
138
|
+
// Busy from now on: a message queued while this one is still starting must
|
|
139
|
+
// wait behind it, not start alongside it.
|
|
140
|
+
draining.add(chatSessionId);
|
|
141
|
+
try {
|
|
142
|
+
await startPrepared(item);
|
|
143
|
+
} finally {
|
|
144
|
+
draining.delete(chatSessionId);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function startPrepared(item: QueuedMessage): Promise<void> {
|
|
149
|
+
const request: StreamRequest = {
|
|
150
|
+
...item.request,
|
|
151
|
+
prompt: {
|
|
152
|
+
...item.request.prompt,
|
|
153
|
+
createdAt: new Date().toISOString(),
|
|
154
|
+
parent: { messageId: null, sessionId: null, toolUseId: null }
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const streamId = await startChatStream(request);
|
|
158
|
+
if (!streamId) return;
|
|
159
|
+
// No connection owns this stream, so the bridge lives until the turn ends.
|
|
160
|
+
bridgeStreamToRoom(streamId, request.chatSessionId, request.projectId);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ============================================================================
|
|
164
|
+
// Lifecycle
|
|
165
|
+
// ============================================================================
|
|
166
|
+
|
|
167
|
+
// A completed turn starts the next queued message. Errors and cancels leave the
|
|
168
|
+
// queue in place: the user stopped (or the engine failed) for a reason, and
|
|
169
|
+
// what was queued behind it may no longer make sense — they send it on purpose.
|
|
170
|
+
streamManager.on('stream:lifecycle', (event: { status: string; streamId: string; projectId?: string; chatSessionId?: string }) => {
|
|
171
|
+
const { status, streamId, chatSessionId } = event;
|
|
172
|
+
if (status !== 'completed' || !chatSessionId) return;
|
|
173
|
+
const queue = queues.get(chatSessionId);
|
|
174
|
+
if (!queue?.length || draining.has(chatSessionId)) return;
|
|
175
|
+
|
|
176
|
+
draining.add(chatSessionId);
|
|
177
|
+
void (async () => {
|
|
178
|
+
try {
|
|
179
|
+
// Let the finished turn wind down (snapshot, cleanup) before the next one.
|
|
180
|
+
await streamManager.getStream(streamId)?.streamPromise?.catch(() => {});
|
|
181
|
+
const next = queues.get(chatSessionId)?.shift();
|
|
182
|
+
if (!next) return;
|
|
183
|
+
if (!queues.get(chatSessionId)?.length) queues.delete(chatSessionId);
|
|
184
|
+
broadcastQueue(chatSessionId);
|
|
185
|
+
debug.log('chat', `Starting queued message ${next.id} in session ${chatSessionId}`);
|
|
186
|
+
await startQueued(next);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
debug.error('chat', 'Failed to start queued message:', error);
|
|
189
|
+
} finally {
|
|
190
|
+
draining.delete(chatSessionId);
|
|
191
|
+
}
|
|
192
|
+
})();
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
// Deleting a session drops everything its composer was holding.
|
|
196
|
+
streamManager.on('session:cleanup', (chatSessionId: string) => {
|
|
197
|
+
for (const key of drafts.keys()) {
|
|
198
|
+
if (key.startsWith(`${chatSessionId}\u0000`)) drafts.delete(key);
|
|
199
|
+
}
|
|
200
|
+
edits.delete(chatSessionId);
|
|
201
|
+
queues.delete(chatSessionId);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// ============================================================================
|
|
205
|
+
// Schemas
|
|
206
|
+
// ============================================================================
|
|
207
|
+
|
|
208
|
+
const attachmentSchema = t.Object({
|
|
209
|
+
id: t.String(),
|
|
210
|
+
fileName: t.String(),
|
|
211
|
+
type: t.String(),
|
|
212
|
+
mediaType: t.String(),
|
|
213
|
+
base64: t.String()
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
const engineSchema = t.Object({
|
|
217
|
+
type: t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen'), t.Literal('pi'), t.Literal('cline'), t.Literal('cursor')]),
|
|
218
|
+
provider: t.String(),
|
|
219
|
+
model: t.Object({ id: t.String(), name: t.String() }),
|
|
220
|
+
account: t.Object({ id: t.Number(), name: t.String() })
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
const editorSchema = t.Object({
|
|
224
|
+
userId: t.String(),
|
|
225
|
+
userName: t.String(),
|
|
226
|
+
messageId: t.String()
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const queueItemSchema = t.Object({
|
|
230
|
+
id: t.String(),
|
|
231
|
+
userId: t.String(),
|
|
232
|
+
userName: t.String(),
|
|
233
|
+
createdAt: t.String(),
|
|
234
|
+
text: t.String(),
|
|
235
|
+
attachmentCount: t.Number()
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
// ============================================================================
|
|
239
|
+
// Router
|
|
240
|
+
// ============================================================================
|
|
241
|
+
|
|
242
|
+
export const composerHandler = createRouter()
|
|
243
|
+
// Everything the composer restores when a session comes on screen.
|
|
244
|
+
.http('chat:composer-state', {
|
|
245
|
+
data: t.Object({
|
|
246
|
+
chatSessionId: t.String()
|
|
247
|
+
}),
|
|
248
|
+
response: t.Object({
|
|
249
|
+
draft: t.Object({
|
|
250
|
+
text: t.String(),
|
|
251
|
+
attachments: t.Array(attachmentSchema),
|
|
252
|
+
textRevision: t.Number(),
|
|
253
|
+
attachmentsRevision: t.Number()
|
|
254
|
+
}),
|
|
255
|
+
edit: t.Union([
|
|
256
|
+
t.Object({ messageId: t.String(), messageTimestamp: t.Union([t.String(), t.Null()]) }),
|
|
257
|
+
t.Null()
|
|
258
|
+
]),
|
|
259
|
+
editors: t.Array(editorSchema),
|
|
260
|
+
queue: t.Array(queueItemSchema)
|
|
261
|
+
})
|
|
262
|
+
}, ({ data, conn }) => {
|
|
263
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
264
|
+
const userId = ws.getUserId(conn);
|
|
265
|
+
const draft = drafts.get(draftKey(data.chatSessionId, userId));
|
|
266
|
+
const ownEdit = edits.get(data.chatSessionId)?.get(userId);
|
|
267
|
+
return {
|
|
268
|
+
draft: draft ?? { text: '', attachments: [], textRevision: 0, attachmentsRevision: 0 },
|
|
269
|
+
edit: ownEdit ? { messageId: ownEdit.messageId, messageTimestamp: ownEdit.messageTimestamp } : null,
|
|
270
|
+
editors: editorsFor(data.chatSessionId, userId),
|
|
271
|
+
queue: queueView(data.chatSessionId)
|
|
272
|
+
};
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
// Save this user's draft. Omitted fields are left as they are, so typing
|
|
276
|
+
// sends text only and attachments travel only when they change. A part is
|
|
277
|
+
// only replaced by a write newer than the one it holds.
|
|
278
|
+
.on('chat:draft-save', {
|
|
279
|
+
data: t.Object({
|
|
280
|
+
chatSessionId: t.String(),
|
|
281
|
+
revision: t.Number(),
|
|
282
|
+
text: t.Optional(t.String()),
|
|
283
|
+
attachments: t.Optional(t.Array(attachmentSchema))
|
|
284
|
+
})
|
|
285
|
+
}, ({ data, conn }) => {
|
|
286
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
287
|
+
const key = draftKey(data.chatSessionId, ws.getUserId(conn));
|
|
288
|
+
const draft = drafts.get(key) ?? { text: '', attachments: [], textRevision: 0, attachmentsRevision: 0 };
|
|
289
|
+
if (data.text !== undefined && data.revision > draft.textRevision) {
|
|
290
|
+
draft.text = data.text;
|
|
291
|
+
draft.textRevision = data.revision;
|
|
292
|
+
}
|
|
293
|
+
if (data.attachments !== undefined && data.revision > draft.attachmentsRevision) {
|
|
294
|
+
draft.attachments = data.attachments;
|
|
295
|
+
draft.attachmentsRevision = data.revision;
|
|
296
|
+
}
|
|
297
|
+
drafts.set(key, draft);
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
// Enter (messageId) or leave (null) edit mode for this user.
|
|
301
|
+
.on('chat:edit-mode', {
|
|
302
|
+
data: t.Object({
|
|
303
|
+
chatSessionId: t.String(),
|
|
304
|
+
messageId: t.Union([t.String(), t.Null()]),
|
|
305
|
+
messageTimestamp: t.Union([t.String(), t.Null()]),
|
|
306
|
+
userName: t.String()
|
|
307
|
+
})
|
|
308
|
+
}, ({ data, conn }) => {
|
|
309
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
310
|
+
const userId = ws.getUserId(conn);
|
|
311
|
+
|
|
312
|
+
if (data.messageId) {
|
|
313
|
+
const message = messageQueries.getById(data.messageId);
|
|
314
|
+
if (!message || message.session_id !== data.chatSessionId) {
|
|
315
|
+
throw new Error('Message not found in this chat session');
|
|
316
|
+
}
|
|
317
|
+
const sessionEdits = edits.get(data.chatSessionId) ?? new Map<string, EditState>();
|
|
318
|
+
sessionEdits.set(userId, {
|
|
319
|
+
messageId: data.messageId,
|
|
320
|
+
messageTimestamp: data.messageTimestamp,
|
|
321
|
+
userName: data.userName
|
|
322
|
+
});
|
|
323
|
+
edits.set(data.chatSessionId, sessionEdits);
|
|
324
|
+
} else {
|
|
325
|
+
const sessionEdits = edits.get(data.chatSessionId);
|
|
326
|
+
sessionEdits?.delete(userId);
|
|
327
|
+
if (sessionEdits && sessionEdits.size === 0) edits.delete(data.chatSessionId);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
ws.emit.chatSession(data.chatSessionId, 'chat:edit-presence', {
|
|
331
|
+
chatSessionId: data.chatSessionId,
|
|
332
|
+
userId,
|
|
333
|
+
userName: data.userName,
|
|
334
|
+
messageId: data.messageId
|
|
335
|
+
});
|
|
336
|
+
})
|
|
337
|
+
|
|
338
|
+
// Where submitting an edit rewinds to: the edited message's parent. Resolved
|
|
339
|
+
// here from the database, never carried by the client — a client that lost
|
|
340
|
+
// it (refresh, another device) used to fall back to the very beginning of
|
|
341
|
+
// the session and revert every change the chat had made.
|
|
342
|
+
.http('chat:edit-target', {
|
|
343
|
+
data: t.Object({
|
|
344
|
+
chatSessionId: t.String(),
|
|
345
|
+
messageId: t.String()
|
|
346
|
+
}),
|
|
347
|
+
response: t.Object({
|
|
348
|
+
targetId: t.String()
|
|
349
|
+
})
|
|
350
|
+
}, ({ data, conn }) => {
|
|
351
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
352
|
+
const message = messageQueries.getById(data.messageId);
|
|
353
|
+
if (!message || message.session_id !== data.chatSessionId) {
|
|
354
|
+
throw new Error('The message being edited no longer exists in this chat session');
|
|
355
|
+
}
|
|
356
|
+
return { targetId: message.parent_message_id || INITIAL_NODE_ID };
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
// Send a message while the AI is working: it waits for the turn to finish.
|
|
360
|
+
// If the session went idle in the meantime it simply starts now.
|
|
361
|
+
.on('chat:queue-add', {
|
|
362
|
+
data: t.Object({
|
|
363
|
+
chatSessionId: t.String(),
|
|
364
|
+
projectPath: t.String(),
|
|
365
|
+
prompt: t.Any(),
|
|
366
|
+
engine: engineSchema,
|
|
367
|
+
sender: t.Object({ id: t.String(), name: t.String() }),
|
|
368
|
+
profileId: t.Optional(t.Union([t.Number(), t.Null()])),
|
|
369
|
+
reasoningEffort: t.Optional(t.Union([t.String(), t.Null()]))
|
|
370
|
+
})
|
|
371
|
+
}, async ({ data, conn }) => {
|
|
372
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
373
|
+
const userId = ws.getUserId(conn);
|
|
374
|
+
const projectId = ws.getProjectId(conn);
|
|
375
|
+
|
|
376
|
+
const item: QueuedMessage = {
|
|
377
|
+
id: crypto.randomUUID(),
|
|
378
|
+
userId,
|
|
379
|
+
userName: data.sender.name,
|
|
380
|
+
createdAt: new Date().toISOString(),
|
|
381
|
+
text: promptText(data.prompt),
|
|
382
|
+
attachmentCount: promptAttachmentCount(data.prompt),
|
|
383
|
+
request: {
|
|
384
|
+
projectPath: data.projectPath,
|
|
385
|
+
projectId,
|
|
386
|
+
chatSessionId: data.chatSessionId,
|
|
387
|
+
prompt: data.prompt,
|
|
388
|
+
engine: data.engine,
|
|
389
|
+
sender: data.sender,
|
|
390
|
+
profileId: data.profileId,
|
|
391
|
+
reasoningEffort: data.reasoningEffort,
|
|
392
|
+
requestedByUserId: userId
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
if (!isSessionBusy(data.chatSessionId, projectId) && !queues.get(data.chatSessionId)?.length) {
|
|
397
|
+
await startQueued(item);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const queue = queues.get(data.chatSessionId) ?? [];
|
|
402
|
+
queue.push(item);
|
|
403
|
+
queues.set(data.chatSessionId, queue);
|
|
404
|
+
broadcastQueue(data.chatSessionId);
|
|
405
|
+
})
|
|
406
|
+
|
|
407
|
+
// Drop a queued message. Only its author can.
|
|
408
|
+
.on('chat:queue-remove', {
|
|
409
|
+
data: t.Object({
|
|
410
|
+
chatSessionId: t.String(),
|
|
411
|
+
id: t.String()
|
|
412
|
+
})
|
|
413
|
+
}, ({ data, conn }) => {
|
|
414
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
415
|
+
const userId = ws.getUserId(conn);
|
|
416
|
+
const queue = queues.get(data.chatSessionId);
|
|
417
|
+
const index = queue?.findIndex((item) => item.id === data.id) ?? -1;
|
|
418
|
+
if (!queue || index === -1) return;
|
|
419
|
+
if (queue[index].userId !== userId) throw new Error('Only the author can remove a queued message');
|
|
420
|
+
queue.splice(index, 1);
|
|
421
|
+
if (queue.length === 0) queues.delete(data.chatSessionId);
|
|
422
|
+
broadcastQueue(data.chatSessionId);
|
|
423
|
+
})
|
|
424
|
+
|
|
425
|
+
// Take a queued message back into the composer to change it. Returns its
|
|
426
|
+
// content so nothing has to be retyped.
|
|
427
|
+
.http('chat:queue-take', {
|
|
428
|
+
data: t.Object({
|
|
429
|
+
chatSessionId: t.String(),
|
|
430
|
+
id: t.String()
|
|
431
|
+
}),
|
|
432
|
+
response: t.Union([
|
|
433
|
+
t.Object({
|
|
434
|
+
text: t.String(),
|
|
435
|
+
attachments: t.Array(t.Object({
|
|
436
|
+
type: t.String(),
|
|
437
|
+
mediaType: t.String(),
|
|
438
|
+
data: t.String(),
|
|
439
|
+
fileName: t.String()
|
|
440
|
+
}))
|
|
441
|
+
}),
|
|
442
|
+
t.Null()
|
|
443
|
+
])
|
|
444
|
+
}, ({ data, conn }) => {
|
|
445
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
446
|
+
const userId = ws.getUserId(conn);
|
|
447
|
+
const queue = queues.get(data.chatSessionId);
|
|
448
|
+
const index = queue?.findIndex((item) => item.id === data.id) ?? -1;
|
|
449
|
+
if (!queue || index === -1) return null;
|
|
450
|
+
if (queue[index].userId !== userId) throw new Error('Only the author can edit a queued message');
|
|
451
|
+
const [item] = queue.splice(index, 1);
|
|
452
|
+
if (queue.length === 0) queues.delete(data.chatSessionId);
|
|
453
|
+
broadcastQueue(data.chatSessionId);
|
|
454
|
+
|
|
455
|
+
const content = Array.isArray((item.request.prompt as any)?.content) ? (item.request.prompt as any).content : [];
|
|
456
|
+
const attachments = content
|
|
457
|
+
.filter((block: any) => (block?.type === 'image' || block?.type === 'document') && typeof block.data === 'string')
|
|
458
|
+
.map((block: any, i: number) => ({
|
|
459
|
+
type: block.type === 'image' ? 'image' : (block.mediaType === 'application/pdf' ? 'pdf' : 'document'),
|
|
460
|
+
mediaType: block.mediaType || 'application/octet-stream',
|
|
461
|
+
data: block.data as string,
|
|
462
|
+
fileName: block.title || `attachment-${i + 1}`
|
|
463
|
+
}));
|
|
464
|
+
return { text: item.text, attachments };
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
// Send a queued message now. While a turn runs that means "next"; when the
|
|
468
|
+
// session is idle (the queue was paused by a cancel or an error) it starts.
|
|
469
|
+
.on('chat:queue-send-now', {
|
|
470
|
+
data: t.Object({
|
|
471
|
+
chatSessionId: t.String(),
|
|
472
|
+
id: t.String()
|
|
473
|
+
})
|
|
474
|
+
}, async ({ data, conn }) => {
|
|
475
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
476
|
+
const userId = ws.getUserId(conn);
|
|
477
|
+
const projectId = ws.getProjectId(conn);
|
|
478
|
+
const queue = queues.get(data.chatSessionId);
|
|
479
|
+
const index = queue?.findIndex((item) => item.id === data.id) ?? -1;
|
|
480
|
+
if (!queue || index === -1) return;
|
|
481
|
+
if (queue[index].userId !== userId) throw new Error('Only the author can send a queued message');
|
|
482
|
+
|
|
483
|
+
const [item] = queue.splice(index, 1);
|
|
484
|
+
if (isSessionBusy(data.chatSessionId, projectId)) {
|
|
485
|
+
queue.unshift(item);
|
|
486
|
+
broadcastQueue(data.chatSessionId);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (queue.length === 0) queues.delete(data.chatSessionId);
|
|
490
|
+
broadcastQueue(data.chatSessionId);
|
|
491
|
+
await startQueued(item);
|
|
492
|
+
})
|
|
493
|
+
|
|
494
|
+
.emit('chat:edit-presence', t.Object({
|
|
495
|
+
chatSessionId: t.String(),
|
|
496
|
+
userId: t.String(),
|
|
497
|
+
userName: t.String(),
|
|
498
|
+
messageId: t.Union([t.String(), t.Null()])
|
|
499
|
+
}))
|
|
500
|
+
|
|
501
|
+
.emit('chat:queue', t.Object({
|
|
502
|
+
chatSessionId: t.String(),
|
|
503
|
+
items: t.Array(queueItemSchema)
|
|
504
|
+
}));
|
package/backend/ws/chat/index.ts
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
import { createRouter } from '$shared/utils/ws-server';
|
|
8
8
|
import { streamHandler } from './stream';
|
|
9
|
+
import { composerHandler } from './composer';
|
|
9
10
|
|
|
10
11
|
export const chatRouter = createRouter()
|
|
11
|
-
.merge(streamHandler)
|
|
12
|
+
.merge(streamHandler)
|
|
13
|
+
.merge(composerHandler);
|