feat(web): attach PDFs, ZIPs, and other files to a turn (#8236)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 authored and GitHub committed 2026-08-28 21:57:54 -07:00
1 parent 6a9d9f9882
commit bcb855a633
30 files changed
+3934 -265

No files matched your search

@@ -36,6 +36,7 @@ import {
shouldDockDraftHeroForSubmission,
shouldReleaseTimelineAnchorForToolActivity,
shouldShowBranchMismatchBanner,
shouldShowPlanFollowUpPrompt,
shouldWriteThreadErrorToCurrentServerThread,
} from "./ChatView.logic";
@@ -591,6 +592,31 @@ describe("shouldShowBranchMismatchBanner", () => {
});
});
describe("shouldShowPlanFollowUpPrompt", () => {
const base = {
pendingUserInputCount: 0,
interactionMode: "plan" as const,
latestTurnSettled: true,
hasActionableProposedPlan: true,
hasComposerAttachments: false,
};
it("shows plan actions for a settled actionable plan without attachments", () => {
expect(shouldShowPlanFollowUpPrompt(base)).toBe(true);
});
it("hides plan actions while the composer has staged attachments", () => {
expect(shouldShowPlanFollowUpPrompt({ ...base, hasComposerAttachments: true })).toBe(false);
});
it("preserves the existing plan follow-up gates", () => {
expect(shouldShowPlanFollowUpPrompt({ ...base, pendingUserInputCount: 1 })).toBe(false);
expect(shouldShowPlanFollowUpPrompt({ ...base, interactionMode: "default" })).toBe(false);
expect(shouldShowPlanFollowUpPrompt({ ...base, latestTurnSettled: false })).toBe(false);
expect(shouldShowPlanFollowUpPrompt({ ...base, hasActionableProposedPlan: false })).toBe(false);
});
});
describe("session branch mismatch dismissal", () => {
it("tracks dismissed keys and treats other keys as active", () => {
expect(isBranchMismatchDismissedForSession("t1:a:b")).toBe(false);
+17
View File
@@ -4,6 +4,7 @@ import {
ProjectId,
type MessageId,
type ModelSelection,
type ProviderInteractionMode,
type ProviderDriverKind,
type ServerProvider,
type ScopedProjectRef,
@@ -445,6 +446,22 @@ export function shouldShowBranchMismatchBanner(input: {
return input.composerHasContent || input.wasShownForCurrentMismatch;
}
export function shouldShowPlanFollowUpPrompt(input: {
pendingUserInputCount: number;
interactionMode: ProviderInteractionMode;
latestTurnSettled: boolean;
hasActionableProposedPlan: boolean;
hasComposerAttachments: boolean;
}): boolean {
return (
input.pendingUserInputCount === 0 &&
input.interactionMode === "plan" &&
input.latestTurnSettled &&
input.hasActionableProposedPlan &&
!input.hasComposerAttachments
);
}
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
// changes). Durable cross-device dismissal is planned as a server-side ack.
const sessionDismissedBranchMismatchKeys = new Set<string>();
+215 -43
View File
@@ -1,5 +1,6 @@
import {
type ApprovalRequestId,
type ChatFileAttachment,
DEFAULT_MODEL,
defaultInstanceIdForDriver,
type EnvironmentId,
@@ -17,6 +18,7 @@ import {
type TurnId,
type KeybindingCommand,
OrchestrationThreadActivity,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ProviderInteractionMode,
ProviderDriverKind,
RuntimeMode,
@@ -231,6 +233,7 @@ import {
beginBackgroundDraftSubmissionByRef,
clearBackgroundDraftSubmissionByRef,
composerDraftHasUserContent,
type ComposerFileAttachment,
type ComposerImageAttachment,
type DraftThreadEnvMode,
finalizePromotedDraftThreadByRef,
@@ -257,6 +260,7 @@ import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import {
environmentServerConfigsAtom,
primaryServerAvailableEditorsAtom,
primaryServerKeybindingsAtom,
primaryServerSettingsAtom,
@@ -346,6 +350,7 @@ import {
shouldDockDraftHeroForSubmission,
shouldReleaseTimelineAnchorForToolActivity,
shouldShowBranchMismatchBanner,
shouldShowPlanFollowUpPrompt,
getStartedThreadModelChangeBlockReason,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
@@ -371,13 +376,19 @@ import { useComposerHandleContext } from "../composerHandleContext";
import {
awaitAttachmentUploads,
getUploadedAttachments,
releaseAttachmentUploads,
releaseDraftAttachments,
startAttachmentUpload,
} from "../lib/attachmentUploadQueue";
import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
import { RightPanelSheet } from "./RightPanelSheet";
import { previewEnvironment } from "../state/preview";
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { fileAttachmentCapabilityBlockReason } from "./chat/composerAttachmentFiles";
import { assetEnvironment } from "../state/assets";
import { readPreparedConnection } from "../state/session";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { Button } from "./ui/button";
import {
AlertDialog,
@@ -398,10 +409,10 @@ import {
resolveServerSelfUpdateCapability,
serverUpdateGuidance,
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
import { resolveAssetUrl, useAssetUrls } from "../assets/assetUrls";
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
const ATTACHMENT_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more files without additional text. Respond using the conversation context and the attached files.]";
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
@@ -1299,6 +1310,9 @@ function ChatViewContent(props: ChatViewProps) {
reportFailure: false,
});
const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
});
const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
reportFailure: false,
});
@@ -1384,8 +1398,13 @@ function ChatViewContent(props: ChatViewProps) {
const composerHasUnsentContent = useComposerDraftStore((store) =>
composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
);
const composerHasAttachments = useComposerDraftStore((store) => {
const draft = store.getComposerDraft(composerDraftTarget);
return (draft?.images.length ?? 0) > 0 || (draft?.files.length ?? 0) > 0;
});
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
const setComposerDraftTerminalContexts = useComposerDraftStore(
(store) => store.setTerminalContexts,
);
@@ -1412,6 +1431,7 @@ function ChatViewContent(props: ChatViewProps) {
);
const promptRef = useRef("");
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerFilesRef = useRef<ComposerFileAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
@@ -2124,6 +2144,12 @@ function ChatViewContent(props: ChatViewProps) {
const attachmentUploadsCapabilityKnown = attachmentEnvironmentConfig !== null;
const supportsAttachmentUploads =
attachmentEnvironmentConfig?.environment.capabilities.attachmentUploads === true;
const advertisedFileAttachmentBytes =
attachmentEnvironmentConfig?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null;
const maxFileAttachmentBytes =
advertisedFileAttachmentBytes === null
? null
: clampFileAttachmentUploadBytes(advertisedFileAttachmentBytes);
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
const versionMismatchDismissKey =
versionMismatch && activeThread
@@ -2403,11 +2429,13 @@ function ChatViewContent(props: ChatViewProps) {
null
);
}, [activeLatestTurn?.turnId, activePlan]);
const showPlanFollowUpPrompt =
pendingUserInputs.length === 0 &&
interactionMode === "plan" &&
latestTurnSettled &&
hasActionableProposedPlan(activeProposedPlan);
const showPlanFollowUpPrompt = shouldShowPlanFollowUpPrompt({
pendingUserInputCount: pendingUserInputs.length,
interactionMode,
latestTurnSettled,
hasActionableProposedPlan: hasActionableProposedPlan(activeProposedPlan),
hasComposerAttachments: composerHasAttachments,
});
const activePendingApproval = pendingApprovals[0] ?? null;
const {
beginLocalDispatch,
@@ -2493,11 +2521,57 @@ function ChatViewContent(props: ChatViewProps) {
});
}, []);
const serverMessages = activeThread?.messages;
const downloadFileAttachment = useCallback(
async (attachment: ChatFileAttachment) => {
const connection = readPreparedConnection(environmentId);
if (!connection) {
toastManager.add({ type: "error", title: "The environment is not connected." });
return;
}
// fileName and mimeType ride in the signed claims so the download gets
// a real filename and Content-Type even when the anchor's `download`
// attribute is ignored (cross-origin environment servers).
const result = await createAttachmentAssetUrl({
environmentId,
input: {
resource: {
_tag: "attachment",
attachmentId: attachment.id,
fileName: attachment.name,
mimeType: attachment.mimeType,
},
},
});
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: `Could not download ${attachment.name}`,
description: error instanceof Error ? error.message : "The attachment is unavailable.",
});
return;
}
const url = resolveAssetUrl(connection.httpBaseUrl, result.value.relativeUrl);
if (!url) {
toastManager.add({ type: "error", title: `Could not download ${attachment.name}` });
return;
}
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = attachment.name;
anchor.click();
},
[createAttachmentAssetUrl, environmentId],
);
const serverAttachmentIds = useMemo(() => {
const attachmentIds = new Set<string>();
for (const message of serverMessages ?? []) {
for (const attachment of message.attachments ?? []) {
attachmentIds.add(attachment.id);
if (isImageAttachment(attachment)) {
attachmentIds.add(attachment.id);
}
}
}
return [...attachmentIds];
@@ -5410,6 +5484,7 @@ function ChatViewContent(props: ChatViewProps) {
}
const {
images: sendContextImages,
files: composerFiles,
terminalContexts: composerTerminalContexts,
elementContexts: composerElementContexts,
previewAnnotations: sendContextPreviewAnnotations,
@@ -5420,9 +5495,17 @@ function ChatViewContent(props: ChatViewProps) {
selectedPromptEffort: ctxSelectedPromptEffort,
selectedModelSelection: ctxSelectedModelSelection,
} = sendCtx;
const annotationImageAlreadyAttached =
directAnnotation?.image !== undefined &&
sendContextImages.some((image) => image.id === directAnnotation.image?.id);
// A full composer (e.g. 8 files) cannot take the annotation screenshot;
// over the cap the server rejects the whole turn.
const annotationImageAppended =
directAnnotation?.image !== undefined &&
!annotationImageAlreadyAttached &&
sendContextImages.length + composerFiles.length < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
const composerImages =
directAnnotation?.image &&
!sendContextImages.some((image) => image.id === directAnnotation.image?.id)
directAnnotation?.image && annotationImageAppended
? [...sendContextImages, directAnnotation.image]
: sendContextImages;
const composerPreviewAnnotations =
@@ -5434,9 +5517,13 @@ function ChatViewContent(props: ChatViewProps) {
...sendContextPreviewAnnotations,
{
...directAnnotation.annotation,
screenshot: directAnnotation.annotation.screenshot
? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
: null,
// Claim an attached crop only when the screenshot really rides
// along; a cap-dropped image must not produce a lying prompt.
screenshot:
directAnnotation.annotation.screenshot &&
(annotationImageAppended || annotationImageAlreadyAttached)
? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
: null,
},
]
: sendContextPreviewAnnotations;
@@ -5448,7 +5535,7 @@ function ChatViewContent(props: ChatViewProps) {
hasSendableContent,
} = deriveComposerSendState({
prompt: promptForSend,
imageCount: composerImages.length,
imageCount: composerImages.length + composerFiles.length,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
@@ -5458,6 +5545,7 @@ function ChatViewContent(props: ChatViewProps) {
const feedbackCommand =
ctxSelectedProvider === "codex" &&
composerImages.length === 0 &&
composerFiles.length === 0 &&
sendableComposerTerminalContexts.length === 0 &&
composerElementContexts.length === 0 &&
composerPreviewAnnotations.length === 0 &&
@@ -5550,7 +5638,13 @@ function ChatViewContent(props: ChatViewProps) {
);
return;
}
if (!directAnnotation && showPlanFollowUpPrompt && activeProposedPlan) {
if (
!directAnnotation &&
showPlanFollowUpPrompt &&
activeProposedPlan &&
composerImages.length === 0 &&
composerFiles.length === 0
) {
const followUp = resolvePlanFollowUpSubmission({
draftText: trimmed,
planMarkdown: activeProposedPlan.planMarkdown,
@@ -5579,6 +5673,7 @@ function ChatViewContent(props: ChatViewProps) {
const standaloneSlashCommand =
settings.planModeEnabled &&
composerImages.length === 0 &&
composerFiles.length === 0 &&
sendableComposerTerminalContexts.length === 0 &&
composerElementContexts.length === 0 &&
composerPreviewAnnotations.length === 0 &&
@@ -5635,6 +5730,8 @@ function ChatViewContent(props: ChatViewProps) {
}
const composerImagesSnapshot = [...composerImages];
const composerFilesSnapshot = [...composerFiles];
const composerAttachmentsSnapshot = [...composerImagesSnapshot, ...composerFilesSnapshot];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
const composerElementContextsSnapshot = [...composerElementContexts];
const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations];
@@ -5656,21 +5753,57 @@ function ChatViewContent(props: ChatViewProps) {
model: ctxSelectedModel,
models: ctxSelectedProviderModels,
effort: ctxSelectedPromptEffort,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
});
if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
return;
}
const readLiveAttachmentCapabilities = () => {
const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
const liveSupportsAttachmentUploads =
config?.environment.capabilities.attachmentUploads === true;
return {
supportsAttachmentUploads: liveSupportsAttachmentUploads,
fileBlockReason: fileAttachmentCapabilityBlockReason({
files: composerFilesSnapshot,
attachmentUploadsCapabilityKnown: config !== null,
supportsAttachmentUploads: liveSupportsAttachmentUploads,
maxFileAttachmentBytes:
config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
}),
};
};
sendInFlightRef.current = true;
if (supportsAttachmentUploads && composerImagesSnapshot.length > 0) {
for (const image of composerImagesSnapshot) {
startAttachmentUpload({ environmentId, image });
const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
return;
}
const turnUsesAttachmentUploads =
composerFilesSnapshot.length > 0
? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
: supportsAttachmentUploads;
if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) {
for (const attachment of composerAttachmentsSnapshot) {
startAttachmentUpload({
environmentId,
image: attachment,
draftTarget: composerDraftTarget,
});
}
await awaitAttachmentUploads(composerImagesSnapshot.map((image) => image.id));
if (getUploadedAttachments({ environmentId, images: composerImagesSnapshot }) === null) {
await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities();
if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, "Retry or remove failed image uploads before sending.");
setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
return;
}
if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
return;
}
}
@@ -5699,6 +5832,16 @@ function ChatViewContent(props: ChatViewProps) {
void dockTransition.catch(() => resolveDockStarted?.());
await dockStarted;
}
const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
if (attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, attachmentCapabilitiesBeforeDispatch.fileBlockReason);
setDockedDraftHeroThreadKey((currentThreadKey) =>
currentThreadKey === activeThreadKey ? null : currentThreadKey,
);
return;
}
beginLocalDispatch({
preparingWorktree: Boolean(baseBranchForWorktree),
submissionIntent: resolvedSubmissionIntent,
@@ -5707,31 +5850,45 @@ function ChatViewContent(props: ChatViewProps) {
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => {
if (supportsAttachmentUploads) {
const uploaded = getUploadedAttachments({ environmentId, images: [image] })?.[0];
composerAttachmentsSnapshot.map(async (attachment) => {
if (turnUsesAttachmentUploads) {
const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
if (!uploaded) {
throw new Error(`Image '${image.name}' did not finish uploading.`);
throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
}
return uploaded;
}
if (attachment.type !== "image") {
throw new Error("This server does not support file attachments.");
}
return {
type: "image" as const,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
dataUrl: await readFileAsDataUrl(attachment.file),
};
}),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
const optimisticAttachments = composerAttachmentsSnapshot.map((attachment) =>
attachment.type === "image"
? {
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: attachment.previewUrl,
}
: {
type: "file" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadable: false,
},
);
const shouldAnchorFirstMessage =
activeThread.latestTurn === null &&
!timelineMessages.some((message) => message.role === "user");
@@ -5793,6 +5950,8 @@ function ChatViewContent(props: ChatViewProps) {
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `Image: ${firstComposerImageName}`;
} else if (composerFilesSnapshot[0]) {
titleSeed = `File: ${composerFilesSnapshot[0].name}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
@@ -5839,7 +5998,14 @@ function ChatViewContent(props: ChatViewProps) {
}
}
const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);
const turnAttachmentsResult = await settlePromise(async () => {
const turnAttachments = await turnAttachmentsPromise;
const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
if (liveFileBlockReason !== null) {
throw new Error(liveFileBlockReason);
}
return turnAttachments;
});
if (failure === null && turnAttachmentsResult._tag === "Failure") {
failure = turnAttachmentsResult;
}
@@ -5909,8 +6075,8 @@ function ChatViewContent(props: ChatViewProps) {
failure = startResult;
} else {
turnStartSucceeded = true;
if (supportsAttachmentUploads) {
releaseAttachmentUploads(composerImagesSnapshot);
if (turnUsesAttachmentUploads) {
releaseDraftAttachments(composerAttachmentsSnapshot);
}
acknowledgeActiveThreadWoke();
if (backgroundThreadRef) {
@@ -5967,6 +6133,7 @@ function ChatViewContent(props: ChatViewProps) {
if (
promptRef.current.length === 0 &&
composerImagesRef.current.length === 0 &&
composerFilesRef.current.length === 0 &&
composerTerminalContextsRef.current.length === 0 &&
composerElementContextsRef.current.length === 0 &&
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations
@@ -5985,10 +6152,12 @@ function ChatViewContent(props: ChatViewProps) {
promptRef.current = promptForSend;
const retryComposerImages = composerImagesSnapshot.map(cloneComposerImageForRetry);
composerImagesRef.current = retryComposerImages;
composerFilesRef.current = composerFilesSnapshot;
composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
composerElementContextsRef.current = composerElementContextsSnapshot;
setComposerDraftPrompt(composerDraftTarget, promptForSend);
addComposerDraftImages(composerDraftTarget, retryComposerImages);
addComposerDraftFiles(composerDraftTarget, composerFilesSnapshot);
setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);
setComposerDraftElementContexts(composerDraftTarget, composerElementContextsSnapshot);
setComposerDraftPreviewAnnotations(composerDraftTarget, composerPreviewAnnotationsSnapshot);
@@ -6958,6 +7127,7 @@ function ChatViewContent(props: ChatViewProps) {
onRevertUserMessage={onRevertUserMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
onFileDownload={downloadFileAttachment}
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
@@ -7057,6 +7227,7 @@ function ChatViewContent(props: ChatViewProps) {
environmentId={environmentId}
attachmentUploadsCapabilityKnown={attachmentUploadsCapabilityKnown}
supportsAttachmentUploads={supportsAttachmentUploads}
maxFileAttachmentBytes={maxFileAttachmentBytes}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
@@ -7111,6 +7282,7 @@ function ChatViewContent(props: ChatViewProps) {
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerFilesRef={composerFilesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
+10 -2
View File
@@ -1471,7 +1471,15 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return result;
}
const draftStore = useComposerDraftStore.getState();
releaseProjectDraftUploads(memberProjectRef);
releaseProjectDraftUploads(
memberProjectRef,
sidebarThreads
.filter(
(thread) =>
thread.environmentId === member.environmentId && thread.projectId === member.id,
)
.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
);
const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
if (projectDraftThread) {
draftStore.clearDraftThread(projectDraftThread.draftId);
@@ -1479,7 +1487,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
draftStore.clearProjectDraftThreadId(memberProjectRef);
return result;
},
[deleteProject],
[deleteProject, sidebarThreads],
);
const handleRemoveProject = useCallback(
+1
View File
@@ -495,6 +495,7 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {
// that only the persisted list is populated, hence max not sum.
const attachmentCount =
Math.max(composer.images.length, composer.persistedAttachments.length) +
composer.files.length +
composer.terminalContexts.length +
composer.elementContexts.length +
composer.previewAnnotations.length +
+573 -63
View File
@@ -13,7 +13,6 @@ import type {
TurnId,
} from "@t3tools/contracts";
import {
isProviderSendTurnSupportedImageMimeType,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -51,9 +50,13 @@ import {
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerFileAttachment,
type ComposerImageAttachment,
type DraftId,
type PersistedComposerFileAttachment,
type PersistedComposerImageAttachment,
composerFileNeedsReattach,
composerTargetKey,
hydrateImagesFromPersisted,
useComposerDraftStore,
useComposerThreadDraft,
@@ -73,16 +76,28 @@ import {
type ComposerTaskStep,
type ComposerTasksProgress,
} from "./ComposerTasksBadge";
import { compressImageForStash, prepareImageForAttachment } from "../../lib/imageCompression";
import {
compressImageForStash,
isHeicImageFile,
prepareImageForAttachment,
} from "../../lib/imageCompression";
fileAttachmentTooLargeMessage,
formatAttachmentSize,
} from "@t3tools/client-runtime/state/attachments";
import {
attachmentsToReleaseOnUploadCapabilityLoss,
classifyComposerAttachmentFile,
fileAttachmentCapabilityBlockReason,
fileAttachmentStagingLimit,
normalizeComposerImageFileMimeType,
shouldHandleComposerAttachmentPaste,
} from "./composerAttachmentFiles";
import {
readAttachmentUpload,
releaseAttachmentUpload,
releaseDraftAttachment,
releasePersistedAttachmentUpload,
retryAttachmentUpload,
startAttachmentUpload,
useAttachmentUploadStore,
verifyStashedAttachmentUpload,
} from "../../lib/attachmentUploadQueue";
import {
attachmentUploadBlockReason,
@@ -241,6 +256,8 @@ import { toastManager } from "../ui/toast";
import {
BotIcon,
CircleAlertIcon,
FileIcon,
PaperclipIcon,
PencilRulerIcon,
type LucideIcon,
LockIcon,
@@ -532,6 +549,7 @@ export interface ChatComposerHandle {
getSendContext: () => {
prompt: string;
images: ComposerImageAttachment[];
files: ComposerFileAttachment[];
terminalContexts: TerminalContextDraft[];
elementContexts: ElementContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
@@ -557,6 +575,7 @@ export interface ChatComposerProps {
environmentId: EnvironmentId;
attachmentUploadsCapabilityKnown: boolean;
supportsAttachmentUploads: boolean;
maxFileAttachmentBytes: number | null;
routeKind: "server" | "draft";
routeThreadRef: ScopedThreadRef;
draftId: DraftId | null;
@@ -630,6 +649,7 @@ export interface ChatComposerProps {
// Refs the parent needs kept in sync
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerFilesRef: React.RefObject<ComposerFileAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
@@ -675,6 +695,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
environmentId,
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
maxFileAttachmentBytes,
routeKind,
routeThreadRef,
draftId,
@@ -721,6 +742,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptRef,
composerRef,
composerImagesRef,
composerFilesRef,
composerTerminalContextsRef,
composerElementContextsRef,
onSend,
@@ -745,21 +767,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Store subscriptions (prompt / images / terminal contexts)
// ------------------------------------------------------------------
const composerDraft = useComposerThreadDraft(composerDraftTarget);
// Live target key, for async flows that must notice a thread switch that
// happened while they awaited.
const composerDraftTargetKeyRef = useRef("");
composerDraftTargetKeyRef.current = composerTargetKey(composerDraftTarget);
const prompt = composerDraft.prompt;
const composerImages = composerDraft.images;
const composerFiles = composerDraft.files;
const composerTerminalContexts = composerDraft.terminalContexts;
const composerElementContexts = composerDraft.elementContexts;
const composerPreviewAnnotations = composerDraft.previewAnnotations;
const composerReviewComments = composerDraft.reviewComments;
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
const attachmentBlockReason = supportsAttachmentUploads
? attachmentUploadBlockReason({
imageIds: composerImages.map((image) => image.id),
uploadsByImageId,
environmentId,
})
: null;
const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length;
const fileStagingLimit = fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
maxFileAttachmentBytes,
});
const fileCapabilityBlockReason = fileAttachmentCapabilityBlockReason({
files: composerFiles,
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
maxFileAttachmentBytes,
});
const attachmentBlockReason =
fileCapabilityBlockReason ??
(supportsAttachmentUploads
? needsReattachFileCount > 0
? needsReattachFileCount === 1
? "Attach the interrupted file again or remove it"
: "Attach the interrupted files again or remove them"
: attachmentUploadBlockReason({
imageIds: [...composerImages, ...composerFiles].map((attachment) => attachment.id),
uploadsByImageId,
environmentId,
})
: null);
const sendDisabledReason =
externalSendDisabledReason ?? (activePendingProgress ? null : attachmentBlockReason);
const isSendDisabled = sendDisabledReason !== null;
@@ -768,6 +813,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
const removeComposerDraftFile = useComposerDraftStore((store) => store.removeFile);
const setComposerDraftFileUpload = useComposerDraftStore((store) => store.setFileUpload);
const insertComposerDraftTerminalContext = useComposerDraftStore(
(store) => store.insertTerminalContext,
);
@@ -802,15 +850,76 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
return;
}
if (!supportsAttachmentUploads) {
for (const image of composerImages) {
releaseAttachmentUpload(image.id);
// The capability can flap on reconnect or version skew. Deleting a
// persisted hydrated upload here would make the next send fail
// verification while the file still sits in the draft.
for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss([
...composerImages,
...composerFiles,
])) {
releaseAttachmentUpload(attachment.id);
}
return;
}
for (const image of composerImages) {
startAttachmentUpload({ environmentId, image });
const invalidFiles =
maxFileAttachmentBytes === null
? composerFiles
: composerFiles.filter((file) => file.sizeBytes > maxFileAttachmentBytes);
for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss(invalidFiles)) {
releaseAttachmentUpload(attachment.id);
}
}, [attachmentUploadsCapabilityKnown, composerImages, environmentId, supportsAttachmentUploads]);
const uploadableFiles =
maxFileAttachmentBytes === null
? []
: composerFiles.filter((file) => file.sizeBytes <= maxFileAttachmentBytes);
const uploadableAttachments = [...composerImages, ...uploadableFiles];
for (const attachment of uploadableAttachments) {
// A needs-reattach file has no bytes to upload and no upload to verify.
if (attachment.type === "file" && composerFileNeedsReattach(attachment)) {
continue;
}
startAttachmentUpload({ environmentId, image: attachment, draftTarget: composerDraftTarget });
}
}, [
attachmentUploadsCapabilityKnown,
composerDraftTarget,
composerFiles,
composerImages,
environmentId,
maxFileAttachmentBytes,
supportsAttachmentUploads,
]);
useEffect(() => {
for (const file of composerFiles) {
if (
!attachmentUploadsCapabilityKnown ||
!supportsAttachmentUploads ||
maxFileAttachmentBytes === null ||
file.sizeBytes > maxFileAttachmentBytes
) {
continue;
}
const upload = uploadsByImageId[file.id];
if (upload?.status === "ready" && upload.environmentId === environmentId) {
setComposerDraftFileUpload(
composerDraftTarget,
file.id,
environmentId,
upload.attachmentId,
);
}
}
}, [
attachmentUploadsCapabilityKnown,
composerDraftTarget,
composerFiles,
environmentId,
maxFileAttachmentBytes,
setComposerDraftFileUpload,
supportsAttachmentUploads,
uploadsByImageId,
]);
// ------------------------------------------------------------------
// Model state
@@ -1068,6 +1177,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const attachmentInputRef = useRef<HTMLInputElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerSurfaceRef = useRef<HTMLDivElement>(null);
const providerInputRejectedRef = useRef(false);
@@ -1102,7 +1212,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
() =>
deriveComposerSendState({
prompt,
imageCount: composerImages.length,
imageCount: composerImages.length + composerFiles.length,
terminalContexts: composerTerminalContexts,
elementContextCount:
composerElementContexts.length +
@@ -1111,6 +1221,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}),
[
composerElementContexts.length,
composerFiles.length,
composerImages.length,
composerPreviewAnnotations.length,
composerReviewComments.length,
@@ -1395,6 +1506,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[composerDraftTarget, addComposerDraftImages],
);
const addComposerFilesToDraft = useCallback(
(files: ComposerFileAttachment[]) => {
addComposerDraftFiles(composerDraftTarget, files);
},
[addComposerDraftFiles, composerDraftTarget],
);
const removeComposerImageFromDraft = useCallback(
(imageId: string) => {
releaseAttachmentUpload(imageId);
@@ -1403,6 +1521,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[composerDraftTarget, removeComposerDraftImage],
);
const removeComposerFileFromDraft = useCallback(
(fileId: string) => {
// Release by the draft attachment, not the bare queue key: a hydrated
// file's upload lives server-side under its persisted attachment id.
const file = composerFilesRef.current.find((candidate) => candidate.id === fileId);
if (file) {
releaseDraftAttachment(file);
} else {
releaseAttachmentUpload(fileId);
}
removeComposerDraftFile(composerDraftTarget, fileId);
},
[composerDraftTarget, composerFilesRef, removeComposerDraftFile],
);
const removeComposerTerminalContextFromDraft = useCallback(
(contextId: string) => {
const contextIndex = composerTerminalContexts.findIndex(
@@ -1459,6 +1592,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerImagesRef.current = composerImages;
}, [composerImages, composerImagesRef]);
useEffect(() => {
composerFilesRef.current = composerFiles;
}, [composerFiles, composerFilesRef]);
useEffect(() => {
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts, composerTerminalContextsRef]);
@@ -2127,9 +2264,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Prompt stash (⌘S)
// ------------------------------------------------------------------
// One global queue. Stashed prompts carry only text + images so they can be
// restored into any thread or provider — stash, switch, restore is the
// whole point.
// Files remain tied to the environment that owns their uploaded bytes.
const stashQueue = usePromptStashStore((state) => state.entries);
const stashEntryToQueue = usePromptStashStore((state) => state.stashEntry);
const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
@@ -2157,10 +2292,45 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}, []);
const restoreStashEntry = useCallback(
(entry: PromptStashEntry) => {
// Remove first so a double activation (click + Enter) can't restore twice.
const { entry: taken, durable } = takeStashEntry(entry.id);
if (!taken) return;
async (menuEntry: PromptStashEntry) => {
const filesToVerify = menuEntry.files ?? [];
if (filesToVerify.some((file) => file.environmentId !== environmentId)) {
toastManager.add({
type: "error",
title: "Stashed files belong to another environment",
description: "Restore this prompt in the environment that received its files.",
});
return;
}
setIsStashMenuOpen(false);
// The server sweeps pending uploads after 24 hours, so ask before
// reattaching. An expired upload restores as a needs-reattach row
// instead of a reference the next send would fail to verify. Verify
// BEFORE taking: the take removes the entry from durable storage, and a
// tab closed during this await must still find it there after reload.
const verifications = await Promise.all(
filesToVerify.map((file) =>
verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }),
),
);
const expiredAttachmentIds = new Set(
filesToVerify
.filter((_, index) => verifications[index]?.status === "missing")
.map((file) => file.attachmentId),
);
// A thread switch during the verify await would mix the new thread's
// prompt with this invocation's captured target. Nothing was taken yet,
// so abort and leave the entry restorable where the user now is.
if (composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current) {
return;
}
// The take is also the double-activation guard (click + Enter): the
// second caller finds the entry gone and stops here.
const { entry, durable } = takeStashEntry(menuEntry.id);
if (!entry) return;
if (!durable) {
toastManager.add({
type: "warning",
@@ -2170,7 +2340,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
data: { hideCopyButton: true },
});
}
setIsStashMenuOpen(false);
const currentPrompt = promptRef.current;
// An image-only stash must not append blank lines to whatever is
@@ -2189,6 +2358,121 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
setComposerTrigger(null);
}
let unrestoredFileNames: string[] = [];
const expiredFileNames: string[] = [];
let restoredFileCount = 0;
const stashedFiles = entry.files ?? [];
if (stashedFiles.length > 0) {
const fileDedupKey = (file: {
readonly mimeType: string;
readonly sizeBytes: number;
readonly name: string;
}) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
const composerFilesNow = composerFilesRef.current;
const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
const retainedUploadIds = new Set(
composerFilesNow.flatMap((file) =>
file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [],
),
);
const existingFileKeys = new Set(composerFilesNow.map(fileDedupKey));
const reattachMarkerKeys = new Set(
composerFilesNow.filter(composerFileNeedsReattach).map(fileDedupKey),
);
const duplicateFiles: PersistedComposerFileAttachment[] = [];
const markerReplacements: ComposerFileAttachment[] = [];
const appendedFiles: ComposerFileAttachment[] = [];
for (const file of stashedFiles) {
const expired = expiredAttachmentIds.has(file.attachmentId);
const key = fileDedupKey(file);
const restored: ComposerFileAttachment = {
type: "file",
id: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: null,
// An expired upload carries no ids, so it hydrates as a
// needs-reattach row and the "Attach again" flow takes over.
...(expired
? {}
: { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }),
};
if (existingFileIds.has(file.id)) {
if (!expired && !retainedUploadIds.has(file.attachmentId)) {
duplicateFiles.push(file);
}
continue;
}
if (existingFileKeys.has(key)) {
if (reattachMarkerKeys.has(key)) {
// The draft row with this identity is a needs-reattach marker,
// not a real duplicate. Replace it (addFiles swaps a matching
// marker in place) instead of deleting the only uploaded copy.
reattachMarkerKeys.delete(key);
existingFileIds.add(file.id);
if (expired) {
// The draft's marker already says "attach again"; nothing to
// restore or release, but say why the stash copy is gone.
expiredFileNames.push(file.name);
} else {
retainedUploadIds.add(file.attachmentId);
markerReplacements.push(restored);
}
continue;
}
if (!expired && !retainedUploadIds.has(file.attachmentId)) {
duplicateFiles.push(file);
}
continue;
}
existingFileIds.add(file.id);
existingFileKeys.add(key);
if (expired) {
expiredFileNames.push(file.name);
} else {
retainedUploadIds.add(file.attachmentId);
}
appendedFiles.push(restored);
}
const capacity = Math.max(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS -
composerImagesRef.current.length -
composerFilesNow.length,
);
// Marker replacements reuse their marker's slot; only appended files
// consume capacity.
const filesToAppend = appendedFiles.slice(0, capacity);
const skippedFiles = appendedFiles.slice(capacity);
unrestoredFileNames = skippedFiles.map((file) => file.name);
// A non-durable take can resurrect the stash entry after a reload;
// deleting these uploads would leave it pointing at nothing.
if (durable) {
for (const file of duplicateFiles) {
releasePersistedAttachmentUpload({
id: file.id,
environmentId,
attachmentId: file.attachmentId,
});
}
for (const file of skippedFiles) {
if (file.uploadedAttachmentId) {
releasePersistedAttachmentUpload({
id: file.id,
environmentId,
attachmentId: file.uploadedAttachmentId,
});
}
}
}
const restoredFiles = [...markerReplacements, ...filesToAppend];
if (restoredFiles.length > 0) {
addComposerDraftFiles(composerDraftTarget, restoredFiles);
restoredFileCount = filesToAppend.length;
}
}
let unrestoredImageNames: string[] = [];
if (entry.attachments.length > 0) {
const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
@@ -2203,7 +2487,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
const capacity = Math.max(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS - composerImagesRef.current.length,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS -
composerImagesRef.current.length -
composerFilesRef.current.length -
restoredFileCount,
);
const pending = entry.attachments.filter(
(attachment) =>
@@ -2242,13 +2529,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
if (unrestoredImageNames.length > 0) {
missingImageReasons.push(
`${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-image limit.`,
`${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
);
}
if (unrestoredFileNames.length > 0) {
missingImageReasons.push(
`${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`,
);
}
if (expiredFileNames.length > 0) {
missingImageReasons.push(
`${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`,
);
}
if (missingImageReasons.length > 0) {
toastManager.add({
type: "warning",
title: "Some images were not restored",
title: "Some attachments were not restored",
description: missingImageReasons.join(" "),
});
}
@@ -2262,9 +2559,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
},
[
addComposerDraftFiles,
addComposerDraftImages,
composerDraftTarget,
composerFilesRef,
composerImagesRef,
environmentId,
promptRef,
setComposerDraftPrompt,
takeStashEntry,
@@ -2273,7 +2573,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const deleteStashEntry = useCallback(
(entry: PromptStashEntry) => {
const { durable } = takeStashEntry(entry.id);
const { entry: removed, durable } = takeStashEntry(entry.id);
if (durable && removed) {
for (const file of removed.files ?? []) {
releasePersistedAttachmentUpload({
id: file.id,
environmentId: file.environmentId,
attachmentId: file.attachmentId,
});
}
}
if (!durable) {
toastManager.add({
type: "warning",
@@ -2292,17 +2601,45 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// round-trip, so they are stripped from the stashed prompt.
const prompt = promptRef.current.split(INLINE_TERMINAL_CONTEXT_PLACEHOLDER).join("").trim();
const images = [...composerImagesRef.current];
if (prompt.length === 0 && images.length === 0) {
const files = [...composerFilesRef.current];
if (prompt.length === 0 && images.length === 0 && files.length === 0) {
setIsStashMenuOpen((open) => !open);
return;
}
const stashedFiles: PersistedComposerFileAttachment[] = [];
for (const file of files) {
if (composerFileNeedsReattach(file)) {
toastManager.add({
type: "error",
title: "Attach dropped files again or remove them before stashing",
});
return;
}
const upload = readAttachmentUpload(file.id);
if (upload?.status !== "ready" || upload.environmentId !== environmentId) {
toastManager.add({
type: "error",
title: "Wait for file uploads before stashing this prompt",
});
return;
}
stashedFiles.push({
id: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
attachmentId: upload.attachmentId,
environmentId,
});
}
// A repeat ⌘S on the *same* still-unencoded snapshot would stash it
// twice. Guard on the snapshot itself rather than a bare boolean: once
// the composer has been cleared the user can type something genuinely
// new (or switch threads) while encoding continues, and that deserves its
// own entry.
const snapshotKey = `${String(composerDraftTarget)}${prompt}${images
.map((image) => image.id)
.map((image) => `image:${image.id}`)
.concat(files.map((file) => `file:${file.id}`))
.join(",")}`;
if (stashInFlightRef.current.has(snapshotKey)) return;
stashInFlightRef.current.add(snapshotKey);
@@ -2320,6 +2657,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
createdAt: new Date().toISOString(),
prompt,
attachments: [],
...(stashedFiles.length > 0 ? { files: stashedFiles } : {}),
droppedImageNames: [],
unreadableImageNames: [],
pendingImageCount: images.length,
@@ -2352,9 +2690,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
});
}
// 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.
// Terminal and preview context stays behind because the stash cannot restore it.
promptRef.current = "";
clearComposerDraftPromptAndImages(stashTarget);
for (const image of images) {
@@ -2365,6 +2701,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
pulseStashBadge();
if (evicted) {
for (const file of evicted.files ?? []) {
releasePersistedAttachmentUpload({
id: file.id,
environmentId: file.environmentId,
attachmentId: file.attachmentId,
});
}
toastManager.add({
type: "warning",
title: "Oldest stashed prompt discarded",
@@ -2440,7 +2783,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}, [
clearComposerDraftPromptAndImages,
composerDraftTarget,
composerFilesRef,
composerImagesRef,
environmentId,
finalizeStashEntryImages,
promptRef,
pulseStashBadge,
@@ -2586,14 +2931,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
]);
// ------------------------------------------------------------------
// Callbacks: images
// Callbacks: attachments
// ------------------------------------------------------------------
const addComposerImages = async (files: File[]) => {
const addComposerAttachments = async (files: File[]) => {
if (!activeThreadId || files.length === 0) return;
if (pendingUserInputs.length > 0) {
toastManager.add({
type: "error",
title: "Attach images after answering plan questions.",
title: "Attach files after answering plan questions.",
});
return;
}
@@ -2606,34 +2951,75 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// accepted files reserve their attachment slots (via the pending counter)
// before the first await, keeping the total under the limit.
const pendingCount = pendingImageCompressionsRef.current.get(threadId) ?? 0;
let reservedCount = composerImagesRef.current.length + pendingCount;
const acceptedFiles: File[] = [];
let reservedCount =
composerImagesRef.current.length + composerFilesRef.current.length + pendingCount;
// A pick that matches a needs-reattach marker replaces it in the draft, so
// it must not consume a slot; a draft full of markers would otherwise hit
// the capacity error before the replacement path could run.
const reattachKeys = new Set(
composerFilesRef.current
.filter(composerFileNeedsReattach)
.map((file) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`),
);
const acceptedImages: File[] = [];
const acceptedFiles: ComposerFileAttachment[] = [];
let error: string | null = null;
for (const file of files) {
const isHeicImage = isHeicImageFile(file);
if (!file.type.startsWith("image/") && !isHeicImage) {
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
const attachmentKind = classifyComposerAttachmentFile(file);
const replacesReattachMarker =
attachmentKind === "file" &&
reattachKeys.delete(
`${file.type || "application/octet-stream"}\u0000${file.size}\u0000${file.name || "file"}`,
);
if (!replacesReattachMarker && reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
// Keep scanning: a later file in this batch can still replace a
// needs-reattach marker without needing a free slot.
continue;
}
if (!isHeicImage && !isProviderSendTurnSupportedImageMimeType(file.type)) {
if (attachmentKind === "unsupported-image") {
error = `'${file.name}' is not a supported image type. Attach GIF, HEIC, HEIF, JPEG, PNG, or WebP images.`;
continue;
}
if (reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
if (attachmentKind === "image") {
acceptedImages.push(normalizeComposerImageFileMimeType(file));
} else {
if (fileStagingLimit === null) {
error = "This server does not support file attachments.";
continue;
}
if (file.size <= 0) {
error = `'${file.name}' is empty or could not be read.`;
continue;
}
if (file.size > fileStagingLimit) {
error = fileAttachmentTooLargeMessage(file.name, fileStagingLimit);
continue;
}
acceptedFiles.push({
type: "file",
id: randomUUID(),
name: file.name || "file",
mimeType: file.type || "application/octet-stream",
sizeBytes: file.size,
file,
});
}
if (!replacesReattachMarker) {
reservedCount += 1;
}
acceptedFiles.push(file);
reservedCount += 1;
}
setThreadError(threadId, error);
if (acceptedFiles.length === 0) return;
if (acceptedFiles.length > 0) {
addComposerFilesToDraft(acceptedFiles);
}
if (acceptedImages.length === 0) return;
pendingImageCompressionsRef.current.set(threadId, pendingCount + acceptedFiles.length);
pendingImageCompressionsRef.current.set(threadId, pendingCount + acceptedImages.length);
try {
const nextImages: ComposerImageAttachment[] = [];
let compressionError: string | null = null;
for (const file of acceptedFiles) {
for (const file of acceptedImages) {
// Images over the wire cap are downscaled to fit rather than
// refused; files already within it pass through byte-for-byte.
const compressed = await prepareImageForAttachment(
@@ -2673,7 +3059,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
} finally {
const remaining =
(pendingImageCompressionsRef.current.get(threadId) ?? 0) - acceptedFiles.length;
(pendingImageCompressionsRef.current.get(threadId) ?? 0) - acceptedImages.length;
if (remaining > 0) {
pendingImageCompressionsRef.current.set(threadId, remaining);
} else {
@@ -2691,13 +3077,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) return;
const imageFiles = files.filter(
(file) => file.type.startsWith("image/") || isHeicImageFile(file),
);
if (imageFiles.length === 0) return;
// Claimable pastes go through even when plan questions are pending or the
// composer is at its attachment limit: `addComposerAttachments` surfaces
// those as a toast and a thread error. An early return here would swallow
// the paste with no feedback.
if (
files.length === 0 ||
!activeThreadId ||
!shouldHandleComposerAttachmentPaste({
files,
plainText: event.clipboardData.getData("text/plain"),
})
) {
return;
}
event.preventDefault();
void addComposerImages(imageFiles);
void addComposerAttachments(files);
};
const insertComposerTextAtEnd = (
@@ -2823,7 +3218,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerEditorRef.current?.focusAt(cursor);
},
addDroppedFiles: (files: File[]) => {
void addComposerImages(files);
void addComposerAttachments(files);
focusComposer();
},
insertTextAtEnd: insertComposerTextAtEnd,
@@ -2894,6 +3289,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
getSendContext: () => ({
prompt: promptRef.current,
images: composerImagesRef.current,
files: composerFilesRef.current,
terminalContexts: composerTerminalContextsRef.current,
elementContexts: composerElementContextsRef.current,
previewAnnotations: composerPreviewAnnotations,
@@ -2919,13 +3315,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}),
[
activeThread,
addComposerImages,
addComposerAttachments,
composerDraftTarget,
composerCursor,
composerTerminalContexts,
insertComposerDraftTerminalContext,
promptRef,
composerImagesRef,
composerFilesRef,
composerTerminalContextsRef,
composerElementContextsRef,
composerPreviewAnnotations,
@@ -3241,7 +3638,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? {
uploadsByImageId,
onRetryUpload: (image: ComposerImageAttachment) =>
retryAttachmentUpload({ environmentId, image }),
retryAttachmentUpload({
environmentId,
image,
draftTarget: composerDraftTarget,
}),
}
: {})}
onRemove={(annotationId) => {
@@ -3367,7 +3768,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
size="icon-xs"
className="absolute bottom-1 left-1 bg-background/85 hover:bg-background/95"
onClick={() =>
retryAttachmentUpload({ environmentId, image })
retryAttachmentUpload({
environmentId,
image,
draftTarget: composerDraftTarget,
})
}
aria-label={`Retry upload for ${image.name}`}
/>
@@ -3398,6 +3803,78 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</div>
)}
{!isComposerCollapsedMobile &&
!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerFiles.length > 0 && (
<div className="mb-3 flex flex-col gap-1">
{composerFiles.map((file) => {
const fileCanUpload =
supportsAttachmentUploads &&
maxFileAttachmentBytes !== null &&
file.sizeBytes <= maxFileAttachmentBytes;
const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
const needsReattach = composerFileNeedsReattach(file);
const canReattachFile =
fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
return (
<div
key={file.id}
className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
>
<FileIcon className="size-4 shrink-0 text-secondary-label" />
<span className="min-w-0 flex-1 truncate">{file.name}</span>
<span className="shrink-0 text-xs text-secondary-label">
{needsReattach
? canReattachFile
? "Attach again"
: "Remove to send"
: upload?.status === "uploading"
? formatAttachmentUploadProgress(upload.progress)
: formatAttachmentSize(file.sizeBytes)}
</span>
{!needsReattach && upload?.status === "failed" ? (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="ghost"
size="icon-xs"
onClick={() =>
retryAttachmentUpload({
environmentId,
image: file,
draftTarget: composerDraftTarget,
})
}
aria-label={`Retry upload for ${file.name}`}
/>
}
>
<RotateCcwIcon />
</TooltipTrigger>
<TooltipPopup
side="top"
className="max-w-64 whitespace-normal leading-tight"
>
{upload.reason}
</TooltipPopup>
</Tooltip>
) : null}
<Button
variant="ghost"
size="icon-xs"
onClick={() => removeComposerFileFromDraft(file.id)}
aria-label={`Remove ${file.name}`}
>
<XIcon />
</Button>
</div>
);
})}
</div>
)}
<div className="relative">
<ComposerPromptEditor
editorRef={composerEditorRef}
@@ -3568,6 +4045,39 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
}
className="flex shrink-0 flex-nowrap items-center justify-end gap-2"
>
{fileStagingLimit !== null && pendingUserInputs.length === 0 ? (
<>
<input
ref={attachmentInputRef}
type="file"
multiple
className="hidden"
onChange={(event) => {
const files = Array.from(event.currentTarget.files ?? []);
event.currentTarget.value = "";
void addComposerAttachments(files);
focusComposer();
}}
/>
<Tooltip>
<TooltipTrigger
render={
<Button
type="button"
variant="ghost"
size="icon-sm"
onPointerDown={(event) => event.preventDefault()}
onClick={() => attachmentInputRef.current?.click()}
aria-label="Attach files"
/>
}
>
<PaperclipIcon />
</TooltipTrigger>
<TooltipPopup>Attach files</TooltipPopup>
</Tooltip>
</>
) : null}
{showMobilePendingAnswerActions ? null : inlineTasksBadge}
{showMobilePendingAnswerActions ? null : inlineStashBadge}
<ComposerFooterPrimaryActions
@@ -1,4 +1,5 @@
import { renderToStaticMarkup } from "react-dom/server";
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { ComposerStashMenu } from "./ComposerStashMenu";
@@ -89,4 +90,45 @@ describe("ComposerStashMenu", () => {
expect(markup).toContain("size-3.5 stroke-2");
expect(markup).not.toContain("bg-background/90");
});
it("labels mixed file and image stashes without treating images as files", () => {
const markup = renderToStaticMarkup(
<ComposerStashMenu
entries={[
{
id: "mixed-attachments",
createdAt: new Date(0).toISOString(),
prompt: "",
attachments: [
{
id: "image-one",
name: "before.png",
mimeType: "image/png",
sizeBytes: 128,
dataUrl: "data:image/png;base64,AA==",
},
],
files: [
{
id: "file-one",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
attachmentId: "pending-report-pdf",
environmentId: EnvironmentId.make("environment-1"),
},
],
droppedImageNames: [],
},
]}
onRestore={() => {}}
onDelete={() => {}}
onClose={() => {}}
/>,
);
expect(markup).toContain("(2 attachments)");
expect(markup).toContain("size-3.5 text-secondary-label");
expect(markup).not.toContain("(2 files)");
});
});
@@ -1,4 +1,4 @@
import { XIcon } from "lucide-react";
import { FileIcon, XIcon } from "lucide-react";
import { memo, useEffect, useRef, useState } from "react";
import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -20,7 +20,13 @@ function stashEntrySnippet(entry: PromptStashEntry): string {
return trimmed.length > SNIPPET_MAX_CHARS ? `${trimmed.slice(0, SNIPPET_MAX_CHARS)}…` : trimmed;
}
const imageCount = entry.attachments.length + entry.droppedImageNames.length;
return imageCount > 0 ? `(${imageCount} image${imageCount === 1 ? "" : "s"})` : "(empty)";
const fileCount = entry.files?.length ?? 0;
const attachmentCount = imageCount + fileCount;
if (attachmentCount === 0) {
return "(empty)";
}
const label = imageCount > 0 && fileCount > 0 ? "attachment" : fileCount > 0 ? "file" : "image";
return `(${attachmentCount} ${label}${attachmentCount === 1 ? "" : "s"})`;
}
/**
@@ -180,6 +186,12 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
))}
</span>
) : null}
{(entry.files?.length ?? 0) > 0 ? (
<span className="flex shrink-0 items-center gap-1 text-secondary-label text-xs">
<FileIcon className="size-3.5 text-secondary-label" />
{entry.files!.length}
</span>
) : null}
<span className="shrink-0 text-secondary-label text-xs max-sm:hidden">
{formatRelativeTimeLabel(entry.createdAt)}
</span>
@@ -558,6 +558,116 @@ describe("MessagesTimeline", () => {
expect(onAnchorReady).not.toHaveBeenCalled();
});
it("renders generic attachments as download links instead of image previews", () => {
const entry = {
...buildUserTimelineEntry("Read the report."),
message: {
...buildUserTimelineEntry("Read the report.").message,
attachments: [
{
type: "file" as const,
id: "attachment-report-pdf",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
previewUrl: "https://environment.test/api/assets/report.pdf",
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain(
'<a href="https://environment.test/api/assets/report.pdf" download="report.pdf" class="flex min-w-0 items-center gap-2 rounded-md py-1 text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">',
);
expect(markup).not.toContain('alt="report.pdf"');
});
it("renders a file download button without creating its URL in advance", () => {
const entry = {
...buildUserTimelineEntry("Read the report."),
message: {
...buildUserTimelineEntry("Read the report.").message,
attachments: [
{
type: "file" as const,
id: "attachment-report-pdf",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain(
'<button type="button" aria-label="Download report.pdf" class="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70">',
);
expect(markup).not.toContain("href=");
});
it("does not download an optimistic file before the server supplies its attachment ID", () => {
const entry = {
...buildUserTimelineEntry("Read the report."),
message: {
...buildUserTimelineEntry("Read the report.").message,
attachments: [
{
type: "file" as const,
id: "composer-local-report",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
downloadable: false,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain("report.pdf");
expect(markup).not.toContain('aria-label="Download report.pdf"');
});
it("renders unknown attachment types as inert rows instead of crashing", () => {
const entry = {
...buildUserTimelineEntry("Play the recording."),
message: {
...buildUserTimelineEntry("Play the recording.").message,
attachments: [
{
// A newer server can introduce attachment types this build does
// not know. They ride the open contract member.
type: "recording",
id: "attachment-voice-memo",
name: "voice-memo.ogg",
mimeType: "audio/ogg",
sizeBytes: 42,
},
],
},
};
const markup = renderToStaticMarkup(
<MessagesTimeline {...buildProps()} timelineEntries={[entry]} />,
);
expect(markup).toContain("voice-memo.ogg");
expect(markup).not.toContain('aria-label="Download voice-memo.ogg"');
expect(markup).not.toContain('alt="voice-memo.ogg"');
expect(markup).not.toContain("href=");
});
it("keeps reserved end space when tool work starts while reading history", () => {
const turnId = TurnId.make("turn-with-active-tool");
const firstEntry = buildUserTimelineEntry("Run the command.");
@@ -1,4 +1,5 @@
import {
type ChatFileAttachment,
type EnvironmentId,
type MessageId,
type ScopedThreadRef,
@@ -14,6 +15,7 @@ import {
const EMPTY_AGENT_PANEL_MODEL = emptyAgentPanelModel();
const NOOP_OPEN_AGENTS = () => {};
const NOOP_DOWNLOAD_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import {
createContext,
@@ -38,7 +40,12 @@ import {
workEntrySignalsSevereFailure,
workLogEntryIsToolLike,
} from "../../session-logic";
import { type ChatImageAttachment, isImageAttachment, type TurnDiffSummary } from "../../types";
import {
type ChatImageAttachment,
isFileAttachment,
isImageAttachment,
type TurnDiffSummary,
} from "../../types";
import {
getRenderablePatch,
resolveDiffThemeName,
@@ -51,7 +58,9 @@ import {
ChevronDownIcon,
ChevronRightIcon,
CircleAlertIcon,
DownloadIcon,
EyeIcon,
FileIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -143,6 +152,7 @@ interface TimelineRowSharedState {
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
onFileDownload: (attachment: ChatFileAttachment) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
@@ -221,6 +231,7 @@ interface MessagesTimelineProps {
onRevertUserMessage: (messageId: MessageId) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (preview: ExpandedImagePreview) => void;
onFileDownload?: (attachment: ChatFileAttachment) => void;
activeThreadEnvironmentId: EnvironmentId;
markdownCwd: string | undefined;
resolvedTheme: "light" | "dark";
@@ -266,6 +277,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
isRevertingCheckpoint,
onImageExpand,
onFileDownload = NOOP_DOWNLOAD_ATTACHMENT,
activeThreadEnvironmentId,
markdownCwd,
resolvedTheme,
@@ -524,6 +536,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
onFileDownload,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
@@ -540,6 +553,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
onFileDownload,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
@@ -986,7 +1000,13 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
const ctx = use(TimelineRowCtx);
// The attachment union has an open member, so guards (not literal type
// comparisons) split it. Unknown types render as inert rows below the files.
const userImages = (row.message.attachments ?? []).filter(isImageAttachment);
const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
const unknownAttachments = (row.message.attachments ?? []).filter(
(attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
);
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
const terminalContexts = displayedUserMessage.contexts;
const previewAnnotations: ParsedPreviewAnnotation[] = [];
@@ -1011,7 +1031,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
<div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
{regularImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{regularImages.map((image: ChatImageAttachment) => (
{regularImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
@@ -1049,6 +1069,51 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
image={previewImages[index] ?? null}
/>
))}
{userFiles.length > 0 || unknownAttachments.length > 0 ? (
<div className="mb-2 flex flex-col gap-1">
{userFiles.map((file) => {
const content = (
<>
<FileIcon className="size-4 shrink-0 text-secondary-label" />
<span className="min-w-0 flex-1 truncate">{file.name}</span>
{file.downloadable === false ? null : (
<DownloadIcon className="size-4 shrink-0" />
)}
</>
);
return file.previewUrl ? (
<a
key={file.id}
href={file.previewUrl}
download={file.name}
className="flex min-w-0 items-center gap-2 rounded-md py-1 text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
>
{content}
</a>
) : file.downloadable === false ? (
<div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
{content}
</div>
) : (
<button
key={file.id}
type="button"
aria-label={`Download ${file.name}`}
onClick={() => ctx.onFileDownload(file)}
className="flex min-w-0 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
>
{content}
</button>
);
})}
{unknownAttachments.map((attachment) => (
<div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
<FileIcon className="size-4 shrink-0 text-secondary-label" />
<span className="min-w-0 flex-1 truncate">{attachment.name}</span>
</div>
))}
</div>
) : null}
{elementContexts.length > 0 ? (
<div className="mb-2 flex flex-wrap gap-1.5">
{elementContexts.map((context) => (
@@ -0,0 +1,280 @@
import { EnvironmentId, PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
import {
attachmentsToReleaseOnUploadCapabilityLoss,
classifyComposerAttachmentFile,
fileAttachmentCapabilityBlockReason,
fileAttachmentStagingLimit,
inferImageMimeTypeFromName,
normalizeComposerImageFileMimeType,
shouldHandleComposerAttachmentPaste,
} from "./composerAttachmentFiles";
describe("composer attachment files", () => {
it("keeps supported images and HEIC photos on the image path", () => {
expect(classifyComposerAttachmentFile({ name: "photo.png", type: "image/png" })).toBe("image");
expect(classifyComposerAttachmentFile({ name: "photo.heic", type: "" })).toBe("image");
});
it("rejects unsupported image types instead of attaching them as generic files", () => {
expect(classifyComposerAttachmentFile({ name: "diagram.svg", type: "image/svg+xml" })).toBe(
"unsupported-image",
);
expect(classifyComposerAttachmentFile({ name: "photo.tiff", type: "image/tiff" })).toBe(
"unsupported-image",
);
expect(classifyComposerAttachmentFile({ name: "report.pdf", type: "application/pdf" })).toBe(
"file",
);
});
it("preserves text paste when an application adds a synthetic generic file", () => {
const file = new File(["clipboard"], "clipboard.rtf", { type: "application/rtf" });
expect(
shouldHandleComposerAttachmentPaste({
files: [file],
plainText: "Copied text",
}),
).toBe(false);
});
it("claims unsupported image pastes so the composer can report them", () => {
const images = [
new File(["svg"], "diagram.svg", { type: "image/svg+xml" }),
new File(["tiff"], "photo.tiff", { type: "image/tiff" }),
];
for (const image of images) {
expect(
shouldHandleComposerAttachmentPaste({
files: [image],
plainText: "Image caption",
}),
).toBe(true);
}
});
it("claims generic file-only pastes so the composer can report validation errors", () => {
const file = new File(["report"], "report.pdf", { type: "application/pdf" });
expect(shouldHandleComposerAttachmentPaste({ files: [file], plainText: "" })).toBe(true);
});
it("routes empty and oversized generic files to composer feedback", () => {
const empty = new File([], "empty.txt", { type: "text/plain" });
const oversized = new File([new Uint8Array(1024)], "large.zip", {
type: "application/zip",
});
expect(shouldHandleComposerAttachmentPaste({ files: [empty], plainText: "" })).toBe(true);
expect(shouldHandleComposerAttachmentPaste({ files: [oversized], plainText: "" })).toBe(true);
});
it("ignores an empty clipboard", () => {
expect(shouldHandleComposerAttachmentPaste({ files: [], plainText: "" })).toBe(false);
});
it("falls back to the extension when an image arrives without a MIME type", () => {
expect(classifyComposerAttachmentFile({ name: "photo.jpg", type: "" })).toBe("image");
expect(classifyComposerAttachmentFile({ name: "shot.PNG", type: "" })).toBe("image");
expect(classifyComposerAttachmentFile({ name: "archive.zip", type: "" })).toBe("file");
expect(classifyComposerAttachmentFile({ name: "no-extension", type: "" })).toBe("file");
expect(inferImageMimeTypeFromName("photo.jpg")).toBe("image/jpeg");
expect(inferImageMimeTypeFromName("archive.zip")).toBeNull();
});
it("infers supported image types from octet-stream files", () => {
const jpeg = new File(["jpeg"], "photo.jpg", { type: "application/octet-stream" });
const png = new File(["png"], "shot.PNG", { type: "application/octet-stream" });
expect(classifyComposerAttachmentFile(jpeg)).toBe("image");
expect(classifyComposerAttachmentFile(png)).toBe("image");
expect(normalizeComposerImageFileMimeType(jpeg).type).toBe("image/jpeg");
expect(normalizeComposerImageFileMimeType(png).type).toBe("image/png");
});
it("does not infer images for unknown extensions or specific conflicting MIME types", () => {
const binary = new File(["binary"], "archive.bin", { type: "application/octet-stream" });
const unknownDocument = new File(["pdf"], "report.pdf", {
type: "application/octet-stream",
});
const document = new File(["pdf"], "photo.jpg", { type: "application/pdf" });
const explicitImage = new File(["png"], "photo.jpg", { type: "image/png" });
expect(classifyComposerAttachmentFile(binary)).toBe("file");
expect(classifyComposerAttachmentFile(unknownDocument)).toBe("file");
expect(classifyComposerAttachmentFile(document)).toBe("file");
expect(classifyComposerAttachmentFile(explicitImage)).toBe("image");
expect(normalizeComposerImageFileMimeType(binary)).toBe(binary);
expect(normalizeComposerImageFileMimeType(document)).toBe(document);
expect(normalizeComposerImageFileMimeType(explicitImage)).toBe(explicitImage);
});
it("uses the hard local limit while server config is unknown", () => {
expect(
fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown: false,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: null,
}),
).toBe(PROVIDER_SEND_TURN_MAX_FILE_BYTES);
expect(
fileAttachmentCapabilityBlockReason({
files: [{ name: "pending.zip", sizeBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES }],
attachmentUploadsCapabilityKnown: false,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: null,
}),
).toBe("Waiting for the server before file attachments can send");
});
it("rejects local staging and send when known config has no file support", () => {
const unsupportedReason =
"This server does not accept file attachments right now. Remove the files to send.";
expect(
fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: null,
}),
).toBeNull();
expect(
fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: 50 * 1024 * 1024,
}),
).toBeNull();
expect(
fileAttachmentCapabilityBlockReason({
files: [{ name: "report.pdf", sizeBytes: 1024 }],
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: null,
}),
).toBe(unsupportedReason);
expect(
fileAttachmentCapabilityBlockReason({
files: [{ name: "report.pdf", sizeBytes: 1024 }],
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: 50 * 1024 * 1024,
}),
).toBe(unsupportedReason);
});
it("blocks retained files that exceed a newly lower server limit", () => {
expect(
fileAttachmentCapabilityBlockReason({
files: [{ name: "large.zip", sizeBytes: 2 * 1024 * 1024 }],
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: 1024 * 1024,
}),
).toBe("'large.zip' exceeds the 1 MB attachment limit.");
});
it("uses the confirmed server limit without exceeding the hard cap", () => {
expect(
fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: 1024 * 1024,
}),
).toBe(1024 * 1024);
expect(
fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES * 2,
}),
).toBe(PROVIDER_SEND_TURN_MAX_FILE_BYTES);
expect(
fileAttachmentCapabilityBlockReason({
files: [{ name: "report.pdf", sizeBytes: 1024 }],
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: true,
maxFileAttachmentBytes: 50 * 1024 * 1024,
}),
).toBeNull();
});
it("does not block empty or image-only composers on legacy servers", () => {
expect(
fileAttachmentCapabilityBlockReason({
files: [],
attachmentUploadsCapabilityKnown: true,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: null,
}),
).toBeNull();
expect(
fileAttachmentCapabilityBlockReason({
files: [],
attachmentUploadsCapabilityKnown: false,
supportsAttachmentUploads: false,
maxFileAttachmentBytes: null,
}),
).toBeNull();
});
it("keeps draft-persisted file uploads when the upload capability flips off", () => {
const environmentId = EnvironmentId.make("environment-1");
const image: ComposerImageAttachment = {
type: "image",
id: "image-1",
name: "photo.png",
mimeType: "image/png",
sizeBytes: 3,
previewUrl: "blob:photo",
file: new File([new Uint8Array([1, 2, 3])], "photo.png", { type: "image/png" }),
};
const uploadingFile: ComposerFileAttachment = {
type: "file",
id: "file-uploading",
name: "fresh.pdf",
mimeType: "application/pdf",
sizeBytes: 3,
file: new File([new Uint8Array([1, 2, 3])], "fresh.pdf", { type: "application/pdf" }),
};
const hydratedFile: ComposerFileAttachment = {
type: "file",
id: "file-hydrated",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 3,
file: null,
uploadedAttachmentId: "pending-report-pdf",
uploadEnvironmentId: environmentId,
};
const uploadedLocalFile: ComposerFileAttachment = {
...uploadingFile,
id: "file-uploaded-local",
uploadedAttachmentId: "pending-fresh-pdf",
uploadEnvironmentId: environmentId,
};
const released = attachmentsToReleaseOnUploadCapabilityLoss([
image,
uploadingFile,
hydratedFile,
uploadedLocalFile,
]);
expect(released.map((attachment) => attachment.id)).toEqual(["image-1", "file-uploading"]);
});
it("claims image pastes even when clipboard text is present", () => {
const image = new File(["image"], "photo.heic", { type: "image/heic" });
expect(
shouldHandleComposerAttachmentPaste({
files: [image],
plainText: "Image caption",
}),
).toBe(true);
});
});
@@ -0,0 +1,153 @@
import {
isProviderSendTurnSupportedImageMimeType,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
} from "@t3tools/contracts";
import {
clampFileAttachmentUploadBytes,
fileAttachmentTooLargeMessage,
} from "@t3tools/client-runtime/state/attachments";
import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore";
import { isHeicImageFile } from "../../lib/imageCompression";
type ComposerAttachmentFileKind = "image" | "file" | "unsupported-image";
interface FileAttachmentCapabilityState {
readonly attachmentUploadsCapabilityKnown: boolean;
readonly supportsAttachmentUploads: boolean;
readonly maxFileAttachmentBytes: number | null;
}
const IMAGE_MIME_TYPE_BY_EXTENSION: Readonly<Record<string, string>> = {
gif: "image/gif",
jpeg: "image/jpeg",
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
};
/**
* Some sources (drags from other apps, files piped through a shell) hand over
* a `File` with an empty or generic MIME type. Maps the extension to a
* provider-supported image type so a plain `photo.jpg` still lands on the
* image path; anything unrecognized stays a generic file.
*/
export function inferImageMimeTypeFromName(name: string): string | null {
const dotIndex = name.lastIndexOf(".");
if (dotIndex <= 0) {
return null;
}
return IMAGE_MIME_TYPE_BY_EXTENSION[name.slice(dotIndex + 1).toLowerCase()] ?? null;
}
function inferImageMimeTypeForUnknownFile(file: Pick<File, "name" | "type">): string | null {
const mimeType = file.type.toLowerCase();
if (mimeType !== "" && mimeType !== "application/octet-stream") {
return null;
}
return inferImageMimeTypeFromName(file.name);
}
/** Give extension-recognized images a concrete type before compression. */
export function normalizeComposerImageFileMimeType(file: File): File {
const inferredMimeType = inferImageMimeTypeForUnknownFile(file);
if (!inferredMimeType) {
return file;
}
return new File([file], file.name, {
type: inferredMimeType,
lastModified: file.lastModified,
});
}
export function classifyComposerAttachmentFile(
file: Pick<File, "name" | "type">,
): ComposerAttachmentFileKind {
if (isHeicImageFile(file)) {
return "image";
}
if (inferImageMimeTypeForUnknownFile(file)) {
return "image";
}
if (!file.type.toLowerCase().startsWith("image/")) {
return "file";
}
return isProviderSendTurnSupportedImageMimeType(file.type) ? "image" : "unsupported-image";
}
/** Byte limit for adding a generic file to the local composer draft. */
export function fileAttachmentStagingLimit(input: FileAttachmentCapabilityState): number | null {
if (!input.attachmentUploadsCapabilityKnown) {
return PROVIDER_SEND_TURN_MAX_FILE_BYTES;
}
if (!input.supportsAttachmentUploads || input.maxFileAttachmentBytes === null) {
return null;
}
return clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
}
/** Why retained generic files cannot send with the current server config. */
export function fileAttachmentCapabilityBlockReason(
input: FileAttachmentCapabilityState & {
readonly files: ReadonlyArray<{ readonly name: string; readonly sizeBytes: number }>;
},
): string | null {
if (input.files.length === 0) {
return null;
}
if (!input.attachmentUploadsCapabilityKnown) {
return "Waiting for the server before file attachments can send";
}
const maxFileAttachmentBytes = fileAttachmentStagingLimit(input);
if (maxFileAttachmentBytes === null) {
return "This server does not accept file attachments right now. Remove the files to send.";
}
const oversizedFile = input.files.find((file) => file.sizeBytes > maxFileAttachmentBytes);
if (oversizedFile) {
return fileAttachmentTooLargeMessage(oversizedFile.name, maxFileAttachmentBytes);
}
return null;
}
/**
* When `capabilities.attachmentUploads` flips off (reconnect, version skew),
* tear down only uploads that have not been persisted onto a draft file.
* Once `uploadedAttachmentId` is stamped, the draft references that server
* copy after reload even if its local `File` is still available in memory.
* Explicit attachment removal releases persisted uploads through
* `releaseDraftAttachment`.
*/
export function attachmentsToReleaseOnUploadCapabilityLoss(
attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
): Array<ComposerImageAttachment | ComposerFileAttachment> {
return attachments.filter(
(attachment) => !(attachment.type === "file" && attachment.uploadedAttachmentId !== undefined),
);
}
/**
* Whether a paste's files should be claimed as composer attachments instead of
* falling through to the default text paste. Deliberately no capacity or
* pending-plan-question gate here: `addComposerAttachments` owns those limits
* and reports them, while a gate at this layer would swallow the paste with no
* feedback.
*/
export function shouldHandleComposerAttachmentPaste(input: {
readonly files: ReadonlyArray<File>;
readonly plainText: string;
}): boolean {
if (
input.files.some((file) => {
const classification = classifyComposerAttachmentFile(file);
return classification === "image" || classification === "unsupported-image";
})
) {
return true;
}
if (input.plainText.length > 0) {
return false;
}
return input.files.some((file) => classifyComposerAttachmentFile(file) === "file");
}
@@ -6,7 +6,7 @@ import {
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { AsyncResult } from "effect/unstable/reactivity";
import {
deriveProjectGroupingOverrideKey,
@@ -733,7 +733,10 @@ function ProjectDetail({ group }: { group: SidebarProjectSnapshot }) {
return;
}
const projectRef = scopeProjectRef(member.environmentId, member.id);
releaseProjectDraftUploads(projectRef);
releaseProjectDraftUploads(
projectRef,
memberThreads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
);
const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef);
if (projectDraftThread) {
draftStore.clearDraftThread(projectDraftThread.draftId);
+483
View File
@@ -11,6 +11,7 @@ import {
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ThreadId,
type ModelSelection,
type ProviderOptionSelection,
@@ -65,7 +66,9 @@ import {
markPromotedDraftThreadByRef,
markPromotedDraftThreads,
markPromotedDraftThreadsByRef,
type ComposerFileAttachment,
type ComposerImageAttachment,
composerFileNeedsReattach,
useComposerDraftStore,
DraftId,
} from "./composerDraftStore";
@@ -104,6 +107,18 @@ function makeImage(input: {
};
}
function makeFile(id: string): ComposerFileAttachment {
const file = new File(["report"], "report.pdf", { type: "application/pdf" });
return {
type: "file",
id,
name: file.name,
mimeType: file.type,
sizeBytes: file.size,
file,
};
}
function makeTerminalContext(input: {
id: string;
text?: string;
@@ -289,6 +304,280 @@ describe("composerDraftStore clearComposerContent", () => {
});
});
describe("composerDraftStore file attachments", () => {
const threadId = ThreadId.make("thread-files");
const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);
beforeEach(() => {
resetComposerDraftStore();
});
it("persists uploaded file references without including file contents", () => {
const store = useComposerDraftStore.getState();
store.addFiles(threadRef, [makeFile("file-1")]);
store.setFileUpload(threadRef, "file-1", TEST_ENVIRONMENT_ID, "pending-report-pdf");
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
) => ReturnType<typeof useComposerDraftStore.getState>;
};
};
const options = persistApi.getOptions();
const persisted = options.partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey: Record<string, { files?: Array<Record<string, unknown>> }>;
};
expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual(
[
{
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 6,
attachmentId: "pending-report-pdf",
environmentId: TEST_ENVIRONMENT_ID,
},
],
);
const hydrated = options.merge(persisted, useComposerDraftStore.getState());
expect(hydrated.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual([
{
type: "file",
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 6,
file: null,
uploadedAttachmentId: "pending-report-pdf",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
]);
});
it("persists a pending file as a needs-reattach marker instead of dropping it", () => {
const store = useComposerDraftStore.getState();
// No setFileUpload: the upload never finished, so there is no attachment
// id and the File handle cannot serialize.
store.addFiles(threadRef, [makeFile("file-pending")]);
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
merge: (
persistedState: unknown,
currentState: ReturnType<typeof useComposerDraftStore.getState>,
) => ReturnType<typeof useComposerDraftStore.getState>;
};
};
const options = persistApi.getOptions();
const persisted = options.partialize(useComposerDraftStore.getState()) as {
draftsByThreadKey: Record<string, { files?: Array<Record<string, unknown>> }>;
};
expect(persisted.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files).toEqual(
[
{
id: "file-pending",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 6,
},
],
);
const hydrated = options.merge(persisted, useComposerDraftStore.getState());
const hydratedFiles =
hydrated.draftsByThreadKey[threadKeyFor(threadId, TEST_ENVIRONMENT_ID)]?.files;
expect(hydratedFiles).toEqual([
{
type: "file",
id: "file-pending",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 6,
file: null,
},
]);
expect(hydratedFiles?.every(composerFileNeedsReattach)).toBe(true);
});
it("marks only the matching byte-less upload as missing", () => {
const store = useComposerDraftStore.getState();
const hydrated: ComposerFileAttachment = {
...makeFile("file-hydrated"),
file: null,
uploadedAttachmentId: "pending-old",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
};
const local: ComposerFileAttachment = {
...makeFile("file-local"),
name: "local.txt",
mimeType: "text/plain",
};
store.addFiles(threadRef, [hydrated, local]);
store.setFileUpload(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-new");
store.setFileUpload(threadRef, local.id, TEST_ENVIRONMENT_ID, "pending-local");
expect(
store.markFileUploadMissing(threadRef, hydrated.id, OTHER_TEST_ENVIRONMENT_ID, "pending-new"),
).toBe(false);
expect(
store.markFileUploadMissing(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-old"),
).toBe(false);
expect(
store.markFileUploadMissing(threadRef, local.id, TEST_ENVIRONMENT_ID, "pending-local"),
).toBe(false);
expect(store.getComposerDraft(threadRef)?.files).toMatchObject([
{
id: hydrated.id,
uploadedAttachmentId: "pending-new",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
{
id: local.id,
file: local.file,
uploadedAttachmentId: "pending-local",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
]);
expect(
store.markFileUploadMissing(threadRef, hydrated.id, TEST_ENVIRONMENT_ID, "pending-new"),
).toBe(true);
const marker = store.getComposerDraft(threadRef)?.files[0];
expect(marker && composerFileNeedsReattach(marker)).toBe(true);
expect(marker?.uploadedAttachmentId).toBeUndefined();
expect(marker?.uploadEnvironmentId).toBeUndefined();
});
it("removes generic files when the composer is cleared", () => {
const store = useComposerDraftStore.getState();
store.addFiles(threadRef, [makeFile("file-clear")]);
store.clearComposerContent(threadRef);
expect(store.getComposerDraft(threadRef)).toBeNull();
});
it("removes generic files when a prompt is moved into the stash", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadRef, "Review the report");
store.addFiles(threadRef, [makeFile("file-stash")]);
store.clearComposerPromptAndImages(threadRef);
expect(store.getComposerDraft(threadRef)).toBeNull();
});
it("enforces the combined file and image limit across separate updates", () => {
const store = useComposerDraftStore.getState();
const images = Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) =>
makeImage({
id: `image-${index}`,
name: `image-${index}.png`,
previewUrl: `blob:image-${index}`,
}),
);
store.addImages(threadRef, images);
store.addFiles(threadRef, [
makeFile("file-accepted"),
{ ...makeFile("file-overflow"), name: "other.pdf" },
]);
store.addImages(threadRef, [
makeImage({ id: "image-overflow", name: "overflow.png", previewUrl: "blob:overflow" }),
]);
const draft = store.getComposerDraft(threadRef);
expect(draft?.images).toHaveLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1);
expect(draft?.files.map((file) => file.id)).toEqual(["file-accepted"]);
});
it("replaces a needs-reattach marker when the same file is picked again", () => {
const store = useComposerDraftStore.getState();
// A hydrated marker: same metadata as the original pick, no bytes and no
// server-side upload.
const marker: ComposerFileAttachment = { ...makeFile("file-marker"), file: null };
store.addFiles(threadRef, [marker]);
expect(store.getComposerDraft(threadRef)?.files.every(composerFileNeedsReattach)).toBe(true);
// Following the "Attach again" instruction produces a fresh id with the
// exact metadata the dedup key hashes.
const repicked = makeFile("file-repicked");
store.addFiles(threadRef, [repicked]);
const files = store.getComposerDraft(threadRef)?.files;
expect(files?.map((file) => file.id)).toEqual(["file-repicked"]);
expect(files?.[0]?.file).not.toBeNull();
expect(files?.some(composerFileNeedsReattach)).toBe(false);
});
it("replaces a needs-reattach marker with a stash-restored uploaded file", () => {
const store = useComposerDraftStore.getState();
const marker: ComposerFileAttachment = { ...makeFile("file-marker"), file: null };
store.addFiles(threadRef, [marker]);
expect(store.getComposerDraft(threadRef)?.files.every(composerFileNeedsReattach)).toBe(true);
// A stash restore carries a finished server-side upload instead of bytes.
// Matching metadata must replace the marker, not be dropped as a
// duplicate: the marker cannot send, and the restored ids are the only
// valid copy.
const restored: ComposerFileAttachment = {
...makeFile("file-restored"),
file: null,
uploadedAttachmentId: "pending-stash-pdf",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
};
store.addFiles(threadRef, [restored]);
const files = store.getComposerDraft(threadRef)?.files;
expect(files?.map((file) => file.id)).toEqual(["file-restored"]);
expect(files?.[0]?.uploadedAttachmentId).toBe("pending-stash-pdf");
expect(files?.[0]?.uploadEnvironmentId).toBe(TEST_ENVIRONMENT_ID);
expect(files?.some(composerFileNeedsReattach)).toBe(false);
});
it("still dedupes a re-pick against a file that does not need reattaching", () => {
const store = useComposerDraftStore.getState();
store.addFiles(threadRef, [makeFile("file-original")]);
store.addFiles(threadRef, [makeFile("file-duplicate")]);
expect(store.getComposerDraft(threadRef)?.files.map((file) => file.id)).toEqual([
"file-original",
]);
});
it("keeps the remaining file slot available after a duplicate is skipped", () => {
const store = useComposerDraftStore.getState();
store.addImages(
threadRef,
Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 2 }, (_, index) =>
makeImage({
id: `image-${index}`,
name: `image-${index}.png`,
previewUrl: `blob:image-${index}`,
}),
),
);
store.addFiles(threadRef, [makeFile("file-original")]);
store.addFiles(threadRef, [
makeFile("file-duplicate"),
{ ...makeFile("file-unique"), name: "unique.pdf" },
]);
expect(store.getComposerDraft(threadRef)?.files.map((file) => file.id)).toEqual([
"file-original",
"file-unique",
]);
});
});
describe("composerDraftStore moveComposerPromptAndImages", () => {
const sourceDraftId = DraftId.make("draft-move-source");
const destinationDraftId = DraftId.make("draft-move-destination");
@@ -335,6 +624,111 @@ describe("composerDraftStore moveComposerPromptAndImages", () => {
expect(draftByKey(destinationDraftId)?.prompt).toBe(" explain this error");
});
it("keeps hydrated file references on their original environment", () => {
const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-file-source"));
const destinationRef = scopeThreadRef(
OTHER_TEST_ENVIRONMENT_ID,
ThreadId.make("thread-file-destination"),
);
const store = useComposerDraftStore.getState();
store.setPrompt(sourceRef, "review the report");
store.addFiles(sourceRef, [
{
...makeFile("file-hydrated"),
file: null,
uploadedAttachmentId: "pending-report-pdf",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
]);
store.moveComposerPromptAndImages(sourceRef, destinationRef);
expect(store.getComposerDraft(sourceRef)?.files.map((file) => file.id)).toEqual([
"file-hydrated",
]);
expect(store.getComposerDraft(destinationRef)?.files).toEqual([]);
expect(store.getComposerDraft(destinationRef)?.prompt).toBe("review the report");
});
it("moves files across environments when the original browser file remains available", () => {
const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-file-source"));
const destinationRef = scopeThreadRef(
OTHER_TEST_ENVIRONMENT_ID,
ThreadId.make("thread-file-destination"),
);
const store = useComposerDraftStore.getState();
store.addFiles(sourceRef, [
{
...makeFile("file-local"),
uploadedAttachmentId: "pending-source-env",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
]);
store.moveComposerPromptAndImages(sourceRef, destinationRef);
expect(store.getComposerDraft(sourceRef)).toBeNull();
const moved = store.getComposerDraft(destinationRef)?.files;
expect(moved?.map((file) => file.id)).toEqual(["file-local"]);
// The source-environment upload is unreachable from the destination; the
// move drops it so the destination upload can mint its own.
expect(moved?.[0]?.uploadedAttachmentId).toBeUndefined();
expect(moved?.[0]?.uploadEnvironmentId).toBeUndefined();
});
it("does not duplicate a file the destination already holds", () => {
const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-dup-source"));
const destinationRef = scopeThreadRef(
TEST_ENVIRONMENT_ID,
ThreadId.make("thread-dup-destination"),
);
const store = useComposerDraftStore.getState();
// Same metadata key on both sides; the ids differ.
store.addFiles(sourceRef, [makeFile("file-copy-a")]);
store.addFiles(destinationRef, [makeFile("file-copy-b")]);
store.moveComposerPromptAndImages(sourceRef, destinationRef);
expect(store.getComposerDraft(destinationRef)?.files.map((file) => file.id)).toEqual([
"file-copy-b",
]);
expect(store.getComposerDraft(sourceRef)?.files.map((file) => file.id)).toEqual([
"file-copy-a",
]);
});
it("keeps overflow attachments on the source when the destination is nearly full", () => {
const store = useComposerDraftStore.getState();
store.addImages(
destinationDraftId,
Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) =>
makeImage({
id: `destination-${index}`,
name: `destination-${index}.png`,
previewUrl: `blob:destination-${index}`,
}),
),
);
store.addImages(sourceDraftId, [
makeImage({ id: "source-first", name: "first.png", previewUrl: "blob:first" }),
makeImage({ id: "source-second", name: "second.png", previewUrl: "blob:second" }),
]);
store.addFiles(sourceDraftId, [makeFile("source-file")]);
store.moveComposerPromptAndImages(sourceDraftId, destinationDraftId);
expect(store.getComposerDraft(destinationDraftId)?.images).toHaveLength(
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
);
expect(store.getComposerDraft(destinationDraftId)?.files).toEqual([]);
expect(store.getComposerDraft(sourceDraftId)?.images.map((image) => image.id)).toEqual([
"source-second",
]);
expect(store.getComposerDraft(sourceDraftId)?.files.map((file) => file.id)).toEqual([
"source-file",
]);
});
it("is a no-op when source and destination are the same target", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(sourceDraftId, "keep me");
@@ -1959,6 +2353,95 @@ describe("composerDraftStore model seed migration", () => {
vi.useRealTimers();
}
});
it("keeps v8 file-only draft sessions and their seeded models", async () => {
vi.useFakeTimers();
try {
const uploadedDraftId = DraftId.make("draft-legacy-uploaded-file");
const markerDraftId = DraftId.make("draft-legacy-file-marker");
const uploadedThreadId = ThreadId.make("thread-legacy-uploaded-file");
const markerThreadId = ThreadId.make("thread-legacy-file-marker");
const staleSelection = modelSelection(CODEX_DRIVER, "gpt-5.4");
const storage = useComposerDraftStore.persist.getOptions().storage;
expect(storage).toBeDefined();
storage?.setItem(COMPOSER_DRAFT_STORAGE_KEY, {
version: 8,
state: {
draftsByThreadKey: {
[uploadedDraftId]: {
prompt: "",
attachments: [],
files: [
{
id: "file-uploaded",
name: "uploaded-report.pdf",
mimeType: "application/pdf",
sizeBytes: 128,
attachmentId: "attachment-uploaded",
environmentId: TEST_ENVIRONMENT_ID,
},
],
modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection },
activeProvider: CODEX_INSTANCE,
},
[markerDraftId]: {
prompt: "",
attachments: [],
files: [
{
id: "file-needs-reattach",
name: "local-notes.txt",
mimeType: "text/plain",
sizeBytes: 64,
},
],
modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection },
activeProvider: CODEX_INSTANCE,
runtimeMode: "approval-required",
},
},
draftThreadsByThreadKey: {
[uploadedDraftId]: draftThread(uploadedThreadId),
[markerDraftId]: draftThread(markerThreadId),
},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
stickyActiveProvider: null,
},
} as never);
await vi.advanceTimersByTimeAsync(300);
await useComposerDraftStore.persist.rehydrate();
expect(draftByKey(uploadedDraftId)).toMatchObject({
files: [
{
id: "file-uploaded",
name: "uploaded-report.pdf",
uploadedAttachmentId: "attachment-uploaded",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
},
],
modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection },
activeProvider: CODEX_INSTANCE,
});
expect(draftByKey(markerDraftId)).toMatchObject({
files: [
{
id: "file-needs-reattach",
name: "local-notes.txt",
file: null,
},
],
modelSelectionByProvider: { [CODEX_INSTANCE]: staleSelection },
activeProvider: CODEX_INSTANCE,
runtimeMode: "approval-required",
});
expect(draftByKey(markerDraftId)?.files.every(composerFileNeedsReattach)).toBe(true);
} finally {
vi.useRealTimers();
}
});
});
describe("composerDraftStore provider-scoped option updates", () => {
+354 -19
View File
@@ -2,13 +2,14 @@ import {
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
defaultInstanceIdForDriver,
type EnvironmentId,
EnvironmentId,
ModelSelection,
ProjectId,
ProviderInstanceId,
ProviderInteractionMode,
ProviderDriverKind,
ProviderOptionSelection,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PreviewAnnotationPayloadSchema,
type PreviewAnnotationPayload,
RuntimeMode,
@@ -33,7 +34,12 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
import { useMemo } from "react";
import { getLocalStorageItem } from "./hooks/useLocalStorage";
import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatFileAttachment,
type ChatImageAttachment,
} from "./types";
import {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
@@ -93,6 +99,49 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
file: File | null;
uploadedAttachmentId?: string;
uploadEnvironmentId?: EnvironmentId;
}
/**
* A hydrated draft file whose upload never finished before the reload has
* neither bytes (`file` is only ever null after hydration) nor a server-side
* upload. The composer renders it as a needs-reattach row: the user must
* attach the file again or remove it before sending.
*/
export function composerFileNeedsReattach(file: ComposerFileAttachment): boolean {
return file.file === null && file.uploadedAttachmentId === undefined;
}
export const PersistedComposerFileAttachment = Schema.Struct({
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
attachmentId: Schema.String,
environmentId: EnvironmentId,
});
export type PersistedComposerFileAttachment = typeof PersistedComposerFileAttachment.Type;
/**
* Draft-persisted file. Unlike a stash entry (which requires a finished
* upload), a draft may hold a file whose upload never completed. Its `File`
* handle cannot serialize, so it persists as a metadata-only marker (no
* `attachmentId`) and hydrates as a needs-reattach row instead of vanishing.
*/
export const PersistedComposerDraftFileAttachment = Schema.Struct({
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
sizeBytes: Schema.Number,
attachmentId: Schema.optionalKey(Schema.String),
environmentId: Schema.optionalKey(EnvironmentId),
});
export type PersistedComposerDraftFileAttachment = typeof PersistedComposerDraftFileAttachment.Type;
const isPersistedComposerDraftFileAttachment = Schema.is(PersistedComposerDraftFileAttachment);
const PersistedTerminalContextDraft = Schema.Struct({
id: Schema.String,
threadId: ThreadId,
@@ -129,6 +178,7 @@ type PersistedElementContextDraft = typeof PersistedElementContextDraft.Type;
const PersistedComposerThreadDraftState = Schema.Struct({
prompt: Schema.String,
attachments: Schema.Array(PersistedComposerImageAttachment),
files: Schema.optionalKey(Schema.Array(PersistedComposerDraftFileAttachment)),
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
elementContexts: Schema.optionalKey(Schema.Array(PersistedElementContextDraft)),
previewAnnotations: Schema.optionalKey(Schema.Array(PreviewAnnotationPayloadSchema)),
@@ -255,6 +305,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
export interface ComposerThreadDraftState {
prompt: string;
images: ComposerImageAttachment[];
files: ComposerFileAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
@@ -305,6 +356,7 @@ export function composerDraftHasUserContent(
return (
draft.prompt.trim().length > 0 ||
draft.images.length > 0 ||
draft.files.length > 0 ||
draft.persistedAttachments.length > 0 ||
draft.terminalContexts.length > 0 ||
draft.elementContexts.length > 0 ||
@@ -351,7 +403,7 @@ interface ProjectDraftSession extends DraftSessionState {
* Raw `ThreadId` is intentionally excluded so callers cannot drop environment
* identity for real threads.
*/
type ComposerThreadTarget = ScopedThreadRef | DraftId;
export type ComposerThreadTarget = ScopedThreadRef | DraftId;
/**
* Persisted store for composer content plus draft-session metadata.
@@ -484,6 +536,20 @@ interface ComposerDraftStoreState {
addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void;
addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void;
removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void;
addFiles: (threadRef: ComposerThreadTarget, files: ComposerFileAttachment[]) => void;
removeFile: (threadRef: ComposerThreadTarget, fileId: string) => void;
setFileUpload: (
threadRef: ComposerThreadTarget,
fileId: string,
environmentId: EnvironmentId,
attachmentId: string,
) => void;
markFileUploadMissing: (
threadRef: ComposerThreadTarget,
fileId: string,
environmentId: EnvironmentId,
attachmentId: string,
) => boolean;
insertTerminalContext: (
threadRef: ComposerThreadTarget,
prompt: string,
@@ -534,19 +600,16 @@ interface ComposerDraftStoreState {
) => void;
clearComposerContent: (threadRef: ComposerThreadTarget) => void;
/**
* Clears only the prompt text and image attachments, preserving terminal /
* Clears the prompt text and attachments, preserving terminal /
* element contexts, preview annotations, and review comments. Used by the
* prompt stash, which can only round-trip text + images: clearing the
* session-bound contexts would destroy state nothing can restore.
* prompt stash. Session-bound context stays in the source draft.
*/
clearComposerPromptAndImages: (threadRef: ComposerThreadTarget) => void;
/**
* Moves the prompt text and image attachments from one composer target to
* another. Used when a draft changes project: the new project gets its own
* draft session and the typed content follows it. Session-bound extras
* (terminal / element contexts, preview annotations, review comments) stay
* on the source — they reference sessions of the source thread that the
* destination cannot use.
* Moves prompt text and transferable attachments into another composer.
* Attachments over the destination limit and uploaded files that belong to
* another environment stay in the source draft. Terminal and element
* context, preview annotations, and review comments also stay in the source.
*/
moveComposerPromptAndImages: (from: ComposerThreadTarget, to: ComposerThreadTarget) => void;
}
@@ -615,6 +678,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
});
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_FILES: ComposerFileAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
@@ -622,6 +686,7 @@ const EMPTY_ELEMENT_CONTEXTS: ElementContextDraft[] = [];
const EMPTY_PREVIEW_ANNOTATIONS: PreviewAnnotationPayload[] = [];
const EMPTY_REVIEW_COMMENTS: ReviewCommentContext[] = [];
Object.freeze(EMPTY_IMAGES);
Object.freeze(EMPTY_FILES);
Object.freeze(EMPTY_IDS);
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
Object.freeze(EMPTY_ELEMENT_CONTEXTS);
@@ -637,6 +702,7 @@ const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>(
const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
prompt: "",
images: EMPTY_IMAGES,
files: EMPTY_FILES,
nonPersistedImageIds: EMPTY_IDS,
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
@@ -659,6 +725,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
return {
prompt: "",
images: [],
files: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
@@ -733,6 +800,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
return (
draft.prompt.length === 0 &&
draft.images.length === 0 &&
draft.files.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
@@ -1263,7 +1331,7 @@ function logicalProjectDraftKey(logicalProjectKey: string): string {
* Draft sessions are keyed by `DraftId`. Real threads are keyed by
* `ScopedThreadRef` so environment identity is always preserved.
*/
function composerTargetKey(target: ScopedThreadRef | DraftId): string {
export function composerTargetKey(target: ScopedThreadRef | DraftId): string {
if (typeof target === "string") {
return target.trim();
}
@@ -1717,6 +1785,9 @@ function normalizePersistedDraftsByThreadId(
return normalized ? [normalized] : [];
})
: [];
const files = Array.isArray(draftCandidate.files)
? draftCandidate.files.filter(isPersistedComposerDraftFileAttachment)
: [];
const terminalContexts = Array.isArray(draftCandidate.terminalContexts)
? draftCandidate.terminalContexts.flatMap((entry) => {
const normalized = normalizePersistedTerminalContextDraft(entry);
@@ -1796,6 +1867,7 @@ function normalizePersistedDraftsByThreadId(
if (
promptCandidate.length === 0 &&
attachments.length === 0 &&
files.length === 0 &&
terminalContexts.length === 0 &&
elementContexts.length === 0 &&
reviewComments.length === 0 &&
@@ -1820,6 +1892,7 @@ function normalizePersistedDraftsByThreadId(
nextDraftsByThreadKey[normalizedThreadKey] = {
prompt,
attachments,
...(files.length > 0 ? { files } : {}),
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
...(elementContexts.length > 0 ? { elementContexts } : {}),
...(reviewComments.length > 0 ? { reviewComments } : {}),
@@ -1842,6 +1915,7 @@ function persistedComposerDraftHasUserContent(draft: PersistedComposerThreadDraf
return (
draft.prompt.trim().length > 0 ||
draft.attachments.length > 0 ||
(draft.files?.length ?? 0) > 0 ||
(draft.terminalContexts?.length ?? 0) > 0 ||
(draft.elementContexts?.length ?? 0) > 0 ||
(draft.previewAnnotations?.length ?? 0) > 0 ||
@@ -1925,6 +1999,7 @@ function partializeComposerDraftStoreState(
if (
draft.prompt.length === 0 &&
draft.persistedAttachments.length === 0 &&
draft.files.length === 0 &&
draft.terminalContexts.length === 0 &&
draft.elementContexts.length === 0 &&
draft.previewAnnotations.length === 0 &&
@@ -1938,6 +2013,25 @@ function partializeComposerDraftStoreState(
const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
prompt: draft.prompt,
attachments: draft.persistedAttachments,
...(draft.files.length > 0
? {
// A file whose upload has not finished has no serializable bytes.
// It persists as a metadata-only marker so it can surface as a
// needs-reattach row after reload instead of silently vanishing.
files: draft.files.map((file) => ({
id: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
...(file.uploadedAttachmentId && file.uploadEnvironmentId
? {
attachmentId: file.uploadedAttachmentId,
environmentId: file.uploadEnvironmentId,
}
: {}),
})),
}
: {}),
...(draft.terminalContexts.length > 0
? {
terminalContexts: draft.terminalContexts.map((context) => ({
@@ -2219,6 +2313,21 @@ function toHydratedThreadDraft(
return {
prompt: persistedDraft.prompt,
images: hydrateImagesFromPersisted(persistedDraft.attachments),
files:
persistedDraft.files?.map((file) => ({
type: "file" as const,
id: file.id,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: null,
// A marker without an attachment id hydrates as needs-reattach: no
// bytes, no server-side upload, only the metadata to tell the user
// what to attach again.
...(file.attachmentId !== undefined && file.environmentId !== undefined
? { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: file.environmentId }
: {}),
})) ?? [],
nonPersistedImageIds: [],
persistedAttachments: [...persistedDraft.attachments],
terminalContexts:
@@ -3008,6 +3117,15 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
}
continue;
}
if (
existing.images.length + existing.files.length + dedupedIncoming.length >=
PROVIDER_SEND_TURN_MAX_ATTACHMENTS
) {
if (!acceptedPreviewUrls.has(image.previewUrl)) {
revokeObjectPreviewUrl(image.previewUrl);
}
continue;
}
dedupedIncoming.push(image);
existingIds.add(image.id);
existingDedupKeys.add(dedupKey);
@@ -3062,6 +3180,160 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
addFiles: (threadRef, files) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0 || files.length === 0) {
return;
}
set((state) => {
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
const knownIds = new Set(existing.files.map((file) => file.id));
const knownFiles = new Map<string, ComposerFileAttachment>(
existing.files.map((file) => [
`${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
file,
]),
);
const accepted: ComposerFileAttachment[] = [];
// Needs-reattach markers replaced in place by a re-pick, keyed by
// the marker's id.
const replacements = new Map<string, ComposerFileAttachment>();
for (const file of files) {
const key = `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`;
if (knownIds.has(file.id)) {
continue;
}
const duplicate = knownFiles.get(key);
if (duplicate) {
// A needs-reattach marker persists exactly the metadata this
// key hashes, so re-picking the same file matches its marker.
// Dropping the pick as a duplicate would leave the draft
// blocked forever; replace the marker so the upload restarts.
if (composerFileNeedsReattach(duplicate) && !replacements.has(duplicate.id)) {
replacements.set(duplicate.id, file);
knownIds.add(file.id);
}
continue;
}
if (
existing.images.length + existing.files.length + accepted.length >=
PROVIDER_SEND_TURN_MAX_ATTACHMENTS
) {
break;
}
accepted.push(file);
knownIds.add(file.id);
knownFiles.set(key, file);
}
if (accepted.length === 0 && replacements.size === 0) {
return state;
}
const retained = existing.files.map((file) => replacements.get(file.id) ?? file);
return {
draftsByThreadKey: {
...state.draftsByThreadKey,
[threadKey]: { ...existing, files: [...retained, ...accepted] },
},
};
});
},
removeFile: (threadRef, fileId) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0) {
return;
}
set((state) => {
const current = state.draftsByThreadKey[threadKey];
if (!current?.files.some((file) => file.id === fileId)) {
return state;
}
const nextDraft = {
...current,
files: current.files.filter((file) => file.id !== fileId),
} satisfies ComposerThreadDraftState;
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextDraft)) {
delete nextDraftsByThreadKey[threadKey];
} else {
nextDraftsByThreadKey[threadKey] = nextDraft;
}
return { draftsByThreadKey: nextDraftsByThreadKey };
});
},
setFileUpload: (threadRef, fileId, environmentId, attachmentId) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0) {
return;
}
set((state) => {
const current = state.draftsByThreadKey[threadKey];
const file = current?.files.find((entry) => entry.id === fileId);
if (
!current ||
!file ||
(file.uploadEnvironmentId === environmentId &&
file.uploadedAttachmentId === attachmentId)
) {
return state;
}
return {
draftsByThreadKey: {
...state.draftsByThreadKey,
[threadKey]: {
...current,
files: current.files.map((entry) =>
entry.id === fileId
? {
...entry,
uploadedAttachmentId: attachmentId,
uploadEnvironmentId: environmentId,
}
: entry,
),
},
},
};
});
},
markFileUploadMissing: (threadRef, fileId, environmentId, attachmentId) => {
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
if (threadKey.length === 0) {
return false;
}
let markedMissing = false;
set((state) => {
const current = state.draftsByThreadKey[threadKey];
const file = current?.files.find((entry) => entry.id === fileId);
if (
!current ||
!file ||
file.file !== null ||
file.uploadEnvironmentId !== environmentId ||
file.uploadedAttachmentId !== attachmentId
) {
return state;
}
markedMissing = true;
return {
draftsByThreadKey: {
...state.draftsByThreadKey,
[threadKey]: {
...current,
files: current.files.map((entry) => {
if (entry.id !== fileId) {
return entry;
}
const marker = { ...entry };
delete marker.uploadedAttachmentId;
delete marker.uploadEnvironmentId;
return marker;
}),
},
},
};
});
return markedMissing;
},
insertTerminalContext: (threadRef, prompt, context, index) => {
const threadKey = resolveComposerDraftKey(get(), threadRef);
const threadId = resolveComposerThreadId(get(), threadRef);
@@ -3462,6 +3734,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
...current,
prompt: "",
images: [],
files: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
@@ -3495,6 +3768,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
...current,
prompt: ensureInlineTerminalContextPlaceholders("", current.terminalContexts.length),
images: [],
files: [],
nonPersistedImageIds: [],
persistedAttachments: [],
};
@@ -3519,6 +3793,59 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
return state;
}
const destination = state.draftsByThreadKey[toKey] ?? createEmptyThreadDraft();
const destinationEnvironmentId =
typeof to === "string"
? (state.draftThreadsByThreadKey[toKey]?.environmentId ??
parseScopedThreadKey(toKey)?.environmentId ??
null)
: to.environmentId;
// A file the destination already holds (same id, or same
// metadata key) stays behind instead of duplicating there.
const destinationFileIds = new Set(destination.files.map((file) => file.id));
const destinationFileKeys = new Set(
destination.files.map(
(file) => `${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
),
);
const transferableFiles = source.files.filter(
(file) =>
(file.file !== null || file.uploadEnvironmentId === destinationEnvironmentId) &&
!destinationFileIds.has(file.id) &&
!destinationFileKeys.has(
`${file.mimeType}\u0000${file.sizeBytes}\u0000${file.name}`,
),
);
const remainingAttachmentSlots = Math.max(
0,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS -
destination.images.length -
destination.files.length,
);
const movedImages = source.images.slice(0, remainingAttachmentSlots);
const movedImageIds = new Set(movedImages.map((image) => image.id));
const retainedImages = source.images.filter((image) => !movedImageIds.has(image.id));
const movedFiles = transferableFiles
.slice(0, remainingAttachmentSlots - movedImages.length)
.map((file) => {
// A byte-backed file moving across environments re-uploads at
// the destination. Keeping the source-environment upload id
// would mark it uploaded after a reload with no local bytes
// and no valid upload anywhere the destination can reach. The
// upload queue keeps the source upload as fallback, then
// deletes it after the destination upload succeeds. Abandoned
// uploads still expire through the server sweep.
if (
file.file === null ||
file.uploadEnvironmentId === undefined ||
file.uploadEnvironmentId === destinationEnvironmentId
) {
return file;
}
const { uploadedAttachmentId: _a, uploadEnvironmentId: _e, ...rest } = file;
return rest;
});
const movedFileIds = new Set(movedFiles.map((file) => file.id));
const retainedFiles = source.files.filter((file) => !movedFileIds.has(file.id));
// Inline placeholders reference the source's terminal contexts,
// which stay behind; re-anchor the moved prompt to whatever
// contexts the destination already holds.
@@ -3529,14 +3856,17 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const nextDestination: ComposerThreadDraftState = {
...destination,
prompt: movedPrompt,
images: [...destination.images, ...source.images],
images: [...destination.images, ...movedImages],
files: [...destination.files, ...movedFiles],
nonPersistedImageIds: [
...destination.nonPersistedImageIds,
...source.nonPersistedImageIds,
...source.nonPersistedImageIds.filter((imageId) => movedImageIds.has(imageId)),
],
persistedAttachments: [
...destination.persistedAttachments,
...source.persistedAttachments,
...source.persistedAttachments.filter((attachment) =>
movedImageIds.has(attachment.id),
),
],
};
// Same clearing shape as clearComposerPromptAndImages, but the
@@ -3545,9 +3875,14 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
const nextSource: ComposerThreadDraftState = {
...source,
prompt: ensureInlineTerminalContextPlaceholders("", source.terminalContexts.length),
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
images: retainedImages,
files: retainedFiles,
nonPersistedImageIds: source.nonPersistedImageIds.filter(
(imageId) => !movedImageIds.has(imageId),
),
persistedAttachments: source.persistedAttachments.filter(
(attachment) => !movedImageIds.has(attachment.id),
),
};
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
if (shouldRemoveDraft(nextSource)) {
+14 -1
View File
@@ -33,6 +33,7 @@ import { primaryServerSettingsAtom } from "../state/server";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useClientSettings } from "./useSettings";
import { toastManager } from "../components/ui/toast";
interface NewThreadWorkspaceOptions {
branch?: string | null;
@@ -78,7 +79,7 @@ export function useNewThreadHandler() {
startFromOrigin?: boolean;
replace?: boolean;
/**
* Move the viewed draft's typed content (prompt + images) into the
* Move the viewed draft's typed content and transferable attachments into the
* draft this request lands on. Set by the draft repo picker: the
* user started writing in the wrong project and the text should
* follow them. Explicit new-thread surfaces leave this unset and
@@ -156,6 +157,18 @@ export function useNewThreadHandler() {
composerDraftHasUserContent(getComposerDraft(carryContentSourceDraftId))
) {
moveComposerPromptAndImages(carryContentSourceDraftId, destinationDraftId);
// The move caps at the destination's free slots and skips
// duplicates, so images and files can both stay behind.
const remainingDraft = getComposerDraft(carryContentSourceDraftId);
const remainingCount =
(remainingDraft?.files.length ?? 0) + (remainingDraft?.images.length ?? 0);
if (remainingCount > 0) {
toastManager.add({
type: "warning",
title: `${remainingCount} attachment${remainingCount === 1 ? " stayed" : "s stayed"} in the original draft`,
description: "Return to the original draft or attach the files again.",
});
}
}
};
const project = projects.find(
+660 -4
View File
@@ -1,21 +1,36 @@
import { EnvironmentId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import type { ComposerImageAttachment } from "../composerDraftStore";
import {
composerFileNeedsReattach,
DraftId,
useComposerDraftStore,
type ComposerFileAttachment,
type ComposerImageAttachment,
} from "../composerDraftStore";
const mocks = vi.hoisted(() => ({
createAssetUrl: vi.fn(),
createUploadUrl: Symbol("create-upload-url"),
executeAtomQuery: vi.fn(),
removeUpload: Symbol("remove-upload"),
runAtomCommand: vi.fn(),
readPreparedConnection: vi.fn(),
}));
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
executeAtomQuery: mocks.executeAtomQuery,
runAtomCommand: mocks.runAtomCommand,
squashAtomCommandFailure: (result: { readonly error: unknown }) => result.error,
}));
vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} }));
vi.mock("../state/assets", () => ({
assetEnvironment: { createUrl: mocks.createAssetUrl },
}));
vi.mock("../state/attachments", () => ({
attachmentEnvironment: {
createUploadUrl: mocks.createUploadUrl,
@@ -32,7 +47,9 @@ import {
getUploadedAttachments,
readAttachmentUpload,
releaseAttachmentUpload,
releaseAttachmentUploads,
releaseDraftAttachment,
releaseDraftAttachments,
releasePersistedAttachmentUpload,
retryAttachmentUpload,
startAttachmentUpload,
useAttachmentUploadStore,
@@ -110,9 +127,27 @@ function makeImage(id: string): ComposerImageAttachment {
};
}
function makeFile(id: string): ComposerFileAttachment {
const file = new File([new Uint8Array([1, 2, 3])], `${id}.pdf`, {
type: "application/pdf",
});
return {
type: "file",
id,
name: file.name,
mimeType: file.type,
sizeBytes: file.size,
file,
};
}
describe("attachmentUploadQueue", () => {
beforeEach(() => {
TestXmlHttpRequest.requests = [];
mocks.createAssetUrl.mockReset();
mocks.createAssetUrl.mockImplementation((target: unknown) => target);
mocks.executeAtomQuery.mockReset();
mocks.executeAtomQuery.mockResolvedValue({ _tag: "Success", value: {} });
mocks.runAtomCommand.mockReset();
mocks.readPreparedConnection.mockReset();
mocks.readPreparedConnection.mockReturnValue({ httpBaseUrl: "https://environment.test/" });
@@ -176,7 +211,7 @@ describe("attachmentUploadQueue", () => {
},
]);
releaseAttachmentUploads([image]);
releaseDraftAttachments([image]);
expect(readAttachmentUpload(image.id)).toBeUndefined();
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
@@ -189,6 +224,543 @@ describe("attachmentUploadQueue", () => {
);
});
it("uploads generic files and sends file attachment references", async () => {
const file = makeFile("report");
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
await Promise.resolve();
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.createUploadUrl,
{
environmentId: firstEnvironment,
input: {
type: "file",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 3,
},
},
expect.anything(),
);
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(getUploadedAttachments({ environmentId: firstEnvironment, images: [file] })).toEqual([
{
type: "file",
id: "pending-environment-1-report.pdf",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 3,
},
]);
});
it("uses the fallback MIME type for both the upload claim and request header", async () => {
const bytes = new File([new Uint8Array([1, 2, 3])], "unknown.bin");
const file: ComposerFileAttachment = {
type: "file",
id: "file-without-browser-mime",
name: bytes.name,
mimeType: "application/octet-stream",
sizeBytes: bytes.size,
file: bytes,
};
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
await Promise.resolve();
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.createUploadUrl,
{
environmentId: firstEnvironment,
input: {
type: "file",
name: "unknown.bin",
mimeType: "application/octet-stream",
sizeBytes: 3,
},
},
expect.anything(),
);
expect(TestXmlHttpRequest.requests[0]?.headers.get("Content-Type")).toBe(
"application/octet-stream",
);
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
});
it("persists a background completion's ids to the draft with no composer mounted", async () => {
const draftId = DraftId.make("draft-background-upload");
const file = makeFile("background");
const draftStore = useComposerDraftStore.getState();
draftStore.addFiles(draftId, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: draftId,
});
await Promise.resolve();
// No composer effect is subscribed; only the queue can stamp the draft.
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
{
id: file.id,
uploadedAttachmentId: "pending-environment-1-background.pdf",
uploadEnvironmentId: firstEnvironment,
},
]);
} finally {
useComposerDraftStore.getState().clearComposerContent(draftId);
}
});
it("persists a pending upload on the same-environment draft that receives its file", async () => {
const source = scopeThreadRef(firstEnvironment, ThreadId.make("thread-background-move-source"));
const destination = scopeThreadRef(
firstEnvironment,
ThreadId.make("thread-background-move-destination"),
);
const file = makeFile("background-move");
const store = useComposerDraftStore.getState();
store.addFiles(source, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: source,
});
await Promise.resolve();
store.moveComposerPromptAndImages(source, destination);
const sourceAfterMove = store.getComposerDraft(source);
// The destination never starts the existing job again. Its completion
// must find the file in current store state instead of the captured row.
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(store.getComposerDraft(source)).toEqual(sourceAfterMove);
expect(store.getComposerDraft(destination)?.files).toMatchObject([
{
id: file.id,
uploadedAttachmentId: "pending-environment-1-background-move.pdf",
uploadEnvironmentId: firstEnvironment,
},
]);
} finally {
store.clearComposerContent(source);
store.clearComposerContent(destination);
}
});
it("does not stamp an old-environment upload after its file moves environments", async () => {
const source = scopeThreadRef(
firstEnvironment,
ThreadId.make("thread-cross-environment-source"),
);
const destination = scopeThreadRef(
secondEnvironment,
ThreadId.make("thread-cross-environment-destination"),
);
const file = makeFile("cross-environment-move");
const store = useComposerDraftStore.getState();
store.addFiles(source, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: source,
});
await Promise.resolve();
store.moveComposerPromptAndImages(source, destination);
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(store.getComposerDraft(source)).toBeNull();
const movedFile = store.getComposerDraft(destination)?.files[0];
expect(movedFile?.id).toBe(file.id);
expect(movedFile?.uploadedAttachmentId).toBeUndefined();
expect(movedFile?.uploadEnvironmentId).toBeUndefined();
} finally {
store.clearComposerContent(source);
store.clearComposerContent(destination);
}
});
it("verifies an uploaded file reference before restoring it", async () => {
const file: ComposerFileAttachment = {
...makeFile("restored"),
file: null,
uploadedAttachmentId: "pending-restored-pdf",
uploadEnvironmentId: firstEnvironment,
};
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
await awaitAttachmentUploads([file.id]);
expect(readAttachmentUpload(file.id)).toEqual({
status: "ready",
environmentId: firstEnvironment,
attachmentId: "pending-restored-pdf",
});
expect(mocks.createAssetUrl).toHaveBeenCalledWith({
environmentId: firstEnvironment,
input: { resource: { _tag: "attachment", attachmentId: "pending-restored-pdf" } },
});
expect(TestXmlHttpRequest.requests).toHaveLength(0);
});
it("turns an expired persisted file into a marker that a re-pick can replace", async () => {
const draftId = DraftId.make("draft-expired-upload");
const file: ComposerFileAttachment = {
...makeFile("expired"),
file: null,
uploadedAttachmentId: "pending-expired-pdf",
uploadEnvironmentId: firstEnvironment,
};
mocks.executeAtomQuery.mockResolvedValueOnce({
_tag: "Failure",
error: { _tag: "AssetAttachmentNotFoundError" },
});
useComposerDraftStore.getState().addFiles(draftId, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: draftId,
});
await awaitAttachmentUploads([file.id]);
const marker = useComposerDraftStore.getState().getComposerDraft(draftId)?.files[0];
expect(readAttachmentUpload(file.id)).toBeUndefined();
expect(marker?.uploadedAttachmentId).toBeUndefined();
expect(marker?.uploadEnvironmentId).toBeUndefined();
expect(marker && composerFileNeedsReattach(marker)).toBe(true);
const replacementBytes = new File([new Uint8Array([1, 2, 3])], file.name, {
type: file.mimeType,
});
const replacement: ComposerFileAttachment = {
type: "file",
id: "expired-repicked",
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: replacementBytes,
};
useComposerDraftStore.getState().addFiles(draftId, [replacement]);
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
{ id: replacement.id, file: replacementBytes },
]);
startAttachmentUpload({
environmentId: firstEnvironment,
image: replacement,
draftTarget: draftId,
});
await Promise.resolve();
const settled = awaitAttachmentUploads([replacement.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
{
id: replacement.id,
uploadedAttachmentId: "pending-environment-1-expired.pdf",
uploadEnvironmentId: firstEnvironment,
},
]);
const removeCalls = mocks.runAtomCommand.mock.calls.filter(
([, command]) => command === mocks.removeUpload,
);
expect(removeCalls).toEqual([]);
} finally {
useComposerDraftStore.getState().clearComposerContent(draftId);
}
});
it("uploads the original file again when its persisted server upload expired", async () => {
const file: ComposerFileAttachment = {
...makeFile("recoverable"),
uploadedAttachmentId: "pending-expired-pdf",
uploadEnvironmentId: firstEnvironment,
};
mocks.executeAtomQuery.mockResolvedValueOnce({
_tag: "Failure",
error: { _tag: "AssetAttachmentNotFoundError" },
});
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
// The verify-then-reupload path crosses several awaits before the
// transfer starts; drain microtasks until the XHR exists.
for (let hop = 0; hop < 20 && TestXmlHttpRequest.requests.length === 0; hop += 1) {
await Promise.resolve();
}
const settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
expect(readAttachmentUpload(file.id)).toMatchObject({
status: "ready",
attachmentId: "pending-environment-1-recoverable.pdf",
});
});
it("removes a persisted upload when its draft is discarded during verification", async () => {
const file: ComposerFileAttachment = {
...makeFile("checking"),
file: null,
uploadedAttachmentId: "pending-checking-pdf",
uploadEnvironmentId: firstEnvironment,
};
let resolveVerification: (result: {
readonly _tag: "Success";
readonly value: object;
}) => void = () => {};
mocks.executeAtomQuery.mockReturnValueOnce(
new Promise((resolve) => {
resolveVerification = resolve;
}),
);
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
releaseDraftAttachment(file);
resolveVerification({ _tag: "Success", value: {} });
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.removeUpload,
{
environmentId: firstEnvironment,
input: { attachmentId: "pending-checking-pdf" },
},
expect.anything(),
);
});
it("keeps the persisted upload when retrying after a transient verification failure", async () => {
const draftId = DraftId.make("draft-transient-verification");
const file: ComposerFileAttachment = {
...makeFile("flaky"),
file: null,
uploadedAttachmentId: "pending-flaky-pdf",
uploadEnvironmentId: firstEnvironment,
};
mocks.executeAtomQuery.mockResolvedValueOnce({
_tag: "Failure",
error: new Error("socket closed"),
});
useComposerDraftStore.getState().addFiles(draftId, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: draftId,
});
await awaitAttachmentUploads([file.id]);
expect(readAttachmentUpload(file.id)).toMatchObject({
status: "failed",
reason: "Uploaded file could not be verified. Retry when the server reconnects.",
});
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
{
uploadedAttachmentId: "pending-flaky-pdf",
uploadEnvironmentId: firstEnvironment,
},
]);
// The persisted id is the only server copy of the bytes (`file` is null
// after a reload), so the retry must verify it again, not delete it.
retryAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: draftId,
});
await awaitAttachmentUploads([file.id]);
expect(readAttachmentUpload(file.id)).toEqual({
status: "ready",
environmentId: firstEnvironment,
attachmentId: "pending-flaky-pdf",
});
expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.files).toMatchObject([
{
uploadedAttachmentId: "pending-flaky-pdf",
uploadEnvironmentId: firstEnvironment,
},
]);
const removeCalls = mocks.runAtomCommand.mock.calls.filter(
([, command]) => command === mocks.removeUpload,
);
expect(removeCalls).toEqual([]);
} finally {
useComposerDraftStore.getState().clearComposerContent(draftId);
}
});
it("keeps the persisted upload when an environment switch cancels its verification", async () => {
const file: ComposerFileAttachment = {
...makeFile("moving"),
file: null,
uploadedAttachmentId: "pending-moving-pdf",
uploadEnvironmentId: firstEnvironment,
};
let resolveVerification: (result: {
readonly _tag: "Success";
readonly value: object;
}) => void = () => {};
mocks.executeAtomQuery.mockReturnValueOnce(
new Promise((resolve) => {
resolveVerification = resolve;
}),
);
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
// Switching environments cancels the in-flight verification. The draft
// still references the upload in the first environment, so the cancel
// must not delete it.
startAttachmentUpload({ environmentId: secondEnvironment, image: file });
resolveVerification({ _tag: "Success", value: {} });
await awaitAttachmentUploads([file.id]);
const persistedRemoveCalls = mocks.runAtomCommand.mock.calls.filter(
([, command, target]) =>
command === mocks.removeUpload &&
(target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
"pending-moving-pdf",
);
expect(persistedRemoveCalls).toEqual([]);
});
it("cancels persisted-upload verification when a stash discards its file", async () => {
const file: ComposerFileAttachment = {
...makeFile("stashed-checking"),
file: null,
uploadedAttachmentId: "pending-stashed-checking-pdf",
uploadEnvironmentId: firstEnvironment,
};
let resolveVerification: (result: {
readonly _tag: "Success";
readonly value: object;
}) => void = () => {};
mocks.executeAtomQuery.mockReturnValueOnce(
new Promise((resolve) => {
resolveVerification = resolve;
}),
);
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
releasePersistedAttachmentUpload({
id: file.id,
environmentId: firstEnvironment,
attachmentId: "pending-stashed-checking-pdf",
});
resolveVerification({ _tag: "Success", value: {} });
await Promise.resolve();
expect(readAttachmentUpload(file.id)).toBeUndefined();
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.removeUpload,
{
environmentId: firstEnvironment,
input: { attachmentId: "pending-stashed-checking-pdf" },
},
expect.anything(),
);
});
it("releases the persisted server upload when a hydrated draft is discarded after a reload", () => {
// After a reload the in-memory queue is empty; the draft file only carries
// its persisted attachment id. Discarding it must still delete the
// server-side pending upload.
const file: ComposerFileAttachment = {
...makeFile("hydrated"),
file: null,
uploadedAttachmentId: "pending-hydrated-pdf",
uploadEnvironmentId: firstEnvironment,
};
releaseDraftAttachment(file);
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.removeUpload,
{
environmentId: firstEnvironment,
input: { attachmentId: "pending-hydrated-pdf" },
},
expect.anything(),
);
});
it("routes a live persisted upload through the queue release exactly once", async () => {
const file: ComposerFileAttachment = {
...makeFile("live"),
file: null,
uploadedAttachmentId: "pending-live-pdf",
uploadEnvironmentId: firstEnvironment,
};
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
await awaitAttachmentUploads([file.id]);
expect(readAttachmentUpload(file.id)).toMatchObject({ status: "ready" });
releaseDraftAttachment(file);
expect(readAttachmentUpload(file.id)).toBeUndefined();
const removeCalls = mocks.runAtomCommand.mock.calls.filter(
([, command]) => command === mocks.removeUpload,
);
expect(removeCalls).toEqual([
[
expect.anything(),
mocks.removeUpload,
{
environmentId: firstEnvironment,
input: { attachmentId: "pending-live-pdf" },
},
expect.anything(),
],
]);
});
it("deletes a persisted server upload even when browser upload state is gone", () => {
releasePersistedAttachmentUpload({
id: "stashed-report",
environmentId: firstEnvironment,
attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf",
});
expect(mocks.runAtomCommand).toHaveBeenCalledWith(
expect.anything(),
mocks.removeUpload,
{
environmentId: firstEnvironment,
input: { attachmentId: "pending-00000000-0000-4000-8000-000000000001-pdf" },
},
expect.anything(),
);
});
it("retries rejected uploads", async () => {
const image = makeImage("image-retry");
startAttachmentUpload({ environmentId: firstEnvironment, image });
@@ -277,6 +849,90 @@ describe("attachmentUploadQueue", () => {
});
});
it("releases a moved file's source upload only after its destination upload succeeds", async () => {
const source = scopeThreadRef(firstEnvironment, ThreadId.make("thread-file-move-source"));
const destination = scopeThreadRef(
secondEnvironment,
ThreadId.make("thread-file-move-destination"),
);
const file = makeFile("moved-report");
const store = useComposerDraftStore.getState();
store.addFiles(source, [file]);
try {
startAttachmentUpload({
environmentId: firstEnvironment,
image: file,
draftTarget: source,
});
await Promise.resolve();
let settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[0]!.complete();
await settled;
const sourceAttachmentId = store.getComposerDraft(source)?.files[0]?.uploadedAttachmentId;
expect(sourceAttachmentId).toBe("pending-environment-1-moved-report.pdf");
store.moveComposerPromptAndImages(source, destination);
const movedFile = store.getComposerDraft(destination)?.files[0];
expect(movedFile).toMatchObject({
id: file.id,
file: file.file,
});
expect(movedFile?.uploadedAttachmentId).toBeUndefined();
expect(movedFile?.uploadEnvironmentId).toBeUndefined();
startAttachmentUpload({
environmentId: secondEnvironment,
image: movedFile!,
draftTarget: destination,
});
await Promise.resolve();
const sourceDeletesBeforeDestinationUpload = mocks.runAtomCommand.mock.calls.filter(
([, command, target]) =>
command === mocks.removeUpload &&
(
target as {
readonly environmentId: EnvironmentId;
readonly input: { readonly attachmentId: string };
}
).environmentId === firstEnvironment &&
(target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
sourceAttachmentId,
);
expect(sourceDeletesBeforeDestinationUpload).toEqual([]);
settled = awaitAttachmentUploads([file.id]);
TestXmlHttpRequest.requests[1]!.complete();
await settled;
const sourceDeletesAfterDestinationUpload = mocks.runAtomCommand.mock.calls.filter(
([, command, target]) =>
command === mocks.removeUpload &&
(
target as {
readonly environmentId: EnvironmentId;
readonly input: { readonly attachmentId: string };
}
).environmentId === firstEnvironment &&
(target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===
sourceAttachmentId,
);
expect(sourceDeletesAfterDestinationUpload).toHaveLength(1);
expect(store.getComposerDraft(destination)?.files).toMatchObject([
{
id: file.id,
uploadedAttachmentId: "pending-environment-2-moved-report.pdf",
uploadEnvironmentId: secondEnvironment,
},
]);
} finally {
store.clearComposerContent(source);
store.clearComposerContent(destination);
}
});
it("does not let stalled uploads block another environment", async () => {
const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);
for (const image of images) {
+311 -91
View File
@@ -3,12 +3,25 @@ import {
type ChatAttachment,
type EnvironmentId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import {
deletePendingAttachmentUpload,
runAttachmentUploadCycle,
verifyPersistedAttachmentUpload,
type PersistedAttachmentVerification,
} from "@t3tools/client-runtime/state/attachments";
import { create } from "zustand";
import type { ComposerImageAttachment } from "../composerDraftStore";
import {
DraftId,
useComposerDraftStore,
type ComposerFileAttachment,
type ComposerImageAttachment,
type ComposerThreadTarget,
} from "../composerDraftStore";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { assetEnvironment } from "../state/assets";
import { attachmentEnvironment } from "../state/attachments";
import { readPreparedConnection } from "../state/session";
import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";
@@ -25,11 +38,23 @@ export const useAttachmentUploadStore = create<AttachmentUploadStore>(() => ({
}));
interface UploadJob {
readonly image: ComposerImageAttachment;
readonly image: ComposerImageAttachment | ComposerFileAttachment;
readonly environmentId: EnvironmentId;
/**
* The draft that owned this file when the job started. Completion resolves
* the current owner because the file can move while the upload is pending.
*/
readonly draftTarget?: ComposerThreadTarget;
readonly previous?: ReadyAttachmentUpload;
/**
* The draft's persisted server-side upload, to verify instead of re-upload.
* The draft owns this id; the queue never deletes it on cancel or retry.
* Deleting it goes through `releasePersistedAttachmentUpload` only.
*/
readonly persistedAttachmentId?: string;
readonly settled: Promise<void>;
resolveSettled: () => void;
/** Only ids this queue minted itself. Cancel and retry may delete these. */
attachmentId: string | null;
cancelled: boolean;
abort: (() => void) | null;
@@ -60,25 +85,73 @@ export function readAttachmentUpload(imageId: string): AttachmentUploadState | u
return useAttachmentUploadStore.getState().uploadsByImageId[imageId];
}
/** Finds the file's current same-environment draft after any in-flight move. */
function resolveCurrentFileDraftTarget(job: UploadJob): ComposerThreadTarget | undefined {
if (job.draftTarget === undefined || job.image.type !== "file") {
return undefined;
}
const store = useComposerDraftStore.getState();
for (const [key, draft] of Object.entries(store.draftsByThreadKey)) {
if (!draft.files.some((file) => file.id === job.image.id)) {
continue;
}
const draftSession = store.draftThreadsByThreadKey[key];
if (draftSession !== undefined) {
if (draftSession.environmentId === job.environmentId) {
return DraftId.make(key);
}
continue;
}
// Tests and legacy callers can use a DraftId without session metadata.
// Only its original job supplies enough environment identity to trust it.
if (typeof job.draftTarget === "string" && job.draftTarget === key) {
return DraftId.make(key);
}
const threadRef = parseScopedThreadKey(key);
if (threadRef?.environmentId === job.environmentId) {
return threadRef;
}
}
return undefined;
}
/**
* Persists a finished upload's ids onto the draft that owns the file. The
* mounted composer effect performs the same write for live UI updates, but a
* background completion (user navigated away, upload finished, reload) must
* not depend on a mounted composer to survive. `setFileUpload` no-ops when
* the draft row is gone or already carries these ids.
*/
function stampDraftFileUpload(job: UploadJob, attachmentId: string): void {
const draftTarget = resolveCurrentFileDraftTarget(job);
if (draftTarget === undefined) {
return;
}
useComposerDraftStore
.getState()
.setFileUpload(draftTarget, job.image.id, job.environmentId, attachmentId);
}
function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {
void runAtomCommand(
appAtomRegistry,
attachmentEnvironment.remove,
{ environmentId, input: { attachmentId } },
{ reportFailure: false, reportDefect: false },
);
deletePendingAttachmentUpload({
registry: appAtomRegistry,
remove: attachmentEnvironment.remove,
environmentId,
attachmentId,
});
}
function uploadBytes(input: {
readonly url: string;
readonly file: File;
readonly mimeType: string;
readonly onProgress: (progress: number) => void;
}): { readonly done: Promise<void>; readonly abort: () => void } {
const xhr = new XMLHttpRequest();
const done = new Promise<void>((resolve, reject) => {
xhr.open("POST", input.url, true);
xhr.timeout = UPLOAD_TIMEOUT_MS;
xhr.setRequestHeader("Content-Type", input.file.type);
xhr.setRequestHeader("Content-Type", input.mimeType);
xhr.upload.addEventListener("progress", (event) => {
if (event.lengthComputable && event.total > 0) {
input.onProgress(event.loaded / event.total);
@@ -101,9 +174,66 @@ function uploadBytes(input: {
}
async function runUpload(job: UploadJob): Promise<void> {
const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
(supportedMimeType) => supportedMimeType === job.image.mimeType.toLowerCase(),
);
if (job.persistedAttachmentId) {
const verification = await verifyPersistedAttachmentUpload({
registry: appAtomRegistry,
createAssetUrl: assetEnvironment.createUrl,
environmentId: job.environmentId,
attachmentId: job.persistedAttachmentId,
});
if (job.cancelled) {
return;
}
if (verification.status === "verified") {
setUploadState(job.image.id, {
status: "ready",
environmentId: job.environmentId,
attachmentId: job.persistedAttachmentId,
});
stampDraftFileUpload(job, job.persistedAttachmentId);
return;
}
if (verification.status === "missing" && !job.image.file && job.image.type === "file") {
const draftTarget = resolveCurrentFileDraftTarget(job);
if (
draftTarget !== undefined &&
useComposerDraftStore
.getState()
.markFileUploadMissing(
draftTarget,
job.image.id,
job.environmentId,
job.persistedAttachmentId,
)
) {
clearUploadState(job.image.id);
return;
}
}
if (verification.status === "failed" || !job.image.file) {
// No `attachmentId` here: a failed state's id marks a pending upload
// this queue minted, which retry and release then delete. The persisted
// id is the only server copy of a hydrated file, so a transient
// verification failure must leave it in place for the next retry.
setUploadState(job.image.id, {
status: "failed",
environmentId: job.environmentId,
reason:
verification.status === "missing"
? "Uploaded file expired. Remove it and attach it again."
: "Uploaded file could not be verified. Retry when the server reconnects.",
...(job.previous ? { previous: job.previous } : {}),
});
return;
}
}
const mimeType =
job.image.type === "file"
? job.image.mimeType.toLowerCase()
: PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
(supportedMimeType) => supportedMimeType === job.image.mimeType.toLowerCase(),
);
if (!mimeType) {
setUploadState(job.image.id, {
status: "failed",
@@ -113,97 +243,93 @@ async function runUpload(job: UploadJob): Promise<void> {
});
return;
}
const minted = await runAtomCommand(
appAtomRegistry,
attachmentEnvironment.createUploadUrl,
{
environmentId: job.environmentId,
input: {
name: job.image.name,
mimeType,
sizeBytes: job.image.file.size,
},
},
{ reportFailure: false },
);
if (job.cancelled) {
if (minted._tag === "Success") {
deletePendingUpload(job.environmentId, minted.value.attachmentId);
}
return;
}
if (minted._tag !== "Success") {
const file = job.image.file;
if (!file) {
setUploadState(job.image.id, {
status: "failed",
environmentId: job.environmentId,
reason: "Upload could not start",
...(job.previous ? { previous: job.previous } : {}),
});
return;
}
job.attachmentId = minted.value.attachmentId;
const connection = readPreparedConnection(job.environmentId);
const url = connection ? resolveAssetUrl(connection.httpBaseUrl, minted.value.relativeUrl) : null;
if (!url) {
setUploadState(job.image.id, {
status: "failed",
environmentId: job.environmentId,
reason: "Not connected",
attachmentId: minted.value.attachmentId,
reason: "Original file is no longer available",
...(job.previous ? { previous: job.previous } : {}),
});
return;
}
let lastStep = -1;
const upload = uploadBytes({
url,
file: job.image.file,
onProgress: (progress) => {
const step = Math.floor(progress * 20);
if (step === lastStep || job.cancelled) {
return;
const result = await runAttachmentUploadCycle({
registry: appAtomRegistry,
createUploadUrl: attachmentEnvironment.createUploadUrl,
remove: attachmentEnvironment.remove,
environmentId: job.environmentId,
upload: {
...(job.image.type === "file" ? { type: "file" as const } : {}),
name: job.image.name,
mimeType,
sizeBytes: file.size,
},
resolveUploadUrl: (relativeUrl) => {
const connection = readPreparedConnection(job.environmentId);
return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null;
},
transport: (url) =>
uploadBytes({
url,
file,
mimeType,
onProgress: (progress) => {
const step = Math.floor(progress * 20);
if (step === lastStep || job.cancelled) {
return;
}
lastStep = step;
setUploadState(job.image.id, {
status: "uploading",
environmentId: job.environmentId,
progress,
...(job.previous ? { previous: job.previous } : {}),
});
},
}),
onMinted: (attachmentId) => {
if (job.cancelled) {
return "cancel";
}
lastStep = step;
setUploadState(job.image.id, {
status: "uploading",
environmentId: job.environmentId,
progress,
...(job.previous ? { previous: job.previous } : {}),
});
job.attachmentId = attachmentId;
return "continue";
},
onTransferStart: (abort) => {
job.abort = abort;
},
});
job.abort = upload.abort;
try {
await upload.done;
if (job.cancelled) {
return;
}
job.abort = null;
if (result.status === "cancelled" || job.cancelled) {
return;
}
if (result.status === "uploaded") {
setUploadState(job.image.id, {
status: "ready",
environmentId: job.environmentId,
attachmentId: minted.value.attachmentId,
attachmentId: result.attachmentId,
});
stampDraftFileUpload(job, result.attachmentId);
if (job.previous) {
deletePendingUpload(job.previous.environmentId, job.previous.attachmentId);
}
} catch (error) {
if (job.cancelled) {
return;
}
setUploadState(job.image.id, {
status: "failed",
environmentId: job.environmentId,
reason: error instanceof Error ? error.message : "Upload failed",
attachmentId: minted.value.attachmentId,
...(job.previous ? { previous: job.previous } : {}),
});
} finally {
job.abort = null;
return;
}
setUploadState(job.image.id, {
status: "failed",
environmentId: job.environmentId,
reason:
result.step === "mint"
? "Upload could not start"
: result.step === "resolve-url"
? "Not connected"
: result.error instanceof Error
? result.error.message
: "Upload failed",
...(result.attachmentId ? { attachmentId: result.attachmentId } : {}),
...(job.previous ? { previous: job.previous } : {}),
});
}
function pumpUploads(): void {
@@ -249,7 +375,9 @@ function pumpUploads(): void {
export function startAttachmentUpload(input: {
readonly environmentId: EnvironmentId;
readonly image: ComposerImageAttachment;
readonly image: ComposerImageAttachment | ComposerFileAttachment;
/** Draft that owns the file; lets a background completion persist its ids. */
readonly draftTarget?: ComposerThreadTarget;
}): void {
const existingJob = jobsByImageId.get(input.image.id);
if (existingJob?.environmentId === input.environmentId) {
@@ -287,7 +415,13 @@ export function startAttachmentUpload(input: {
const job: UploadJob = {
image: input.image,
environmentId: input.environmentId,
...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
...(previous ? { previous } : {}),
...(input.image.type === "file" &&
input.image.uploadEnvironmentId === input.environmentId &&
input.image.uploadedAttachmentId
? { persistedAttachmentId: input.image.uploadedAttachmentId }
: {}),
settled,
resolveSettled,
attachmentId: null,
@@ -306,6 +440,11 @@ export function startAttachmentUpload(input: {
pumpUploads();
}
/**
* Stops the job and deletes only the pending upload it minted itself. A
* persisted draft upload survives cancellation (an environment switch cancels
* the old job, and the draft still references that server copy).
*/
export function cancelAttachmentUpload(imageId: string): void {
const job = jobsByImageId.get(imageId);
if (!job) {
@@ -340,12 +479,42 @@ export function releaseAttachmentUpload(imageId: string): void {
clearUploadState(imageId);
}
export function releasePersistedAttachmentUpload(input: {
readonly id: string;
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
}): void {
const upload = readAttachmentUpload(input.id);
if (
upload?.status === "ready" &&
upload.environmentId === input.environmentId &&
upload.attachmentId === input.attachmentId
) {
releaseAttachmentUpload(input.id);
return;
}
const job = jobsByImageId.get(input.id);
if (
job?.environmentId === input.environmentId &&
job.persistedAttachmentId === input.attachmentId
) {
// Tears down the in-flight verification or re-upload. The queue only
// deletes ids it minted, so the persisted id still needs the delete below.
releaseAttachmentUpload(input.id);
}
deletePendingUpload(input.environmentId, input.attachmentId);
}
export function retryAttachmentUpload(input: {
readonly environmentId: EnvironmentId;
readonly image: ComposerImageAttachment;
readonly image: ComposerImageAttachment | ComposerFileAttachment;
readonly draftTarget?: ComposerThreadTarget;
}): void {
const previous = readAttachmentUpload(input.image.id);
cancelAttachmentUpload(input.image.id);
// A failed state's `attachmentId` is always one this queue minted, so this
// never deletes a persisted draft upload. Retrying a hydrated file whose
// verification failed leaves the server copy alone and verifies it again.
if (previous?.status === "failed" && previous.attachmentId) {
deletePendingUpload(previous.environmentId, previous.attachmentId);
}
@@ -357,13 +526,30 @@ export function retryAttachmentUpload(input: {
startAttachmentUpload(input);
}
/**
* Checks that a stashed upload still exists on the server. Pending uploads
* are swept after 24 hours, so a stash restore asks first instead of handing
* the composer a dead reference.
*/
export function verifyStashedAttachmentUpload(input: {
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
}): Promise<PersistedAttachmentVerification> {
return verifyPersistedAttachmentUpload({
registry: appAtomRegistry,
createAssetUrl: assetEnvironment.createUrl,
environmentId: input.environmentId,
attachmentId: input.attachmentId,
});
}
export async function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): Promise<void> {
await Promise.all(imageIds.map((imageId) => jobsByImageId.get(imageId)?.settled));
}
export function getUploadedAttachments(input: {
readonly environmentId: EnvironmentId;
readonly images: ReadonlyArray<ComposerImageAttachment>;
readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
}): ChatAttachment[] | null {
const attachments: ChatAttachment[] = [];
for (const image of input.images) {
@@ -372,7 +558,7 @@ export function getUploadedAttachments(input: {
return null;
}
attachments.push({
type: "image",
type: image.type,
id: upload.attachmentId,
name: image.name,
mimeType: image.mimeType,
@@ -382,8 +568,42 @@ export function getUploadedAttachments(input: {
return attachments;
}
export function releaseAttachmentUploads(images: ReadonlyArray<ComposerImageAttachment>): void {
for (const image of images) {
releaseAttachmentUpload(image.id);
/**
* The one owner for discarding a draft attachment's server-side upload. The
* queue-keyed release only sees in-memory state, so after a reload it finds
* nothing and the pending upload leaks. When the draft carries a persisted
* `uploadedAttachmentId` (which survives reloads), route through the persisted
* release; it still prefers the queue path when the queue owns that same
* attachment. Every draft discard path must funnel through here.
*/
export function releaseDraftAttachment(
attachment: ComposerImageAttachment | ComposerFileAttachment,
): void {
if (
attachment.type === "file" &&
attachment.uploadedAttachmentId !== undefined &&
attachment.uploadEnvironmentId !== undefined
) {
releasePersistedAttachmentUpload({
id: attachment.id,
environmentId: attachment.uploadEnvironmentId,
attachmentId: attachment.uploadedAttachmentId,
});
// A failed re-upload after verification can hold a newer minted
// attachment under the queue key. Release whatever is left so neither
// copy stays behind. (The pending delete is idempotent server-side.)
if (jobsByImageId.has(attachment.id) || readAttachmentUpload(attachment.id)) {
releaseAttachmentUpload(attachment.id);
}
return;
}
releaseAttachmentUpload(attachment.id);
}
export function releaseDraftAttachments(
attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
): void {
for (const attachment of attachments) {
releaseDraftAttachment(attachment);
}
}
@@ -34,7 +34,7 @@ describe("attachmentUploadBlockReason", () => {
"image-1": { status: "uploading", environmentId, progress: 0.5 },
},
}),
).toBe("Images still uploading");
).toBe("Attachments still uploading");
});
it("asks the user to retry or remove failed uploads", () => {
@@ -46,7 +46,7 @@ describe("attachmentUploadBlockReason", () => {
"image-1": { status: "failed", environmentId, reason: "Upload failed" },
},
}),
).toBe("Retry or remove the failed image");
).toBe("Retry or remove the failed attachment");
});
it("does not accept an upload from another environment", () => {
@@ -62,7 +62,7 @@ describe("attachmentUploadBlockReason", () => {
},
},
}),
).toBe("Image still uploading");
).toBe("Attachment still uploading");
});
});
+9 -2
View File
@@ -18,6 +18,11 @@ export type AttachmentUploadState =
readonly status: "failed";
readonly environmentId: EnvironmentId;
readonly reason: string;
/**
* A pending upload the queue minted for this failed attempt. Retry and
* release delete it, so it must never carry a draft's persisted
* attachment id.
*/
readonly attachmentId?: string;
readonly previous?: ReadyAttachmentUpload;
};
@@ -40,10 +45,12 @@ export function attachmentUploadBlockReason(input: {
}
if (failed > 0) {
return failed === 1 ? "Retry or remove the failed image" : "Retry or remove the failed images";
return failed === 1
? "Retry or remove the failed attachment"
: "Retry or remove the failed attachments";
}
if (pending > 0) {
return pending === 1 ? "Image still uploading" : "Images still uploading";
return pending === 1 ? "Attachment still uploading" : "Attachments still uploading";
}
return null;
}
+21 -4
View File
@@ -1,23 +1,40 @@
import type { ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
import { releaseAttachmentUploads } from "./attachmentUploadQueue";
import { releaseDraftAttachments } from "./attachmentUploadQueue";
export function releaseComposerDraftUploads(target: ScopedThreadRef | DraftId): void {
const draft = useComposerDraftStore.getState().getComposerDraft(target);
if (draft) {
releaseAttachmentUploads(draft.images);
releaseDraftAttachments([...draft.images, ...draft.files]);
}
}
export function releaseProjectDraftUploads(projectRef: ScopedProjectRef): void {
/**
* Releases every upload a deleted project's drafts still hold. Draft-thread
* sessions carry their project ref, but drafts on the project's real threads
* live in `draftsByThreadKey` under scoped thread keys with no project in the
* key, so the caller passes the project's thread refs alongside.
*/
export function releaseProjectDraftUploads(
projectRef: ScopedProjectRef,
projectThreadRefs: ReadonlyArray<ScopedThreadRef> = [],
): void {
const store = useComposerDraftStore.getState();
for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) {
if (
session.environmentId === projectRef.environmentId &&
session.projectId === projectRef.projectId
) {
releaseAttachmentUploads(store.draftsByThreadKey[draftKey]?.images ?? []);
const draft = store.draftsByThreadKey[draftKey];
releaseDraftAttachments(draft ? [...draft.images, ...draft.files] : []);
}
}
for (const threadRef of projectThreadRefs) {
const draft = store.draftsByThreadKey[scopedThreadKey(threadRef)];
if (draft) {
releaseDraftAttachments([...draft.images, ...draft.files]);
}
}
}
+57
View File
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
import { EnvironmentId } from "@t3tools/contracts";
import { removeLocalStorageItem } from "./hooks/useLocalStorage";
@@ -162,6 +163,62 @@ describe("promptStashStore", () => {
expect(entry?.pendingImageCount).toBe(0);
});
it("takeEntry returns images and drop metadata finalized after a menu snapshot", () => {
const store = usePromptStashStore.getState();
store.stashEntry({ ...makeEntry({ id: "pending-restore" }), pendingImageCount: 1 });
const menuSnapshot = usePromptStashStore.getState().entries[0];
expect(menuSnapshot?.attachments).toEqual([]);
store.finalizeEntryImages("pending-restore", {
attachments: [
{
id: "img-finalized",
name: "finalized.webp",
mimeType: "image/webp",
sizeBytes: 12,
dataUrl: "data:image/webp;base64,BBBB",
},
],
droppedImageNames: ["too-large.png"],
unreadableImageNames: ["unreadable.png"],
});
const { entry: taken } = store.takeEntry("pending-restore");
expect(taken).not.toBe(menuSnapshot);
expect(taken).toMatchObject({
attachments: [
{
id: "img-finalized",
name: "finalized.webp",
},
],
droppedImageNames: ["too-large.png"],
unreadableImageNames: ["unreadable.png"],
pendingImageCount: 0,
});
});
it("preserves uploaded file references without storing file contents", () => {
const store = usePromptStashStore.getState();
const file = {
id: "file-1",
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 42,
attachmentId: "pending-report-pdf",
environmentId: EnvironmentId.make("environment-1"),
};
store.stashEntry({ ...makeEntry({ id: "with-file" }), files: [file] });
store.finalizeEntryImages("with-file", {
attachments: [],
droppedImageNames: [],
unreadableImageNames: [],
});
expect(usePromptStashStore.getState().entries[0]?.files).toEqual([file]);
});
it("finalizeEntryImages reports false when the entry was already taken", () => {
const store = usePromptStashStore.getState();
store.stashEntry({ ...makeEntry({ id: "racing" }), pendingImageCount: 1 });
+7 -5
View File
@@ -1,7 +1,10 @@
import * as Schema from "effect/Schema";
import { create } from "zustand";
import { PersistedComposerImageAttachment } from "./composerDraftStore";
import {
PersistedComposerFileAttachment,
PersistedComposerImageAttachment,
} from "./composerDraftStore";
import { createMemoryStorage, type StateStorage } from "./lib/storage";
export const PROMPT_STASH_STORAGE_KEY = "t3code:prompt-stash:v2";
@@ -27,16 +30,15 @@ export const MAX_STASH_ENTRIES = 20;
export const MAX_STASH_ENTRY_ATTACHMENT_CHARS = 2_700_000;
/**
* A stashed prompt carries only what every provider can accept: text and
* image attachments. Deliberately no provider instance or model selection —
* the point of stashing is to move a prompt into a different thread or
* provider, so restoring must never drag the old model choice along.
* Stashed files keep signed-upload references instead of storing their bytes.
* Image payloads remain subject to the localStorage budget.
*/
const StashEntrySchema = Schema.Struct({
id: Schema.String,
createdAt: Schema.String,
prompt: Schema.String,
attachments: Schema.Array(PersistedComposerImageAttachment),
files: Schema.optionalKey(Schema.Array(PersistedComposerFileAttachment)),
/** Names of images that exceeded the attachment budget and were not saved. */
droppedImageNames: Schema.Array(Schema.String),
/**
+2 -12
View File
@@ -1,15 +1,5 @@
import { WS_METHODS } from "@t3tools/contracts";
import { createEnvironmentRpcCommand } from "@t3tools/client-runtime/state/runtime";
import { createAttachmentEnvironmentAtoms } from "@t3tools/client-runtime/state/attachments";
import { connectionAtomRuntime } from "../connection/runtime";
export const attachmentEnvironment = {
createUploadUrl: createEnvironmentRpcCommand(connectionAtomRuntime, {
label: "environment-command:attachments:create-upload-url",
tag: WS_METHODS.attachmentsCreateUploadUrl,
}),
remove: createEnvironmentRpcCommand(connectionAtomRuntime, {
label: "environment-command:attachments:delete",
tag: WS_METHODS.attachmentsDelete,
}),
};
export const attachmentEnvironment = createAttachmentEnvironmentAtoms(connectionAtomRuntime);
+18 -7
View File
@@ -1,6 +1,7 @@
import type {
ChatAttachment as ContractChatAttachment,
ChatFileAttachment as ContractChatFileAttachment,
ChatImageAttachment as ContractChatImageAttachment,
ChatUnknownAttachment as ContractChatUnknownAttachment,
OrchestrationCheckpointFile,
OrchestrationCheckpointSummary,
OrchestrationLatestTurn,
@@ -36,18 +37,28 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
readonly previewUrl?: string;
}
// Non-image members pass through with the contract shape. The web UI renders
// them once it grows file support; until then they only need to typecheck.
export type ChatAttachment =
| ChatImageAttachment
| Exclude<ContractChatAttachment, ContractChatImageAttachment>;
export interface ChatFileAttachment extends ContractChatFileAttachment {
readonly previewUrl?: string;
readonly downloadable?: boolean;
}
// Attachment types this build does not know pass through with the contract
// shape. The UI renders them as inert rows so a newer server cannot crash an
// older client.
export type ChatUnknownAttachment = ContractChatUnknownAttachment;
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment | ChatUnknownAttachment;
// The union has an open member (`type: string`), so a literal comparison does
// not narrow. Use this guard wherever image-only fields are read.
// not narrow. Use these guards wherever type-specific fields are read.
export function isImageAttachment(attachment: ChatAttachment): attachment is ChatImageAttachment {
return attachment.type === "image";
}
export function isFileAttachment(attachment: ChatAttachment): attachment is ChatFileAttachment {
return attachment.type === "file";
}
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
}