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);