Open History to see the last commit
1import { EnvironmentId, type ServerConfig } from "@t3tools/contracts";
2import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
3
4import type { DraftComposerAttachment } from "./composerImages";
5
6export interface ComposerAttachmentUploadRequest {
7 readonly environmentId: EnvironmentId;
8 readonly attachment: DraftComposerAttachment;
9}
10
11export type ComposerAttachmentUploadState =
12 | { readonly status: "uploading"; readonly progress: number }
13 | { readonly status: "ready" }
14 | { readonly status: "failed"; readonly reason: string };
15
16export function composerAttachmentUploadKey(
17 environmentId: EnvironmentId,
18 attachmentId: string,
19): string {
20 return `${environmentId}:${attachmentId}`;
21}
22
23export function composerDraftEnvironmentId(
24 draftKey: string,
25 queuedMessages: ReadonlyArray<{
26 readonly messageId: string;
27 readonly environmentId: EnvironmentId;
28 }>,
29): EnvironmentId | null {
30 if (draftKey.startsWith("pending-task:")) {
31 return (
32 queuedMessages.find((message) => `pending-task:${message.messageId}` === draftKey)
33 ?.environmentId ?? null
34 );
35 }
36 const scope = draftKey.startsWith("new-task:") ? draftKey.slice("new-task:".length) : draftKey;
37 const separator = scope.lastIndexOf(":");
38 return separator > 0 ? EnvironmentId.make(scope.slice(0, separator)) : null;
39}
40
41type UploadServerConfig = {
42 readonly environment: {
43 readonly capabilities: Pick<
44 ServerConfig["environment"]["capabilities"],
45 "attachmentUploads" | "fileAttachments"
46 >;
47 };
48};
49
50export function canUploadComposerAttachment(
51 attachment: DraftComposerAttachment,
52 config: UploadServerConfig | null | undefined,
53): boolean {
54 const capabilities = config?.environment.capabilities;
55 return (
56 capabilities?.attachmentUploads === true &&
57 (attachment.type === "image" ||
58 (capabilities.fileAttachments !== undefined &&
59 attachment.sizeBytes <=
60 clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)))
61 );
62}
63
64export function composerAttachmentUploadBlockReason(input: {
65 readonly environmentId: EnvironmentId;
66 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
67 readonly connected: boolean;
68 readonly serverConfig: UploadServerConfig | null;
69 readonly states: Readonly<Record<string, ComposerAttachmentUploadState>>;
70}): string | null {
71 if (!input.connected) return null;
72 for (const attachment of input.attachments) {
73 if (!canUploadComposerAttachment(attachment, input.serverConfig)) continue;
74 const state = input.states[composerAttachmentUploadKey(input.environmentId, attachment.id)];
75 if (state?.status === "failed") return "Retry or remove the failed attachment";
76 if (state?.status !== "ready") return "Attachment still uploading";
77 }
78 return null;
79}
80
81/** Bounds transfers across environments; disconnected or discarded drafts keep their local bytes. */
82export function createComposerAttachmentUploadQueue(options: {
83 readonly upload: (
84 request: ComposerAttachmentUploadRequest,
85 signal: AbortSignal,
86 onProgress: (progress: number) => void,
87 ) => Promise<boolean>;
88 readonly onChange: (states: Readonly<Record<string, ComposerAttachmentUploadState>>) => void;
89}) {
90 const jobs = new Map<
91 string,
92 { readonly controller: AbortController; readonly done: Promise<void> }
93 >();
94 let desired = new Map<string, ComposerAttachmentUploadRequest>();
95 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
96 let disposed = false;
97
98 function setState(key: string, state: ComposerAttachmentUploadState | undefined) {
99 const previous = states[key];
100 if (
101 previous === state ||
102 (previous?.status === "uploading" &&
103 state?.status === "uploading" &&
104 previous.progress === state.progress)
105 )
106 return;
107 const next = { ...states };
108 if (state) next[key] = state;
109 else delete next[key];
110 states = next;
111 options.onChange(states);
112 }
113
114 function pump() {
115 if (disposed) return;
116 for (const [key, request] of desired) {
117 if (jobs.size >= 3) break;
118 if (jobs.has(key) || states[key]?.status === "ready" || states[key]?.status === "failed")
119 continue;
120 const controller = new AbortController();
121 setState(key, { status: "uploading", progress: 0 });
122 // Publish the job before starting async work, including synchronous test transports.
123 const done = Promise.resolve()
124 .then(() =>
125 options.upload(request, controller.signal, (progress) => {
126 if (controller.signal.aborted) return;
127 setState(key, {
128 status: "uploading",
129 progress: Math.floor(Math.max(0, Math.min(1, progress)) * 20) / 20,
130 });
131 }),
132 )
133 .then((persisted) => {
134 if (!controller.signal.aborted && desired.has(key)) {
135 if (!persisted) desired.delete(key);
136 setState(key, persisted ? { status: "ready" } : undefined);
137 }
138 })
139 .catch((error: unknown) => {
140 if (!controller.signal.aborted && desired.has(key)) {
141 setState(key, {
142 status: "failed",
143 reason: error instanceof Error ? error.message : "Upload failed. Tap to retry.",
144 });
145 }
146 })
147 .finally(() => {
148 jobs.delete(key);
149 pump();
150 });
151 jobs.set(key, { controller, done });
152 }
153 }
154
155 return {
156 sync(requests: ReadonlyArray<ComposerAttachmentUploadRequest>) {
157 if (disposed) return;
158 desired = new Map(
159 requests.map((request) => [
160 composerAttachmentUploadKey(request.environmentId, request.attachment.id),
161 request,
162 ]),
163 );
164 for (const [key, job] of jobs) {
165 if (!desired.has(key)) job.controller.abort();
166 }
167 for (const key of Object.keys(states)) {
168 if (!desired.has(key)) setState(key, undefined);
169 }
170 for (const key of desired.keys()) {
171 if (!states[key]) setState(key, { status: "uploading", progress: 0 });
172 }
173 pump();
174 },
175 retry(environmentId: EnvironmentId, attachmentId: string) {
176 const key = composerAttachmentUploadKey(environmentId, attachmentId);
177 if (states[key]?.status !== "failed") return;
178 setState(key, undefined);
179 pump();
180 },
181 /** Waits for the current transfers, useful for shutdown and focused verification. */
182 async settled() {
183 while (jobs.size > 0) await Promise.all([...jobs.values()].map((job) => job.done));
184 },
185 dispose() {
186 disposed = true;
187 desired.clear();
188 for (const job of jobs.values()) job.controller.abort();
189 states = {};
190 options.onChange(states);
191 },
192 };
193}