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