Repository navigation
Expand file tree
/
Copy pathattachmentStore.ts
More file actions
321 lines (293 loc) · 10.4 KB
/
Copy pathattachmentStore.ts
File metadata and controls
321 lines (293 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import type { ChatAttachment } from "@t3tools/contracts";
import {
htmlRenderFromToolItem,
mcpAppFromToolItem,
previewRecordingIdFromToolItem,
} from "@t3tools/shared/toolOutput";
import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
export const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_FILE_EXTENSION_PATTERN = "[a-z0-9]{1,10}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})(?:-(${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}))?$`,
"i",
);
export const PENDING_ATTACHMENT_THREAD_SEGMENT = "pending";
const PENDING_ATTACHMENT_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const PARTIAL_UPLOAD_MAX_AGE_MS = 60 * 60 * 1000;
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
const segment = threadId
.trim()
.toLowerCase()
.replace(/[^a-z0-9_-]+/gi, "-")
.replace(/-+/g, "-")
.replace(/^[-_]+|[-_]+$/g, "")
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
.replace(/[-_]+$/g, "");
if (segment.length === 0) {
return null;
}
return segment === PENDING_ATTACHMENT_THREAD_SEGMENT ? "_pending" : segment;
}
export function attachmentFileExtension(fileName: string): string {
const extension = NodePath.extname(fileName).toLowerCase();
// .part is reserved for pending uploads; the stale-upload sweep would delete stored files.
if (extension === ".part" || !/^\.[a-z0-9]{1,10}$/.test(extension)) {
return ".bin";
}
return extension;
}
function attachmentIdExtensionSuffix(extension: string | undefined): string {
if (!extension) {
return "";
}
const normalized = extension.replace(/^\./, "").toLowerCase();
return new RegExp(`^${ATTACHMENT_ID_FILE_EXTENSION_PATTERN}$`).test(normalized)
? `-${normalized}`
: "-bin";
}
export function createPendingAttachmentId(extension?: string): string {
return `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
}
export function parseAttachmentUuid(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[2]?.toLowerCase() ?? null;
}
export function parseAttachmentFileExtension(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
return normalizedId.match(ATTACHMENT_ID_PATTERN)?.[3]?.toLowerCase() ?? null;
}
export function createAttachmentId(threadId: string, extension?: string): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) {
return null;
}
return `${threadSegment}-${NodeCrypto.randomUUID()}${attachmentIdExtensionSuffix(extension)}`;
}
export function createDeterministicAttachmentId(
threadId: string,
stableKey: string,
): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) return null;
const hash = NodeCrypto.createHash("sha256")
.update(JSON.stringify([threadId, stableKey]))
.digest("hex")
.slice(0, 32);
const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
return `${threadSegment}-${uuid}`;
}
/** Retries keep ids; changed bytes must get new ids because clients cache images by id. */
export function chatAttachmentStableKey(
messageId: string,
index: number,
bytes: Uint8Array,
): string {
const digest = NodeCrypto.createHash("sha256").update(bytes).digest("hex");
return `${messageId}:${index}:${digest}`;
}
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
if (!match) {
return null;
}
return match[1]?.toLowerCase() ?? null;
}
/** Only this thread's ids qualify, preserving source pages when deleting a fork. */
export function threadHtmlRenderAttachmentIds(
threadId: string,
items: Iterable<{ readonly toolName: string | null | undefined; readonly output?: unknown }>,
) {
const segment = toSafeThreadAttachmentSegment(threadId);
if (segment === null) return [];
return Array.from(items).flatMap((item) => {
const attachmentId =
htmlRenderFromToolItem(item)?.attachmentId ??
mcpAppFromToolItem(item)?.attachmentId ??
previewRecordingIdFromToolItem(item);
return attachmentId !== undefined &&
parseThreadSegmentFromAttachmentId(attachmentId) === segment
? [attachmentId]
: [];
});
}
export function attachmentRelativePath(attachment: ChatAttachment): string | null {
switch (attachment.type) {
case "image": {
const extension = inferImageExtension({
mimeType: attachment.mimeType,
fileName: attachment.name,
});
return `${attachment.id}${extension}`;
}
case "file":
return `${attachment.id}${attachmentFileExtension(attachment.name)}`;
default:
return null;
}
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly attachment: ChatAttachment;
}): string | null {
const relativePath = attachmentRelativePath(input.attachment);
if (!relativePath) {
return null;
}
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath,
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
return null;
}
const fileExtension = parseAttachmentFileExtension(normalizedId);
if (fileExtension) {
const filePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}.${fileExtension.toLowerCase()}`,
});
return filePath && NodeFS.existsSync(filePath) ? filePath : null;
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && NodeFS.existsSync(maybePath)) {
return maybePath;
}
}
return null;
}
export type AttachmentClaimPlan =
| {
readonly ok: true;
readonly finalId: string;
readonly currentPath: string;
readonly finalPath: string;
}
| { readonly ok: false; readonly reason: string };
export function planAttachmentClaim(input: {
readonly attachmentsDir: string;
readonly threadId: string;
readonly attachmentId: string;
}): AttachmentClaimPlan {
const uuid = parseAttachmentUuid(input.attachmentId);
const requestedSegment = parseThreadSegmentFromAttachmentId(input.attachmentId);
if (!uuid || !requestedSegment) {
return { ok: false, reason: "invalid attachment id" };
}
if (!toSafeThreadAttachmentSegment(input.threadId)) {
return { ok: false, reason: "invalid thread id" };
}
if (requestedSegment !== PENDING_ATTACHMENT_THREAD_SEGMENT) {
return { ok: false, reason: "attachment must be a pending upload" };
}
const currentPath = resolveAttachmentPathById({
attachmentsDir: input.attachmentsDir,
attachmentId: input.attachmentId,
});
if (!currentPath) {
return { ok: false, reason: "attachment not found (removed or expired)" };
}
const fileExtension = parseAttachmentFileExtension(input.attachmentId) ?? undefined;
const finalId = createAttachmentId(input.threadId, fileExtension);
if (!finalId) {
return { ok: false, reason: "failed to create attachment id" };
}
const expectedFinalPath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: `${finalId}${NodePath.extname(currentPath)}`,
});
if (!expectedFinalPath) {
return { ok: false, reason: "failed to resolve attachment path" };
}
return {
ok: true,
finalId,
currentPath,
finalPath: expectedFinalPath,
};
}
export function sweepStalePendingAttachments(input: {
readonly attachmentsDir: string;
readonly nowMs: number;
}): { readonly deleted: number } {
let entries: string[];
try {
entries = NodeFS.readdirSync(input.attachmentsDir);
} catch {
return { deleted: 0 };
}
let deleted = 0;
for (const entry of entries) {
const isPartial = entry.endsWith(".part");
if (!isPartial) {
const attachmentId = parseAttachmentIdFromRelativePath(
entry.endsWith(".txt") && entry.slice(0, -4).includes(".") ? entry.slice(0, -4) : entry,
);
if (
!attachmentId ||
parseThreadSegmentFromAttachmentId(attachmentId) !== PENDING_ATTACHMENT_THREAD_SEGMENT
) {
continue;
}
}
const resolved = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
relativePath: entry,
});
if (!resolved) {
continue;
}
try {
const maxAgeMs = isPartial ? PARTIAL_UPLOAD_MAX_AGE_MS : PENDING_ATTACHMENT_MAX_AGE_MS;
if (input.nowMs - NodeFS.statSync(resolved).mtimeMs > maxAgeMs) {
NodeFS.unlinkSync(resolved);
deleted += 1;
}
} catch {
continue;
}
}
return { deleted };
}
function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
const normalized = normalizeAttachmentRelativePath(relativePath);
if (!normalized || normalized.includes("/")) {
return null;
}
const extensionIndex = normalized.lastIndexOf(".");
if (extensionIndex <= 0) {
return null;
}
const id = normalized.slice(0, extensionIndex);
return id.length > 0 && !id.includes(".") ? id : null;
}