feat(composer): fold large pastes into text attachments (#11442)

This commit is contained in:
Chris Deeming authored and GitHub committed 2026-09-12 17:28:28 -07:00
1 parent 36caf200c2
commit 68c2277f50
77 files changed
+3278 -465

No files matched your search

+25 -6
View File
@@ -46,6 +46,8 @@ import {
} from "@t3tools/contracts";
import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
import { readPastedComposerContext } from "./composerInlineTokenPaste";
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
import { type CodexArtifactTemplate } from "@t3tools/client-runtime/codex-artifact-templates";
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
import {
@@ -95,6 +97,7 @@ import { flushSync } from "react-dom";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
import { isMacPlatform } from "../lib/utils";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import { useShallow } from "zustand/react/shallow";
import {
@@ -1608,6 +1611,7 @@ export default function ChatView(props: ChatViewProps) {
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
const composerRef = useComposerHandleContext() ?? localComposerRef;
const pasteAsTextShortcutUntilRef = useRef(0);
const [restingComposerControlsHost, setRestingComposerControlsHost] =
useState<HTMLDivElement | null>(null);
const [restingComposerControlsVisible, setRestingComposerControlsVisible] = useState(false);
@@ -6519,24 +6523,38 @@ export default function ChatView(props: ChatViewProps) {
// so a paste that follows has no editable target and would be dropped.
// Route it to the composer like a typed key, which also expands it.
useEffect(() => {
const keyHandler = (event: KeyboardEvent) => {
if (
shouldRedirectInputToComposer(event) &&
isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
) {
pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
}
};
const handler = (event: ClipboardEvent) => {
if (!activeThreadId || isCommandPaletteOpen()) return;
if (getTerminalFocusOwner() !== null) return;
if (composerRef.current?.isModelPickerOpen()) return;
const text = pasteTextToFocusComposer(event);
if (text === null) return;
const clipboardData = event.clipboardData;
if (text === null || clipboardData === null) return;
const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current;
pasteAsTextShortcutUntilRef.current = 0;
if (
composerRef.current?.insertTextAtEnd(
text,
event.clipboardData ? { clipboardData: event.clipboardData } : undefined,
)
((readPastedComposerContext(clipboardData)?.records.length ?? 0) === 0 &&
composerRef.current?.pasteTextAtEnd(text, { bypassAutoAttachment })) ||
composerRef.current?.insertTextAtEnd(text, { clipboardData })
) {
event.preventDefault();
event.stopPropagation();
}
};
window.addEventListener("keydown", keyHandler, true);
window.addEventListener("paste", handler, true);
return () => window.removeEventListener("paste", handler, true);
return () => {
window.removeEventListener("keydown", keyHandler, true);
window.removeEventListener("paste", handler, true);
};
}, [activeThreadId, composerRef]);
const [pendingRevert, setPendingRevert] = useState<{
@@ -7257,6 +7275,7 @@ export default function ChatView(props: ChatViewProps) {
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadable: false,
...(attachment.source ? { source: attachment.source } : {}),
},
);
const shouldAnchorFirstMessage =
@@ -18,6 +18,7 @@ import {
import {
importPastedComposerText,
readPastedComposerContext,
registerComposerInlineTokenPaste,
} from "./composerInlineTokenPaste";
import {
@@ -498,92 +499,103 @@ describe("registerComposerInlineTokenPaste", () => {
});
describe("context reference paste", () => {
it.each(["focused", "blurred"])("imports structured paste when %s", (focus) => {
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
const editor = createEditor({ nodes: [ComposerCitationNode] });
editor.update(
() => {
const paragraph = $createParagraphNode();
$getRoot().append(paragraph);
paragraph.selectEnd();
},
{ discrete: true },
);
const imported: string[] = [];
const importFragment = (
fragment: import("@t3tools/contracts").ComposerContextClipboardFragment,
) => {
imported.push(...fragment.records.map((record) => record.contextId));
return new Map([["img-old", "img-new"]]);
};
registerComposerInlineTokenPaste(editor, {
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
createCitationNode: $createComposerCitationNode,
createContextReferenceNode: (reference) =>
$createTextNode(`<context:${reference.contextId}>`),
getExpandedAbsoluteOffsetForPoint: () => 0,
importContextFragment: importFragment,
});
const event = new TestClipboardEvent(
"![shot](t3-context://v1/image/img-old) and [T](t3-context://v1/terminal/ctx-t)",
{
"web application/x-t3-context-fragment+json": JSON.stringify({
version: 1,
source: { environmentId: "env-1" },
records: [
{
version: 1,
contextId: "img-old",
kind: "image",
label: "shot",
attachmentId: "a",
name: "shot.png",
mimeType: "image/png",
sizeBytes: 1,
},
{
version: 1,
contextId: "ctx-t",
kind: "terminal",
label: "T",
terminalId: "t",
terminalLabel: "T",
lineStart: 1,
lineEnd: 1,
text: "x",
},
{
version: 1,
contextId: "img-unrelated",
kind: "image",
label: "other",
attachmentId: "b",
name: "other.png",
mimeType: "image/png",
sizeBytes: 1,
},
],
}),
},
);
if (focus === "blurred") {
expect(importPastedComposerText(event.clipboardData, importFragment)).toBe(
"![shot](t3-context://v1/image/img-new) and [T](t3-context://v1/terminal/ctx-t)",
it.each([
{ focus: "focused", prefix: "" },
{ focus: "blurred", prefix: "" },
{ focus: "focused", prefix: "log ".repeat(10_000) },
{ focus: "blurred", prefix: "log ".repeat(10_000) },
])(
"imports structured paste when $focus with $prefix.length extra characters",
({ focus, prefix }) => {
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
const editor = createEditor({ nodes: [ComposerCitationNode] });
editor.update(
() => {
const paragraph = $createParagraphNode();
$getRoot().append(paragraph);
paragraph.selectEnd();
},
{ discrete: true },
);
const imported: string[] = [];
const importFragment = (
fragment: import("@t3tools/contracts").ComposerContextClipboardFragment,
) => {
imported.push(...fragment.records.map((record) => record.contextId));
return new Map([["img-old", "img-new"]]);
};
registerComposerInlineTokenPaste(editor, {
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
createCitationNode: $createComposerCitationNode,
createContextReferenceNode: (reference) =>
$createTextNode(`<context:${reference.contextId}>`),
getExpandedAbsoluteOffsetForPoint: () => 0,
importContextFragment: importFragment,
});
const event = new TestClipboardEvent(
`${prefix}![shot](t3-context://v1/image/img-old) and [T](t3-context://v1/terminal/ctx-t)`,
{
"web application/x-t3-context-fragment+json": JSON.stringify({
version: 1,
source: { environmentId: "env-1" },
records: [
{
version: 1,
contextId: "img-old",
kind: "image",
label: "shot",
attachmentId: "a",
name: "shot.png",
mimeType: "image/png",
sizeBytes: 1,
},
{
version: 1,
contextId: "ctx-t",
kind: "terminal",
label: "T",
terminalId: "t",
terminalLabel: "T",
lineStart: 1,
lineEnd: 1,
text: "x",
},
{
version: 1,
contextId: "img-unrelated",
kind: "image",
label: "other",
attachmentId: "b",
name: "other.png",
mimeType: "image/png",
sizeBytes: 1,
},
],
}),
},
);
expect(
readPastedComposerContext(event.clipboardData)?.records.map((record) => record.contextId),
).toEqual(["img-old", "ctx-t"]);
if (focus === "blurred") {
expect(importPastedComposerText(event.clipboardData, importFragment)).toBe(
`${prefix}![shot](t3-context://v1/image/img-new) and [T](t3-context://v1/terminal/ctx-t)`,
);
expect(imported).toEqual(["img-old", "ctx-t"]);
return;
}
editor.update(
() => {
editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
},
{ discrete: true },
);
expect(imported).toEqual(["img-old", "ctx-t"]);
return;
}
editor.update(
() => {
editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
},
{ discrete: true },
);
expect(imported).toEqual(["img-old", "ctx-t"]);
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
"<context:img-new> and <context:ctx-t>",
);
});
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
`${prefix}<context:img-new> and <context:ctx-t>`,
);
},
);
it("converts a copied legacy element into a sendable annotation and rewrites its link", () => {
const copied = upgradeLegacyContextMessage(
@@ -838,6 +838,7 @@ export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
readSelectionRange: () => { start: number; end: number };
requestCitationComment: (request: ComposerCitationCommentRequest) => void;
readSnapshot: () => {
value: string;
@@ -1854,6 +1855,10 @@ function ComposerPromptEditorInner({
),
);
},
readSelectionRange: () => {
readSnapshot();
return selectionRangeRef.current;
},
requestCitationComment: (request) => {
citationCommentRequestRef.current = request;
const target = editor
@@ -2021,7 +2026,7 @@ function ComposerPromptEditorInner({
}}
onKeyUp={(event) => onPageScrollKeyUp?.(event.key)}
onBlur={onPageScrollRelease}
onPaste={onPaste}
onPasteCapture={onPaste}
/>
}
placeholder={
+226 -35
View File
@@ -1,13 +1,15 @@
import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
import { runtimeModeConfig, runtimeModeOptions } from "./runtimeModeConfig";
import { useRightPanelStore } from "~/rightPanelStore";
import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
import { filterComposerPullRequestMatches } from "@t3tools/shared/composerPullRequestMatches";
import { importPastedComposerText } from "../composerInlineTokenPaste";
import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste";
import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
import { RefreshIcon } from "~/components/ui/refresh-icon";
import {
questionAttachmentDraftId,
countQuestionAttachments,
useQuestionAttachmentPreparation,
changeQuestionAttachmentPreparation,
} from "../../questionAttachments";
@@ -34,8 +36,15 @@ import {
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
} from "@t3tools/contracts";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import {
isPasteAsTextShortcut,
nextPastedTextFileName,
pastedTextDisposition,
wouldTextPasteExceedLimit,
} from "@t3tools/client-runtime/text-paste";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
@@ -194,6 +203,7 @@ import {
ensureInlineContextReferences,
formatInlineContextReference,
insertInlineContextReference,
inlineContextReferenceReplacement,
toKindScopedComposerContextId,
} from "~/lib/composerContextReferences";
import {
@@ -284,7 +294,7 @@ import {
} from "../../lib/snapShotAnimation";
import { resizeSnapShotSource } from "../../lib/snapShotSource";
import { basenameOfPath } from "../../pierre-icons";
import { cn, randomUUID } from "~/lib/utils";
import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
import {
getComposerPromptLengthValidationMessage,
getComposerSubmissionValidationMessage,
@@ -1212,6 +1222,8 @@ export interface ChatComposerHandle {
text: string,
options?: { ensureLeadingBoundary?: boolean; clipboardData?: DataTransfer },
) => boolean;
/** Apply large-paste folding for text redirected from a blurred composer. */
pasteTextAtEnd: (text: string, options?: { bypassAutoAttachment?: boolean }) => boolean;
citeAssistantText: (
citation: AssistantCitation,
sourceAnchor: AssistantCitationSourceAnchor,
@@ -2064,6 +2076,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// Refs
// ------------------------------------------------------------------
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const pasteAsTextShortcutUntilRef = useRef(0);
const pastedTextFileNamesRef = useRef<{ targetKey: string; names: Set<string> }>({
targetKey: "",
names: new Set(),
});
const attachmentInputRef = useRef<HTMLInputElement>(null);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerFooterControlsRef = useRef<HTMLDivElement>(null);
@@ -2099,6 +2116,49 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
isRevertingCheckpointRef.current = isRevertingCheckpoint;
useEffect(() => {
const armPasteAsTextShortcut = () => {
// Electron can deliver its native menu action just before the paste
// event, while browsers normally deliver keydown first. A short deadline
// bridges both event paths without leaving later pastes in bypass mode.
pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
};
const onKeyDown = (event: KeyboardEvent) => {
if (
event.target instanceof Node &&
composerFormRef.current?.contains(event.target) &&
isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
) {
armPasteAsTextShortcut();
}
};
const onBlur = () => {
pasteAsTextShortcutUntilRef.current = 0;
};
const onDesktopPasteAsText = () => {
const activeElement = document.activeElement;
const blocksPasteToFocus =
activeElement instanceof Element &&
activeElement.closest(
'input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]',
) !== null;
if (
(activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) ||
!blocksPasteToFocus
) {
armPasteAsTextShortcut();
}
};
window.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
window.addEventListener("keydown", onKeyDown, true);
window.addEventListener("blur", onBlur);
return () => {
window.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
window.removeEventListener("keydown", onKeyDown, true);
window.removeEventListener("blur", onBlur);
};
}, []);
// ------------------------------------------------------------------
// Derived: composer send state
// ------------------------------------------------------------------
@@ -4041,6 +4101,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: null,
...(file.source ? { source: file.source } : {}),
// An expired upload carries no ids, so it hydrates as a
// needs-reattach row and the "Attach again" flow takes over.
...(expired
@@ -4319,6 +4380,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
sizeBytes: file.sizeBytes,
attachmentId: upload.attachmentId,
environmentId,
...(file.source ? { source: file.source } : {}),
});
}
// A repeat ⌘S on the *same* still-unencoded snapshot would stash it
@@ -5032,8 +5094,36 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Callbacks: attachments
// ------------------------------------------------------------------
const countReservedAttachments = () => {
const questionRequest = pendingUserInputs[0];
const otherQuestionKeys =
questionAttachmentTarget && questionRequest && activeThreadId
? questionRequest.questions
.map((question) =>
questionAttachmentDraftId(
environmentId,
activeThreadId,
questionRequest.requestId,
question.id,
),
)
.filter((key) => key !== questionAttachmentTarget)
: [];
return (
composerImagesRef.current.length +
composerFilesRef.current.length +
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
countQuestionAttachments(otherQuestionKeys)
);
};
/** Resolves true when at least one chip was inserted for the accepted attachments. */
const addComposerAttachments = async (files: File[]): Promise<boolean> => {
const addComposerAttachments = async (
files: File[],
options?: {
readonly source?: ChatFileAttachment["source"];
readonly selection?: { start: number; end: number };
},
): Promise<boolean> => {
if (!activeThreadId || files.length === 0 || isRevertingCheckpointRef.current) return false;
if (
pendingUserInputs.length > 0 &&
@@ -5056,30 +5146,7 @@ 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(attachmentTargetKey) ?? 0;
const otherQuestionAttachments =
questionAttachmentTarget && pendingUserInputs[0]
? pendingUserInputs[0].questions.reduce((count, question) => {
const target = questionAttachmentDraftId(
environmentId,
threadId,
pendingUserInputs[0]!.requestId,
question.id,
);
if (target === questionAttachmentTarget) return count;
const draft = getComposerDraft(target);
return (
count +
(draft?.images.length ?? 0) +
(draft?.files.length ?? 0) +
(useQuestionAttachmentPreparation.getState().counts[target] ?? 0)
);
}, 0)
: 0;
let reservedCount =
composerImagesRef.current.length +
composerFilesRef.current.length +
pendingCount +
otherQuestionAttachments;
let reservedCount = countReservedAttachments();
// 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.
@@ -5146,6 +5213,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
mimeType: fileMimeType,
sizeBytes: attachmentFile.size,
file: attachmentFile,
...(options?.source ? { source: options.source } : {}),
});
}
if (!matchingReattachMarker) {
@@ -5160,7 +5228,21 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const storedIds = new Set(addComposerFilesToDraft(acceptedFiles));
const storedFiles = acceptedFiles.filter((file) => storedIds.has(file.id));
if (storedFiles.length > 0) {
insertedAny = insertAttachmentReferences(storedFiles.map(fileContextReference));
insertedAny = insertAttachmentReferences(
storedFiles.map(fileContextReference),
options?.selection,
);
}
if (options?.source?._tag === "pasted-text" && storedFiles.length > 0) {
const attached = storedFiles[0]!;
toastManager.add({
type: "info",
title: `Large paste attached as ${attached.name}`,
description: `${formatAttachmentSize(attached.sizeBytes)} · Use ${
isMacPlatform(navigator.platform) ? "⌘⇧V" : "Ctrl+Shift+V"
} to keep a large paste inline.`,
data: { hideCopyButton: true },
});
}
}
if (acceptedImages.length === 0) return insertedAny;
@@ -5246,11 +5328,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
*/
const insertAttachmentReferences = (
references: ReadonlyArray<ComposerContextReference>,
selection?: { start: number; end: number },
): boolean => {
if (references.length === 0) return false;
// Question answers carry attachments beside the answer, never as chips. Falling back to
// the thread prompt here would hide the file behind a reference the question never shows.
if (questionAttachmentTarget) return false;
if (selection) {
const edit = inlineContextReferenceReplacement(promptRef.current, selection, references);
return applyPromptReplacement(edit.start, edit.end, edit.text);
}
const text = references.map(formatInlineContextReference).join(" ");
const inserted = insertComposerText(`${text} `, "cursor", { ensureLeadingBoundary: true });
if (!inserted) {
@@ -5284,24 +5371,110 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
// ------------------------------------------------------------------
// Callbacks: paste / drag
// ------------------------------------------------------------------
const foldPastedText = (
plainText: string,
bypassAutoAttachment: boolean,
selectionOverride?: { start: number; end: number },
): boolean => {
const questionCanAttach =
pendingUserInputs.length === 0 ||
(supportsQuestionAttachments &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
!activePendingIsResponding);
const hasAttachmentSlot = countReservedAttachments() < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
const selection = selectionOverride ?? composerEditorRef.current?.readSelectionRange();
const wouldExceedInputLimit = wouldTextPasteExceedLimit({
valueLength: promptRef.current.length,
selection: selection ?? { start: 0, end: 0 },
textLength: plainText.length,
maxLength: PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
});
const shouldFold =
pastedTextDisposition({
text: plainText,
bypassAutoAttachment,
wouldExceedInputLimit,
canAttach: true,
}) === "attachment";
if (!shouldFold) {
return false;
}
const canStageAttachment =
Boolean(activeThreadId) &&
!isRevertingCheckpointRef.current &&
questionCanAttach &&
hasAttachmentSlot;
if (!canStageAttachment || fileStagingLimit === null) {
if (!wouldExceedInputLimit) {
return false;
}
toastManager.add({
type: "error",
title: "Pasted text is too large for this message",
description: "Remove some text or an attachment, then paste again.",
data: { hideCopyButton: true },
});
return true;
}
if (pastedTextFileNamesRef.current.targetKey !== attachmentTargetKey) {
pastedTextFileNamesRef.current = { targetKey: attachmentTargetKey, names: new Set() };
}
const reservedNames = pastedTextFileNamesRef.current.names;
for (const file of composerFilesRef.current) reservedNames.add(file.name);
const foldedFileName = nextPastedTextFileName([...reservedNames]);
reservedNames.add(foldedFileName);
const foldedFile = new File([plainText], foldedFileName, {
type: "text/plain;charset=utf-8",
});
if (foldedFile.size > fileStagingLimit) {
reservedNames.delete(foldedFileName);
if (!wouldExceedInputLimit) return false;
toastManager.add({
type: "error",
title: "Pasted text is too large to attach",
description: "Reduce the clipboard contents or save a smaller excerpt as a file.",
data: { hideCopyButton: true },
});
return true;
}
void addComposerAttachments([foldedFile], {
source: { _tag: "pasted-text" },
...(selection ? { selection } : {}),
});
return true;
};
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
const files = Array.from(event.clipboardData.files);
const plainText = event.clipboardData.getData("text/plain");
const bypassAutoAttachment = Date.now() <= pasteAsTextShortcutUntilRef.current;
pasteAsTextShortcutUntilRef.current = 0;
// Claimable pastes go through even when agent 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"),
})
files.length > 0 &&
activeThreadId &&
shouldHandleComposerAttachmentPaste({ files, plainText })
) {
event.preventDefault();
event.stopPropagation();
void addComposerAttachments(files);
return;
}
// Copied T3 chips need the structured importer to bring their records and files along.
if ((readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0) return;
if (!foldPastedText(plainText, bypassAutoAttachment)) {
return;
}
event.preventDefault();
void addComposerAttachments(files);
event.stopPropagation();
};
const insertComposerText = useCallback(
@@ -5526,6 +5699,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
hasPendingAttachments: () =>
(pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0,
insertTextAtEnd: insertComposerTextAtEnd,
pasteTextAtEnd: (text: string, options) => {
const bypassAutoAttachment =
options?.bypassAutoAttachment === true ||
Date.now() <= pasteAsTextShortcutUntilRef.current;
pasteAsTextShortcutUntilRef.current = 0;
const promptLength = promptRef.current.length;
if (
!foldPastedText(text, bypassAutoAttachment, {
start: promptLength,
end: promptLength,
})
) {
return false;
}
focusComposer();
return true;
},
citeAssistantText: (citation, sourceAnchor) =>
insertComposerText(
formatAssistantCitationForComposer(citation, citation.comment),
@@ -5626,6 +5816,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[
activeThread,
addComposerAttachments,
foldPastedText,
composerDraftTarget,
composerCursor,
composerTerminalContexts,
@@ -144,40 +144,43 @@ export function registerComposerInlineTokenPaste(
);
}
/** Clipboard records referenced by the copied text, including dependent screenshots. */
export function readPastedComposerContext(
clipboardData: Pick<DataTransfer, "getData">,
): ComposerContextClipboardFragment | null {
const pastedText = clipboardData.getData("text/plain");
// Only records whose links are in the pasted text get imported; a fragment may carry
// more (it was built for a larger copy) and must not start transfers for those.
const decodedFragment =
decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ??
decodeComposerContextClipboardHtml(clipboardData.getData("text/html"));
if (decodedFragment === null) return null;
const pastedIds = new Set<string>(
collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId),
);
for (const record of decodedFragment.records) {
if (
record.kind === "preview-annotation" &&
!("payload" in record) &&
pastedIds.has(record.contextId) &&
record.screenshotContextId
) {
pastedIds.add(record.screenshotContextId);
}
}
return {
...decodedFragment,
records: decodedFragment.records.filter((record) => pastedIds.has(record.contextId)),
};
}
/** Imports the same structured clipboard payload for focused paste and paste-to-focus. */
export function importPastedComposerText(
clipboardData: Pick<DataTransfer, "getData">,
importContextFragment?: ComposerInlineTokenPasteOptions["importContextFragment"],
): string {
const pastedText = clipboardData.getData("text/plain");
// Only records whose links are in the pasted text get imported; a fragment may carry
// more (it was built for a larger copy) and must not start transfers for those.
const decodedFragment = importContextFragment
? (decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ??
decodeComposerContextClipboardHtml(clipboardData.getData("text/html")))
: null;
const pastedIds = new Set<string>(
collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId),
);
if (decodedFragment) {
for (const record of decodedFragment.records) {
if (
record.kind === "preview-annotation" &&
!("payload" in record) &&
pastedIds.has(record.contextId) &&
record.screenshotContextId
) {
pastedIds.add(record.screenshotContextId);
}
}
}
const fragment =
decodedFragment === null
? null
: {
...decodedFragment,
records: decodedFragment.records.filter((record) => pastedIds.has(record.contextId)),
};
const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null;
const rewrittenIds =
fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null;
const text =
+23 -22
View File
@@ -119,29 +119,30 @@ export function PullRequestChip(props: {
onOpen: (event: MouseEvent<HTMLElement>, url: string) => void;
}) {
return (
<ContextChipPopover
accessibleLabel={`${props.kindLabel} ${props.label}: ${props.metadata.title}`}
{...(props.copyMarkdown ? { copyMarkdown: props.copyMarkdown } : {})}
triggerClassName={props.className}
chip={
<>
<GitPullRequestIcon className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />
<span className={props.labelClassName}>{props.label}</span>
</>
}
>
<div className="space-y-3 p-2">
<Tooltip>
<TooltipTrigger
render={
<Button
variant="chip"
className={cn(
props.className,
CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
"cursor-pointer",
)}
aria-label={`Open ${props.kindLabel} ${props.label}: ${props.metadata.title}`}
data-markdown-copy={props.copyMarkdown}
onClick={(event) => props.onOpen(event, props.metadata.url)}
>
<GitPullRequestIcon className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />
<span className={props.labelClassName}>{props.label}</span>
</Button>
}
/>
<TooltipPopup side="top">
<PullRequestContextDetails metadata={props.metadata} />
<p className="text-xs text-muted-foreground">Captured pull request context</p>
<Button
variant="outline"
size="sm"
onClick={(event) => props.onOpen(event, props.metadata.url)}
>
Open pull request
</Button>
</div>
</ContextChipPopover>
</TooltipPopup>
</Tooltip>
);
}
@@ -12,6 +12,7 @@ import {
Eye,
Table2,
Trash2Icon,
WrapTextIcon,
XIcon,
} from "lucide-react";
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
@@ -21,6 +22,7 @@ import ChatMarkdown from "~/components/ChatMarkdown";
import { ScrollArea } from "~/components/ui/scroll-area";
import { toastManager } from "~/components/ui/toast";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { cn } from "~/lib/utils";
import { AudioPreview } from "./AudioPreview";
@@ -180,6 +182,16 @@ export function AttachmentFilePreview(props: {
return () => controller.abort();
}, [url, needsText, revision, props.sizeBytes, props.file, refresh]);
const failure = error ?? (needsText ? contentError : null);
const wordWrap = useClientSettings((settings) => settings.wordWrap);
const updateClientSettings = useUpdateClientSettings();
// Only the raw-text body honours word wrap. A rendered table or Markdown lays itself out,
// so offering the toggle there would be a control that visibly does nothing.
const showsRawText =
failure === null &&
needsText &&
content !== null &&
!(delimiter && rendered) &&
!(kind === "markdown" && rendered);
const save = () => {
setSaving(true);
@@ -302,6 +314,15 @@ export function AttachmentFilePreview(props: {
)}
</FileSurfaceAction>
) : null}
{showsRawText ? (
<FileSurfaceAction
label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
pressed={wordWrap}
onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
>
<WrapTextIcon className="size-3.5" />
</FileSurfaceAction>
) : null}
{content ? (
<FileSurfaceAction
label={isCopied ? "Copied" : content.truncated ? "Copy preview" : "Copy contents"}
@@ -21,7 +21,7 @@ import {
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { mediaFileReference } from "@t3tools/client-runtime/media-reference";
import { Code2, Eye, FolderTree, Globe2, Table2 } from "lucide-react";
import { Code2, Eye, FolderTree, Globe2, Table2, WrapTextIcon } from "lucide-react";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -31,7 +31,7 @@ import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { MediaVideoPlayer } from "~/components/media/MediaVideoPlayer";
import { MediaActions, type MediaActionSource } from "~/components/media/MediaActions";
import { useRemoteOpenState } from "~/remoteOpen";
import { useClientSettings } from "~/hooks/useSettings";
import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh";
@@ -995,6 +995,15 @@ export default function FilePreviewPanel({
? ("html" as const)
: null;
const canToggleRendered = attachment === undefined && renderedMode !== null;
const updateClientSettings = useUpdateClientSettings();
// Word wrap only reaches the text bodies. A rendered Markdown document, a table and the
// browser frame all lay themselves out, so the toggle stays hidden rather than inert.
const showsRawText =
relativePath !== null &&
file.data !== null &&
!(isMarkdown && renderMarkdown) &&
!(tableDelimiter && renderTable) &&
!renderBrowserFile;
const rendered = isMarkdown ? renderMarkdown : tableDelimiter ? renderTable : renderBrowserFile;
const setRenderedPreferred = isMarkdown
? setRenderMarkdownPreferred
@@ -1122,6 +1131,15 @@ export default function FilePreviewPanel({
)}
</FileSurfaceAction>
) : null}
{showsRawText ? (
<FileSurfaceAction
label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
pressed={wordWrap}
onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
>
<WrapTextIcon className="size-3.5" />
</FileSurfaceAction>
) : null}
{canOpenInBrowser ? (
<FileSurfaceAction label="Open file in preview browser" onPress={handleOpenInBrowser}>
<Globe2 className="size-3.5" />
+5 -1
View File
@@ -436,7 +436,9 @@ describe("composerDraftStore file attachments", () => {
it("persists uploaded file references without including file contents", () => {
const store = useComposerDraftStore.getState();
store.addFiles(threadRef, [makeFile("file-1")]);
store.addFiles(threadRef, [
{ ...makeFile("file-1"), source: { _tag: "pasted-text" as const } },
]);
store.setFileUpload(threadRef, "file-1", TEST_ENVIRONMENT_ID, "pending-report-pdf");
const persistApi = useComposerDraftStore.persist as unknown as {
@@ -459,6 +461,7 @@ describe("composerDraftStore file attachments", () => {
sizeBytes: 6,
attachmentId: "pending-report-pdf",
environmentId: TEST_ENVIRONMENT_ID,
source: { _tag: "pasted-text" },
},
],
);
@@ -474,6 +477,7 @@ describe("composerDraftStore file attachments", () => {
file: null,
uploadedAttachmentId: "pending-report-pdf",
uploadEnvironmentId: TEST_ENVIRONMENT_ID,
source: { _tag: "pasted-text" },
},
]);
});
+5
View File
@@ -13,6 +13,7 @@ import {
ProviderOptionSelection,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PreviewAnnotationPayloadSchema,
PastedTextAttachmentSource,
type PreviewAnnotationPayload,
RuntimeMode,
type ServerProvider,
@@ -191,6 +192,7 @@ export const PersistedComposerFileAttachment = Schema.Struct({
sizeBytes: Schema.Number,
attachmentId: Schema.String,
environmentId: EnvironmentId,
source: Schema.optional(PastedTextAttachmentSource),
});
export type PersistedComposerFileAttachment = typeof PersistedComposerFileAttachment.Type;
@@ -207,6 +209,7 @@ export const PersistedComposerDraftFileAttachment = Schema.Struct({
sizeBytes: Schema.Number,
attachmentId: Schema.optionalKey(Schema.String),
environmentId: Schema.optionalKey(EnvironmentId),
source: Schema.optional(PastedTextAttachmentSource),
});
export type PersistedComposerDraftFileAttachment = typeof PersistedComposerDraftFileAttachment.Type;
const isPersistedComposerDraftFileAttachment = Schema.is(PersistedComposerDraftFileAttachment);
@@ -2144,6 +2147,7 @@ export function partializeComposerDraftStoreState(
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
...(file.source ? { source: file.source } : {}),
...(file.uploadedAttachmentId && file.uploadEnvironmentId
? {
attachmentId: file.uploadedAttachmentId,
@@ -2423,6 +2427,7 @@ function toHydratedThreadDraft(
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
file: null,
...(file.source ? { source: file.source } : {}),
// A marker without an attachment id hydrates as needs-reattach: no
// bytes, no server-side upload, only the metadata to tell the user
// what to attach again.
@@ -238,7 +238,10 @@ describe("attachmentUploadQueue", () => {
});
it("uploads generic files and sends file attachment references", async () => {
const file = makeFile("report");
const file = {
...makeFile("report"),
source: { _tag: "pasted-text" as const },
};
startAttachmentUpload({ environmentId: firstEnvironment, image: file });
await Promise.resolve();
@@ -268,6 +271,7 @@ describe("attachmentUploadQueue", () => {
name: "report.pdf",
mimeType: "application/pdf",
sizeBytes: 3,
source: { _tag: "pasted-text" },
},
]);
});
+1 -1
View File
@@ -563,7 +563,7 @@ export function getUploadedAttachments(input: {
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
...(image.type === "image" && image.source ? { source: image.source } : {}),
...(image.source ? { source: image.source } : {}),
});
}
return attachments;
@@ -6,6 +6,7 @@ import {
ensureInlineContextReferences,
formatInlineContextReference,
insertInlineContextReference,
inlineContextReferenceReplacement,
removeInlineContextReference,
stripInlineContextReferences,
toComposerContextId,
@@ -18,6 +19,17 @@ const reviewLink = "[a.ts L4](t3-context://v1/review-comment/rc-1)";
const previewLink = "[Checkout](t3-context://v1/preview-annotation/pa-1)";
describe("composerContextReferences", () => {
it.each([
{ prompt: "before selected after", start: 7, end: 15, expected: `before ${reviewLink} after` },
{ prompt: "selected", start: 0, end: 8, expected: `${reviewLink} ` },
{ prompt: "aSELECTb", start: 1, end: 7, expected: `a ${reviewLink} b` },
])(
"replaces selected text in '$prompt' with the attachment chip",
({ prompt, start, end, expected }) => {
const edit = inlineContextReferenceReplacement(prompt, { start, end }, [review]);
expect(`${prompt.slice(0, edit.start)}${edit.text}${prompt.slice(edit.end)}`).toBe(expected);
},
);
it("formats, collects and strips references of any kind", () => {
expect(formatInlineContextReference(review)).toBe(reviewLink);
const prompt = `x ${reviewLink} y ${previewLink} ${reviewLink}`;
+21 -6
View File
@@ -93,19 +93,34 @@ function isBoundaryWhitespace(char: string | undefined): boolean {
return char === undefined || char === " " || char === "\n" || char === "\t" || char === "\r";
}
/** Replaces a selected range with chips, keeping word boundaries and the trailing caret space. */
export function inlineContextReferenceReplacement(
prompt: string,
selection: { start: number; end: number },
references: ReadonlyArray<ComposerContextReference>,
): { start: number; end: number; text: string } {
const start = Math.max(0, Math.min(prompt.length, Math.floor(selection.start)));
const end = Math.max(start, Math.min(prompt.length, Math.floor(selection.end)));
const needsLeadingSpace = !isBoundaryWhitespace(prompt[start - 1]);
return {
start,
end: prompt[end] === " " ? end + 1 : end,
text: `${needsLeadingSpace ? " " : ""}${references.map(formatInlineContextReference).join(" ")} `,
};
}
/** Inserts a link at the cursor, padding with spaces only where words would otherwise join. */
export function insertInlineContextReference(
prompt: string,
cursorInput: number,
reference: ComposerContextReference,
): { prompt: string; cursor: number } {
const cursor = Math.max(0, Math.min(prompt.length, Math.floor(cursorInput)));
const needsLeadingSpace = !isBoundaryWhitespace(prompt[cursor - 1]);
const replacement = `${needsLeadingSpace ? " " : ""}${formatInlineContextReference(reference)} `;
const rangeEnd = prompt[cursor] === " " ? cursor + 1 : cursor;
const edit = inlineContextReferenceReplacement(prompt, { start: cursorInput, end: cursorInput }, [
reference,
]);
return {
prompt: `${prompt.slice(0, cursor)}${replacement}${prompt.slice(rangeEnd)}`,
cursor: cursor + replacement.length,
prompt: `${prompt.slice(0, edit.start)}${edit.text}${prompt.slice(edit.end)}`,
cursor: edit.start + edit.text.length,
};
}
@@ -0,0 +1,32 @@
import type { DesktopBridge } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { DESKTOP_PASTE_AS_TEXT_EVENT, installDesktopPasteAsText } from "./desktopPasteAsText";
describe("desktop paste as text", () => {
it.each([false, true])("pastes with a mounted composer: %s", (hasComposer) => {
const target = new EventTarget();
let menuAction: ((action: string) => void) | undefined;
const order: string[] = [];
const bridge = {
onMenuAction: (listener) => {
menuAction = listener;
return () => {
menuAction = undefined;
};
},
pasteAsText: vi.fn(async () => {
order.push("paste");
}),
} satisfies Pick<DesktopBridge, "onMenuAction" | "pasteAsText">;
if (hasComposer)
target.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, () => order.push("armed"));
const uninstall = installDesktopPasteAsText(bridge, target);
menuAction?.("open-settings");
expect(order).toEqual([]);
menuAction?.("paste-as-text");
expect(order).toEqual(hasComposer ? ["armed", "paste"] : ["paste"]);
uninstall?.();
menuAction?.("paste-as-text");
expect(bridge.pasteAsText).toHaveBeenCalledOnce();
});
});
+15
View File
@@ -0,0 +1,15 @@
import type { DesktopBridge } from "@t3tools/contracts";
export const DESKTOP_PASTE_AS_TEXT_EVENT = "t3:paste-as-text";
/** Arm composer paste handling before Electron delivers the native clipboard event. */
export function installDesktopPasteAsText(
bridge: Pick<DesktopBridge, "onMenuAction" | "pasteAsText"> | undefined,
target: EventTarget,
): (() => void) | undefined {
return bridge?.onMenuAction((action) => {
if (action !== "paste-as-text") return;
target.dispatchEvent(new Event(DESKTOP_PASTE_AS_TEXT_EVENT));
void bridge.pasteAsText?.();
});
}
+41
View File
@@ -3,6 +3,7 @@ import { beforeEach, expect, it, vi } from "vite-plus/test";
import { useComposerDraftStore } from "./composerDraftStore";
import {
questionAttachmentDraftId,
countQuestionAttachments,
questionAttachmentDraftPrefix,
changeQuestionAttachmentPreparation,
clearQuestionAttachmentDraft,
@@ -98,3 +99,43 @@ it("does not clear another environment whose id contains a question prefix", ()
expect(store.getComposerDraft(ownKey)).toBeNull();
expect(store.getComposerDraft(otherKey)?.prompt).toBe("Keep this answer");
});
it("counts files, images, and pending preparation across the shared question budget", () => {
const first = questionAttachmentDraftId(environmentId, threadId, requestId, "first");
const second = questionAttachmentDraftId(environmentId, threadId, requestId, "second");
const other = questionAttachmentDraftId(
EnvironmentId.make("other"),
threadId,
requestId,
"first",
);
const store = useComposerDraftStore.getState();
store.addFiles(
second,
Array.from({ length: 6 }, (_, index) => ({
type: "file" as const,
id: `file-${index}`,
name: `spec-${index}.txt`,
mimeType: "text/plain",
sizeBytes: 4,
file: new File(["spec"], `spec-${index}.txt`),
})),
);
store.addImages(first, [
{
type: "image",
id: "image",
name: "image.png",
mimeType: "image/png",
sizeBytes: 5,
previewUrl: "blob:count-test",
file: new File(["image"], "image.png"),
},
]);
changeQuestionAttachmentPreparation(second, 1);
changeQuestionAttachmentPreparation(other, 8);
expect(countQuestionAttachments([first, second])).toBe(8);
expect(countQuestionAttachments([second])).toBe(7);
changeQuestionAttachmentPreparation(second, -1);
expect(countQuestionAttachments([first, second])).toBe(7);
});
+10
View File
@@ -25,6 +25,16 @@ export const useQuestionAttachmentPreparation = create<{ counts: Record<string,
counts: {},
}));
/** Count both staged files and in-flight preparation against the shared question limit. */
export function countQuestionAttachments(keys: ReadonlyArray<DraftId>): number {
const store = useComposerDraftStore.getState();
const { counts } = useQuestionAttachmentPreparation.getState();
return keys.reduce((total, key) => {
const draft = store.getComposerDraft(key);
return total + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + (counts[key] ?? 0);
}, 0);
}
export function changeQuestionAttachmentPreparation(key: DraftId, delta: number): void {
useQuestionAttachmentPreparation.setState((state) =>
delta < 0 && !(key in state.counts)
+2
View File
@@ -67,6 +67,7 @@ import {
} from "../components/KeybindingsUpdateToast.logic";
import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
export const Route = createRootRoute({
@@ -108,6 +109,7 @@ export const Route = createRootRoute({
});
function RootRouteView() {
useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";