Open History to see the last commit
1import * as FileSystem from "effect/FileSystem";
2import {
3 ChatAttachmentId,
4 getProviderAttachmentLimitError,
5 type ChatAttachment,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as Schema from "effect/Schema";
9
10import {
11 parseThreadSegmentFromAttachmentId,
12 PENDING_ATTACHMENT_THREAD_SEGMENT,
13 planAttachmentClaim,
14 resolveAttachmentPath,
15} from "../attachmentStore.ts";
16import * as ServerConfig from "../config.ts";
17
18export class AttachmentClaimError extends Schema.TaggedError<AttachmentClaimError>()(
19 "AttachmentClaimError",
20 {
21 message: Schema.String,
22 cause: Schema.optional(Schema.Defect()),
23 },
24) {}
25
26export const validateAttachmentLimits = Effect.fn("AttachmentClaims.validateAttachmentLimits")(
27 function* (attachments: ReadonlyArray<ChatAttachment>) {
28 const error = getProviderAttachmentLimitError(attachments);
29 if (error) return yield* new AttachmentClaimError({ message: error });
30 },
31);
32
33export interface ClaimedAttachments {
34 readonly attachments: ReadonlyArray<ChatAttachment>;
35 readonly claimedPaths: ReadonlyArray<string>;
36}
37
38export function attachmentIsPendingUpload(attachment: ChatAttachment): boolean {
39 return parseThreadSegmentFromAttachmentId(attachment.id) === PENDING_ATTACHMENT_THREAD_SEGMENT;
40}
41
42/** Remove partial claims only before dispatch, or after proving they were not accepted. */
43export const releaseClaimedAttachments = Effect.fn("AttachmentClaims.releaseClaimedAttachments")(
44 function* (claimedPaths: ReadonlyArray<string>) {
45 if (claimedPaths.length === 0) return;
46 const fileSystem = yield* FileSystem.FileSystem;
47 yield* Effect.forEach(claimedPaths, (path) => fileSystem.remove(path).pipe(Effect.ignore), {
48 concurrency: 1,
49 discard: true,
50 }).pipe(Effect.uninterruptible);
51 },
52);
53
54/**
55 * A copy, not a move — the pending file stays behind as the retry source for a
56 * failed bootstrap, and the periodic pending sweep reclaims it later.
57 */
58export const claimPendingAttachments = Effect.fn("AttachmentClaims.claimPendingAttachments")(
59 function* (input: {
60 readonly threadId: string;
61 readonly attachments: ReadonlyArray<ChatAttachment>;
62 }) {
63 yield* validateAttachmentLimits(input.attachments);
64 if (
65 new Set(input.attachments.map((attachment) => attachment.id)).size !==
66 input.attachments.length
67 ) {
68 return yield* new AttachmentClaimError({
69 message: "Duplicate attachment ids are not allowed.",
70 });
71 }
72 if (!input.attachments.some(attachmentIsPendingUpload)) {
73 return { attachments: input.attachments, claimedPaths: [] } satisfies ClaimedAttachments;
74 }
75 const serverConfig = yield* ServerConfig.ServerConfig;
76 const fileSystem = yield* FileSystem.FileSystem;
77 const claimedPaths: string[] = [];
78 const attachments = yield* Effect.forEach(
79 input.attachments,
80 (attachment) =>
81 Effect.gen(function* () {
82 if (!attachmentIsPendingUpload(attachment)) {
83 return attachment;
84 }
85 const claim = planAttachmentClaim({
86 attachmentsDir: serverConfig.attachmentsDir,
87 threadId: input.threadId,
88 attachmentId: attachment.id,
89 });
90 if (!claim.ok) {
91 return yield* new AttachmentClaimError({
92 message: `Attachment '${attachment.name}' cannot be sent: ${claim.reason}.`,
93 });
94 }
95 const info = yield* fileSystem.stat(claim.currentPath).pipe(
96 Effect.mapError(
97 (cause) =>
98 new AttachmentClaimError({
99 message: `Attachment '${attachment.name}' cannot be sent: attachment not found.`,
100 cause,
101 }),
102 ),
103 );
104 if (Number(info.size) !== attachment.sizeBytes) {
105 return yield* new AttachmentClaimError({
106 message: `Attachment '${attachment.name}' cannot be sent: stored size does not match.`,
107 });
108 }
109 const normalized: ChatAttachment = {
110 ...attachment,
111 id: ChatAttachmentId.make(claim.finalId),
112 mimeType: attachment.mimeType.toLowerCase(),
113 };
114 const expectedPath = resolveAttachmentPath({
115 attachmentsDir: serverConfig.attachmentsDir,
116 attachment: normalized,
117 });
118 if (expectedPath !== claim.finalPath) {
119 return yield* new AttachmentClaimError({
120 message: `Attachment '${attachment.name}' cannot be sent: attachment type does not match the upload.`,
121 });
122 }
123 // A copy, not a hard link: an agent editing the delivered file in
124 // place must not mutate the retry source. fs.copyFile cannot be
125 // cancelled, so the copy and its rollback registration stay in one
126 // uninterruptible region: an interrupt landing mid-copy still waits
127 // for the write to settle and records the path before cleanup runs.
128 yield* fileSystem.copyFile(claim.currentPath, claim.finalPath).pipe(
129 Effect.mapError(
130 (cause) =>
131 new AttachmentClaimError({
132 message: `Failed to claim attachment '${attachment.name}' for this thread.`,
133 cause,
134 }),
135 ),
136 Effect.andThen(Effect.sync(() => claimedPaths.push(claim.finalPath))),
137 Effect.uninterruptible,
138 );
139 return normalized;
140 }),
141 { concurrency: 1 },
142 ).pipe(Effect.onError(() => releaseClaimedAttachments(claimedPaths)));
143 return { attachments, claimedPaths } satisfies ClaimedAttachments;
144 },
145);