diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index bae452bad7c48..f717e961379b2 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -125,17 +125,13 @@ export function ComposerEditor({ const warnings: string[] = []; if (result.failures.length > 0) warnings.push( - "Some attachments could not be copied. Reconnect to the source environment and copy them again.", + "Some attachments could not be copied. Reconnect to the source environment and copy them again. Those references are marked unavailable.", ); if (result.skippedThreads.length > 0) warnings.push( - `${result.skippedThreads.map((title) => `"${title}"`).join(", ")} ${result.skippedThreads.length === 1 ? "is" : "are"} on another machine.`, - ); - if (warnings.length > 0) - Dialog.alert( - "Some context is unavailable", - [...warnings, "Those references are marked unavailable."].join("\n\n"), + `${result.skippedThreads.map((title) => `"${title}"`).join(", ")} ${result.skippedThreads.length === 1 ? "is" : "are"} on another machine, so the agent gets a link instead.`, ); + if (warnings.length > 0) Dialog.alert("Some context is unavailable", warnings.join("\n\n")); }); operation.finish(); setComposerContextImporting(draftKey, false); diff --git a/apps/mobile/src/lib/composerContextClipboard.test.ts b/apps/mobile/src/lib/composerContextClipboard.test.ts index 41cdcf3078bce..d235f99530523 100644 --- a/apps/mobile/src/lib/composerContextClipboard.test.ts +++ b/apps/mobile/src/lib/composerContextClipboard.test.ts @@ -6,6 +6,7 @@ import { ThreadId, } from "@t3tools/contracts"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; +import { formatHostedThreadLink } from "@t3tools/shared/threadLinks"; import { collectComposerContextReferences, formatComposerContextReference, @@ -245,21 +246,20 @@ describe("mobile context clipboard imports", () => { ]); expect(result!.failures).toEqual([]); expect(result!.skippedThreads).toEqual([foreignThread.title]); + // The foreign thread stays a link to its machine, not a reference with no record behind it. + expect(result!.text).toContain(formatHostedThreadLink(foreignThread, foreignThread.label)); const references = collectComposerContextReferences(result!.text); - expect(references.map((reference) => reference.label)).toEqual( - mixedRecords.map((record) => record.label), - ); expect(result!.context.records.map((record) => record.contextId)).toEqual( - references.slice(1).map((reference) => reference.contextId), + references.map((reference) => reference.contextId), + ); + expect(references.map((reference) => reference.label)).toEqual( + mixedRecords.slice(1).map((record) => record.label), ); expect( references.every( (reference) => !mixedRecords.some((record) => record.contextId === reference.contextId), ), ).toBe(true); - expect( - result!.context.records.some((record) => record.contextId === references[0]!.contextId), - ).toBe(false); expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/); const restoreHistory = createComposerContextHistory(); @@ -301,9 +301,6 @@ describe("mobile context clipboard imports", () => { expect(result!.failures).toEqual([image.name]); expect(result!.skippedThreads).toEqual([foreignThread.title]); const references = collectComposerContextReferences(result!.text); - expect(references.map((reference) => reference.label)).toEqual( - mixedRecords.map((record) => record.label), - ); expect( references .filter( @@ -311,7 +308,7 @@ describe("mobile context clipboard imports", () => { !result!.context.records.some((record) => record.contextId === reference.contextId), ) .map((reference) => reference.label), - ).toEqual([foreignThread.label, image.label]); + ).toEqual([image.label]); expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/); }); diff --git a/apps/mobile/src/lib/composerContextClipboard.ts b/apps/mobile/src/lib/composerContextClipboard.ts index e744a2cbbf96a..72c796c914ccf 100644 --- a/apps/mobile/src/lib/composerContextClipboard.ts +++ b/apps/mobile/src/lib/composerContextClipboard.ts @@ -14,9 +14,11 @@ import { encodeComposerContextFragment, } from "@t3tools/shared/composerContextClipboard"; import { + replaceComposerContextReferences, threadContextsOutsideEnvironment, threadLinkContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { formatHostedThreadLink } from "@t3tools/shared/threadLinks"; import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; import * as Option from "effect/Option"; @@ -116,8 +118,13 @@ export async function importComposerContextClipboard( environmentId: destinationEnvironmentId, linkedEnvironments, }); - const skippedIds = new Set(skippedThreads.map((record) => record.contextId)); - const retained = imported.context.records.filter((record) => !skippedIds.has(record.contextId)); + const skippedById = new Map(skippedThreads.map((record) => [record.contextId, record])); + // The agent cannot read these threads, so each stays a link that opens it on its machine. + const text = replaceComposerContextReferences(imported.text, (reference) => { + const thread = skippedById.get(reference.contextId); + return thread ? formatHostedThreadLink(thread, reference.label) : reference.source; + }); + const retained = imported.context.records.filter((record) => !skippedById.has(record.contextId)); if (existingContextCount + retained.length > COMPOSER_CONTEXT_MAX_RECORDS) throw new Error("Remove some context items from the draft before pasting more."); const attachments: DraftComposerAttachment[] = []; @@ -144,7 +151,7 @@ export async function importComposerContextClipboard( // The last copy can be cancelled after its own check; a cancelled import must not return files nobody will release. checkAborted(signal); return { - text: imported.text, + text, context: { version: 1 as const, records }, attachments, failures, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 58e9a29b57c1d..fa00aca05bba5 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -2,10 +2,12 @@ import type { ComposerFileAttachment } from "../composerDraftStore"; import { formatInlineContextReference } from "../lib/composerContextReferences"; import { fileContextReference } from "../lib/composerContextRecords"; import { + heldContextIds, reconcileAttachmentContextReferences, type RetainedContextPayloads, useRetainedContextPayloads, } from "./chat/composerContextUndo"; +import { importPastedComposerText } from "./composerInlineTokenPaste"; import { ComposerContextId, @@ -64,7 +66,7 @@ function Composer({ skills, onChange, onCommandKeyDown = () => false, - importContextFragment, + importPastedText, literalText = false, }: { value: string; @@ -72,7 +74,7 @@ function Composer({ skills: ReadonlyArray; onChange?: ComposerPromptEditorProps["onChange"] | undefined; onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined; - importContextFragment?: ComposerPromptEditorProps["importContextFragment"]; + importPastedText?: ComposerPromptEditorProps["importPastedText"]; literalText?: boolean; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); @@ -92,7 +94,7 @@ function Composer({ }} onPaste={() => {}} onCommandKeyDown={onCommandKeyDown} - importContextFragment={importContextFragment} + importPastedText={importPastedText} literalText={literalText} /> ); @@ -514,14 +516,16 @@ it.each([ mimeType: "image/png", sizeBytes: 3, } satisfies ComposerContextRecord; - const importContextFragment = vi.fn(() => new Map([[record.contextId, record.contextId]])); + const importPastedText = vi.fn((clipboardData: DataTransfer) => + clipboardData.getData("text/plain"), + ); await using screen = await render( , ); const editor = editorIn(screen.container); @@ -543,7 +547,7 @@ it.each([ new ClipboardEvent("paste", { clipboardData, cancelable: true }), ); }); - expect(importContextFragment).toHaveBeenCalledTimes(imports); + expect(importPastedText).toHaveBeenCalledTimes(imports); }, ); @@ -907,17 +911,24 @@ describe("composer context undo lifetime", () => { current = draft; retained = payloads; }); + const contextRecords = new Map( + draft.files.map((entry) => [ + fileContextReference(entry).contextId, + { kind: "file" as const, record: entry }, + ]), + ); const editorProps = { draftKey: targetKey, editorRef, value: draft.value, cursor: 0, - contextRecords: new Map( - draft.files.map((entry) => [ - fileContextReference(entry).contextId, - { kind: "file" as const, record: entry }, - ]), - ), + contextRecords, + importPastedText: (clipboardData) => + importPastedComposerText( + clipboardData, + () => new Map(), + heldContextIds(contextRecords, new Set(), payloads), + ), skills: [], disabled: false, placeholder: "", @@ -990,6 +1001,22 @@ describe("composer context undo lifetime", () => { expect(retained.files.size).toBe(0); }); + // A plain-text paste carries no record, so the cut chip used to come back as its label. + it("restores a cut chip and its file bytes when its text is pasted back as plain text", async () => { + await using composer = await mountComposer(); + await composer.deleteDraft(); + expect(composer.draft()).toEqual({ value: "", files: [] }); + await act(async () => { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", composer.initialValue); + composer + .editor() + .view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true })); + }); + expect(composer.draft().value.trimEnd()).toBe(composer.initialValue); + expect(composer.draft().files[0]?.file).toBe(file.file); + }); + it.each(["", "Draft B"])( "releases deleted payloads and prevents undo into the previous draft when switching to %j", async (destinationValue) => { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index de37050121ddc..1f88289d5ae92 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -27,11 +27,7 @@ import { } from "@tiptap/pm/state"; import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view"; import type { NodeType, ResolvedPos } from "@tiptap/pm/model"; -import type { - AssistantCitation, - ComposerContextClipboardFragment, - ServerProviderSkill, -} from "@t3tools/contracts"; +import type { AssistantCitation, ServerProviderSkill } from "@t3tools/contracts"; import { serializeAssistantCitation, withAssistantCitationComment, @@ -139,11 +135,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView"; import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal"; import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight"; -import { - importPastedComposerText, - readPastedComposerContext, - readPastedPlainText, -} from "./composerInlineTokenPaste"; +import { readPastedComposerContext, readPastedPlainText } from "./composerInlineTokenPaste"; import { didComposerSelectionChangeVisibly } from "./composerSelection"; import { captureComposerAttachmentInsertion, @@ -177,9 +169,8 @@ export interface ComposerPromptEditorProps { buildContextClipboardFragment?: | ((contextIds: ReadonlyArray) => string | null) | undefined; - importContextFragment?: - | ((fragment: ComposerContextClipboardFragment) => ReadonlyMap) - | undefined; + /** Imports a paste's context records and returns its text with references rewritten. */ + importPastedText?: ((clipboardData: DataTransfer) => string) | undefined; skills: ReadonlyArray; disabled: boolean; placeholder: string; @@ -945,7 +936,7 @@ function ComposerPromptEditorTiptapInner( literalText = false, contextRecords, buildContextClipboardFragment, - importContextFragment, + importPastedText, skills, disabled, placeholder, @@ -987,7 +978,7 @@ function ComposerPromptEditorTiptapInner( onVisibleSelectionChange, onCommandKeyDown, isPathQueryActive, - importContextFragment, + importPastedText, })); const { environmentId } = use(ComposerContextActionsContext); @@ -1445,11 +1436,8 @@ function ComposerPromptEditorTiptapInner( ); return true; } - const importFragment = readCallbacks().importContextFragment; - let text = - !literalText && importFragment - ? importPastedComposerText(clipboardData, importFragment) - : pastedText; + const importText = readCallbacks().importPastedText; + let text = !literalText && importText ? importText(clipboardData) : pastedText; const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); const isChip = (token: (typeof tokens)[number] | undefined) => token?.type === "mention" || diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 69250e47b89c3..8039574680c65 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -63,7 +63,6 @@ import { memo, use, useEffect, - useEffectEvent, useId, useImperativeHandle, useLayoutEffect, @@ -119,6 +118,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + heldContextIds, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -1380,7 +1380,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) countReservedAttachmentsStable, importContextRecords, importContextFragment, - importContextFragmentStable, } = useComposerContextImport({ environmentId, linkedEnvironments, @@ -1398,6 +1397,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + importThreadTranscript: (ref, draftTarget) => { + const targetKey = composerTargetKey(draftTarget); + void importThreadTranscript( + ref, + draftTarget, + () => + attachmentTargetKeyRef.current === targetKey || + composerDraftTargetKeyRef.current === targetKey, + ); + }, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -2618,6 +2627,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : bannerItems; + const importPastedText = (clipboardData: DataTransfer) => + importPastedComposerText( + clipboardData, + importContextFragment, + heldContextIds( + composerContextRecords, + pendingDraftWork.importingContextIds(attachmentTargetKey), + retainedContextPayloads, + ), + ); + const importPastedTextStable = useStableCallback(importPastedText); + const insertComposerText = ( text: string, position: "cursor" | "end", @@ -2636,8 +2657,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) { return false; } - if (options?.clipboardData) { - text = importPastedComposerText(options.clipboardData, importContextFragment); + if (options?.clipboardData && !isLiteralPendingAnswer) { + text = importPastedText(options.clipboardData); } const prompt = promptRef.current; const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; @@ -2881,10 +2902,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, }); - const attachDroppedThreadFile = useEffectEvent((file: File) => addComposerAttachments([file])); - const importDroppedThread = useEffectEvent( - async (ref: ScopedThreadRef, isActive: () => boolean) => { - const targetKey = attachmentTargetKey; + // The editor shows the attachment draft; a stash restore can name the draft behind a question. + const attachThreadTranscript = useStableCallback( + async (draftTarget: ChatComposerProps["composerDraftTarget"], file: File) => + composerTargetKey(draftTarget) === attachmentTargetKey + ? addComposerAttachments([file]) + : addComposerDraftFiles( + draftTarget, + [ + { + type: "file", + id: randomUUID(), + name: file.name, + mimeType: file.type, + sizeBytes: file.size, + file, + }, + ], + { appendReference: true }, + ).length > 0, + ); + const importThreadTranscript = useStableCallback( + async ( + ref: ScopedThreadRef, + draftTarget: ChatComposerProps["composerDraftTarget"], + isActive: () => boolean, + ) => { + const targetKey = composerTargetKey(draftTarget); pendingDraftWork.begin(targetKey); const loadingToast = toastManager.add({ type: "loading", @@ -2896,7 +2940,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) importComposerThreadAttachment({ targetKey, pendingImports: pendingThreadImportsRef.current, - countReservedAttachments: countReservedAttachmentsStable, + countReservedAttachments: () => countReservedAttachmentsStable(draftTarget), load: async () => { const result = await loadThreadTranscript({ environmentId: ref.environmentId, @@ -2908,7 +2952,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return threadContextAttachment(ref.environmentId, result.value); }, isActive, - attach: attachDroppedThreadFile, + attach: (file) => attachThreadTranscript(draftTarget, file), onLimitReached: () => { if (activeThreadId) { setThreadError( @@ -2923,7 +2967,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const error = squashAtomCommandFailure(importResult); toastManager.add({ type: "error", - title: "Unable to read the dropped thread", + title: "Unable to read the attached thread", description: isEnvironmentRequestInvalidError(error) && error.reason === "thread_transcript_too_large" @@ -2941,8 +2985,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // The agent reads a linked machine's thread itself, like the `@` picker's; any other // machine's comes in as its transcript. if (ref.environmentId !== environmentId && !linkedEnvironments.has(ref.environmentId)) { - void importDroppedThread( + void importThreadTranscript( ref, + attachmentDraftTarget, () => isActive() && attachmentTargetKeyRef.current === attachmentTargetKey, ); return []; @@ -3685,7 +3730,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursor={composerCursor} contextRecords={composerContextRecords} buildContextClipboardFragment={buildContextClipboardFragmentStable} - importContextFragment={importContextFragmentStable} + importPastedText={importPastedTextStable} skills={selectedProviderSkills} className={cn(showMobilePendingAnswerActions && "max-sm:pb-12")} onChange={onPromptChangeStable} diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde59341..fb6ba9da2cd6c 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -58,6 +58,21 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont return retained; } +/** Context ids a pasted reference keeps its link for: live, still importing, or cut and restorable. */ +export function heldContextIds( + live: ReadonlyMap, + importing: ReadonlySet, + retained: RetainedContextPayloads, +): Pick, "has"> { + const retainedMaps: ReadonlyArray> = Object.values(retained); + return { + has: (contextId) => + live.has(contextId) || + importing.has(contextId) || + retainedMaps.some((payloads) => payloads.has(contextId)), + }; +} + export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; diff --git a/apps/web/src/components/chat/pendingDraftWork.ts b/apps/web/src/components/chat/pendingDraftWork.ts index f004e5c4e65d2..6a0b380aeda4a 100644 --- a/apps/web/src/components/chat/pendingDraftWork.ts +++ b/apps/web/src/components/chat/pendingDraftWork.ts @@ -1,20 +1,33 @@ // Count per draft so overlapping pastes cannot release each other and strand chips. class PendingDraftWork { private readonly counts = new Map(); + // Chips whose bytes are still downloading; a paste of one has no record yet but will. + private readonly contextIds = new Map>(); - begin(draftKey: string): void { + begin(draftKey: string, contextId?: string): void { this.counts.set(draftKey, (this.counts.get(draftKey) ?? 0) + 1); + if (contextId !== undefined) { + this.contextIds.set(draftKey, (this.contextIds.get(draftKey) ?? new Set()).add(contextId)); + } } - end(draftKey: string): void { + end(draftKey: string, contextId?: string): void { const remaining = (this.counts.get(draftKey) ?? 0) - 1; if (remaining > 0) this.counts.set(draftKey, remaining); else this.counts.delete(draftKey); + const contextIds = this.contextIds.get(draftKey); + if (contextId !== undefined && contextIds?.delete(contextId) && contextIds.size === 0) { + this.contextIds.delete(draftKey); + } } has(draftKey: string): boolean { return (this.counts.get(draftKey) ?? 0) > 0; } + + importingContextIds(draftKey: string): ReadonlySet { + return this.contextIds.get(draftKey) ?? new Set(); + } } // Keep claims across composer remounts. diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index d48e965895ddd..29ae82a486762 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -4,14 +4,23 @@ import { type ComposerContextRecord, ComposerContextId, EnvironmentId, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ThreadId, } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { hostedThreadLink } from "@t3tools/shared/threadLinks"; import { expect, it, vi } from "vite-plus/test"; import { act, render, stubGlobal } from "../../../test/render"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; +import { configuredHostedAppUrl } from "../../hostedPairing"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { environmentContextRecord, threadContextReference } from "../../lib/composerContextRecords"; import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments"; +import { importPastedComposerText } from "../composerInlineTokenPaste"; import { pendingDraftWork } from "./pendingDraftWork"; import { useComposerContextImport } from "./useComposerContextImport"; @@ -25,7 +34,8 @@ vi.mock("../../state/use-atom-command", async (importOriginal) => ({ })); vi.mock("~/state/session", async (importOriginal) => ({ ...(await importOriginal()), - readPreparedConnection: () => ({ httpBaseUrl: "http://localhost" }), + readPreparedConnection: (environmentId: string) => + environmentId === "disconnected-machine" ? null : { httpBaseUrl: "http://localhost" }, })); type ImportInput = Parameters[0]; @@ -37,6 +47,30 @@ function Harness({ input, ready }: { input: ImportInput; ready: (value: Importer return null; } +function importInput(target: DraftId, promptRef: { current: string }) { + const store = useComposerDraftStore.getState(); + return { + environmentId: EnvironmentId.make("clipboard-target"), + linkedEnvironments: new Map(), + activeThread: undefined, + activeThreadId: null, + composerDraftTarget: target, + attachmentDraftTarget: target, + attachmentTargetKey: target, + attachmentTargetKeyRef: { current: target }, + questionAttachmentTarget: null, + pendingUserInputs: [], + composerContextRecords: new Map(), + composerImages: [], + composerFilesRef: { current: [] }, + pendingThreadImportsRef: { current: new Map() }, + promptRef, + addComposerFilesToDraft: (files: Parameters[1]) => + store.addFiles(target, files), + importThreadTranscript: () => {}, + } satisfies ImportInput; +} + function deferred() { let resolve!: (value: T) => void; const promise = new Promise((fulfill) => { @@ -57,6 +91,10 @@ it.each([ { kind: "image", edit: "question" }, { kind: "image", edit: "annotation" }, { kind: "image", edit: "delete-annotation" }, + // Copying a pending chip carries no record; pasting it over itself must keep its link. + { kind: "file", edit: "repaste" }, + // The download outlives the composer that started it, so a remounted one must see it. + { kind: "file", edit: "remount-repaste" }, ] as const)("settles a delayed $kind import after $edit", async ({ kind, edit }) => { const target = DraftId.make(`clipboard-${kind}-${edit}`); const store = useComposerDraftStore.getState(); @@ -76,36 +114,25 @@ it.each([ const requested = deferred(); const settled = deferred(); const input = { - environmentId: EnvironmentId.make("clipboard-target"), - linkedEnvironments: new Map(), - activeThread: undefined, - activeThreadId: null, - composerDraftTarget: target, - attachmentDraftTarget: target, - attachmentTargetKey: target, - attachmentTargetKeyRef: { current: target }, + ...importInput(target, promptRef), questionAttachmentTarget: edit === "question" ? target : null, - pendingUserInputs: [], - composerContextRecords: new Map(), - composerImages: [], - composerFilesRef: { current: [] }, - pendingThreadImportsRef: { current: new Map() }, - promptRef, addComposerFilesToDraft: (files: Parameters[1]) => store.addFiles(target, files, { appendReference: edit !== "question" }), - } satisfies ImportInput & { promptRef: { current: string } }; + } satisfies ImportInput; let importer!: Importer; - await using _screen = await render( + const harness = (key: string) => ( { importer = value; }} - />, + /> ); + await using screen = await render(harness("first")); const end = pendingDraftWork.end.bind(pendingDraftWork); - using _settled = vi.spyOn(pendingDraftWork, "end").mockImplementation((key) => { - end(key); + using _settled = vi.spyOn(pendingDraftWork, "end").mockImplementation((...args) => { + end(...args); settled.resolve(); }); using _fetch = stubGlobal("fetch", () => { @@ -168,13 +195,24 @@ it.each([ if (edit !== "cached") await requested.promise; }); if (edit !== "cached") expect(pendingDraftWork.has(target)).toBe(true); + if (edit === "remount-repaste") await screen.rerender(harness("second")); await act(() => { + if (edit === "repaste" || edit === "remount-repaste") { + promptRef.current = importPastedComposerText( + { getData: (format) => (format === "text/plain" ? pastedPrompt : "") }, + importer.importContextFragment, + pendingDraftWork.importingContextIds(target), + ); + store.setPrompt(target, promptRef.current); + } if ( edit !== "annotation" && edit !== "retain" && edit !== "cached" && edit !== "question" && - edit !== "switch" + edit !== "switch" && + edit !== "repaste" && + edit !== "remount-repaste" ) { promptRef.current = "Keep this edit"; store.setPrompt(target, promptRef.current); @@ -200,6 +238,8 @@ it.each([ expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || + edit === "repaste" || + edit === "remount-repaste" || edit === "annotation" || edit === "cached" || edit === "question" @@ -208,6 +248,144 @@ it.each([ ); }); +// Its chip used to resolve to nothing; now it keeps a link naming the thread and its machine. +it.each([ + { machine: "unlinked-machine", transcript: true }, + // Nothing can load a machine this client is not connected to, so only the link remains. + { machine: "disconnected-machine", transcript: false }, +])( + "pastes a thread from $machine, importing its transcript: $transcript", + async ({ machine, transcript }) => { + const target = DraftId.make(`clipboard-${machine}-thread`); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; + const ref = { + environmentId: EnvironmentId.make(machine), + threadId: ThreadId.make("remote"), + }; + const record = threadContextRecord(ref, "Remote thread"); + const importThreadTranscript = vi.fn(); + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ref.environmentId }, + records: [record], + })!; + let pasted = ""; + await act(() => { + pasted = importPastedComposerText( + { + getData: (format) => + format === "text/plain" + ? `See ${formatInlineContextReference(threadContextReference(record))}` + : format === COMPOSER_CONTEXT_CLIPBOARD_MIME + ? fragment + : "", + }, + importer.importContextFragment, + ); + }); + expect(pasted).toBe(`See [Remote thread](${hostedThreadLink(ref, configuredHostedAppUrl())})`); + expect(importThreadTranscript.mock.calls).toEqual(transcript ? [[ref, target]] : []); + expect(store.getComposerDraft(target)?.threadContexts ?? []).toEqual([]); + }, +); + +it("points a pasted duplicate at the id the draft holds it under", async () => { + const target = DraftId.make("clipboard-alias-duplicate"); + const held = environmentContextRecord(EnvironmentId.make("alias"), "Alias machine"); + const pasted = { ...held, contextId: ComposerContextId.make("alias") }; + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + expect(importer.importContextRecords([pasted], null).get("alias")).toBe(held.contextId); +}); + +// A stash restores into the prompt behind an open question, not into the question's answer. +it("imports a restored thread's transcript into the draft the restore names", async () => { + const target = DraftId.make("stash-unlinked-thread"); + const question = DraftId.make("stash-unlinked-thread-question"); + const ref = { + environmentId: EnvironmentId.make("unlinked-machine"), + threadId: ThreadId.make("remote"), + }; + const importThreadTranscript = vi.fn(); + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + const rewritten = importer.importContextRecords( + [threadContextRecord(ref, "Remote thread")], + null, + target, + ); + expect([...rewritten.values()]).toEqual([null]); + expect(importThreadTranscript).toHaveBeenCalledWith(ref, target); +}); + +it("counts the attachments of the draft a restore names, not the open question's", async () => { + const target = DraftId.make("stash-limit-target"); + const question = DraftId.make("stash-limit-question"); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(question) }; + store.addFiles( + question, + Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }, (_, index) => { + const file = new File([`${index}`], `answer-${index}.txt`, { type: "text/plain" }); + return { + type: "file" as const, + id: `answer-${index}`, + name: file.name, + mimeType: file.type, + sizeBytes: file.size, + file, + }; + }), + ); + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + expect(importer.countReservedAttachments()).toBe(PROVIDER_SEND_TURN_MAX_ATTACHMENTS); + expect(importer.countReservedAttachments(target)).toBe(0); +}); + it.each(["same", "other-environment"] as const)( "preserves thread identity across repeated pastes: %s", async (variant) => { @@ -232,29 +410,17 @@ it.each(["same", "other-environment"] as const)( await using _screen = await render( [], }} ready={(value) => { importer = value; }} />, ); - let importedId: string | undefined; + let importedId: string | null | undefined; await act(() => { importedId = importer .importContextRecords([pasted], pasted.environmentId, target) diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 265278faec747..5315b42fc5a6b 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -12,6 +12,7 @@ import { type ComposerContextRecord, type EnvironmentId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + type ScopedThreadRef, } from "@t3tools/contracts"; import { type ComposerFileAttachment, @@ -19,6 +20,7 @@ import { type DraftId, composerFileMatchesReattachMarker, composerFileNeedsReattach, + composerTargetKey, useComposerDraftStore, } from "../../composerDraftStore"; import { type PendingUserInput } from "../../session-logic"; @@ -92,6 +94,11 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + /** Attaches a thread's transcript to a draft, as dropping it does. */ + readonly importThreadTranscript: ( + ref: ScopedThreadRef, + draftTarget: ChatComposerProps["composerDraftTarget"], + ) => void; }) { const { environmentId, @@ -110,6 +117,7 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + importThreadTranscript, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -128,10 +136,14 @@ export function useComposerContextImport(input: { const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { reportFailure: false, }); - const countReservedAttachments = () => { + const countReservedAttachments = (draftTarget = attachmentDraftTarget) => { + const targetKey = composerTargetKey(draftTarget); const questionRequest = pendingUserInputs[0]; const otherQuestionKeys = - questionAttachmentTarget && questionRequest && activeThreadId + questionAttachmentTarget && + targetKey === attachmentTargetKey && + questionRequest && + activeThreadId ? questionRequest.questions .map((question) => questionAttachmentDraftId( @@ -143,12 +155,12 @@ export function useComposerContextImport(input: { ) .filter((key) => key !== questionAttachmentTarget) : []; - const draft = getComposerDraft(attachmentDraftTarget); + const draft = getComposerDraft(draftTarget); return ( (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + - countPreparingComposerImages(attachmentTargetKey) + - (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) + + countPreparingComposerImages(targetKey) + + (pendingThreadImportsRef.current.get(targetKey) ?? 0) + countQuestionAttachments(otherQuestionKeys) ); }; @@ -282,17 +294,19 @@ export function useComposerContextImport(input: { // the transfer against its own draft so a send cannot snapshot a message whose chip has no // attachment behind it, and so bytes for an abandoned draft never enter the next one. const importTargetKey = attachmentTargetKey; - pendingDraftWork.begin(importTargetKey); + const contextId = toKindScopedComposerContextId(record.kind, localId); + pendingDraftWork.begin(importTargetKey, contextId); await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => - pendingDraftWork.end(importTargetKey), + pendingDraftWork.end(importTargetKey, contextId), ); }; const importContextRecords = ( records: ReadonlyArray, sourceEnvironmentId: EnvironmentId | null, threadDraftTarget = attachmentDraftTarget, - ): ReadonlyMap => { - const rewritten = new Map(); + ): ReadonlyMap => { + // A null id means the reference becomes a link to a thread the agent cannot read. + const rewritten = new Map(); const dependentAttachmentLocalIds = new Map(); const skippedDependentAttachmentIds = new Set(); // Resolve annotations before their dependent screenshot records even if a foreign @@ -311,12 +325,13 @@ export function useComposerContextImport(input: { const record = asKnownContextRecord(candidate); if (!record) continue; // A reminted annotation needs its screenshot under the new annotation id. - const existing = dependentAttachmentLocalIds.has(record.contextId) + const existingId = dependentAttachmentLocalIds.has(record.contextId) ? undefined - : composerContextImportLookupIds(record).flatMap((contextId) => { - const found = composerContextRecords.get(contextId); - return found ? [found] : []; - })[0]; + : composerContextImportLookupIds(record).find((contextId) => + composerContextRecords.has(contextId), + ); + const existing = + existingId === undefined ? undefined : composerContextRecords.get(existingId); // Upload completion can change the server id since copy; the local bytes still match. if ( sourceEnvironmentId !== null && @@ -325,8 +340,10 @@ export function useComposerContextImport(input: { existing.record.file !== null && existing.record.file === copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId) - ) + ) { + rewritten.set(record.contextId, existingId ?? record.contextId); continue; + } const existingRecord = existing?.kind === "terminal" ? terminalContextRecord(existing.record) @@ -353,6 +370,8 @@ export function useComposerContextImport(input: { if (record.kind === "preview-annotation" && record.screenshotContextId) { skippedDependentAttachmentIds.add(record.screenshotContextId); } + // The draft may hold the record under its kind-scoped alias. + rewritten.set(record.contextId, existingId ?? record.contextId); continue; } const conflicts = existing !== undefined; @@ -394,13 +413,21 @@ export function useComposerContextImport(input: { break; } case "thread": { - // The agent reads threads on its own server and the machines it links to; a pasted - // thread from any other machine is dropped. + // The agent reads threads on its own server and the machines it links to; any other + // machine this client is connected to sends its transcript, as a dropped one does. if ( record.environmentId !== environmentId && !linkedEnvironments.has(record.environmentId) - ) + ) { + if (readPreparedConnection(record.environmentId)) { + importThreadTranscript( + { environmentId: record.environmentId, threadId: record.threadId }, + threadDraftTarget, + ); + } + rewritten.set(record.contextId, null); break; + } // Threads reuse their destination record by identity, reminting only on an ID collision. const threads = getComposerDraft(threadDraftTarget)?.threadContexts ?? []; const attached = threads.find( @@ -449,9 +476,8 @@ export function useComposerContextImport(input: { }; const importContextFragment = ( fragment: ComposerContextClipboardFragment, - ): ReadonlyMap => + ): ReadonlyMap => importContextRecords(fragment.records, fragment.source.environmentId); - const importContextFragmentStable = useStableCallback(importContextFragment); return { loadThreadTranscript, @@ -459,6 +485,5 @@ export function useComposerContextImport(input: { countReservedAttachmentsStable, importContextRecords, importContextFragment, - importContextFragmentStable, }; } diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index f89a51a2f8c99..2b13ae0bbbb29 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -34,6 +34,7 @@ import { compressImageForStash } from "../../lib/imageCompression"; import { formatInlineContextReference } from "~/lib/composerContextReferences"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { pendingDraftWork } from "./pendingDraftWork"; +import { unreadableThreadLink } from "../composerInlineTokenPaste"; import { countPreparingComposerImages } from "./preparingComposerImages"; import { isResponseContextRecord, @@ -100,7 +101,7 @@ export function useComposerStash(input: { records: ReadonlyArray, sourceEnvironmentId: EnvironmentId | null, threadDraftTarget?: ChatComposerProps["composerDraftTarget"], - ) => ReadonlyMap; + ) => ReadonlyMap; readonly expandMobileComposer: () => void; }) { const { @@ -234,7 +235,7 @@ export function useComposerStash(input: { const rewrittenContextIds = entry.records ? importContextRecords(entry.records, null, composerDraftTarget) - : new Map(); + : new Map(); // A reply only makes sense in the thread that holds the response, and one already pending wins. const stashedReply = entry.records?.find(isResponseContextRecord); if ( @@ -248,6 +249,7 @@ export function useComposerStash(input: { } const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { const contextId = rewrittenContextIds.get(reference.contextId); + if (contextId === null) return unreadableThreadLink(entry.records ?? [], reference); return contextId ? formatInlineContextReference({ ...reference, diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index d201cd3adc71a..e71bc63b397ad 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -1,21 +1,41 @@ import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; -import { type ComposerContextClipboardFragment, EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + type ComposerContextClipboardFragment, + ComposerContextId, + EnvironmentId, + ThreadId, +} from "@t3tools/contracts"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, encodeComposerContextFragment, } from "@t3tools/shared/composerContextClipboard"; -import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import { + formatComposerContextReference, + threadContextRecord, +} from "@t3tools/shared/composerContextReferences"; import { describe, expect, it } from "vite-plus/test"; import { importPastedComposerText } from "./composerInlineTokenPaste"; +const sourceThread = threadContextRecord( + { + environmentId: EnvironmentId.make("environment-elsewhere"), + threadId: ThreadId.make("thread-source"), + }, + "Source Thread Ready", +); +const pastedText = `Read this: ${formatComposerContextReference(sourceThread)} and continue.`; + +function clipboard(data: Record) { + return { getData: (format: string) => data[format] ?? "" }; +} + +const importNothing = () => new Map(); + const thread = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("thread-1"), }; -const clipboard = (data: Record) => ({ - getData: (type: string) => data[type] ?? "", -}); const chip = (title: string) => `[${title}](t3-context://v1/thread/${threadContextRecord(thread, title).contextId})`; @@ -28,6 +48,80 @@ const importAll = }; describe("importPastedComposerText", () => { + const reference = formatComposerContextReference(sourceThread); + const codeThread = threadContextRecord( + { environmentId: sourceThread.environmentId, threadId: ThreadId.make("thread-code") }, + "Fix `foo` bug", + ); + const localId = ComposerContextId.make("thread-local"); + const importAsLocal = (pasted: ComposerContextClipboardFragment) => + new Map(pasted.records.map((record) => [record.contextId, localId])); + it.each([ + { + name: "a reference without a fragment becomes its label", + text: pastedText, + expected: "Read this: Source Thread Ready and continue.", + }, + { + name: "a reference whose record the import dropped becomes its label", + text: pastedText, + records: [sourceThread], + expected: "Read this: Source Thread Ready and continue.", + }, + { + name: "a reference the draft already holds stays", + text: pastedText, + held: [sourceThread.contextId], + expected: pastedText, + }, + { + name: "references inside fenced and inline code stay as written", + text: `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and ${reference}`, + expected: `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and Source Thread Ready`, + }, + { + name: "a fence holding a fence marker mid-line stays open", + text: `\`\`\`js\nconsole.log("\`\`\`");\n${reference}\n\`\`\``, + expected: `\`\`\`js\nconsole.log("\`\`\`");\n${reference}\n\`\`\``, + }, + { + name: "a reference between escaped backticks is imported", + text: `\\\`${reference}\\\``, + records: [sourceThread], + importContext: importAsLocal, + expected: `\\\`${formatComposerContextReference({ ...sourceThread, contextId: localId })}\\\``, + }, + { + name: "a CR-only fence closes before a reference after it", + text: `~~~\rcode\r~~~\r${reference}`, + records: [sourceThread], + importContext: importAsLocal, + expected: `~~~\ncode\n~~~\n${formatComposerContextReference({ ...sourceThread, contextId: localId })}`, + }, + { + name: "backticks in a reference's label do not open code", + text: `Quote with \`, see ${formatComposerContextReference(codeThread)}`, + records: [codeThread], + importContext: importAsLocal, + expected: `Quote with \`, see ${formatComposerContextReference({ ...codeThread, contextId: localId })}`, + }, + ])("$name", ({ text, records, importContext = importNothing, held = [], expected }) => { + const fragment = records + ? encodeComposerContextFragment({ + version: 1, + source: { environmentId: sourceThread.environmentId }, + records, + })! + : ""; + expect( + importPastedComposerText( + clipboard({ "text/plain": text, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment }), + importContext, + new Set(held), + ), + ).toBe(expected); + }); + it("pastes a copied thread link back as the chip it was copied from", () => { const target = threadChipCopyTarget(thread, "Fix the login flow"); const imported: Array = []; diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 0e1a84aa71af2..b087ca3dccf80 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -13,13 +13,104 @@ import { collectComposerContextReferences, formatComposerContextReference, replaceComposerContextReferences, + sanitizeComposerContextLabel, threadLinkContextReferences, } from "@t3tools/shared/composerContextReferences"; - +import { hostedThreadLink } from "@t3tools/shared/threadLinks"; +import { isClosingFence, parseOpeningFence } from "~/composer-rich-text-doc"; +import { configuredHostedAppUrl } from "~/hostedPairing"; import { readThreadShell } from "~/state/entities"; const threadTitle = (ref: ScopedThreadRef) => readThreadShell(ref)?.title; +/** + * Code ranges by the composer's rules: fences open and close only on their own line, and a + * backtick run spans to the next run of its length on that line. Linear in the text length. + */ +function markdownCodeRanges(text: string): Array { + const ranges: Array = []; + const lines = text.split("\n"); + let lineStart = 0; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]!; + const opening = parseOpeningFence(line); + if (opening) { + const fenceStart = lineStart; + do { + lineStart += lines[index]!.length + 1; + index += 1; + } while (index < lines.length && !isClosingFence(lines[index]!, opening.fence)); + ranges.push([fenceStart, Math.min(text.length, lineStart + (lines[index]?.length ?? 0))]); + } else { + pushCodeSpans(line, lineStart, ranges); + } + lineStart += (lines[index]?.length ?? 0) + 1; + } + return ranges; +} + +function pushCodeSpans(line: string, offset: number, ranges: Array) { + const runs = Array.from(line.matchAll(/`+/g), (match) => ({ + start: match.index, + end: match.index + match[0].length, + })); + // Run indexes by length, each with a cursor that only moves forward. + const byLength = new Map(); + runs.forEach((run, index) => { + const entry = byLength.get(run.end - run.start) ?? { indexes: [], next: 0 }; + entry.indexes.push(index); + byLength.set(run.end - run.start, entry); + }); + let codeEnd = 0; + for (let index = 0; index < runs.length; index += 1) { + const run = runs[index]!; + let backslashes = 0; + while (run.start - backslashes > codeEnd && line[run.start - backslashes - 1] === "\\") { + backslashes += 1; + } + // An escaped backtick is literal and the rest of its run may still open. + const start = run.start + (backslashes % 2); + const candidates = byLength.get(run.end - start); + if (!candidates) continue; + while ( + candidates.next < candidates.indexes.length && + candidates.indexes[candidates.next]! <= index + ) { + candidates.next += 1; + } + const closeIndex = candidates.indexes[candidates.next]; + if (closeIndex === undefined) continue; + ranges.push([offset + start, offset + runs[closeIndex]!.end]); + codeEnd = runs[closeIndex]!.end; + index = closeIndex; + } +} + +/** Whether an offset is inside code; call it with ascending offsets. */ +function codeOffsetTest(text: string): (offset: number) => boolean { + let ranges: Array | null = null; + let next = 0; + return (offset) => { + // The editor holds each reference as an atom, so backticks in its label never open code. + ranges ??= markdownCodeRanges( + replaceComposerContextReferences(text, (occurrence) => " ".repeat(occurrence.source.length)), + ); + while (next < ranges.length && ranges[next]![1] <= offset) next += 1; + return next < ranges.length && ranges[next]![0] <= offset; + }; +} + +/** A thread the agent cannot read stays a link to its machine, whether or not its transcript arrives. */ +export function unreadableThreadLink( + records: ReadonlyArray, + reference: { readonly contextId: string; readonly label: string }, +): string { + const record = records.find((candidate) => candidate.contextId === reference.contextId); + if (record?.kind !== "thread" || !("threadId" in record)) return reference.label; + const link = hostedThreadLink(record, configuredHostedAppUrl()); + return `[${sanitizeComposerContextLabel(reference.label, "thread")}](${link})`; +} + // Matches ProseMirror's default clipboard parser, which a custom handlePaste bypasses. export function readPastedPlainText(clipboardData: Pick): string { return clipboardData.getData("text/plain").replace(/\r\n?/g, "\n"); @@ -29,7 +120,7 @@ export function readPastedPlainText(clipboardData: Pick export function readPastedComposerContext( clipboardData: Pick, ): ComposerContextClipboardFragment | null { - const pastedText = clipboardData.getData("text/plain"); + const pastedText = readPastedPlainText(clipboardData); const decodedFragment = decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ?? decodeComposerContextClipboardHtml(clipboardData.getData("text/html")); @@ -42,8 +133,11 @@ export function readPastedComposerContext( decodedFragment?.source ?? (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null); if (source === null) return null; + const inCode = codeOffsetTest(threads.text); const pastedIds = new Set( - collectComposerContextReferences(threads.text).map((occurrence) => occurrence.contextId), + collectComposerContextReferences(threads.text) + .filter((occurrence) => !inCode(occurrence.start)) + .map((occurrence) => occurrence.contextId), ); const records = new Map(); for (const record of [...(decodedFragment?.records ?? []), ...threads.records]) { @@ -64,30 +158,40 @@ export function readPastedComposerContext( }; } +/** + * References with no record behind them, in the paste or the draft, paste as their label. + * References inside code stay as written. + */ export function importPastedComposerText( clipboardData: Pick, importContextFragment?: ( fragment: ComposerContextClipboardFragment, - ) => ReadonlyMap, + ) => ReadonlyMap, + heldContextIds: Pick, "has"> = new Set(), ): string { const pastedText = readPastedPlainText(clipboardData); const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null; const rewrittenIds = fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null; - if (!rewrittenIds || rewrittenIds.size === 0) return pastedText; const nextId = (contextId: string) => { - const id = rewrittenIds.get(contextId); + const id = rewrittenIds?.get(contextId); return id ? ComposerContextId.make(id) : undefined; }; + const inCode = codeOffsetTest(pastedText); const text = replaceComposerContextReferences(pastedText, (occurrence) => { + if (inCode(occurrence.start)) return occurrence.source; const contextId = nextId(occurrence.contextId); - return contextId - ? formatComposerContextReference({ - ...occurrence, - contextId, - kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, - }) - : occurrence.source; + if (contextId) { + return formatComposerContextReference({ + ...occurrence, + contextId, + kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, + }); + } + if (rewrittenIds?.get(occurrence.contextId) === null) { + return unreadableThreadLink(fragment?.records ?? [], occurrence); + } + return heldContextIds.has(occurrence.contextId) ? occurrence.source : occurrence.label; }); // A thread the import refused, on a machine this agent cannot read, stays the link it was. return threadLinkContextReferences(text, fragment?.records ?? [], threadTitle, (record) => diff --git a/docs/user/composer.md b/docs/user/composer.md index 89a96f120d4d0..4e77fcce282ef 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -352,10 +352,10 @@ history on demand, so attaching a long thread costs nothing until the agent look thread does not change it, and the agent cannot send messages to it unless you ask. A thread from a linked machine, picked, pasted or dropped, stays a reference that the agent reads -on that machine. A pasted link to a thread on any other machine stays a link. Dropping a thread -from any other environment attaches a saved transcript file. The source +on that machine. Pasting or dropping a thread from any other environment attaches a saved +transcript file, and a pasted one also stays a link to the thread. The source environment must be connected and up to date. The transcript includes the visible history and -saved text context at the time of the drop; later messages and the contents of attached files +saved text context at the time you attached it; later messages and the contents of attached files are not copied. The agent can read the saved transcript after the source disconnects. Normal file attachment limits apply.