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:
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);
|
||||
|
||||
@@ -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>();
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 +
|
||||
|
||||
@@ -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)} | ||||