Open History to see the last commit
1import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2import { useAtomValue } from "@effect/atom-react";
3import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
4import { Atom, AsyncResult } from "effect/reactivity";
5
6import { prepareTurnAttachments } from "../lib/attachmentUpload";
7import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";
8import {
9 isFileBackedComposerAttachment,
10 type DraftComposerAttachment,
11} from "../lib/composerImages";
12import {
13 composerAttachmentUploadKey,
14 composerDraftEnvironmentId,
15 canUploadComposerAttachment,
16 createComposerAttachmentUploadQueue,
17 type ComposerAttachmentUploadState,
18} from "../lib/composerAttachmentUploadQueue";
19import { appAtomRegistry } from "./atom-registry";
20import { environmentServerConfigsAtom } from "./server";
21import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox";
22import {
23 ComposerDraftPersistenceError,
24 type ComposerDraft,
25 composerDraftsAtom,
26 composerDraftUploadSourcesAtom,
27 ensureComposerDraftsLoaded,
28 flushComposerDrafts,
29 setComposerDraftAttachmentUpload,
30} from "./use-composer-drafts";
31import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session";
32import { workspaceConnections } from "./workspace";
33
34export {
35 composerAttachmentUploadBlockReason,
36 composerAttachmentsStillUploading,
37} from "../lib/composerAttachmentUploadQueue";
38
39export const composerAttachmentUploadsAtom = Atom.make<
40 Readonly<Record<string, ComposerAttachmentUploadState>>
41>({}).pipe(Atom.keepAlive);
42const uploadStateAtom = Atom.family((key: string) =>
43 Atom.map(composerAttachmentUploadsAtom, (states) => states[key]),
44);
45let uploadQueue: ReturnType<typeof createComposerAttachmentUploadQueue> | null = null;
46
47export function useComposerAttachmentUploadState(
48 environmentId: EnvironmentId | undefined,
49 attachmentId: string,
50) {
51 return useAtomValue(
52 uploadStateAtom(environmentId ? composerAttachmentUploadKey(environmentId, attachmentId) : ""),
53 );
54}
55
56export function retryComposerAttachmentUpload(environmentId: EnvironmentId, attachmentId: string) {
57 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
58 uploadQueue?.retry(environmentId, attachmentId);
59}
60
61type ComposerAttachmentUploadRequest = {
62 readonly environmentId: EnvironmentId;
63 readonly attachment: DraftComposerAttachment;
64};
65
66export function composerAttachmentUploadRequests(input: {
67 readonly drafts: Readonly<Record<string, Pick<ComposerDraft, "attachments" | "project">>>;
68 readonly queuedMessagesByThreadKey: Parameters<typeof flattenQueuedThreadMessages>[0];
69 /** Every environment the client knows, so a draft key never resolves to a shorter connected prefix. */
70 readonly knownEnvironmentIds: Iterable<EnvironmentId>;
71 readonly connectedEnvironmentIds: ReadonlySet<EnvironmentId>;
72 readonly operableEnvironmentIds: ReadonlySet<EnvironmentId>;
73 readonly serverConfigs: ReadonlyMap<
74 EnvironmentId,
75 Parameters<typeof canUploadComposerAttachment>[1]
76 >;
77}): ReadonlyArray<ComposerAttachmentUploadRequest> {
78 const queued = flattenQueuedThreadMessages(input.queuedMessagesByThreadKey);
79 return Object.entries(input.drafts).flatMap(([key, draft]) => {
80 const environmentId = composerDraftEnvironmentId(key, input.knownEnvironmentIds, queued, draft);
81 if (
82 environmentId === null ||
83 !input.connectedEnvironmentIds.has(environmentId) ||
84 !input.operableEnvironmentIds.has(environmentId)
85 )
86 return [];
87 return draft.attachments
88 .filter((attachment) =>
89 canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)),
90 )
91 .map((attachment) => ({ environmentId, attachment }));
92 });
93}
94
95// Each connected environment's session is read here so a granted or revoked
96// operate scope re-syncs the queue.
97const composerAttachmentUploadRequestsAtom = Atom.make((get) => {
98 const environments = get(workspaceConnections.environmentsAtom);
99 const connected = environments.filter(
100 (environment) => environment.connectionState === "connected",
101 );
102 const operableEnvironmentIds = new Set<EnvironmentId>();
103 for (const { environmentId } of connected) {
104 if (
105 sessionHasScope(
106 get(environmentSession.sessionStateAtom(environmentId)),
107 AuthOrchestrationOperateScope,
108 )
109 ) {
110 operableEnvironmentIds.add(environmentId);
111 }
112 }
113 return composerAttachmentUploadRequests({
114 drafts: get(composerDraftUploadSourcesAtom),
115 queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
116 knownEnvironmentIds: environments.map((environment) => environment.environmentId),
117 connectedEnvironmentIds: new Set(connected.map((environment) => environment.environmentId)),
118 operableEnvironmentIds,
119 serverConfigs: get(environmentServerConfigsAtom),
120 });
121}).pipe(Atom.withLabel("mobile:composer-attachment-upload-requests"));
122
123/**
124 * Uploads draft attachments to their environment as soon as it is connected and
125 * operable. The queue follows the requests atom for its whole lifetime.
126 */
127export function createComposerAttachmentUploadWorker(
128 requestsAtom: Atom.Atom<
129 ReadonlyArray<ComposerAttachmentUploadRequest>
130 > = composerAttachmentUploadRequestsAtom,
131) {
132 ensureComposerDraftsLoaded();
133 const queue = createComposerAttachmentUploadQueue({
134 onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
135 upload: async ({ environmentId, attachment }, signal, onProgress) => {
136 const release = isFileBackedComposerAttachment(attachment)
137 ? retainComposerAttachmentFileForPreview(attachment)
138 : undefined;
139 const prepared = await settlePromise(() =>
140 prepareTurnAttachments({
141 environmentId,
142 attachments: [attachment],
143 supportsImageUploads: true,
144 signal,
145 onUploadProgress: (_, progress) => onProgress(progress),
146 persistUploadedReferences: async ([uploaded]) => {
147 if (signal.aborted || !uploaded) return "abandon";
148 const queued = flattenQueuedThreadMessages(
149 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
150 );
151 const knownEnvironmentIds = appAtomRegistry
152 .get(workspaceConnections.environmentsAtom)
153 .map((environment) => environment.environmentId);
154 let retained = false;
155 for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
156 if (
157 composerDraftEnvironmentId(key, knownEnvironmentIds, queued, draft) ===
158 environmentId &&
159 draft.attachments.some((candidate) => candidate.id === attachment.id)
160 ) {
161 retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
162 }
163 }
164 if (!retained) return "abandon";
165 // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads.
166 await flushComposerDrafts().catch((error: unknown) => {
167 if (!(error instanceof ComposerDraftPersistenceError)) throw error;
168 console.warn("[composer-attachments] could not save the uploaded reference", error);
169 });
170 return "persisted";
171 },
172 }),
173 );
174 release?.();
175 if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
176 return prepared.value.status === "ready";
177 },
178 });
179 uploadQueue = queue;
180 const unsubscribe = appAtomRegistry.subscribe(requestsAtom, (requests) => queue.sync(requests), {
181 immediate: true,
182 });
183 return {
184 queue,
185 dispose: () => {
186 unsubscribe();
187 queue.dispose();
188 if (uploadQueue === queue) uploadQueue = null;
189 },
190 };
191}
192
193export function installComposerAttachmentUploads(): () => void {
194 return createComposerAttachmentUploadWorker().dispose;
195}