fix: address review findings on upload-on-attach

Real bugs from Macroscope and Bugbot, all verified against source:

- awaitAttachmentUploads consulted only live jobs, so an upload that
  settled before the await lost its result and a ready image could drop
  from a pick-and-send message. Terminal states are now kept in a
  settled map that cancel/release clean up.
- Stashing cancelled in-flight uploads before the localStorage write was
  confirmed; a quota failure stranded chips in uploading forever.
  Cancellation now happens only after the write lands.
- Retargeting a draft to another environment overwrote a reload-restored
  attachment's ready state with a dead failed state. The mismatch is now
  derived (never written), so switching back recovers the attachment,
  and re-uploads release the old environment's bytes first.
- The turn-start failure path restored chips from the pre-await
  snapshot, resurrecting uploading states no job would ever advance.
- The "images were not attached" toast could fire when no message was
  sent; it now waits for the turn to actually start.
- Removing a preview annotation or discarding a draft leaked the upload
  and its server-side bytes; both now release like chip removal.
- Mobile paste drops now surface the needs-an-update banner instead of
  a console.warn.
- Normalizer error mappings keep their PlatformError causes; the dead
  unstructured AttachmentUploadRequestError is deleted; the sweep test
  no longer reads the real clock (effect-diagnostics CI failure).

Also folds the rebase onto main: the new moveComposerPromptAndImages
draft-carry now merges the unified image list, and in-flight uploads are
retargeted to the destination draft so moved chips keep their progress.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-08-13 18:03:23 -07:00
1 parent f695b6f5bf
commit 03196ef7ad
18 files changed
+299 -135

No files matched your search

@@ -95,12 +95,15 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
const handleNativePaste = useNativePaste((uris) => {
void (async () => {
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: attachments.length,
});
if (images.length > 0) {
setAttachments((current) => [...current, ...images]);
if (pasted.images.length > 0) {
setAttachments((current) => [...current, ...pasted.images]);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[review comment] error converting pasted images", error);
@@ -618,12 +618,15 @@ export function NewTaskDraftScreen(props: {
const handleNativePasteImages = useCallback(
async (uris: ReadonlyArray<string>) => {
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: flow.attachments.length,
});
if (images.length > 0) {
flow.appendAttachments(images);
if (pasted.images.length > 0) {
flow.appendAttachments(pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[native paste] error converting images", error);
+4 -2
View File
@@ -80,12 +80,14 @@ describe("native pasted image cleanup", () => {
files.set(owned, { base64: "aGVsbG8=", deleted: false });
files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
const attachments = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris: [owned, userOwned],
existingCount: 0,
});
expect(attachments).toEqual([]);
expect(pasted.images).toEqual([]);
// The drop is surfaced to callers, not just logged.
expect(pasted.error).toContain("app update");
expect(files.get(owned)?.deleted).toBe(true);
expect(files.get(userOwned)?.deleted).toBe(false);
});
+8 -5
View File
@@ -258,16 +258,19 @@ export function isOwnedPastedImageUri(uri: string): boolean {
export async function convertPastedImagesToAttachments(input: {
readonly uris: ReadonlyArray<string>;
readonly existingCount: number;
}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
}): Promise<{
readonly images: ReadonlyArray<DraftComposerImageAttachment>;
/** Set when pasted images were dropped; callers surface it like a pick error. */
readonly error: string | null;
}> {
const { File } = await import("expo-file-system");
// Zero slots while attach is disabled: the loop below still runs so owned
// temporary paste files are deleted, but nothing is decoded or attached.
const remainingSlots = IMAGE_ATTACH_ENABLED
? PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount
: 0;
if (!IMAGE_ATTACH_ENABLED && input.uris.length > 0) {
console.warn(IMAGE_ATTACH_UNAVAILABLE_MESSAGE, { droppedPastedImages: input.uris.length });
}
const error =
!IMAGE_ATTACH_ENABLED && input.uris.length > 0 ? IMAGE_ATTACH_UNAVAILABLE_MESSAGE : null;
const results: DraftComposerImageAttachment[] = [];
for (const [index, uri] of input.uris.entries()) {
@@ -308,5 +311,5 @@ export async function convertPastedImagesToAttachments(input: {
}
}
return results;
return { images: results, error };
}
@@ -238,12 +238,15 @@ export function useThreadComposerState() {
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
try {
const images = await convertPastedImagesToAttachments({
const pasted = await convertPastedImagesToAttachments({
uris,
existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
});
if (images.length > 0) {
appendComposerDraftAttachments(threadKey, images);
if (pasted.images.length > 0) {
appendComposerDraftAttachments(threadKey, pasted.images);
}
if (pasted.error) {
setPendingConnectionError(pasted.error);
}
} catch (error) {
console.error("[native paste] error converting images", {
+12 -7
View File
@@ -48,9 +48,19 @@ const UploadClaimsSchema = Schema.Struct({
export type AttachmentUploadClaims = typeof UploadClaimsSchema.Type;
const UploadClaimsJson = Schema.fromJsonString(UploadClaimsSchema);
const decodeUploadClaims = Schema.decodeUnknownOption(UploadClaimsJson);
const decodeUploadClaimsOption = Schema.decodeUnknownOption(UploadClaimsJson);
const encodeUploadClaims = Schema.encodeSync(UploadClaimsJson);
// Plain function (not Effect) so the base64/JSON failure modes stay a simple
// null, mirroring AssetAccess.decodeClaims.
function decodeUploadClaims(encodedPayload: string): AttachmentUploadClaims | null {
try {
return Option.getOrNull(decodeUploadClaimsOption(base64UrlDecodeUtf8(encodedPayload)));
} catch {
return null;
}
}
const loadSigningSecret = Effect.gen(function* () {
const secretStore = yield* ServerSecretStore.ServerSecretStore;
return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
@@ -104,12 +114,7 @@ export const validateAttachmentUploadToken = Effect.fn("AttachmentUpload.validat
if (!secret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) return null;
let claims: AttachmentUploadClaims | null;
try {
claims = Option.getOrNull(decodeUploadClaims(base64UrlDecodeUtf8(encodedPayload)));
} catch {
claims = null;
}
const claims = decodeUploadClaims(encodedPayload);
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
return claims;
});
+7 -2
View File
@@ -191,17 +191,22 @@ describe("attachmentStore", () => {
attachmentsDir,
"pending-00000000-0000-4000-8000-000000000004.png.part",
);
// Fixed epoch so the test never touches the real clock: files are
// stamped relative to `nowMs` below, not to wall time.
const nowMs = 1_800_000_000_000;
const freshMs = nowMs - 60_000;
const staleMs = nowMs - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
for (const filePath of [stalePending, freshPending, scoped, stalePart]) {
NodeFS.writeFileSync(filePath, Buffer.from("x"));
}
const staleMs = Date.now() - PENDING_ATTACHMENT_MAX_AGE_MS - 60_000;
NodeFS.utimesSync(freshPending, freshMs / 1000, freshMs / 1000);
NodeFS.utimesSync(stalePending, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(scoped, staleMs / 1000, staleMs / 1000);
NodeFS.utimesSync(stalePart, staleMs / 1000, staleMs / 1000);
const swept = sweepStalePendingAttachments({
attachmentsDir,
nowMs: Date.now(),
nowMs,
});
expect(swept.deleted).toBe(2);
expect(NodeFS.existsSync(stalePending)).toBe(false);
+4 -2
View File
@@ -121,9 +121,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(
Effect.mapError(
() =>
(cause) =>
new OrchestrationDispatchCommandError({
message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,
cause,
}),
),
);
@@ -136,9 +137,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
if (!claimPlan.alreadyScoped) {
yield* fileSystem.rename(claimPlan.currentPath, claimPlan.finalPath).pipe(
Effect.mapError(
() =>
(cause) =>
new OrchestrationDispatchCommandError({
message: `Failed to claim attachment '${attachment.name}' for this thread.`,
cause,
}),
),
);
+18 -13
View File
@@ -4964,7 +4964,7 @@ function ChatViewContent(props: ChatViewProps) {
prompt: promptForSend,
// Only uploaded attachments count: an image still in flight (or failed)
// is not sendable content, and the composer blocks the send anyway.
imageCount: summarizeAttachmentUploads(composerImages).ready,
imageCount: summarizeAttachmentUploads(composerImages, environmentId).ready,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
@@ -5211,19 +5211,12 @@ function ChatViewContent(props: ChatViewProps) {
const settledUpload = settledUploads.get(image.id);
return settledUpload ? { ...image, upload: settledUpload } : image;
});
const turnAttachments = readyAttachmentRefs(sendableImages);
const turnAttachments = readyAttachmentRefs(sendableImages, environmentId);
const unsentImageNames = sendableImages
.filter((image) => image.upload.status !== "ready")
.filter(
(image) => image.upload.status !== "ready" || image.upload.environmentId !== environmentId,
)
.map((image) => image.name);
if (unsentImageNames.length > 0) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Some images were not attached",
description: `${unsentImageNames.join(", ")} did not finish uploading, so the message was sent without them.`,
}),
);
}
let turnStartSucceeded = false;
if (failure === null) {
@@ -5281,6 +5274,15 @@ function ChatViewContent(props: ChatViewProps) {
} else {
turnStartSucceeded = true;
acknowledgeActiveThreadWoke();
if (unsentImageNames.length > 0) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Some images were not attached",
description: `${unsentImageNames.join(", ")} did not finish uploading, so the message was sent without them.`,
}),
);
}
}
}
@@ -5304,7 +5306,10 @@ function ChatViewContent(props: ChatViewProps) {
return next.length === existing.length ? existing : next;
});
promptRef.current = promptForSend;
const retryComposerImages = composerImagesSnapshot.map(cloneComposerImageForRetry);
// `sendableImages` carries the settled upload states; the pre-await
// snapshot can still say `uploading` for a job that finished during
// the await and would restore chips no live job will ever advance.
const retryComposerImages = sendableImages.map(cloneComposerImageForRetry);
composerImagesRef.current = retryComposerImages;
composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
composerElementContextsRef.current = composerElementContextsSnapshot;
+9
View File
@@ -176,6 +176,7 @@ import {
type ComposerThreadDraftState,
type DraftSessionState,
} from "../composerDraftStore";
import { releaseComposerAttachment } from "../lib/attachmentUploadQueue";
// Settled-tail paging: recent history is the common lookup; the deep tail
// stays behind an explicit Show more.
@@ -609,6 +610,14 @@ const SidebarDraftBlock = memo(function SidebarDraftBlock(props: {
]);
const handleDiscard = useCallback(
(draftId: DraftId) => {
// Discarding the draft abandons its attachments: stop in-flight
// uploads and free the server-side bytes before the store forgets
// them. (Server-side, only never-sent `pending-` files can be
// deleted, so this can never touch a sent thread's attachments.)
const draftImages = useComposerDraftStore.getState().getComposerDraft(draftId)?.images ?? [];
for (const image of draftImages) {
releaseComposerAttachment(image);
}
// The /draft/$draftId route redirects home on its own when the draft
// it renders disappears, so discarding the open draft needs no
// special-casing here.
+66 -25
View File
@@ -73,6 +73,7 @@ import {
ATTACHMENT_WRONG_ENVIRONMENT_REASON,
attachmentUploadBlockReason,
formatAttachmentUploadProgress,
isAttachmentInWrongEnvironment,
resolveAttachmentEnvironmentAction,
summarizeAttachmentUploads,
} from "../../lib/attachmentUploadState";
@@ -991,8 +992,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Derived: composer send state
// ------------------------------------------------------------------
const attachmentUploadSummary = useMemo(
() => summarizeAttachmentUploads(composerImages),
[composerImages],
() => summarizeAttachmentUploads(composerImages, environmentId),
[composerImages, environmentId],
);
const composerSendState = useMemo(
() =>
@@ -1501,21 +1502,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// The bytes live in exactly one environment. When a draft is pointed at a
// different one, an attachment we still hold the File for is silently
// re-uploaded; one restored after a reload has no File to re-send, so it
// fails and has to be removed.
// re-uploaded (releasing the old environment's copy first, so nothing
// orphans there). One restored after a reload has no File to re-send; its
// ready state is left intact and the mismatch is rendered and send-gated
// as a derived condition, so switching back recovers it.
useEffect(() => {
for (const image of composerImages) {
const action = resolveAttachmentEnvironmentAction(image, environmentId);
if (action === "reupload") {
retryAttachmentUpload({ target: composerDraftTarget, environmentId, image });
} else if (action === "unavailable") {
setComposerDraftImageUpload(composerDraftTarget, image.id, {
status: "failed",
reason: ATTACHMENT_WRONG_ENVIRONMENT_REASON,
});
if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") {
releaseComposerAttachment(image);
startAttachmentUpload({ target: composerDraftTarget, environmentId, image });
}
}
}, [composerDraftTarget, composerImages, environmentId, setComposerDraftImageUpload]);
}, [composerDraftTarget, composerImages, environmentId]);
// ------------------------------------------------------------------
// Callbacks: prompt change
@@ -2089,11 +2087,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Attachments are already on the server, so the entry is a handful of id
// references and the whole stash is one synchronous write. Anything that
// has not landed yet cannot be referenced: its upload is cancelled (and
// its reservation released) and it comes back as a named drop.
// has not landed yet cannot be referenced and comes back as a named drop.
// Nothing is cancelled yet: if the write fails below, the composer (and
// its in-flight uploads) must be left exactly as they were.
const stashTarget = composerDraftTarget;
const attachments: PersistedComposerImageAttachment[] = [];
const stillUploadingImageNames: string[] = [];
const stillUploadingImages: ComposerImageAttachment[] = [];
const failedImageNames: string[] = [];
for (const image of images) {
if (image.upload.status === "ready") {
@@ -2107,11 +2106,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
});
continue;
}
(image.upload.status === "failed" ? failedImageNames : stillUploadingImageNames).push(
image.name,
);
cancelAttachmentUpload(image.id);
if (image.upload.status === "failed") {
failedImageNames.push(image.name);
} else {
stillUploadingImages.push(image);
}
}
const stillUploadingImageNames = stillUploadingImages.map((image) => image.name);
const { evicted, written, durable } = stashEntryToQueue({
id: randomUUID(),
@@ -2149,6 +2150,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
});
}
// The write landed, so the composer is being cleared: uploads that could
// not be stashed (still in flight) are cancelled now, and failed ones lose
// their settled record. Doing this before the write would strand the
// chips in `uploading` forever on a rejected write.
for (const image of stillUploadingImages) {
cancelAttachmentUpload(image.id);
}
// Only the prompt and images are cleared — terminal/element contexts,
// preview annotations, and review comments are not stashable, so
// destroying them here would be unrecoverable.
@@ -2890,9 +2899,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerPreviewAnnotationCards
annotations={composerPreviewAnnotations}
images={displayComposerImages}
onRemove={(annotationId) =>
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
onRemove={(annotationId) => {
// The annotation's screenshot is a composer image with a
// server-side upload behind it; removing the card must
// stop that upload / free those bytes like removing a
// chip does.
const annotationImage = displayComposerImages.find(
(image) => image.id === annotationId,
);
if (annotationImage) {
releaseComposerAttachment(annotationImage);
}
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId);
}}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(displayComposerImages, imageId);
if (preview) onExpandImage(preview);
@@ -2947,7 +2966,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
key={image.id}
className={cn(
"relative h-16 w-16 overflow-hidden rounded-lg border bg-background",
image.upload.status === "failed"
image.upload.status === "failed" ||
isAttachmentInWrongEnvironment(image, environmentId)
? "border-destructive/70"
: "border-border/80",
)}
@@ -2971,7 +2991,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
alt={image.name}
className={cn(
"h-full w-full object-cover",
image.upload.status === "ready" ? "" : "opacity-40",
image.upload.status === "ready" &&
!isAttachmentInWrongEnvironment(image, environmentId)
? ""
: "opacity-40",
)}
/>
</button>
@@ -2990,6 +3013,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{formatAttachmentUploadProgress(image.upload.progress)}
</span>
)}
{isAttachmentInWrongEnvironment(image, environmentId) && (
<Tooltip>
<TooltipTrigger
render={
<span className="pointer-events-auto absolute inset-x-0 bottom-0 truncate bg-background/85 px-1 py-0.5 text-center text-[10px] text-destructive">
{ATTACHMENT_WRONG_ENVIRONMENT_REASON}
</span>
}
/>
<TooltipPopup
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
This image was uploaded to a different environment. Switch back to
send it from there, or remove it.
</TooltipPopup>
</Tooltip>
)}
{image.upload.status === "failed" && (
<Tooltip>
<TooltipTrigger
+4 -10
View File
@@ -3408,24 +3408,18 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
...destination,
prompt: movedPrompt,
images: [...destination.images, ...source.images],
nonPersistedImageIds: [
...destination.nonPersistedImageIds,
...source.nonPersistedImageIds,
],
persistedAttachments: [
...destination.persistedAttachments,
...source.persistedAttachments,
],
};
// Same clearing shape as clearComposerPromptAndImages, but the
// preview URLs are NOT revoked: the images moved and their blobs
// are still referenced from the destination.
//
// Callers must retarget in-flight uploads to the destination
// (`retargetAttachmentUploads`) or progress writes keep aiming at
// the source draft and the moved chip never leaves `uploading`.
const nextSource: ComposerThreadDraftState = {
...source,
prompt: ensureInlineTerminalContextPlaceholders("", source.terminalContexts.length),
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
};
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextSource)) {
+7
View File
@@ -15,6 +15,7 @@ import {
type DraftThreadState,
useComposerDraftStore,
} from "../composerDraftStore";
import { retargetAttachmentUploads } from "../lib/attachmentUploadQueue";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import {
@@ -153,7 +154,13 @@ export function useNewThreadHandler() {
!composerDraftHasUserContent(getComposerDraft(destinationDraftId)) &&
composerDraftHasUserContent(getComposerDraft(carryContentSourceDraftId))
) {
const movedImageIds =
getComposerDraft(carryContentSourceDraftId)?.images.map((image) => image.id) ?? [];
moveComposerPromptAndImages(carryContentSourceDraftId, destinationDraftId);
// In-flight uploads keep writing to their original target; point
// them at the destination or the moved chips never leave
// `uploading`.
retargetAttachmentUploads(movedImageIds, destinationDraftId);
}
};
const project = projects.find(
+51 -8
View File
@@ -28,7 +28,8 @@ import { readPreparedConnection } from "../state/session";
interface UploadJob {
readonly imageId: string;
readonly target: ComposerThreadTarget;
/** Mutable: a draft move retargets live jobs (`retargetAttachmentUploads`). */
target: ComposerThreadTarget;
readonly environmentId: EnvironmentId;
readonly file: File;
readonly name: string;
@@ -44,6 +45,14 @@ interface UploadJob {
}
const jobsByImageId = new Map<string, UploadJob>();
/**
* Terminal states of finished jobs, kept after the job itself is discarded.
* `awaitAttachmentUploads` reads through this so an upload that completed
* before the await started is still reported instead of silently dropped.
* Entries die on cancel/release; the map is bounded by images attached in a
* session.
*/
const settledUploadsByImageId = new Map<string, ComposerAttachmentUpload>();
const queue: UploadJob[] = [];
let activeCount = 0;
@@ -56,6 +65,9 @@ function setUploadState(job: UploadJob, upload: ComposerAttachmentUpload): void
function finishJob(job: UploadJob): void {
if (jobsByImageId.get(job.imageId) === job) {
jobsByImageId.delete(job.imageId);
if (job.finalUpload !== null) {
settledUploadsByImageId.set(job.imageId, job.finalUpload);
}
}
job.resolveSettled(job.finalUpload);
}
@@ -220,6 +232,7 @@ export function startAttachmentUpload(input: {
* Used by chip removal and by the retry path before it re-queues.
*/
export function cancelAttachmentUpload(imageId: string): void {
settledUploadsByImageId.delete(imageId);
const job = jobsByImageId.get(imageId);
if (!job) return;
job.cancelled = true;
@@ -246,6 +259,24 @@ export function releaseComposerAttachment(image: ComposerImageAttachment): void
}
}
/**
* Points in-flight uploads at a new composer target after
* `moveComposerPromptAndImages`. Without this, progress and completion writes
* keep landing on the source draft and the moved chip never leaves
* `uploading`.
*/
export function retargetAttachmentUploads(
imageIds: ReadonlyArray<string>,
target: ComposerThreadTarget,
): void {
for (const imageId of imageIds) {
const job = jobsByImageId.get(imageId);
if (job) {
job.target = target;
}
}
}
/** Re-runs a failed (or environment-stale) upload with the File still in memory. */
export function retryAttachmentUpload(input: {
target: ComposerThreadTarget;
@@ -266,12 +297,24 @@ export function retryAttachmentUpload(input: {
export async function awaitAttachmentUploads(
imageIds: ReadonlyArray<string>,
): Promise<Map<string, ComposerAttachmentUpload>> {
const pending = imageIds.flatMap((imageId) => {
const results = new Map<string, ComposerAttachmentUpload>();
const pending: Array<Promise<readonly [string, ComposerAttachmentUpload | null]>> = [];
for (const imageId of imageIds) {
const job = jobsByImageId.get(imageId);
return job ? [job.settled.then((upload) => [imageId, upload] as const)] : [];
});
const settled = await Promise.all(pending);
return new Map(
settled.flatMap(([imageId, upload]) => (upload ? [[imageId, upload] as const] : [])),
);
if (job) {
pending.push(job.settled.then((upload) => [imageId, upload] as const));
continue;
}
// The job may have settled (and been discarded) before this await began.
const settledUpload = settledUploadsByImageId.get(imageId);
if (settledUpload) {
results.set(imageId, settledUpload);
}
}
for (const [imageId, upload] of await Promise.all(pending)) {
if (upload) {
results.set(imageId, upload);
}
}
return results;
}
+43 -15
View File
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
attachmentUploadBlockReason,
formatAttachmentUploadProgress,
isAttachmentInWrongEnvironment,
readyAttachmentRefs,
resolveAttachmentEnvironmentAction,
summarizeAttachmentUploads,
@@ -29,34 +30,59 @@ const ready = (attachmentId: string, environmentId = ENVIRONMENT_ID): ComposerAt
describe("attachment upload gating", () => {
it("blocks the send while any attachment is uploading", () => {
const summary = summarizeAttachmentUploads([
image("a.png", ready("pending-a")),
image("b.png", { status: "uploading", progress: 0.4 }),
]);
expect(summary).toEqual({ ready: 1, uploading: 1, failed: 0 });
const summary = summarizeAttachmentUploads(
[image("a.png", ready("pending-a")), image("b.png", { status: "uploading", progress: 0.4 })],
ENVIRONMENT_ID,
);
expect(summary).toEqual({ ready: 1, uploading: 1, failed: 0, wrongEnvironment: 0 });
expect(attachmentUploadBlockReason(summary)).toBe("Image still uploading");
});
it("blocks the send on a failed attachment so it cannot be silently dropped", () => {
const summary = summarizeAttachmentUploads([
image("a.png", { status: "failed", reason: "Upload failed" }),
]);
const summary = summarizeAttachmentUploads(
[image("a.png", { status: "failed", reason: "Upload failed" })],
ENVIRONMENT_ID,
);
expect(attachmentUploadBlockReason(summary)).toBe("Retry or remove the failed image");
});
it("does not block once every attachment is ready", () => {
const summary = summarizeAttachmentUploads([image("a.png", ready("pending-a"))]);
const summary = summarizeAttachmentUploads(
[image("a.png", ready("pending-a"))],
ENVIRONMENT_ID,
);
expect(attachmentUploadBlockReason(summary)).toBeNull();
});
it("blocks the send on a ready attachment whose bytes live elsewhere", () => {
const summary = summarizeAttachmentUploads(
[image("a.png", ready("pending-a", OTHER_ENVIRONMENT_ID))],
ENVIRONMENT_ID,
);
expect(summary).toEqual({ ready: 0, uploading: 0, failed: 0, wrongEnvironment: 1 });
expect(attachmentUploadBlockReason(summary)).toBe("Remove the image from another environment");
});
it("derives the wrong-environment condition without mutating upload state", () => {
const wrongEnvironmentImage = image("a.png", ready("pending-a", OTHER_ENVIRONMENT_ID));
expect(isAttachmentInWrongEnvironment(wrongEnvironmentImage, ENVIRONMENT_ID)).toBe(true);
// Pointing the composer back at the bytes' environment recovers it.
expect(isAttachmentInWrongEnvironment(wrongEnvironmentImage, OTHER_ENVIRONMENT_ID)).toBe(false);
});
});
describe("readyAttachmentRefs", () => {
it("emits id references for uploaded attachments only", () => {
expect(
readyAttachmentRefs([
image("a.png", ready("pending-a")),
image("b.png", { status: "uploading", progress: 0.9 }),
]),
readyAttachmentRefs(
[
image("a.png", ready("pending-a")),
image("b.png", { status: "uploading", progress: 0.9 }),
// Uploaded, but to a different environment: not sendable here.
image("c.png", ready("pending-c", OTHER_ENVIRONMENT_ID)),
],
ENVIRONMENT_ID,
),
).toEqual([
{ type: "image", id: "pending-a", name: "a.png", mimeType: "image/png", sizeBytes: 10 },
]);
@@ -92,13 +118,15 @@ describe("resolveAttachmentEnvironmentAction", () => {
).toBe("reupload");
});
it("reports unavailable after a reload dropped the File", () => {
it("keeps (does not destroy) a File-less attachment from another environment", () => {
// No File means no re-upload is possible; the ready state survives so
// switching back to the bytes' environment restores the attachment.
expect(
resolveAttachmentEnvironmentAction(
image("a.png", ready("pending-a", OTHER_ENVIRONMENT_ID), null),
ENVIRONMENT_ID,
),
).toBe("unavailable");
).toBe("keep");
});
it("leaves an in-flight upload alone", () => {
+44 -13
View File
@@ -37,30 +37,51 @@ interface UploadableImage {
readonly upload: ComposerAttachmentUpload;
}
/**
* True for an uploaded attachment whose bytes live in a different environment
* than the composer currently targets. This is a *derived* condition, never
* written into the upload state: the ready state (with its attachmentId and
* home environment) survives untouched, so pointing the draft back at the
* bytes' environment makes the attachment sendable again with no re-upload.
*/
export function isAttachmentInWrongEnvironment(
image: UploadableImage,
environmentId: EnvironmentId,
): boolean {
return image.upload.status === "ready" && image.upload.environmentId !== environmentId;
}
export interface AttachmentUploadSummary {
/** Uploaded into the composer's current environment: sendable. */
readonly ready: number;
readonly uploading: number;
readonly failed: number;
/** Uploaded, but into a different environment: blocks send until resolved. */
readonly wrongEnvironment: number;
}
export function summarizeAttachmentUploads(
images: ReadonlyArray<UploadableImage>,
environmentId: EnvironmentId,
): AttachmentUploadSummary {
let ready = 0;
let uploading = 0;
let failed = 0;
let wrongEnvironment = 0;
for (const image of images) {
if (image.upload.status === "ready") ready += 1;
else if (image.upload.status === "uploading") uploading += 1;
if (image.upload.status === "ready") {
if (image.upload.environmentId === environmentId) ready += 1;
else wrongEnvironment += 1;
} else if (image.upload.status === "uploading") uploading += 1;
else failed += 1;
}
return { ready, uploading, failed };
return { ready, uploading, failed, wrongEnvironment };
}
/**
* Why the send button is disabled, or null when attachments are not blocking.
* A failed chip has to be retried or removed: silently dropping it would send
* a message the user believes carries an image.
* A failed or unreachable chip has to be retried or removed: silently
* dropping it would send a message the user believes carries an image.
*/
export function attachmentUploadBlockReason(summary: AttachmentUploadSummary): string | null {
if (summary.uploading > 0) {
@@ -71,6 +92,11 @@ export function attachmentUploadBlockReason(summary: AttachmentUploadSummary): s
? "Retry or remove the failed image"
: "Retry or remove the failed images";
}
if (summary.wrongEnvironment > 0) {
return summary.wrongEnvironment === 1
? "Remove the image from another environment"
: "Remove the images from another environment";
}
return null;
}
@@ -81,9 +107,10 @@ export function formatAttachmentUploadProgress(progress: number): string {
}
/**
* Turn-start references for the images that actually made it to the server.
* Non-ready images are skipped: the send path is gated on all-ready, so this
* only drops attachments that were never sendable in the first place.
* Turn-start references for the images that actually made it to the server
* *in the target environment*. Everything else is skipped: the send path is
* gated on all-ready-here, so this only drops attachments that were never
* sendable in the first place.
*/
export function readyAttachmentRefs(
images: ReadonlyArray<
@@ -93,9 +120,10 @@ export function readyAttachmentRefs(
readonly sizeBytes: number;
}
>,
environmentId: EnvironmentId,
): ChatAttachment[] {
return images.flatMap((image) =>
image.upload.status === "ready"
image.upload.status === "ready" && image.upload.environmentId === environmentId
? [
{
type: "image" as const,
@@ -112,18 +140,21 @@ export function readyAttachmentRefs(
/**
* What to do with an attachment when the composer's target environment
* changes. The bytes live in exactly one environment, so a ready attachment
* pointing anywhere else has to be re-uploaded — and can only be re-uploaded
* while the original `File` is still in memory (it is not, after a reload).
* pointing anywhere else has to be re-uploaded — possible only while the
* original `File` is still in memory (it is not, after a reload). Without a
* File the attachment is left untouched: the mismatch is *derived* for
* display and send-gating (`isAttachmentInWrongEnvironment`), and switching
* back to the bytes' environment restores it for free.
*/
export function resolveAttachmentEnvironmentAction(
image: UploadableImage & { readonly file: File | null },
targetEnvironmentId: EnvironmentId,
): "keep" | "reupload" | "unavailable" {
): "keep" | "reupload" {
if (image.upload.status !== "ready") {
return "keep";
}
if (image.upload.environmentId === targetEnvironmentId) {
return "keep";
}
return image.file ? "reupload" : "unavailable";
return image.file ? "reupload" : "keep";
}
-17
View File
@@ -75,17 +75,6 @@ export const AttachmentDeleteInput = Schema.Struct({
});
export type AttachmentDeleteInput = typeof AttachmentDeleteInput.Type;
export class AttachmentUploadRequestError extends Schema.TaggedErrorClass<AttachmentUploadRequestError>()(
"AttachmentUploadRequestError",
{
detail: Schema.String,
},
) {
override get message(): string {
return this.detail;
}
}
export class AttachmentUploadSigningKeyError extends Schema.TaggedErrorClass<AttachmentUploadSigningKeyError>()(
"AttachmentUploadSigningKeyError",
{
@@ -97,12 +86,6 @@ export class AttachmentUploadSigningKeyError extends Schema.TaggedErrorClass<Att
}
}
export const AttachmentUploadError = Schema.Union([
AttachmentUploadRequestError,
AttachmentUploadSigningKeyError,
]);
export type AttachmentUploadError = typeof AttachmentUploadError.Type;
export class AssetWorkspaceContextNotFoundError extends Schema.TaggedErrorClass<AssetWorkspaceContextNotFoundError>()(
"AssetWorkspaceContextNotFoundError",
{
+4 -7
View File
@@ -25,7 +25,6 @@ import {
AttachmentCreateUploadUrlInput,
AttachmentCreateUploadUrlResult,
AttachmentDeleteInput,
AttachmentUploadRequestError,
AttachmentUploadSigningKeyError,
} from "./assets.ts";
import {
@@ -671,16 +670,14 @@ export const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, {
export const WsAttachmentsCreateUploadUrlRpc = Rpc.make(WS_METHODS.attachmentsCreateUploadUrl, {
payload: AttachmentCreateUploadUrlInput,
success: AttachmentCreateUploadUrlResult,
error: Schema.Union([
AttachmentUploadRequestError,
AttachmentUploadSigningKeyError,
EnvironmentAuthorizationError,
]),
error: Schema.Union([AttachmentUploadSigningKeyError, EnvironmentAuthorizationError]),
});
// Delete is a validated no-op for anything it cannot remove, so the only
// failure it can surface is authorization.
export const WsAttachmentsDeleteRpc = Rpc.make(WS_METHODS.attachmentsDelete, {
payload: AttachmentDeleteInput,
error: Schema.Union([AttachmentUploadRequestError, EnvironmentAuthorizationError]),
error: EnvironmentAuthorizationError,
});
export const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {