From 4b5e9612ddcc00d9c12afd20a307c141b9163490 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 04:21:53 +0000 Subject: [PATCH 01/13] test(web): reproduce #29925 unbacked pasted context references These tests reproduce #29925: a pasted t3-context reference with no record behind it (plain-text paste, or a fragment record the import dropped) stays a link instead of becoming its plain label. Co-Authored-By: Claude Opus 5.5 --- .../composerInlineTokenPaste.test.ts | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 apps/web/src/components/composerInlineTokenPaste.test.ts diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts new file mode 100644 index 0000000000000..5ef0ed12c0f8c --- /dev/null +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -0,0 +1,49 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; +import { + formatComposerContextReference, + threadContextRecord, +} from "@t3tools/shared/composerContextReferences"; +import { describe, expect, it } from "vitest"; + +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(); + +describe("importPastedComposerText", () => { + it("turns a context reference without a fragment into its plain label", () => { + expect(importPastedComposerText(clipboard({ "text/plain": pastedText }), importNothing)).toBe( + "Read this: Source Thread Ready and continue.", + ); + }); + + it("turns a context reference whose record the import dropped into its plain label", () => { + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: sourceThread.environmentId }, + records: [sourceThread], + }); + expect( + importPastedComposerText( + clipboard({ "text/plain": pastedText, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "" }), + importNothing, + ), + ).toBe("Read this: Source Thread Ready and continue."); + }); +}); From 334a40b31c7f5eaa2dd2946829019f70845eee7e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 04:27:32 +0000 Subject: [PATCH 02/13] fix(web): pasted context links without a record paste as plain text A pasted t3-context reference with no record behind it (a plain-text clipboard, or a fragment record the import dropped, such as a thread from an unlinked environment) stayed a chip that resolved to nothing, and the agent received an "unavailable" context entry. The paste now keeps a reference as a link only when the import rewrote it or the destination draft already holds its record; any other reference becomes its plain label. Co-Authored-By: Claude Opus 5.5 --- .../components/ComposerPromptEditorTiptap.tsx | 6 +++-- apps/web/src/components/chat/ChatComposer.tsx | 6 ++++- .../composerInlineTokenPaste.test.ts | 12 ++++++++- .../components/composerInlineTokenPaste.ts | 27 +++++++++---------- 4 files changed, 33 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 3df1e47613370..8f0b799f0b2ee 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -977,6 +977,7 @@ function ComposerPromptEditorTiptapInner( onCommandKeyDown, isPathQueryActive, importContextFragment, + contextRecords, })); // Stable so a skills refresh does not rerun the controlled-value effect. @@ -1368,10 +1369,11 @@ function ComposerPromptEditorTiptapInner( ); return true; } - const importFragment = readCallbacks().importContextFragment; + const { importContextFragment: importFragment, contextRecords: heldRecords } = + readCallbacks(); let text = !literalText && importFragment - ? importPastedComposerText(clipboardData, importFragment) + ? importPastedComposerText(clipboardData, importFragment, heldRecords) : pastedText; const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); const isChip = (token: (typeof tokens)[number] | undefined) => diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9ad9158cd4da3..a86a3e4b8e541 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2420,7 +2420,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return false; } if (options?.clipboardData) { - text = importPastedComposerText(options.clipboardData, importContextFragment); + text = importPastedComposerText( + options.clipboardData, + importContextFragment, + composerContextRecords, + ); } const prompt = promptRef.current; const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index 5ef0ed12c0f8c..daded97b11bde 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -7,7 +7,7 @@ import { formatComposerContextReference, threadContextRecord, } from "@t3tools/shared/composerContextReferences"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it } from "vite-plus/test"; import { importPastedComposerText } from "./composerInlineTokenPaste"; @@ -46,4 +46,14 @@ describe("importPastedComposerText", () => { ), ).toBe("Read this: Source Thread Ready and continue."); }); + + it("keeps a context reference whose record the draft already holds", () => { + expect( + importPastedComposerText( + clipboard({ "text/plain": pastedText }), + importNothing, + new Set([sourceThread.contextId]), + ), + ).toBe(pastedText); + }); }); diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 32722ad6a9571..ac1a6f0dad2b9 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -37,28 +37,27 @@ export function readPastedComposerContext( }; } +/** References with no record behind them, in the paste or the draft, paste as their label. */ export function importPastedComposerText( clipboardData: Pick, importContextFragment?: ( fragment: ComposerContextClipboardFragment, ) => ReadonlyMap, + heldContextIds: Pick, "has"> = new Set(), ): string { const pastedText = clipboardData.getData("text/plain"); const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null; const rewrittenIds = fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null; - const text = - rewrittenIds && rewrittenIds.size > 0 - ? replaceComposerContextReferences(pastedText, (occurrence) => { - const nextId = rewrittenIds.get(occurrence.contextId); - return nextId - ? formatComposerContextReference({ - ...occurrence, - contextId: ComposerContextId.make(nextId), - kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, - }) - : occurrence.source; - }) - : pastedText; - return text; + return replaceComposerContextReferences(pastedText, (occurrence) => { + const nextId = rewrittenIds?.get(occurrence.contextId); + if (nextId) { + return formatComposerContextReference({ + ...occurrence, + contextId: ComposerContextId.make(nextId), + kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, + }); + } + return heldContextIds.has(occurrence.contextId) ? occurrence.source : occurrence.label; + }); } From 70c4e8a7580bee67d8eb2c92f7a060e0e2918275 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 04:45:54 +0000 Subject: [PATCH 03/13] fix(web): pasted threads from unlinked machines keep their chip A thread pasted from a machine this one does not link to was dropped by the import, so its chip resolved to nothing and the agent got an unavailable reference. The record is now kept: sending stops with the existing "Attached thread is on another machine" guidance, and an answer to an agent's question carries it as a t3-thread link naming its machine. The plain-label fallback for references with nothing behind them now also counts chips cut from the draft and still restorable, and attachments still downloading, as held, through one predicate shared by the editor paste and the paste-to-focus path. Paste-to-focus no longer rewrites a literal pending answer. Fixes pingdotgg/t3code#29925 Co-Authored-By: Claude Opus 5.5 --- ...rPromptEditorTiptap.input.browser.test.tsx | 37 ++++++-- .../components/ComposerPromptEditorTiptap.tsx | 25 ++---- apps/web/src/components/chat/ChatComposer.tsx | 26 ++++-- .../components/chat/composerContextUndo.ts | 15 ++++ .../useComposerContextImport.browser.test.tsx | 88 +++++++++++++++---- .../chat/useComposerContextImport.ts | 28 +++--- 6 files changed, 154 insertions(+), 65 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index c59724cccf693..40757fea5d03d 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 type { ServerProviderSkill } from "@t3tools/contracts"; import type { Editor } from "@tiptap/core"; @@ -268,17 +270,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: "", @@ -351,6 +360,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 8f0b799f0b2ee..567f5d22f1d46 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -24,11 +24,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, @@ -123,7 +119,6 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView"; import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal"; import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight"; -import { importPastedComposerText } from "./composerInlineTokenPaste"; import { didComposerSelectionChangeVisibly } from "./composerSelection"; import type { ComposerDraftContextRecords } from "./composerContextPresentation"; @@ -152,9 +147,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; @@ -935,7 +929,7 @@ function ComposerPromptEditorTiptapInner( literalText = false, contextRecords, buildContextClipboardFragment, - importContextFragment, + importPastedText, skills, disabled, placeholder, @@ -976,8 +970,7 @@ function ComposerPromptEditorTiptapInner( onVisibleSelectionChange, onCommandKeyDown, isPathQueryActive, - importContextFragment, - contextRecords, + importPastedText, })); // Stable so a skills refresh does not rerun the controlled-value effect. @@ -1369,12 +1362,8 @@ function ComposerPromptEditorTiptapInner( ); return true; } - const { importContextFragment: importFragment, contextRecords: heldRecords } = - readCallbacks(); - let text = - !literalText && importFragment - ? importPastedComposerText(clipboardData, importFragment, heldRecords) - : 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 a86a3e4b8e541..39e74dce651ba 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -113,6 +113,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + heldContextIds, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -1376,10 +1377,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) countReservedAttachmentsStable, importContextRecords, importContextFragment, - importContextFragmentStable, + importingContextIdsRef, } = useComposerContextImport({ environmentId, - linkedEnvironments, activeThread, activeThreadId, composerDraftTarget, @@ -2401,6 +2401,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : bannerItems; + const importPastedText = (clipboardData: DataTransfer) => + importPastedComposerText( + clipboardData, + importContextFragment, + heldContextIds( + composerContextRecords, + importingContextIdsRef.current, + retainedContextPayloads, + ), + ); + const importPastedTextStable = useStableCallback(importPastedText); + const insertComposerText = ( text: string, position: "cursor" | "end", @@ -2419,12 +2431,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) { return false; } - if (options?.clipboardData) { - text = importPastedComposerText( - options.clipboardData, - importContextFragment, - composerContextRecords, - ); + if (options?.clipboardData && !isLiteralPendingAnswer) { + text = importPastedText(options.clipboardData); } const prompt = promptRef.current; const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; @@ -3408,7 +3416,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/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index a050b0f51edf0..3e2ffdf36afb2 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -1,11 +1,18 @@ import { useEffect } from "react"; -import { type ComposerContextRecord, ComposerContextId, EnvironmentId } from "@t3tools/contracts"; +import { + type ComposerContextRecord, + ComposerContextId, + EnvironmentId, + ThreadId, +} from "@t3tools/contracts"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { expect, it, vi } from "vite-plus/test"; import { act, render, stubGlobal } from "../../../test/render"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments"; +import { importPastedComposerText } from "../composerInlineTokenPaste"; import { pendingDraftWork } from "./pendingDraftWork"; import { useComposerContextImport } from "./useComposerContextImport"; @@ -31,6 +38,28 @@ 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"), + 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), + } satisfies ImportInput; +} + function deferred() { let resolve!: (value: T) => void; const promise = new Promise((fulfill) => { @@ -50,6 +79,8 @@ 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" }, ] as const)("settles a delayed $kind import after $edit", async ({ kind, edit }) => { const target = DraftId.make(`clipboard-${kind}-${edit}`); const store = useComposerDraftStore.getState(); @@ -69,24 +100,11 @@ 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( { + if (edit === "repaste") { + promptRef.current = importPastedComposerText( + { getData: (format) => (format === "text/plain" ? pastedPrompt : "") }, + importer.importContextFragment, + importer.importingContextIdsRef.current, + ); + store.setPrompt(target, promptRef.current); + } if ( edit !== "annotation" && edit !== "retain" && edit !== "cached" && edit !== "question" && - edit !== "switch" + edit !== "switch" && + edit !== "repaste" ) { promptRef.current = "Keep this edit"; store.setPrompt(target, promptRef.current); @@ -179,6 +206,7 @@ it.each([ expect(attachments.map((file) => file.name)).toEqual( edit === "undo" || edit === "retain" || + edit === "repaste" || edit === "annotation" || edit === "cached" || edit === "question" @@ -186,3 +214,29 @@ it.each([ : [], ); }); + +// Dropping it left the pasted chip resolving to nothing, so the agent saw an unavailable thread. +it("keeps a pasted thread from a machine this one does not link to", async () => { + const target = DraftId.make("clipboard-unlinked-thread"); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; + const record = threadContextRecord( + { environmentId: EnvironmentId.make("unlinked-machine"), threadId: ThreadId.make("remote") }, + "Remote thread", + ); + let importer!: Importer; + await using _screen = await render( + { + importer = value; + }} + />, + ); + let rewritten = new Map(); + await act(() => { + rewritten = new Map(importer.importContextRecords([record], record.environmentId)); + }); + expect(rewritten.get(record.contextId)).toBe(record.contextId); + expect(store.getComposerDraft(target)?.threadContexts).toEqual([record]); +}); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 74e97a5076d7d..860a78656346e 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -5,7 +5,7 @@ import { import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; -import type { RefObject } from "react"; +import { type RefObject, useRef } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { type ComposerContextClipboardFragment, @@ -76,7 +76,6 @@ async function downloadAttachmentBlob(url: string): Promise { */ export function useComposerContextImport(input: { readonly environmentId: EnvironmentId; - readonly linkedEnvironments: ReadonlyMap; readonly activeThread: ChatComposerProps["activeThread"]; readonly activeThreadId: ChatComposerProps["activeThreadId"]; readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"]; @@ -94,7 +93,6 @@ export function useComposerContextImport(input: { }) { const { environmentId, - linkedEnvironments, activeThread, activeThreadId, composerDraftTarget, @@ -127,6 +125,8 @@ export function useComposerContextImport(input: { const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { reportFailure: false, }); + // Chips whose bytes are still downloading; a paste of one has no record yet but will. + const importingContextIdsRef = useRef(new Set()); const countReservedAttachments = () => { const questionRequest = pendingUserInputs[0]; const otherQuestionKeys = @@ -279,10 +279,13 @@ 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; + const contextId = toKindScopedComposerContextId(record.kind, localId); pendingDraftWork.begin(importTargetKey); - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => - pendingDraftWork.end(importTargetKey), - ); + importingContextIdsRef.current.add(contextId); + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => { + importingContextIdsRef.current.delete(contextId); + pendingDraftWork.end(importTargetKey); + }); }; const importContextRecords = ( records: ReadonlyArray, @@ -391,13 +394,9 @@ 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. - if ( - record.environmentId !== environmentId && - !linkedEnvironments.has(record.environmentId) - ) - break; + // A thread from a machine this one does not link to is kept so its chip and target + // survive: a send stops with guidance to remove it or switch machines, and an + // answer to an agent's question carries it as a link naming its machine. addComposerDraftThreadContexts(threadDraftTarget, [record], { appendReference: false, }); @@ -437,7 +436,6 @@ export function useComposerContextImport(input: { fragment: ComposerContextClipboardFragment, ): ReadonlyMap => importContextRecords(fragment.records, fragment.source.environmentId); - const importContextFragmentStable = useStableCallback(importContextFragment); return { loadThreadTranscript, @@ -445,6 +443,6 @@ export function useComposerContextImport(input: { countReservedAttachmentsStable, importContextRecords, importContextFragment, - importContextFragmentStable, + importingContextIdsRef, }; } From e2bca443b79cd0479e57996b146645c37a565428 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 05:07:34 +0000 Subject: [PATCH 04/13] fix(web): pasted threads from unlinked machines attach their transcript Pasting a thread from a machine this one does not link to now does what dropping it does: the thread's transcript is imported as a file attachment, into the question's draft when answering one, and its link pastes as the thread's title. Its chip is no longer kept for the send guard to block. Restoring a stash that holds such a thread does the same instead of leaving a dead link. Chips whose bytes are still downloading are tracked in pendingDraftWork per draft, so a composer that remounts mid-download still keeps a re-pasted chip's link and the finished download. References inside pasted fenced code or code spans stay as written. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 8 ++- .../src/components/chat/pendingDraftWork.ts | 17 ++++- .../useComposerContextImport.browser.test.tsx | 68 ++++++++++++++----- .../chat/useComposerContextImport.ts | 44 +++++++----- .../src/components/chat/useComposerStash.ts | 5 +- .../composerInlineTokenPaste.test.ts | 8 +++ .../components/composerInlineTokenPaste.ts | 36 ++++++++-- docs/user/composer.md | 4 +- 8 files changed, 144 insertions(+), 46 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 39e74dce651ba..8672aaf4ab738 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1377,9 +1377,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) countReservedAttachmentsStable, importContextRecords, importContextFragment, - importingContextIdsRef, } = useComposerContextImport({ environmentId, + linkedEnvironments, activeThread, activeThreadId, composerDraftTarget, @@ -1394,6 +1394,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + importThreadTranscript: (ref) => { + const targetKey = attachmentTargetKey; + void importDroppedThread(ref, () => attachmentTargetKeyRef.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 @@ -2407,7 +2411,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) importContextFragment, heldContextIds( composerContextRecords, - importingContextIdsRef.current, + pendingDraftWork.importingContextIds(attachmentTargetKey), retainedContextPayloads, ), ); 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 3e2ffdf36afb2..fa231f6936917 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -5,12 +5,17 @@ import { EnvironmentId, ThreadId, } from "@t3tools/contracts"; +import { + COMPOSER_CONTEXT_CLIPBOARD_MIME, + encodeComposerContextFragment, +} from "@t3tools/shared/composerContextClipboard"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { expect, it, vi } from "vite-plus/test"; import { act, render, stubGlobal } from "../../../test/render"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { threadContextReference } from "../../lib/composerContextRecords"; import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments"; import { importPastedComposerText } from "../composerInlineTokenPaste"; import { pendingDraftWork } from "./pendingDraftWork"; @@ -42,6 +47,7 @@ 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, @@ -57,6 +63,7 @@ function importInput(target: DraftId, promptRef: { current: string }) { promptRef, addComposerFilesToDraft: (files: Parameters[1]) => store.addFiles(target, files), + importThreadTranscript: () => {}, } satisfies ImportInput; } @@ -81,6 +88,8 @@ it.each([ { 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(); @@ -106,17 +115,19 @@ it.each([ store.addFiles(target, files, { appendReference: edit !== "question" }), } 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", () => { @@ -169,12 +180,13 @@ 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") { + if (edit === "repaste" || edit === "remount-repaste") { promptRef.current = importPastedComposerText( { getData: (format) => (format === "text/plain" ? pastedPrompt : "") }, importer.importContextFragment, - importer.importingContextIdsRef.current, + pendingDraftWork.importingContextIds(target), ); store.setPrompt(target, promptRef.current); } @@ -184,7 +196,8 @@ it.each([ edit !== "cached" && edit !== "question" && edit !== "switch" && - edit !== "repaste" + edit !== "repaste" && + edit !== "remount-repaste" ) { promptRef.current = "Keep this edit"; store.setPrompt(target, promptRef.current); @@ -207,6 +220,7 @@ it.each([ edit === "undo" || edit === "retain" || edit === "repaste" || + edit === "remount-repaste" || edit === "annotation" || edit === "cached" || edit === "question" @@ -215,28 +229,46 @@ it.each([ ); }); -// Dropping it left the pasted chip resolving to nothing, so the agent saw an unavailable thread. -it("keeps a pasted thread from a machine this one does not link to", async () => { +// Its chip used to resolve to nothing, or block the send; a dropped one comes in as its transcript. +it("imports a pasted thread from a machine this one does not link to as its transcript", async () => { const target = DraftId.make("clipboard-unlinked-thread"); const store = useComposerDraftStore.getState(); using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; - const record = threadContextRecord( - { environmentId: EnvironmentId.make("unlinked-machine"), threadId: ThreadId.make("remote") }, - "Remote thread", - ); + const ref = { + environmentId: EnvironmentId.make("unlinked-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; }} />, ); - let rewritten = new Map(); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: ref.environmentId }, + records: [record], + })!; + let pasted = ""; await act(() => { - rewritten = new Map(importer.importContextRecords([record], record.environmentId)); + pasted = importPastedComposerText( + { + getData: (format) => + format === "text/plain" + ? `See ${formatInlineContextReference(threadContextReference(record))}` + : format === COMPOSER_CONTEXT_CLIPBOARD_MIME + ? fragment + : "", + }, + importer.importContextFragment, + ); }); - expect(rewritten.get(record.contextId)).toBe(record.contextId); - expect(store.getComposerDraft(target)?.threadContexts).toEqual([record]); + expect(pasted).toBe("See Remote thread"); + expect(importThreadTranscript).toHaveBeenCalledWith(ref); + expect(store.getComposerDraft(target)?.threadContexts ?? []).toEqual([]); }); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 860a78656346e..40e336e2483a4 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -5,13 +5,14 @@ import { import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc"; import * as Cause from "effect/Cause"; import * as Schema from "effect/Schema"; -import { type RefObject, useRef } from "react"; +import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + type ScopedThreadRef, } from "@t3tools/contracts"; import { type ComposerFileAttachment, @@ -76,6 +77,7 @@ async function downloadAttachmentBlob(url: string): Promise { */ export function useComposerContextImport(input: { readonly environmentId: EnvironmentId; + readonly linkedEnvironments: ReadonlyMap; readonly activeThread: ChatComposerProps["activeThread"]; readonly activeThreadId: ChatComposerProps["activeThreadId"]; readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"]; @@ -90,9 +92,12 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + /** Attaches a thread's transcript, as dropping it does. */ + readonly importThreadTranscript: (ref: ScopedThreadRef) => void; }) { const { environmentId, + linkedEnvironments, activeThread, activeThreadId, composerDraftTarget, @@ -107,6 +112,7 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + importThreadTranscript, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -125,8 +131,6 @@ export function useComposerContextImport(input: { const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { reportFailure: false, }); - // Chips whose bytes are still downloading; a paste of one has no record yet but will. - const importingContextIdsRef = useRef(new Set()); const countReservedAttachments = () => { const questionRequest = pendingUserInputs[0]; const otherQuestionKeys = @@ -280,19 +284,18 @@ export function useComposerContextImport(input: { // attachment behind it, and so bytes for an abandoned draft never enter the next one. const importTargetKey = attachmentTargetKey; const contextId = toKindScopedComposerContextId(record.kind, localId); - pendingDraftWork.begin(importTargetKey); - importingContextIdsRef.current.add(contextId); - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => { - importingContextIdsRef.current.delete(contextId); - pendingDraftWork.end(importTargetKey); - }); + pendingDraftWork.begin(importTargetKey, contextId); + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() => + 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 its plain label. + const rewritten = new Map(); const dependentAttachmentLocalIds = new Map(); const skippedDependentAttachmentIds = new Set(); // Resolve annotations before their dependent screenshot records even if a foreign @@ -394,9 +397,19 @@ export function useComposerContextImport(input: { break; } case "thread": { - // A thread from a machine this one does not link to is kept so its chip and target - // survive: a send stops with guidance to remove it or switch machines, and an - // answer to an agent's question carries it as a link naming its machine. + // The agent reads threads on its own server and the machines it links to; any other + // machine's comes in as its transcript, as a dropped one does. + if ( + record.environmentId !== environmentId && + !linkedEnvironments.has(record.environmentId) + ) { + importThreadTranscript({ + environmentId: record.environmentId, + threadId: record.threadId, + }); + rewritten.set(record.contextId, null); + break; + } addComposerDraftThreadContexts(threadDraftTarget, [record], { appendReference: false, }); @@ -434,7 +447,7 @@ export function useComposerContextImport(input: { }; const importContextFragment = ( fragment: ComposerContextClipboardFragment, - ): ReadonlyMap => + ): ReadonlyMap => importContextRecords(fragment.records, fragment.source.environmentId); return { @@ -443,6 +456,5 @@ export function useComposerContextImport(input: { countReservedAttachmentsStable, importContextRecords, importContextFragment, - importingContextIdsRef, }; } diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index 1d480dcf150e1..889d77c8d17c3 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -95,7 +95,7 @@ export function useComposerStash(input: { records: ReadonlyArray, sourceEnvironmentId: EnvironmentId | null, threadDraftTarget?: ChatComposerProps["composerDraftTarget"], - ) => ReadonlyMap; + ) => ReadonlyMap; readonly expandMobileComposer: () => void; }) { const { @@ -206,9 +206,10 @@ export function useComposerStash(input: { const rewrittenContextIds = entry.records ? importContextRecords(entry.records, null, composerDraftTarget) - : new Map(); + : new Map(); const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { const contextId = rewrittenContextIds.get(reference.contextId); + if (contextId === null) return reference.label; return contextId ? formatInlineContextReference({ ...reference, diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index daded97b11bde..55b06e8056f13 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -47,6 +47,14 @@ describe("importPastedComposerText", () => { ).toBe("Read this: Source Thread Ready and continue."); }); + it("keeps context references inside pasted code as written", () => { + const reference = formatComposerContextReference(sourceThread); + const code = `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and ${reference}`; + expect(importPastedComposerText(clipboard({ "text/plain": code }), importNothing)).toBe( + `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and Source Thread Ready`, + ); + }); + it("keeps a context reference whose record the draft already holds", () => { expect( importPastedComposerText( diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index ac1a6f0dad2b9..d9f3b701e0910 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -10,6 +10,24 @@ import { formatComposerContextReference, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; + +// Fences, then code spans, as threadLinks reads them: a reference inside one is literal text. +const MARKDOWN_CODE = /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`+)[^\n]*?\2/g; + +/** 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) => { + ranges ??= Array.from(text.matchAll(MARKDOWN_CODE), (match) => [ + match.index, + match.index + match[0].length, + ]); + while (next < ranges.length && ranges[next]![1] <= offset) next += 1; + return next < ranges.length && ranges[next]![0] <= offset; + }; +} + export function readPastedComposerContext( clipboardData: Pick, ): ComposerContextClipboardFragment | null { @@ -18,8 +36,11 @@ export function readPastedComposerContext( decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ?? decodeComposerContextClipboardHtml(clipboardData.getData("text/html")); if (decodedFragment === null) return null; + const inCode = codeOffsetTest(pastedText); const pastedIds = new Set( - collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId), + collectComposerContextReferences(pastedText) + .filter((occurrence) => !inCode(occurrence.start)) + .map((occurrence) => occurrence.contextId), ); for (const record of decodedFragment.records) { if ( @@ -37,19 +58,24 @@ export function readPastedComposerContext( }; } -/** References with no record behind them, in the paste or the draft, paste as their label. */ +/** + * 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 = clipboardData.getData("text/plain"); const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null; const rewrittenIds = fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null; + const inCode = codeOffsetTest(pastedText); return replaceComposerContextReferences(pastedText, (occurrence) => { + if (inCode(occurrence.start)) return occurrence.source; const nextId = rewrittenIds?.get(occurrence.contextId); if (nextId) { return formatComposerContextReference({ @@ -58,6 +84,8 @@ export function importPastedComposerText( kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, }); } - return heldContextIds.has(occurrence.contextId) ? occurrence.source : occurrence.label; + return nextId !== null && heldContextIds.has(occurrence.contextId) + ? occurrence.source + : occurrence.label; }); } diff --git a/docs/user/composer.md b/docs/user/composer.md index a3e06c9aed6f7..9f6819c1f9df3 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -303,9 +303,9 @@ 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. 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. 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. From a7ef64cc89da6f10b13dd15c0192a6bcfc9f32f6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 05:28:13 +0000 Subject: [PATCH 05/13] fix(web): transcript import failure toast no longer says dropped Pasted and stash-restored threads reach the same toast as dropped ones. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8672aaf4ab738..7eb73c6e28868 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2686,7 +2686,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" From 38a48ea48904b3da8392a2ee4469c5ebad859916 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 05:39:53 +0000 Subject: [PATCH 06/13] fix(web): restored thread transcripts land in the restored draft; paste code detection follows composer rules A stash restored while a question was open put the unlinked thread's transcript on the question answer. The transcript import now takes the draft it belongs to, attaching through the editor when that draft is shown and through the draft store otherwise. Pasted-code detection used a backreferencing regex that closed fences mid-line and read escaped backticks as code spans. It now uses the composer's own fence rules and a linear per-line code-span scan. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 49 ++++++++++--- .../useComposerContextImport.browser.test.tsx | 34 ++++++++- .../chat/useComposerContextImport.ts | 15 ++-- .../composerInlineTokenPaste.test.ts | 24 ++++++- .../components/composerInlineTokenPaste.ts | 70 +++++++++++++++++-- 5 files changed, 168 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 7eb73c6e28868..8bc1e73db62c7 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -57,7 +57,6 @@ import { memo, use, useEffect, - useEffectEvent, useId, useImperativeHandle, useLayoutEffect, @@ -1394,9 +1393,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, - importThreadTranscript: (ref) => { - const targetKey = attachmentTargetKey; - void importDroppedThread(ref, () => attachmentTargetKeyRef.current === targetKey); + importThreadTranscript: (ref, draftTarget) => { + const targetKey = composerTargetKey(draftTarget); + void importThreadTranscript( + ref, + draftTarget, + () => + attachmentTargetKeyRef.current === targetKey || + composerDraftTargetKeyRef.current === targetKey, + ); }, }); @@ -2644,10 +2649,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", @@ -2671,7 +2699,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( @@ -2704,8 +2732,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 []; diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index fa231f6936917..56272d4091945 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -269,6 +269,38 @@ it("imports a pasted thread from a machine this one does not link to as its tran ); }); expect(pasted).toBe("See Remote thread"); - expect(importThreadTranscript).toHaveBeenCalledWith(ref); + expect(importThreadTranscript).toHaveBeenCalledWith(ref, target); expect(store.getComposerDraft(target)?.threadContexts ?? []).toEqual([]); }); + +// 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); +}); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 40e336e2483a4..9f90b7753c66c 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -92,8 +92,11 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; - /** Attaches a thread's transcript, as dropping it does. */ - readonly importThreadTranscript: (ref: ScopedThreadRef) => void; + /** Attaches a thread's transcript to a draft, as dropping it does. */ + readonly importThreadTranscript: ( + ref: ScopedThreadRef, + draftTarget: ChatComposerProps["composerDraftTarget"], + ) => void; }) { const { environmentId, @@ -403,10 +406,10 @@ export function useComposerContextImport(input: { record.environmentId !== environmentId && !linkedEnvironments.has(record.environmentId) ) { - importThreadTranscript({ - environmentId: record.environmentId, - threadId: record.threadId, - }); + importThreadTranscript( + { environmentId: record.environmentId, threadId: record.threadId }, + threadDraftTarget, + ); rewritten.set(record.contextId, null); break; } diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index 55b06e8056f13..cdc5e867fd468 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, encodeComposerContextFragment, @@ -55,6 +55,28 @@ describe("importPastedComposerText", () => { ); }); + it("keeps a reference in a fence whose body holds a fence marker mid-line", () => { + const reference = formatComposerContextReference(sourceThread); + const code = `\`\`\`js\nconsole.log("\`\`\`");\n${reference}\n\`\`\``; + expect(importPastedComposerText(clipboard({ "text/plain": code }), importNothing)).toBe(code); + }); + + it("imports a reference between escaped backticks", () => { + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: sourceThread.environmentId }, + records: [sourceThread], + }); + const localId = ComposerContextId.make("thread-local"); + const text = `\\\`${formatComposerContextReference(sourceThread)}\\\``; + expect( + importPastedComposerText( + clipboard({ "text/plain": text, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "" }), + () => new Map([[sourceThread.contextId, localId]]), + ), + ).toBe(`\\\`${formatComposerContextReference({ ...sourceThread, contextId: localId })}\\\``); + }); + it("keeps a context reference whose record the draft already holds", () => { expect( importPastedComposerText( diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index d9f3b701e0910..9920c8f1e66c4 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -10,19 +10,77 @@ import { formatComposerContextReference, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { isClosingFence, parseOpeningFence } from "~/composer-rich-text-doc"; -// Fences, then code spans, as threadLinks reads them: a reference inside one is literal text. -const MARKDOWN_CODE = /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`+)[^\n]*?\2/g; +/** + * 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) => { - ranges ??= Array.from(text.matchAll(MARKDOWN_CODE), (match) => [ - match.index, - match.index + match[0].length, - ]); + ranges ??= markdownCodeRanges(text); while (next < ranges.length && ranges[next]![1] <= offset) next += 1; return next < ranges.length && ranges[next]![0] <= offset; }; From 809724eb7a456cf8c1a4e46dd285d2725d6acdfa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 05:52:08 +0000 Subject: [PATCH 07/13] fix(web): backticks in a pasted reference's label no longer read as code; restored transcripts check the restored draft's limit Code detection on paste ran over the reference text too, so a thread titled "Fix `foo` bug" could open an inline code span and leave its chip unresolved. References are masked to spaces before code ranges are computed; code that contains a whole reference still counts as code. A transcript restored into the draft behind an open question checked the question's attachment count. countReservedAttachments now takes the draft target and the transcript import counts the draft it is for. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 2 +- .../useComposerContextImport.browser.test.tsx | 37 +++++++++++++++++++ .../chat/useComposerContextImport.ts | 15 +++++--- .../composerInlineTokenPaste.test.ts | 24 ++++++++++++ .../components/composerInlineTokenPaste.ts | 5 ++- 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8bc1e73db62c7..2e609455ea64b 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2687,7 +2687,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, diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index 56272d4091945..9f3fe8a856eba 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -3,6 +3,7 @@ import { type ComposerContextRecord, ComposerContextId, EnvironmentId, + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, ThreadId, } from "@t3tools/contracts"; import { @@ -304,3 +305,39 @@ it("imports a restored thread's transcript into the draft the restore names", as 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); +}); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 9f90b7753c66c..c52c2c9d65d36 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -20,6 +20,7 @@ import { type DraftId, composerFileMatchesReattachMarker, composerFileNeedsReattach, + composerTargetKey, useComposerDraftStore, } from "../../composerDraftStore"; import { type PendingUserInput } from "../../session-logic"; @@ -134,10 +135,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( @@ -149,12 +154,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) ); }; diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index cdc5e867fd468..2e64d8b00254c 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -77,6 +77,30 @@ describe("importPastedComposerText", () => { ).toBe(`\\\`${formatComposerContextReference({ ...sourceThread, contextId: localId })}\\\``); }); + it("imports a reference whose label holds backticks", () => { + const thread = threadContextRecord( + { environmentId: sourceThread.environmentId, threadId: ThreadId.make("thread-code") }, + "Fix `foo` bug", + ); + const fragment = encodeComposerContextFragment({ + version: 1, + source: { environmentId: thread.environmentId }, + records: [thread], + }); + const localId = ComposerContextId.make("thread-local"); + expect( + importPastedComposerText( + clipboard({ + "text/plain": `Quote with \`, see ${formatComposerContextReference(thread)}`, + [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "", + }), + (pasted) => new Map(pasted.records.map((record) => [record.contextId, localId])), + ), + ).toBe( + `Quote with \`, see ${formatComposerContextReference({ ...thread, contextId: localId })}`, + ); + }); + it("keeps a context reference whose record the draft already holds", () => { expect( importPastedComposerText( diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 9920c8f1e66c4..6ee3433fcca99 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -80,7 +80,10 @@ function codeOffsetTest(text: string): (offset: number) => boolean { let ranges: Array | null = null; let next = 0; return (offset) => { - ranges ??= markdownCodeRanges(text); + // 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; }; From ef88e9033d7c8d568fdb853ef37216ab6c1230a3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 3 Nov 2026 05:58:02 +0000 Subject: [PATCH 08/13] fix(web): pasted duplicates keep their chip when the draft holds them under an alias A pasted record that matches a draft record found under its kind-scoped id was skipped without a rewrite, so the paste turned its reference into a label. Co-Authored-By: Claude Opus 5.5 --- .../useComposerContextImport.browser.test.tsx | 22 +++++++++++++++++++ .../chat/useComposerContextImport.ts | 17 +++++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index 9f3fe8a856eba..77298f54bf695 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -274,6 +274,28 @@ it("imports a pasted thread from a machine this one does not link to as its tran 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 = threadContextRecord( + { environmentId: EnvironmentId.make("clipboard-target"), threadId: ThreadId.make("alias") }, + "Alias thread", + ); + 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"); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index c52c2c9d65d36..19769b51bea6a 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -322,12 +322,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 && @@ -336,8 +337,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) @@ -364,6 +367,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; From 94d52af58b28438f023207a8f80e3c1a454088ad Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:47:18 +0000 Subject: [PATCH 09/13] fix(web): pasted threads from machines this client is not connected to stay links A pasted link to a thread on an unknown machine would start a transcript load that cannot succeed and show an error toast. Only connected machines send their transcript now; a link to any other stays a link, as it did before. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 --- .../useComposerContextImport.browser.test.tsx | 92 ++++++++++--------- .../chat/useComposerContextImport.ts | 3 +- 2 files changed, 52 insertions(+), 43 deletions(-) diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index 77298f54bf695..3306f83dddc8f 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -32,7 +32,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]; @@ -231,48 +232,55 @@ it.each([ }); // Its chip used to resolve to nothing, or block the send; a dropped one comes in as its transcript. -it("imports a pasted thread from a machine this one does not link to as its transcript", async () => { - const target = DraftId.make("clipboard-unlinked-thread"); - const store = useComposerDraftStore.getState(); - using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; - const ref = { - environmentId: EnvironmentId.make("unlinked-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, +it.each([ + { machine: "unlinked-machine", transcript: true }, + // Nothing can load a machine this client is not connected to, so the chip is only its label. + { 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; + }} + />, ); - }); - expect(pasted).toBe("See Remote thread"); - expect(importThreadTranscript).toHaveBeenCalledWith(ref, target); - expect(store.getComposerDraft(target)?.threadContexts ?? []).toEqual([]); -}); + 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"); + 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"); diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 19769b51bea6a..e2b6910333209 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -411,11 +411,12 @@ export function useComposerContextImport(input: { } case "thread": { // The agent reads threads on its own server and the machines it links to; any other - // machine's comes in as its transcript, as a dropped one does. + // 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)) break; importThreadTranscript( { environmentId: record.environmentId, threadId: record.threadId }, threadDraftTarget, From 7ce31b680be95d2c23ea4d9821f53be1f94d36a5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:57:59 +0000 Subject: [PATCH 10/13] fix(web): pasted threads the agent cannot read keep a link to their machine A pasted or restored chip for a thread on an unlinked machine became its bare label, so a failed transcript import left the agent nothing to find the thread by. It now becomes a link that names the thread and its environment, while the transcript import still runs. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 --- .../useComposerContextImport.browser.test.tsx | 8 ++++--- .../chat/useComposerContextImport.ts | 13 ++++++----- .../src/components/chat/useComposerStash.ts | 3 ++- .../components/composerInlineTokenPaste.ts | 22 +++++++++++++++---- docs/user/composer.md | 2 +- 5 files changed, 33 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index 3306f83dddc8f..66f192c41927c 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -11,10 +11,12 @@ import { encodeComposerContextFragment, } from "@t3tools/shared/composerContextClipboard"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +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 { threadContextReference } from "../../lib/composerContextRecords"; import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments"; @@ -231,10 +233,10 @@ it.each([ ); }); -// Its chip used to resolve to nothing, or block the send; a dropped one comes in as its transcript. +// 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 the chip is only its label. + // 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", @@ -276,7 +278,7 @@ it.each([ importer.importContextFragment, ); }); - expect(pasted).toBe("See Remote thread"); + expect(pasted).toBe(`See [Remote thread](${hostedThreadLink(ref, configuredHostedAppUrl())})`); expect(importThreadTranscript.mock.calls).toEqual(transcript ? [[ref, target]] : []); expect(store.getComposerDraft(target)?.threadContexts ?? []).toEqual([]); }, diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index e2b6910333209..f7476ee3c1d17 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -302,7 +302,7 @@ export function useComposerContextImport(input: { sourceEnvironmentId: EnvironmentId | null, threadDraftTarget = attachmentDraftTarget, ): ReadonlyMap => { - // A null id means the reference becomes its plain label. + // 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(); @@ -416,11 +416,12 @@ export function useComposerContextImport(input: { record.environmentId !== environmentId && !linkedEnvironments.has(record.environmentId) ) { - if (!readPreparedConnection(record.environmentId)) break; - importThreadTranscript( - { environmentId: record.environmentId, threadId: record.threadId }, - threadDraftTarget, - ); + if (readPreparedConnection(record.environmentId)) { + importThreadTranscript( + { environmentId: record.environmentId, threadId: record.threadId }, + threadDraftTarget, + ); + } rewritten.set(record.contextId, null); break; } diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts index 889d77c8d17c3..08dce33556bdc 100644 --- a/apps/web/src/components/chat/useComposerStash.ts +++ b/apps/web/src/components/chat/useComposerStash.ts @@ -32,6 +32,7 @@ import { compressImageForStash } from "../../lib/imageCompression"; import { formatInlineContextReference } from "~/lib/composerContextReferences"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { pendingDraftWork } from "./pendingDraftWork"; +import { unreadableThreadLink } from "../composerInlineTokenPaste"; import { previewAnnotationContextRecord, reviewCommentContextRecord, @@ -209,7 +210,7 @@ export function useComposerStash(input: { : new Map(); const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { const contextId = rewrittenContextIds.get(reference.contextId); - if (contextId === null) return reference.label; + if (contextId === null) return unreadableThreadLink(entry.records ?? [], reference); return contextId ? formatInlineContextReference({ ...reference, diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 1ab70fde8bf10..6b082d08654c4 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -13,9 +13,12 @@ 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; @@ -97,6 +100,17 @@ function codeOffsetTest(text: string): (offset: number) => boolean { }; } +/** 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})`; +} + /** Pasted thread links count as context too, so they become chips like a copied chip does. */ export function readPastedComposerContext( clipboardData: Pick, @@ -169,10 +183,10 @@ export function importPastedComposerText( kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind, }); } - return rewrittenIds?.get(occurrence.contextId) !== null && - heldContextIds.has(occurrence.contextId) - ? occurrence.source - : occurrence.label; + 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 c3f7ae974ccef..3ec4ec9d1dcde 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -349,7 +349,7 @@ thread does not change it, and the agent cannot send messages to it unless you a A thread from a linked machine, picked, pasted or dropped, stays a reference that the agent reads on that machine. Pasting or dropping a thread from any other environment attaches a saved -transcript file, and a pasted link to it stays a link. The source +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 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 From 00fd41bb38d98e346abc9e0aa987c920f738e940 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 03:01:59 +0000 Subject: [PATCH 11/13] test(web): fold pasted-reference cases into one table The label, held-id and code-range cases share one shape, so they are rows of one table. Main's thread identity test reuses the shared import input. Co-Authored-By: Claude Opus 5.5 --- .../useComposerContextImport.browser.test.tsx | 15 +- .../composerInlineTokenPaste.test.ts | 137 ++++++++---------- 2 files changed, 61 insertions(+), 91 deletions(-) diff --git a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx index 02390fc946f68..29ae82a486762 100644 --- a/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx +++ b/apps/web/src/components/chat/useComposerContextImport.browser.test.tsx @@ -410,23 +410,10 @@ it.each(["same", "other-environment"] as const)( await using _screen = await render( [], - importThreadTranscript: () => {}, }} ready={(value) => { importer = value; diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index 3cd6a95a54439..038c9ff53bb83 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -48,88 +48,71 @@ const importAll = }; describe("importPastedComposerText", () => { - it("turns a context reference without a fragment into its plain label", () => { - expect(importPastedComposerText(clipboard({ "text/plain": pastedText }), importNothing)).toBe( - "Read this: Source Thread Ready and continue.", - ); - }); - - it("turns a context reference whose record the import dropped into its plain label", () => { - const fragment = encodeComposerContextFragment({ - version: 1, - source: { environmentId: sourceThread.environmentId }, + 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], - }); - expect( - importPastedComposerText( - clipboard({ "text/plain": pastedText, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "" }), - importNothing, - ), - ).toBe("Read this: Source Thread Ready and continue."); - }); - - it("keeps context references inside pasted code as written", () => { - const reference = formatComposerContextReference(sourceThread); - const code = `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and ${reference}`; - expect(importPastedComposerText(clipboard({ "text/plain": code }), importNothing)).toBe( - `\`\`\`md\n${reference}\n\`\`\`\nInline \`${reference}\` and Source Thread Ready`, - ); - }); - - it("keeps a reference in a fence whose body holds a fence marker mid-line", () => { - const reference = formatComposerContextReference(sourceThread); - const code = `\`\`\`js\nconsole.log("\`\`\`");\n${reference}\n\`\`\``; - expect(importPastedComposerText(clipboard({ "text/plain": code }), importNothing)).toBe(code); - }); - - it("imports a reference between escaped backticks", () => { - const fragment = encodeComposerContextFragment({ - version: 1, - source: { environmentId: sourceThread.environmentId }, + 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], - }); - const localId = ComposerContextId.make("thread-local"); - const text = `\\\`${formatComposerContextReference(sourceThread)}\\\``; - expect( - importPastedComposerText( - clipboard({ "text/plain": text, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "" }), - () => new Map([[sourceThread.contextId, localId]]), - ), - ).toBe(`\\\`${formatComposerContextReference({ ...sourceThread, contextId: localId })}\\\``); - }); - - it("imports a reference whose label holds backticks", () => { - const thread = threadContextRecord( - { environmentId: sourceThread.environmentId, threadId: ThreadId.make("thread-code") }, - "Fix `foo` bug", - ); - const fragment = encodeComposerContextFragment({ - version: 1, - source: { environmentId: thread.environmentId }, - records: [thread], - }); - const localId = ComposerContextId.make("thread-local"); - expect( - importPastedComposerText( - clipboard({ - "text/plain": `Quote with \`, see ${formatComposerContextReference(thread)}`, - [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment ?? "", - }), - (pasted) => new Map(pasted.records.map((record) => [record.contextId, localId])), - ), - ).toBe( - `Quote with \`, see ${formatComposerContextReference({ ...thread, contextId: localId })}`, - ); - }); - - it("keeps a context reference whose record the draft already holds", () => { + importContext: importAsLocal, + expected: `\\\`${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": pastedText }), - importNothing, - new Set([sourceThread.contextId]), + clipboard({ "text/plain": text, [COMPOSER_CONTEXT_CLIPBOARD_MIME]: fragment }), + importContext, + new Set(held), ), - ).toBe(pastedText); + ).toBe(expected); }); it("pastes a copied thread link back as the chip it was copied from", () => { From f8f3e26ec2da30da587db651bc5316f201e14dd2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 03:07:21 +0000 Subject: [PATCH 12/13] fix(web): CR-only pastes keep their thread records readPastedComposerContext scanned the raw clipboard text for code while the rewrite used the LF-normalized text, so a CR-only fence swallowed the rest of the paste and its records were dropped. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/composerInlineTokenPaste.test.ts | 7 +++++++ apps/web/src/components/composerInlineTokenPaste.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index 038c9ff53bb83..e71bc63b397ad 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -91,6 +91,13 @@ describe("importPastedComposerText", () => { 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)}`, diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index ecb4cd77b0eea..b087ca3dccf80 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -120,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")); From e430470d873b0a6c1c8132df6ff0ab799b89fed0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 17 Nov 2026 03:27:11 +0000 Subject: [PATCH 13/13] fix(mobile): pasted threads from unlinked machines stay links The native importer dropped an unlinked thread's record but kept its t3-context reference, so the agent read it as unavailable. The reference now becomes a hosted link naming the thread and its machine, as on web. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/components/ComposerEditor.tsx | 10 +++------- .../src/lib/composerContextClipboard.test.ts | 19 ++++++++----------- .../src/lib/composerContextClipboard.ts | 13 ++++++++++--- 3 files changed, 21 insertions(+), 21 deletions(-) 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,