Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix file drops in new project chats (#14472)
Lee Jacksonf9329a7de2a0
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex cb94fdcc330..f8b3f183d44 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -222,9 +222,11 @@ import {NativeAttachmentDragContext,type NativeIntent,useNativeAttachmentTargetKey,+ useNativeAttachmentOwnerScope,useNativeIntentStore,} from "@/features/native-intents";import { nativeAttachmentIntentToFile } from "@/features/native-intents/native-attachment-file";+import { wasAttachmentAddCancelled } from "@/features/chat/draft-attachment-adapter";import {attachLibraryChatFiles,useLibraryChatHandoffStore,@@ -3169,6 +3171,7 @@ const Composer: FC<{event,async (file) => {await aui.composer().addAttachment(file);+ if (wasAttachmentAddCancelled(file)) return;dropReplacedSelection();},() =>@@ -3354,7 +3357,11 @@ const Composer: FC<{const hasPendingAudio = useChatRuntimeStore((s) =>Boolean(s.pendingAudioName),);+ const threadListItemId = useAuiState(+ ({ threadListItem }) => threadListItem.id,+ );const nativeAttachmentTargetKey = useNativeAttachmentTargetKey();+ const nativeAttachmentOwnerScope = useNativeAttachmentOwnerScope();const nativeAttachmentTargetKeyRef = useRef(nativeAttachmentTargetKey);nativeAttachmentTargetKeyRef.current = nativeAttachmentTargetKey;@@ -3368,6 +3375,10 @@ const Composer: FC<{throw new Error("The chat changed before this file was attached.");}await aui.composer().addAttachment(file);+ // The draft-scoped adapter resolves a cancelled add; throwing keeps the file held.+ if (wasAttachmentAddCancelled(file)) {+ throw new Error("The chat changed before this file was attached.");+ }};const drain = async () => {const held = await attachLibraryChatFiles(targetKey, add);@@ -3457,6 +3468,11 @@ const Composer: FC<{// A parked send must not fire on a failed drop. Assigned below once the callback exists.const cancelQueuedSendRef = useRef<(() => void) | null>(null);const composerIdentityRef = useRef("");+ const nativeAttachmentOwner = nativeAttachmentOwnerScope+ ? JSON.stringify([nativeAttachmentOwnerScope, threadListItemId ?? ""])+ : threadListItemId ?? "";+ const nativeAttachmentOwnerRef = useRef(nativeAttachmentOwner);+ nativeAttachmentOwnerRef.current = nativeAttachmentOwner;const imageDropFailures = useNativeIntentStore((s) => (nativeAttachmentTargetKey ? s.imageDropFailures[nativeAttachmentTargetKey] : 0) ?? 0,);@@ -3489,20 +3505,22 @@ const Composer: FC<{}, [videoDropFailures]);// Hold the send gate while the dropped clip is registered and read.useEffect(() => {- if (!nativeAttachmentTargetKey) {+ // aui.composer() is still the previous chat until the runtime reaches this route's thread.+ if (!nativeAttachmentTargetKey || disabled) {return;}const targetKey = nativeAttachmentTargetKey;- const identityAtSetup = composerIdentityRef.current;+ const identityAtSetup = nativeAttachmentOwnerRef.current;useNativeIntentStore.getState().claimAudioAttachments(identityAtSetup, targetKey);let disposed = false;let draining = false;+ const cancelledOnce = new Set<string>();// A re-key follows the same composer; a thread switch parks the clip back.const stillThisComposer = () =>- composerIdentityRef.current === identityAtSetup;+ nativeAttachmentOwnerRef.current === identityAtSetup;// A remount hides the new key, so tag the batch; the next instance claims it.const requeue = (intents: NativeIntent[]) => {const key = stillThisComposer()@@ -3549,6 +3567,20 @@ const Composer: FC<{}try {await aui.composer().addAttachment(file);+ if (wasAttachmentAddCancelled(file)) {+ // Same owner and key means the destination refused it: retry once, never spin.+ const sameDestination =+ stillThisComposer() &&+ nativeAttachmentTargetKeyRef.current === targetKey;+ if (!sameDestination || !cancelledOnce.has(intent.id)) {+ if (sameDestination) cancelledOnce.add(intent.id);+ requeue(intents.slice(index));+ return;+ }+ cancelledOnce.delete(intent.id);+ cancelQueuedSendRef.current?.();+ continue;+ }} catch {// The adapter toasted. Keep going: a later, smaller clip may still fit.if (stillThisComposer()) cancelQueuedSendRef.current?.();@@ -3596,23 +3628,24 @@ const Composer: FC<{setMaterializingDroppedAudio(false);unsubscribe();};- }, [nativeAttachmentTargetKey, aui]);+ }, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);// Same drain as audio: one clip per message, and the send gate holds across the read.useEffect(() => {- if (!nativeAttachmentTargetKey) {+ if (!nativeAttachmentTargetKey || disabled) {return;}const targetKey = nativeAttachmentTargetKey;- const identityAtSetup = composerIdentityRef.current;+ const identityAtSetup = nativeAttachmentOwnerRef.current;useNativeIntentStore.getState().claimVideoAttachments(identityAtSetup, targetKey);let disposed = false;let draining = false;+ const cancelledOnce = new Set<string>();const stillThisComposer = () =>- composerIdentityRef.current === identityAtSetup;+ nativeAttachmentOwnerRef.current === identityAtSetup;const requeue = (intents: NativeIntent[]) => {const key = stillThisComposer()? (nativeAttachmentTargetKeyRef.current ?? targetKey)@@ -3657,6 +3690,20 @@ const Composer: FC<{}try {await aui.composer().addAttachment(file);+ if (wasAttachmentAddCancelled(file)) {+ // Same owner and key means the destination refused it: retry once, never spin.+ const sameDestination =+ stillThisComposer() &&+ nativeAttachmentTargetKeyRef.current === targetKey;+ if (!sameDestination || !cancelledOnce.has(intent.id)) {+ if (sameDestination) cancelledOnce.add(intent.id);+ requeue(intents.slice(index));+ return;+ }+ cancelledOnce.delete(intent.id);+ cancelQueuedSendRef.current?.();+ continue;+ }} catch {// Chat-wide failure and the adapter already toasted: stop quietly.if (stillThisComposer()) cancelQueuedSendRef.current?.();@@ -3700,23 +3747,24 @@ const Composer: FC<{setMaterializingDroppedVideo(false);unsubscribe();};- }, [nativeAttachmentTargetKey, aui]);+ }, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);useEffect(() => {- if (!nativeAttachmentTargetKey) {+ if (!nativeAttachmentTargetKey || disabled) {return;}const targetKey = nativeAttachmentTargetKey;- const identityAtSetup = composerIdentityRef.current;+ const identityAtSetup = nativeAttachmentOwnerRef.current;useNativeIntentStore.getState().claimImageAttachments(identityAtSetup, targetKey);let disposed = false;let draining = false;+ const cancelledOnce = new Set<string>();// A fresh chat re-keys from "single:new" to its thread id under the same composer, so follow it.const stillThisComposer = () =>- composerIdentityRef.current === identityAtSetup;+ nativeAttachmentOwnerRef.current === identityAtSetup;const requeueKey = () =>stillThisComposer()? (nativeAttachmentTargetKeyRef.current ?? targetKey)@@ -3772,6 +3820,20 @@ const Composer: FC<{}try {await aui.composer().addAttachment(file);+ if (wasAttachmentAddCancelled(file)) {+ // Same owner and key means the destination refused it: retry once, never spin.+ const sameDestination =+ stillThisComposer() &&+ nativeAttachmentTargetKeyRef.current === targetKey;+ if (!sameDestination || !cancelledOnce.has(intent.id)) {+ if (sameDestination) cancelledOnce.add(intent.id);+ requeue(intents.slice(index));+ return;+ }+ cancelledOnce.delete(intent.id);+ cancelQueuedSendRef.current?.();+ continue;+ }} catch {// Chat-wide failure and the adapter already toasted: stop quietly.if (stillThisComposer()) cancelQueuedSendRef.current?.();@@ -3796,7 +3858,7 @@ const Composer: FC<{const pending =useNativeIntentStore.getState().pendingImageAttachments[targetKey]?.length ?? 0;- if (pending > 0) {+ if (pending > 0 && stillThisComposer()) {void drainPendingImages();} else {setMaterializingDroppedImages(false);@@ -3829,21 +3891,22 @@ const Composer: FC<{setMaterializingDroppedImages(false);unsubscribe();};- }, [nativeAttachmentTargetKey, aui]);+ }, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);useEffect(() => {- if (!nativeAttachmentTargetKey) {+ if (!nativeAttachmentTargetKey || disabled) {return;}const targetKey = nativeAttachmentTargetKey;- const identityAtSetup = composerIdentityRef.current;+ const identityAtSetup = nativeAttachmentOwnerRef.current;useNativeIntentStore.getState().claimImageAttachments(identityAtSetup, targetKey);let disposed = false;let draining = false;+ const cancelledOnce = new Set<string>();const stillThisComposer = () =>- composerIdentityRef.current === identityAtSetup;+ nativeAttachmentOwnerRef.current === identityAtSetup;const requeue = (intents: NativeIntent[]) => {const key = stillThisComposer()? (nativeAttachmentTargetKeyRef.current ?? targetKey)@@ -3888,6 +3951,20 @@ const Composer: FC<{}try {await aui.composer().addAttachment(file);+ if (wasAttachmentAddCancelled(file)) {+ // Same owner and key means the destination refused it: retry once, never spin.+ const sameDestination =+ stillThisComposer() &&+ nativeAttachmentTargetKeyRef.current === targetKey;+ if (!sameDestination || !cancelledOnce.has(intent.id)) {+ if (sameDestination) cancelledOnce.add(intent.id);+ requeue(intents.slice(index));+ return;+ }+ cancelledOnce.delete(intent.id);+ cancelQueuedSendRef.current?.();+ continue;+ }} catch {if (stillThisComposer()) cancelQueuedSendRef.current?.();}@@ -3932,7 +4009,7 @@ const Composer: FC<{setMaterializingDroppedOpenDocuments(false);unsubscribe();};- }, [nativeAttachmentTargetKey, aui]);+ }, [nativeAttachmentTargetKey, nativeAttachmentOwner, aui, disabled]);const hasMaterializingImageAttachments =registeringImageDrops ||hasPendingImageAttachments ||@@ -3948,9 +4025,6 @@ const Composer: FC<{hasPendingVideoAttachments ||materializingDroppedVideo;const threadIsRunning = useAuiState(({ thread }) => thread.isRunning);- const threadListItemId = useAuiState(- ({ threadListItem }) => threadListItem.id,- );const threadListItemRemoteId = useAuiState(({ threadListItem }) => threadListItem.remoteId,);diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 241f5dda15c..03cfdf96e94 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -78,6 +78,7 @@ import {type NativeIntent,NativeAttachmentTargetContext,NativeAttachmentDragContext,+ NativeAttachmentOwnerScopeContext,NativeModelChip,NativeModelDropOverlay,useNativeIntentStore,@@ -3504,6 +3505,7 @@ export function ChatPage({useEffect(() => {setProjectBrowserBaseline(projectViewId ? useBrowserStore.getState().openSequence : null);}, [projectViewId]);+ const nativeAttachmentScopesByThread = useRef(new Map<string, string>());const artifactViewKey =view.mode === "single"? `single:${view.threadId ?? view.newThreadNonce ?? "new"}`@@ -3511,10 +3513,18 @@ export function ChatPage({? `compare:${view.pairId}`: `project:${view.projectId}`;+ // Per draft: a project reuses its route for successive drafts. A saved project chat keeps it on its thread route.+ const nativeAttachmentTargetKey =+ view.mode === "project"+ ? `project:${view.projectId}:${projectNewThreadNonce}`+ : view.mode === "single" && view.threadId+ ? nativeAttachmentScopesByThread.current.get(view.threadId) ?? artifactViewKey+ : artifactViewKey;+const attachmentScope =view.mode === "single" && !search.thread && !search.new && !search.project? "single:implicit"- : artifactViewKey;+ : nativeAttachmentTargetKey;// Kept mounted behind compare: unmounting detaches the runtime and the backend cancels the run.const keptBaseViewRef = useRef<{@@ -3522,11 +3532,14 @@ export function ChatPage({attachmentTargetKey: string;} | null>(null);if (view.mode !== "compare") {- keptBaseViewRef.current = { view, attachmentTargetKey: artifactViewKey };+ keptBaseViewRef.current = {+ view,+ attachmentTargetKey: nativeAttachmentTargetKey,+ };}const baseView = keptBaseViewRef.current?.view ?? null;const baseAttachmentTargetKey =- keptBaseViewRef.current?.attachmentTargetKey ?? artifactViewKey;+ keptBaseViewRef.current?.attachmentTargetKey ?? nativeAttachmentTargetKey;const baseBackgrounded = view.mode === "compare";// Keyed by project, not a boolean: the hoisted provider is not remounted on project change.@@ -3577,6 +3590,19 @@ export function ChatPage({projectChat.nonce === projectNewThreadNonce? projectChat.threadId: null;+ // Remembered per saved chat, so a revisit after another project cannot adopt that project's files.+ if (projectChatShownId) {+ nativeAttachmentScopesByThread.current.set(+ projectChatShownId,+ nativeAttachmentTargetKey,+ );+ }+ const baseAttachmentOwnerScope =+ baseView?.mode === "project"+ ? baseAttachmentTargetKey+ : nativeAttachmentScopesByThread.current.get(+ baseView?.mode === "single" ? baseView.threadId ?? "" : "",+ ) ?? null;const shownChatKey =view.mode === "single"? `single:${view.threadId ?? newChatShownId ?? activeThreadId ?? view.newThreadNonce ?? "new"}`@@ -3834,39 +3860,45 @@ export function ChatPage({);const handleNativeImageDrop = useCallback((intents: NativeIntent[]) => {- useNativeIntentStore.getState().addImageAttachments(artifactViewKey, intents);+ useNativeIntentStore+ .getState()+ .addImageAttachments(nativeAttachmentTargetKey, intents);},- [artifactViewKey],+ [nativeAttachmentTargetKey],);const handleNativeDocumentDrop = useCallback((intents: NativeIntent[]) => {useNativeIntentStore.getState()- .addOpenDocumentAttachments(artifactViewKey, intents);+ .addOpenDocumentAttachments(nativeAttachmentTargetKey, intents);},- [artifactViewKey],+ [nativeAttachmentTargetKey],);const handleNativeAudioDrop = useCallback((intents: NativeIntent[]) => {- useNativeIntentStore.getState().addAudioAttachments(artifactViewKey, intents);+ useNativeIntentStore+ .getState()+ .addAudioAttachments(nativeAttachmentTargetKey, intents);},- [artifactViewKey],+ [nativeAttachmentTargetKey],);const handleNativeVideoDrop = useCallback((intents: NativeIntent[]) => {- useNativeIntentStore.getState().addVideoAttachments(artifactViewKey, intents);+ useNativeIntentStore+ .getState()+ .addVideoAttachments(nativeAttachmentTargetKey, intents);},- [artifactViewKey],+ [nativeAttachmentTargetKey],);const nativeModelDropState = useNativeModelDrop({// Stay enabled in compare and refuse drops out loud; disabling made them vanish silently.enabled: active,dropsUnsupportedReason:- view.mode === "single"- ? undefined- : "Dropped files need a single chat. Open one, then drop it there.",+ view.mode === "compare"+ ? "Dropped files need a single chat. Open one, then drop it there."+ : undefined,attachmentScope,- attachmentTargetKey: artifactViewKey,+ attachmentTargetKey: nativeAttachmentTargetKey,nativePathLeasesSupported,hasActiveModel,isModelLoading: Boolean(loadingModel) || modelLoading,@@ -5018,29 +5050,35 @@ export function ChatPage({}onCompactionCountChange={handleCompactionCountChange}>- {baseView.mode === "project" ? (- <ProjectLanding- key={baseView.projectId}- projectId={baseView.projectId}- projectName={currentProject?.name ?? "Project"}- items={currentProjectItems}- newThreadNonce={projectNewThreadNonce}- rotateNewThreadNonce={rotateProjectNewThreadNonce}- dataLoaded={currentProjectItemsLoaded && !projectsLoading}- runtimeReady={projectRuntimeReady}- />- ) : (- <NativeAttachmentDragContext.Provider- value={nativeModelDropState.status === "attach"}+ <NativeAttachmentDragContext.Provider+ value={nativeModelDropState.status === "attach"}+ >+ <NativeAttachmentTargetContext.Provider+ value={baseAttachmentTargetKey}>- <NativeAttachmentTargetContext.Provider- value={baseAttachmentTargetKey}+ <NativeAttachmentOwnerScopeContext.Provider+ value={baseAttachmentOwnerScope}>- <TemporaryChatSaveBridge />- <SingleContent threadId={baseView.threadId} />- </NativeAttachmentTargetContext.Provider>- </NativeAttachmentDragContext.Provider>- )}+ {baseView.mode === "project" ? (+ <ProjectLanding+ key={baseView.projectId}+ projectId={baseView.projectId}+ projectName={currentProject?.name ?? "Project"}+ items={currentProjectItems}+ newThreadNonce={projectNewThreadNonce}+ rotateNewThreadNonce={rotateProjectNewThreadNonce}+ dataLoaded={currentProjectItemsLoaded && !projectsLoading}+ runtimeReady={projectRuntimeReady}+ />+ ) : (+ <>+ <TemporaryChatSaveBridge />+ <SingleContent threadId={baseView.threadId} />+ </>+ )}+ </NativeAttachmentOwnerScopeContext.Provider>+ </NativeAttachmentTargetContext.Provider>+ </NativeAttachmentDragContext.Provider></ChatRuntimeProvider></ChatActiveContext.Provider></BrowserOverlaidContext.Provider>diff --git a/studio/frontend/src/features/chat/draft-attachment-adapter.ts b/studio/frontend/src/features/chat/draft-attachment-adapter.tsnew file mode 100644index 00000000000..b2cdf79a387--- /dev/null+++ b/studio/frontend/src/features/chat/draft-attachment-adapter.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type {+ Attachment,+ AttachmentAdapter,+ CompleteAttachment,+ PendingAttachment,+} from "@assistant-ui/react";++const cancelledAdds = new WeakSet<File>();++// Native consumers requeue a cancelled intent; a picker add just drops with its draft.+export function wasAttachmentAddCancelled(file: File): boolean {+ return cancelledAdds.has(file);+}++// The runtime reuses its blank thread for successive drafts and clearing does not cancel adapter reads.+export class DraftScopedAttachmentAdapter implements AttachmentAdapter {+ private readonly delegate: AttachmentAdapter;+ private readonly captureCurrent: () => () => boolean;++ constructor(+ delegate: AttachmentAdapter,+ captureCurrent: () => () => boolean,+ ) {+ this.delegate = delegate;+ this.captureCurrent = captureCurrent;+ }++ get accept(): string {+ return this.delegate.accept;+ }++ add(state: { file: File }): AsyncGenerator<PendingAttachment, void> {+ // Capture at invocation, before the generator starts on its first next().+ const isCurrent = this.captureCurrent();+ cancelledAdds.delete(state.file);+ return this.addToDraft(state, isCurrent);+ }++ private async *addToDraft(+ state: { file: File },+ isCurrent: () => boolean,+ ): AsyncGenerator<PendingAttachment, void> {+ let last: PendingAttachment | undefined;+ let cancelled = false;+ const cancel = () => {+ cancelled = true;+ cancelledAdds.add(state.file);+ };+ try {+ if (!isCurrent()) {+ cancel();+ return;+ }+ const result = this.delegate.add(state);+ if (Symbol.asyncIterator in result) {+ for await (const attachment of result) {+ last = attachment;+ if (!isCurrent()) {+ cancel();+ return;+ }+ yield attachment;+ }+ } else {+ last = await result;+ if (!isCurrent()) {+ cancel();+ return;+ }+ yield last;+ }+ // Delegates return without another yield once the switch cleared their chip.+ if (!isCurrent()) cancel();+ } catch (error) {+ if (isCurrent()) throw error;+ // Throwing after a running yield would make assistant-ui resurrect the cleared chip as an error.+ cancel();+ } finally {+ if (cancelled && last) {+ // Frees adapter caches, upload slots and object URLs; removal is idempotent.+ try {+ await this.delegate.remove(last);+ } catch {+ // Cleanup must not become a stale error yield.+ }+ }+ }+ }++ remove(attachment: Attachment): Promise<void> {+ return this.delegate.remove(attachment);+ }++ send(attachment: PendingAttachment): Promise<CompleteAttachment> {+ return this.delegate.send(attachment);+ }+}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex ac24b969426..70c36ae1ec1 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -89,6 +89,7 @@ import {withAttachmentOriginal,} from "./attachment-originals";import { AudioAttachmentAdapter } from "./audio-attachment-adapter";+import { DraftScopedAttachmentAdapter } from "./draft-attachment-adapter";import {isBinaryPropertyList,isBinaryTrackerModule,@@ -2105,6 +2106,7 @@ function createStudioDbAdapter(pairId?: string,projectId?: string | null,listThreads = true,+ newThreadSwitchStateRef?: { current: NewThreadSwitchState },): unstable_RemoteThreadListAdapter {return {async fetch(remoteId: string) {@@ -2149,6 +2151,8 @@ function createStudioDbAdapter(},initialize(threadId: string) {+ // Recorded synchronously: a pending attachment may finish after several later drafts.+ const attachmentDraft = getAttachmentDraft(newThreadSwitchStateRef?.current, threadId);// Tracked, not awaited: assistant-ui withholds the first message until this resolves.const claim = readThreadCreationClaim(threadId);const runtimeStateAtInit = useChatRuntimeStore.getState();@@ -2177,6 +2181,7 @@ function createStudioDbAdapter();// Re-key handles a running stream filed under "__default".useChatRuntimeStore.getState().adoptDefaultThreadRun(threadId);+ if (attachmentDraft) attachmentDraft.initialized = true;return Promise.resolve({ remoteId: threadId, externalId: undefined });},@@ -3071,7 +3076,8 @@ function useStudioRuntimeAdapters(const text = new TextAttachmentAdapter();const largeFallback = (browser: AttachmentAdapter) =>new LargeDocumentFallbackAdapter(browser, server);- return new PreStreamAwareAttachmentAdapter(+ return new DraftScopedAttachmentAdapter(+ new PreStreamAwareAttachmentAdapter(new CompositeAttachmentAdapter([new VisionImageAdapter(),new AudioAttachmentAdapter(),@@ -3096,8 +3102,32 @@ function useStudioRuntimeAdapters(useChatRuntimeStore.getState().activeThreadId,);},- );- }, [aui]);+ ),+ () => {+ const { id, remoteId } = aui.threadListItem().getState();+ const switchState = newThreadSwitchStateRef?.current;+ const attempt = switchState?.attempt;+ // Saved background runtimes must not replace the foreground draft's token.+ const draft = remoteId ? undefined : getAttachmentDraft(switchState, id);+ return () => {+ let current: ReturnType<ReturnType<typeof aui.threadListItem>["getState"]>;+ try {+ current = aui.threadListItem().getState();+ } catch {+ return false; // The thread was deleted while the adapter read it.+ }+ if (current.id !== id) return false;+ if (isChatThreadDeleted(current.remoteId ?? id)) return false;+ // Saved runtimes remain their own destination while backgrounded.+ if (remoteId) return true;+ const latest = newThreadSwitchStateRef?.current;+ if (latest?.attempt === attempt) return true;+ // Only this add's own draft saving qualifies, not a later draft reusing the runtime.+ return Boolean(current.remoteId && draft?.initialized);+ };+ },+ );+ }, [aui, newThreadSwitchStateRef]);const adapters = useMemo(() => ({ history, dictation, speech, attachments }),[history, dictation, speech, attachments],@@ -3158,11 +3188,15 @@ const MAX_PENDING_SAVED_THREAD_SWITCHES = 16;type PendingSavedThreadSwitch = { id: string; settled: boolean };+type AttachmentDraft = { attempt: number; threadId: string; initialized: boolean };+type NewThreadSwitchState = {activeNonce: string | null;hasSwitched: boolean;// Bumped per switch: two switches for the same nonce can be in flight.attempt: number;+ // Current draft only: pending adds hold their captured token, so no thread-ID map grows.+ attachmentDraft?: AttachmentDraft;// One entry per switch started, matched by id, not id shape.pendingSavedThreadIds: PendingSavedThreadSwitch[];// ?new= survives materialization, so the nonce/thread pair tells return from new.@@ -3171,6 +3205,17 @@ type NewThreadSwitchState = {landedAttempt: number;};+function getAttachmentDraft(+ state: NewThreadSwitchState | undefined,+ threadId: string,+): AttachmentDraft | undefined {+ if (!state) return undefined;+ if (state.attachmentDraft?.attempt !== state.attempt || state.attachmentDraft.threadId !== threadId) {+ state.attachmentDraft = { attempt: state.attempt, threadId, initialized: false };+ }+ return state.attachmentDraft;+}+function ThreadAutoSwitch({threadId,syncActiveThreadId = true,@@ -4388,7 +4433,7 @@ export function ChatRuntimeProvider({);const runtime = useRemoteThreadListRuntime({runtimeHook,- adapter: createStudioDbAdapter(modelType, pairId, projectId, listThreads),+ adapter: createStudioDbAdapter(modelType, pairId, projectId, listThreads, newThreadSwitchStateRef),});const signalFailedInitialSwitchReady = useCallback(() => {if (onInitialHistoryReady) {diff --git a/studio/frontend/src/features/native-intents/attachment-target.ts b/studio/frontend/src/features/native-intents/attachment-target.tsindex c9fe5775954..d20812f7092 100644--- a/studio/frontend/src/features/native-intents/attachment-target.ts+++ b/studio/frontend/src/features/native-intents/attachment-target.ts@@ -7,6 +7,13 @@ export const NativeAttachmentDragContext = createContext(false);export const NativeAttachmentTargetContext = createContext<string | null>(null);+// Distinguishes successive unsent drafts that reuse one local thread ID.+export const NativeAttachmentOwnerScopeContext = createContext<string | null>(null);+export function useNativeAttachmentTargetKey(): string | null {return useContext(NativeAttachmentTargetContext);}++export function useNativeAttachmentOwnerScope(): string | null {+ return useContext(NativeAttachmentOwnerScopeContext);+}diff --git a/studio/frontend/src/features/native-intents/index.ts b/studio/frontend/src/features/native-intents/index.tsindex 2f903bc70ce..0d114d9f33b 100644--- a/studio/frontend/src/features/native-intents/index.ts+++ b/studio/frontend/src/features/native-intents/index.ts@@ -23,7 +23,9 @@ export type { NativeFileDrop, NativeFileDropOptions } from "./use-native-file-drexport {NativeAttachmentTargetContext,NativeAttachmentDragContext,+ NativeAttachmentOwnerScopeContext,useNativeAttachmentTargetKey,+ useNativeAttachmentOwnerScope,} from "./attachment-target";export { useNativeIntentStore } from "./store";export type { NativeIntent } from "./types";diff --git a/studio/frontend/tests/draft-attachment-adapter.test.ts b/studio/frontend/tests/draft-attachment-adapter.test.tsnew file mode 100644index 00000000000..afded6054e6--- /dev/null+++ b/studio/frontend/tests/draft-attachment-adapter.test.ts@@ -0,0 +1,374 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { readFileSync } from "node:fs";+import ts from "@typescript/typescript6";+import type { AttachmentAdapter, PendingAttachment } from "@assistant-ui/react";+import {+ DraftScopedAttachmentAdapter,+ wasAttachmentAddCancelled,+} from "../src/features/chat/draft-attachment-adapter.ts";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });+ return { promise, resolve, reject };+}++function attachment(file: File, running = false): PendingAttachment {+ return {+ id: "test-attachment",+ type: "document",+ name: file.name,+ contentType: file.type,+ file,+ status: running+ ? { type: "running", reason: "uploading", progress: 0 }+ : { type: "requires-action", reason: "composer-send" },+ };+}++function setup(add: AttachmentAdapter["add"]) {+ let generation = 1;+ const removed: string[] = [];+ const delegate: AttachmentAdapter = {+ accept: ".txt",+ add,+ remove: async (value) => { removed.push(value.id); },+ send: async (value) => ({ ...value, status: { type: "complete" }, content: [] }),+ };+ const guarded = new DraftScopedAttachmentAdapter(delegate, () => {+ const captured = generation;+ return () => generation === captured;+ });+ return { guarded, delegate, removed, switchDraft: () => { generation += 1; } };+}++async function collect(values: AsyncGenerator<PendingAttachment, void>) {+ const found: PendingAttachment[] = [];+ for await (const value of values) found.push(value);+ return found;+}++test("a promise attachment finishes normally in its original draft", async () => {+ const file = new File(["content"], "notes.txt");+ const value = attachment(file);+ const h = setup(async () => value);+ assert.deepEqual(await collect(h.guarded.add({ file })), [value]);+ assert.equal(wasAttachmentAddCancelled(file), false);+ assert.deepEqual(h.removed, []);+ assert.equal(h.guarded.accept, ".txt");+});++test("a late promise result is discarded and its resources removed", async () => {+ const file = new File(["content"], "notes.txt");+ const gate = deferred<PendingAttachment>();+ const h = setup(() => gate.promise);+ const pending = collect(h.guarded.add({ file }));+ h.switchDraft();+ gate.resolve(attachment(file));+ assert.deepEqual(await pending, []);+ assert.equal(wasAttachmentAddCancelled(file), true);+ assert.deepEqual(h.removed, ["test-attachment"]);+});++test("ownership is captured before a generator is first advanced", async () => {+ const file = new File(["content"], "notes.txt");+ let calls = 0;+ const h = setup(async () => { calls += 1; return attachment(file); });+ const generator = h.guarded.add({ file });+ h.switchDraft();+ assert.deepEqual(await collect(generator), []);+ assert.equal(calls, 0);+ assert.equal(wasAttachmentAddCancelled(file), true);+});++test("every streamed result is checked before it can restore a removed chip", async () => {+ const file = new File(["content"], "notes.txt");+ const gate = deferred<void>();+ let closed = false;+ const h = setup(async function* () {+ try {+ yield attachment(file, true);+ await gate.promise;+ yield attachment(file);+ } finally { closed = true; }+ });+ const iterator = h.guarded.add({ file });+ assert.equal((await iterator.next()).value?.status.type, "running");+ const pending = iterator.next();+ h.switchDraft();+ gate.resolve();+ assert.equal((await pending).done, true);+ assert.equal(closed, true);+ assert.equal(wasAttachmentAddCancelled(file), true);+ assert.deepEqual(h.removed, ["test-attachment"]);+});++test("late generator errors finish quietly instead of resurrecting an incomplete chip", async () => {+ const file = new File(["content"], "notes.txt");+ const gate = deferred<void>();+ const h = setup(async function* () {+ yield attachment(file, true);+ await gate.promise;+ });+ const iterator = h.guarded.add({ file });+ await iterator.next();+ const pending = iterator.next();+ h.switchDraft();+ gate.reject(new Error("Old upload failed"));+ assert.equal((await pending).done, true);+ assert.equal(wasAttachmentAddCancelled(file), true);+ assert.deepEqual(h.removed, ["test-attachment"]);+});++test("current-draft errors still reach the normal attachment error handling", async () => {+ const file = new File(["content"], "notes.txt");+ const h = setup(async () => { throw new Error("Unreadable"); });+ await assert.rejects(collect(h.guarded.add({ file })), /Unreadable/);+ assert.equal(wasAttachmentAddCancelled(file), false);+});++test("cancellation survives a cleanup error and does not poison a later add", async () => {+ const file = new File(["content"], "notes.txt");+ const gate = deferred<PendingAttachment>();+ const h = setup(() => gate.promise);+ h.delegate.remove = () => { throw new Error("Already removed"); };+ const pending = collect(h.guarded.add({ file }));+ h.switchDraft();+ gate.resolve(attachment(file));+ assert.deepEqual(await pending, []);+ assert.equal(wasAttachmentAddCancelled(file), true);+ assert.equal((await collect(h.guarded.add({ file }))).length, 1);+ assert.equal(wasAttachmentAddCancelled(file), false);+});++test("send and explicit removal preserve the delegate contract", async () => {+ const file = new File(["content"], "notes.txt");+ const value = attachment(file);+ const h = setup(async () => value);+ assert.equal((await h.guarded.send(value)).status.type, "complete");+ await h.guarded.remove(value);+ assert.deepEqual(h.removed, [value.id]);+});+++function runtimeScope() {+ const source = ts.createSourceFile(+ "runtime-provider.tsx",+ readFileSync(new URL("../src/features/chat/runtime-provider.tsx", import.meta.url), "utf8"),+ ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX,+ );+ let capture: ts.Expression | undefined;+ let dbFactory: ts.FunctionDeclaration | undefined;+ let draftHelper: ts.FunctionDeclaration | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isNewExpression(node) && node.expression.getText(source) === "DraftScopedAttachmentAdapter") {+ capture = node.arguments?.[1];+ }+ if (ts.isFunctionDeclaration(node) && node.name?.text === "createStudioDbAdapter") {+ dbFactory = node;+ }+ if (ts.isFunctionDeclaration(node) && node.name?.text === "getAttachmentDraft") {+ draftHelper = node;+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ assert.ok(capture);+ assert.ok(dbFactory);+ const helperCode = draftHelper?.getText(source) ?? "";+ const code = ts.transpileModule(`${helperCode}\nreturn (${capture.getText(source)});`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+ }).outputText;+ let current: { id: string; remoteId?: string } = { id: "local" };+ const switchRef: { current: {+ attempt: number;+ activeNonce: string;+ nonceThread: { nonce: string; threadId: string } | null;+ } } = { current: {+ attempt: 1,+ activeNonce: "original-draft",+ nonceThread: { nonce: "original-draft", threadId: "local" },+ } };+ let deleted = false;+ let tombstoned = false;+ let failInitialization = false;+ const aui = { threadListItem: () => ({ getState: () => {+ if (deleted) throw new Error("Thread removed");+ return current;+ } }) };+ const captureCurrent = new Function("aui", "newThreadSwitchStateRef", "isChatThreadDeleted", code)(+ aui, switchRef, () => tombstoned,+ ) as () => () => boolean;+ const factoryCode = ts.transpileModule(`${helperCode}\n${dbFactory.getText(source)}\nreturn createStudioDbAdapter;`, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },+ }).outputText;+ const createAdapter = new Function(+ "readThreadCreationClaim", "useChatRuntimeStore", "trackStoredChatThreadRecord", factoryCode,+ )(+ () => undefined,+ { getState: () => ({ params: {}, adoptDefaultThreadRun: () => {+ if (failInitialization) throw new Error("Initialization failed");+ } }) },+ () => {}, // Persistence is separate; exercise the actual synchronous ownership boundary.+ );+ const db = createAdapter("base", undefined, undefined, true, switchRef) as {+ initialize(id: string): Promise<{ remoteId: string }>;+ };+ return {+ captureCurrent,+ switchDraft() {+ switchRef.current.attempt += 1;+ switchRef.current.activeNonce = `draft-${switchRef.current.attempt}`;+ switchRef.current.nonceThread = null;+ },+ async initialize() {+ const result = await db.initialize(current.id);+ current.remoteId = result.remoteId;+ },+ replaceRuntime(id: string, remoteId?: string) { current = { id, remoteId }; },+ deleteRuntime() { deleted = true; },+ tombstone() { tombstoned = true; },+ failInitialization(value: boolean) { failInitialization = value; },+ };+}++test("a draft saved through Sources retains pending attachments after New chat", async () => {+ const h = runtimeScope();+ const valid = h.captureCurrent();+ assert.equal(valid(), true, "same draft and backgrounded Compare retain ownership");+ await h.initialize();+ h.switchDraft();+ assert.equal(valid(), true, "the saved original retains its pending picker read");+});++test("initialization started before navigation retains the original pending add", async () => {+ const h = runtimeScope();+ const valid = h.captureCurrent();+ const saving = h.initialize();+ h.switchDraft();+ await saving;+ assert.equal(valid(), true);+});++test("an add begun while initialization publishes its saved ID retains ownership", async () => {+ const h = runtimeScope();+ const saving = h.initialize();+ const valid = h.captureCurrent();+ h.switchDraft();+ await saving;+ assert.equal(valid(), true);+});++test("a failed initialization cannot authorize an old add when a later draft saves", async () => {+ const h = runtimeScope();+ const original = h.captureCurrent();+ h.failInitialization(true);+ await assert.rejects(h.initialize(), /Initialization failed/);+ h.switchDraft();+ const later = h.captureCurrent();+ h.failInitialization(false);+ await h.initialize();+ assert.equal(original(), false);+ assert.equal(later(), true);+});++test("adding to a saved background chat cannot replace the unsaved foreground owner", async () => {+ const h = runtimeScope();+ const original = h.captureCurrent();+ h.replaceRuntime("saved", "saved");+ h.captureCurrent();+ h.replaceRuntime("local");+ await h.initialize();+ h.switchDraft();+ assert.equal(original(), true);+});++test("later drafts and saves cannot erase an earlier saved attachment owner", async () => {+ const h = runtimeScope();+ const original = h.captureCurrent();+ await h.initialize();+ for (let index = 0; index < 20; index += 1) {+ h.switchDraft();+ h.replaceRuntime(`later-${index}`);+ const later = h.captureCurrent();+ await h.initialize();+ assert.equal(later(), true);+ }+ h.replaceRuntime("local", "local");+ assert.equal(original(), true);+});++test("a reused blank runtime saved by a later draft cannot claim an abandoned file", async () => {+ const h = runtimeScope();+ const original = h.captureCurrent();+ h.switchDraft();+ const later = h.captureCurrent();+ await h.initialize();+ assert.equal(original(), false, "even a mutated original snapshot cannot acquire ownership");+ assert.equal(later(), true);+});++test("initializing a later draft without a new attachment does not adopt the old add", async () => {+ const h = runtimeScope();+ const original = h.captureCurrent();+ h.switchDraft();+ await h.initialize();+ assert.equal(original(), false);+});++test("a saved runtime keeps background attachments but cannot transfer them to another runtime", () => {+ const h = runtimeScope();+ h.replaceRuntime("saved", "saved");+ const valid = h.captureCurrent();+ h.switchDraft();+ assert.equal(valid(), true);+ h.replaceRuntime("other", "other");+ assert.equal(valid(), false);+});++test("removed and retained-but-tombstoned saved runtimes both cancel pending adds", () => {+ for (const deletion of ["deleteRuntime", "tombstone"] as const) {+ const h = runtimeScope();+ h.replaceRuntime("saved", "saved");+ const valid = h.captureCurrent();+ h[deletion]();+ assert.equal(valid(), false, deletion);+ }+});++test("a cancelled overlapping add cannot remove the valid add's resources", async () => {+ const file = new File(["content"], "notes.txt");+ const oldGate = deferred<PendingAttachment>();+ const newGate = deferred<PendingAttachment>();+ let calls = 0;+ const h = setup(() => (++calls === 1 ? oldGate.promise : newGate.promise));+ const oldAdd = collect(h.guarded.add({ file }));+ h.switchDraft();+ const newAdd = collect(h.guarded.add({ file }));+ oldGate.resolve({ ...attachment(file), id: "old" });+ assert.deepEqual(await oldAdd, []);+ newGate.resolve({ ...attachment(file), id: "new" });+ assert.equal((await newAdd)[0].id, "new");+ assert.deepEqual(h.removed, ["old"]);+});++test("a generator that finishes without another yield after a switch still cancels", async () => {+ const file = new File(["content"], "notes.txt");+ const gate = deferred<void>();+ const h = setup(async function* () {+ yield attachment(file, true);+ await gate.promise;+ });+ const pending = collect(h.guarded.add({ file }));+ await new Promise<void>((resolve) => setImmediate(resolve));+ h.switchDraft();+ gate.resolve();+ assert.equal((await pending).length, 1);+ assert.equal(wasAttachmentAddCancelled(file), true);+ assert.deepEqual(h.removed, ["test-attachment"]);+});diff --git a/studio/frontend/tests/native-drop-consumer-ownership.test.ts b/studio/frontend/tests/native-drop-consumer-ownership.test.tsnew file mode 100644index 00000000000..5ab7de4b8c9--- /dev/null+++ b/studio/frontend/tests/native-drop-consumer-ownership.test.ts@@ -0,0 +1,466 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import ts from "@typescript/typescript6";+import { create } from "zustand";++import type { NativeIntent } from "../src/features/native-intents/types.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++const source = ts.createSourceFile(+ "thread.tsx",+ readFileSync(+ new URL("../src/components/assistant-ui/thread.tsx", import.meta.url),+ "utf8",+ ),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);++function findNode(predicate: (node: ts.Node) => boolean): ts.Node {+ let result: ts.Node | undefined;+ function visit(node: ts.Node) {+ if (!result && predicate(node)) result = node;+ if (!result) ts.forEachChild(node, visit);+ }+ visit(source);+ assert.ok(result, "expected the native attachment consumer source");+ return result;+}++function evaluate<T>(body: string, bindings: Record<string, unknown>): T {+ const { outputText } = ts.transpileModule(body, {+ compilerOptions: {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.CommonJS,+ },+ });+ return new Function(...Object.keys(bindings), outputText)(+ ...Object.values(bindings),+ ) as T;+}++type Kind = "Image" | "OpenDocument" | "Audio" | "Video";+type Destination = {+ key: string;+ draft: string;+ project: string | null;+ runtimeId: string;+};+const original: Destination = {+ key: "project:project-a:draft-one",+ draft: "draft-one",+ project: "project-a",+ runtimeId: "__LOCALID_shared",+};++// The real owner assignment is evaluated separately from the effects because+// React completes render (including this assignment) before running effects.+function ownerFor(destination: Destination): string {+ const declaration = findNode(+ (node) =>+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === "nativeAttachmentOwner",+ );+ const assignment = findNode(+ (node) =>+ ts.isBinaryExpression(node) &&+ node.left.getText(source) === "nativeAttachmentOwnerRef.current",+ );+ assert.ok(ts.isBinaryExpression(assignment));+ return evaluate(+ `const ${declaration.getText(source)}; return (${assignment.right.getText(source)});`,+ {+ threadListItemId: destination.runtimeId,+ nativeAttachmentOwnerScope: destination.project+ ? `project:${destination.project}:${destination.draft}`+ : null,+ },+ );+}++function drainEffect(kind: Kind): string {+ const node = findNode(+ (node) =>+ ts.isCallExpression(node) &&+ node.expression.getText(source) === "useEffect" &&+ node.arguments[0]?.getText(source).includes(`.take${kind}Attachments(`),+ );+ assert.ok(ts.isCallExpression(node));+ return `return { run: ${node.arguments[0]!.getText(source)}, dependencies: ${node.arguments[1]!.getText(source)} };`;+}++const effects = Object.fromEntries(+ (["Image", "OpenDocument", "Audio", "Video"] as const).map((kind) => [+ kind,+ drainEffect(kind),+ ]),+) as Record<Kind, string>;++function attachment(kind: Kind): NativeIntent {+ const name = {+ Image: "photo.png",+ OpenDocument: "notes.txt",+ Audio: "clip.wav",+ Video: "movie.mp4",+ }[kind];+ return {+ id: name,+ kind: "attachment",+ sourceKind: "drop",+ displayLabel: name,+ path: {+ token: name,+ kind: "attachment",+ displayLabel: name,+ allowedOperations: ["attach"],+ expiresAtMs: Date.now() + 60_000,+ },+ };+}++async function settle() {+ // Native reads and normalization both cross promise boundaries. A macrotask+ // lets all continuations and synchronous store subscribers settle together.+ await new Promise<void>((resolve) => setImmediate(resolve));+}++let composerDisabled = false;++function harness(+ kind: Kind,+ stage: "native read" | "adapter add" | "destination refused" = "native read",+ initial = original,+) {+ const { useNativeIntentStore: store } = loadWithStubs<+ typeof import("../src/features/native-intents/store.ts")+ >(+ new URL("../src/features/native-intents/store.ts", import.meta.url),+ { zustand: { create } },+ { relativePassthrough: true },+ );+ let destination = initial;+ let keyRef = { current: destination.key };+ let identityRef = { current: ownerFor(destination) };+ let composerRef = { current: destination.runtimeId };+ let cleanup: (() => void) | undefined;+ let previousDependencies: unknown[] | undefined;+ let firstRead = true;+ let firstAdd = true;+ let addAttempts = 0;+ let blocked!: () => void;+ const suspended = new Promise<void>((resolve) => {+ blocked = resolve;+ });+ let release!: () => void;+ const readGate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const attached: Array<{ key: string; name: string }> = [];+ const errors: string[] = [];+ const cancelled: string[] = [];+ const cancelledAdds = new WeakSet<File>();+ const materializing = new Map<string, boolean>();+ const aui = {+ composer: () => ({+ addAttachment: async (file: File) => {+ cancelledAdds.delete(file);+ addAttempts += 1;+ assert.ok(+ addAttempts <= 3,+ "a cancelled add must not loop through the same drain",+ );+ if (stage === "destination refused") {+ cancelledAdds.add(file);+ return;+ }+ const owner = ownerFor(destination);+ if (firstAdd && stage === "adapter add") {+ firstAdd = false;+ blocked();+ await readGate;+ // The guarded adapter settles without mutating a different owner.+ // Its own generation checks have separate integration coverage.+ if (ownerFor(destination) !== owner) {+ cancelledAdds.add(file);+ return;+ }+ }+ attached.push({ key: destination.key, name: file.name });+ },+ }),+ };+ const intent = attachment(kind);++ function mount(next: Destination, remount = false) {+ destination = next;+ if (remount) {+ cleanup?.();+ cleanup = undefined;+ previousDependencies = undefined;+ keyRef = { current: next.key };+ identityRef = { current: ownerFor(next) };+ composerRef = { current: next.runtimeId };+ } else {+ keyRef.current = next.key;+ identityRef.current = ownerFor(next);+ composerRef.current = next.runtimeId;+ }+ const bindings = {+ disabled: composerDisabled,+ nativeAttachmentTargetKey: next.key,+ nativeAttachmentTargetKeyRef: keyRef,+ composerIdentityRef: composerRef,+ nativeAttachmentOwnerRef: identityRef,+ nativeAttachmentOwner: identityRef.current,+ wasAttachmentAddCancelled: (file: File) => cancelledAdds.has(file),+ useNativeIntentStore: store,+ aui,+ cancelQueuedSendRef: { current: () => cancelled.push(destination.key) },+ toast: { error: (message: string) => errors.push(message) },+ nativeAttachmentIntentToFile: async (item: NativeIntent) => {+ if (firstRead) {+ firstRead = false;+ if (stage === "native read") {+ blocked();+ await readGate;+ }+ }+ return new File(["fixture"], item.displayLabel);+ },+ normalizeChatImage: async (file: File) => file,+ setMaterializingDroppedImages: (value: boolean) =>+ materializing.set(next.key, value),+ setMaterializingDroppedOpenDocuments: (value: boolean) =>+ materializing.set(next.key, value),+ setMaterializingDroppedAudio: (value: boolean) =>+ materializing.set(next.key, value),+ setMaterializingDroppedVideo: (value: boolean) =>+ materializing.set(next.key, value),+ };+ const effect = evaluate<{+ run: () => (() => void) | undefined;+ dependencies: unknown[];+ }>(effects[kind], bindings);+ if (+ previousDependencies?.every((value, index) =>+ Object.is(value, effect.dependencies[index]),+ )+ )+ return;+ cleanup?.();+ previousDependencies = effect.dependencies;+ cleanup = effect.run();+ }++ store.getState()[`add${kind}Attachments`](initial.key, [intent]);+ mount(initial);+ assert.equal(+ firstRead,+ false,+ "the originating composer must have started reading the file",+ );+ return {+ store,+ intent,+ attached,+ errors,+ cancelled,+ materializing,+ suspended,+ get addAttempts() {+ return addAttempts;+ },+ mount,+ async finishRead() {+ release();+ await settle();+ },+ cleanup() {+ release();+ cleanup?.();+ },+ pending(key: string) {+ return store.getState()[`take${kind}Attachments`](key);+ },+ };+}++for (const kind of ["Image", "OpenDocument", "Audio", "Video"] as const) {+ for (const stage of ["native read", "adapter add"] as const) {+ for (const [label, next, remount] of [+ [+ "another project",+ {+ ...original,+ key: "project:project-b:draft-one",+ project: "project-b",+ },+ true,+ ],+ [+ "a new draft in the same project",+ { ...original, key: "project:project-a:draft-two", draft: "draft-two" },+ false,+ ],+ ] as const) {+ test(`${kind}: a delayed ${stage} stays with its draft when the runtime ID is reused for ${label}`, async () => {+ const h = harness(kind, stage);+ try {+ await h.suspended;+ h.mount(next, remount);+ await h.finishRead();+ assert.deepEqual(+ h.attached,+ [],+ "the newly opened composer must not receive the previous draft's file",+ );+ assert.deepEqual(h.pending(next.key), []);+ assert.deepEqual(+ h.pending(original.key),+ [h.intent],+ "the originating draft keeps the file available",+ );+ assert.deepEqual(h.errors, []);+ assert.deepEqual(h.cancelled, []);+ } finally {+ h.cleanup();+ }+ });+ }++ for (const remount of [false, true]) {+ test(`${kind}: first persistence ${remount ? "with a remount" : "under the mounted composer"} preserves a delayed ${stage}`, async () => {+ const h = harness(kind, stage);+ const persisted = { ...original, key: "single:persisted-thread" };+ try {+ await h.suspended;+ h.mount(persisted, remount);+ await h.finishRead();+ assert.deepEqual(h.attached, [+ { key: persisted.key, name: h.intent.displayLabel },+ ]);+ assert.deepEqual(h.pending(original.key), []);+ assert.deepEqual(h.pending(persisted.key), []);+ assert.equal(h.materializing.get(persisted.key), false);+ assert.deepEqual(h.errors, []);+ } finally {+ h.cleanup();+ }+ });+ }+ }+}++for (const kind of ["Image", "OpenDocument", "Audio", "Video"] as const) {+ test(`${kind}: a destination that keeps refusing the add is retried once, not looped`, async () => {+ const h = harness(kind, "destination refused");+ try {+ await h.finishRead();+ assert.equal(h.addAttempts, 2);+ assert.deepEqual(h.attached, []);+ assert.deepEqual(h.pending(original.key), []);+ assert.deepEqual(h.cancelled, [original.key]);+ } finally {+ h.cleanup();+ }+ });+}++test("a Library handoff add the draft-scoped adapter cancels is refused, so the file stays held", async () => {+ const effect = findNode(+ (node) =>+ ts.isCallExpression(node) &&+ node.expression.getText(source) === "useEffect" &&+ node.arguments[0]?.getText(source).includes("attachLibraryChatFiles("),+ );+ let addDeclaration: ts.Node | undefined;+ ts.forEachChild(effect, function visit(node) {+ if (+ !addDeclaration &&+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === "add"+ ) {+ addDeclaration = node;+ }+ if (!addDeclaration) ts.forEachChild(node, visit);+ });+ assert.ok(addDeclaration);+ const cancelled = new WeakSet<File>();+ const add = evaluate<(file: File) => Promise<void>>(+ `const ${addDeclaration.getText(source)}; return add;`,+ {+ disposed: false,+ targetKey: "single:library",+ nativeAttachmentTargetKeyRef: { current: "single:library" },+ aui: {+ composer: () => ({+ addAttachment: async (file: File) => {+ cancelled.add(file);+ },+ }),+ },+ wasAttachmentAddCancelled: (file: File) => cancelled.has(file),+ },+ );+ await assert.rejects(add(new File(["fixture"], "notes.pdf")));+});++for (const kind of ["Image", "OpenDocument", "Audio", "Video"] as const) {+ test(`${kind}: a queued file waits until the runtime reaches the route's thread`, async () => {+ // The route already names the saved chat while aui.composer() is still the previous one.+ composerDisabled = true;+ const { useNativeIntentStore: store } = loadWithStubs<+ typeof import("../src/features/native-intents/store.ts")+ >(+ new URL("../src/features/native-intents/store.ts", import.meta.url),+ { zustand: { create } },+ { relativePassthrough: true },+ );+ const attached: string[] = [];+ const run = (disabled: boolean) =>+ evaluate<{ run: () => (() => void) | undefined }>(effects[kind], {+ disabled,+ nativeAttachmentTargetKey: original.key,+ nativeAttachmentTargetKeyRef: { current: original.key },+ nativeAttachmentOwnerRef: { current: ownerFor(original) },+ nativeAttachmentOwner: ownerFor(original),+ wasAttachmentAddCancelled: () => false,+ useNativeIntentStore: store,+ aui: {+ composer: () => ({+ addAttachment: async (file: File) => {+ attached.push(file.name);+ },+ }),+ },+ cancelQueuedSendRef: { current: () => undefined },+ toast: { error: () => undefined },+ nativeAttachmentIntentToFile: async (item: NativeIntent) =>+ new File(["fixture"], item.displayLabel),+ normalizeChatImage: async (file: File) => file,+ setMaterializingDroppedImages: () => undefined,+ setMaterializingDroppedOpenDocuments: () => undefined,+ setMaterializingDroppedAudio: () => undefined,+ setMaterializingDroppedVideo: () => undefined,+ }).run();+ try {+ const intent = attachment(kind);+ store.getState()[`add${kind}Attachments`](original.key, [intent]);+ const waiting = run(true);+ await settle();+ assert.deepEqual(attached, []);+ waiting?.();+ const cleanup = run(false);+ await settle();+ cleanup?.();+ assert.deepEqual(attached, [intent.displayLabel]);+ } finally {+ composerDisabled = false;+ }+ });+}diff --git a/studio/frontend/tests/native-drop-paths.test.ts b/studio/frontend/tests/native-drop-paths.test.tsindex 9e37fd62600..c24d5bb1d4f 100644--- a/studio/frontend/tests/native-drop-paths.test.ts+++ b/studio/frontend/tests/native-drop-paths.test.ts@@ -122,7 +122,7 @@ const OPEN_DOCUMENT_IMAGE_REGISTRATION_RE =const OPEN_DOCUMENT_BACKEND_GATE_RE =/function canAttachDocs[\s\S]*?return Boolean\(options\.onAttachDocuments\);/;const OPEN_DOCUMENT_CHAT_QUEUE_RE =- /const handleNativeDocumentDrop = useCallback\([\s\S]*?addOpenDocumentAttachments\(artifactViewKey, intents\)[\s\S]*?onAttachDocuments: handleNativeDocumentDrop/;+ /const handleNativeDocumentDrop = useCallback\([\s\S]*?addOpenDocumentAttachments\(nativeAttachmentTargetKey, intents\)[\s\S]*?onAttachDocuments: handleNativeDocumentDrop/;const OPEN_DOCUMENT_DRAIN_RE =/takeOpenDocumentAttachments\(targetKey\)[\s\S]*?nativeAttachmentIntentToFile\(intent\)[\s\S]*?await aui\.composer\(\)\.addAttachment\(file\)/;diff --git a/studio/frontend/tests/project-native-drop.test.ts b/studio/frontend/tests/project-native-drop.test.tsnew file mode 100644index 00000000000..825f2c8212f--- /dev/null+++ b/studio/frontend/tests/project-native-drop.test.ts@@ -0,0 +1,591 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import ts from "@typescript/typescript6";+import { create } from "zustand";++import * as dropPaths from "../src/features/native-intents/drop-paths.ts";+import type { NativeIntent } from "../src/features/native-intents/types.ts";+import type { useNativeModelDrop } from "../src/features/native-intents/use-native-drop.ts";+import {+ loadWithStubs,+ stubJsxRuntime,+ type StubElement,+} from "./helpers/module-stubs.ts";++type DropOptions = Parameters<typeof useNativeModelDrop>[0];+type View = {+ mode: "project" | "single" | "compare";+ projectId?: string;+ threadId?: string;+ newThreadNonce?: string;+ pairId?: string;+};+const source = ts.createSourceFile(+ "chat-page.tsx",+ readFileSync(+ new URL("../src/features/chat/chat-page.tsx", import.meta.url),+ "utf8",+ ),+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+);++function findNode(predicate: (node: ts.Node) => boolean): ts.Node {+ let result: ts.Node | undefined;+ function visit(node: ts.Node) {+ if (!result && predicate(node)) result = node;+ if (!result) ts.forEachChild(node, visit);+ }+ visit(source);+ assert.ok(result, "expected ChatPage's native-drop wiring to exist");+ return result;+}++function declaration(name: string): string {+ return `const ${findNode((node) => ts.isVariableDeclaration(node) && node.name.getText(source) === name).getText(source)};`;+}++// Execute the shipped callbacks/options and JSX, rather than repeating their+// predicates in the test. ChatPage's unrelated services need no DOM or mocks.+function evaluate<T>(body: string, bindings: Record<string, unknown>): T {+ const { outputText } = ts.transpileModule(body, {+ fileName: "chat-drop-fragment.tsx",+ compilerOptions: {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.CommonJS,+ jsx: ts.JsxEmit.ReactJSX,+ },+ });+ return new Function(+ "require",+ "exports",+ ...Object.keys(bindings),+ outputText,+ )(() => stubJsxRuntime(), {}, ...Object.values(bindings)) as T;+}++function pageOptions(+ view: View,+ nonce: string,+ store: unknown,+ savedScopes: Map<string, string>,+): DropOptions {+ const keyStart = findNode(+ (node) =>+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === "artifactViewKey",+ ).parent.parent.getStart(source);+ const keyEnd = findNode(+ (node) =>+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === "attachmentScope",+ ).parent.parent.end;+ const names = [+ "handleNativeImageDrop",+ "handleNativeDocumentDrop",+ "handleNativeAudioDrop",+ "handleNativeVideoDrop",+ "nativeModelDropState",+ ];+ return evaluate(+ `${source.text.slice(keyStart, keyEnd)}\n${names.map(declaration).join("\n")} return nativeModelDropState;`,+ {+ view,+ search: {},+ projectNewThreadNonce: nonce,+ nativeAttachmentScopesByThread: { current: savedScopes },+ active: true,+ nativePathLeasesSupported: true,+ hasActiveModel: false,+ loadingModel: null,+ modelLoading: false,+ useCallback: (callback: unknown) => callback,+ useNativeIntentStore: store,+ useNativeModelDrop: (options: DropOptions) => options,+ handleNativeModelDropAutoLoad: () => {+ throw new Error("unexpected model load");+ },+ },+ );+}++function consumerContexts(view: View, targetKey: string, dragging = true) {+ const runtime = findNode(+ (node) =>+ ts.isJsxElement(node) &&+ node.openingElement.tagName.getText(source) === "ChatRuntimeProvider" &&+ node.openingElement.attributes.properties.some(+ (prop) =>+ ts.isJsxAttribute(prop) &&+ prop.name.getText(source) === "modelType" &&+ prop.initializer?.getText(source) === '"base"',+ ),+ );+ const rendered = evaluate<StubElement>(+ `return (${runtime.getText(source)});`,+ {+ ChatRuntimeProvider: "runtime",+ baseView: view,+ projectNewThreadNonce: "draft",+ baseBackgrounded: false,+ markProjectRuntimeReady: () => {},+ handleCompactionCountChange: () => {},+ NativeAttachmentTargetContext: { Provider: "target" },+ NativeAttachmentOwnerScopeContext: { Provider: "owner" },+ baseAttachmentOwnerScope: view.mode === "project" ? targetKey : null,+ NativeAttachmentDragContext: { Provider: "drag" },+ baseAttachmentTargetKey: targetKey,+ nativeModelDropState: { status: dragging ? "attach" : "idle" },+ ProjectLanding: "project",+ SingleContent: "single",+ TemporaryChatSaveBridge: "temporary-save",+ currentProject: { name: "Project" },+ currentProjectItems: [],+ rotateProjectNewThreadNonce: () => {},+ currentProjectItemsLoaded: true,+ projectsLoading: false,+ projectRuntimeReady: true,+ },+ );+ const found: Array<{+ component: unknown;+ target: unknown;+ dragging: unknown;+ ownerScope: unknown;+ }> = [];+ function walk(value: unknown, target?: unknown, drag?: unknown, ownerScope?: unknown) {+ if (Array.isArray(value)) {+ for (const child of value) walk(child, target, drag, ownerScope);+ return;+ }+ if (!value || typeof value !== "object" || !("props" in value)) return;+ const node = value as StubElement;+ if (node.type === "target") target = node.props.value;+ if (node.type === "drag") drag = node.props.value;+ if (node.type === "owner") ownerScope = node.props.value;+ if (node.type === "project" || node.type === "single")+ found.push({ component: node.type, target, dragging: drag, ownerScope });+ walk(node.props.children, target, drag, ownerScope);+ }+ walk(rendered);+ return found;+}++function intent(path: string): NativeIntent {+ return {+ id: path,+ kind: "attachment",+ sourceKind: "drop",+ displayLabel: path,+ path: {+ token: path,+ kind: "attachment",+ displayLabel: path,+ allowedOperations: ["attach"],+ expiresAtMs: Date.now() + 60_000,+ },+ };+}++async function harness(+ view: View,+ nonce = "draft-one",+ register = async (path: string) => intent(path),+ savedScopes = new Map<string, string>(),+) {+ const { useNativeIntentStore: realStore } = loadWithStubs<+ typeof import("../src/features/native-intents/store.ts")+ >(+ new URL("../src/features/native-intents/store.ts", import.meta.url),+ { zustand: { create } },+ { relativePassthrough: true },+ );+ const store = Object.assign(+ (select: (state: ReturnType<typeof realStore.getState>) => unknown) =>+ select(realStore.getState()),+ { getState: realStore.getState },+ );+ let options = pageOptions(view, nonce, store, savedScopes);+ const optionsRef = { current: options };+ let overlay: ReturnType<typeof useNativeModelDrop> = { status: "idle" };+ let mounted = false;+ let dispose: (() => void) | undefined;+ const errors: string[] = [];+ let deliver!: (event: {+ payload: {+ type: string;+ paths: string[];+ position: { x: number; y: number };+ };+ }) => Promise<void>;+ let installed!: () => void;+ const ready = new Promise<void>((resolve) => {+ installed = resolve;+ });+ const hook = loadWithStubs<{ useNativeModelDrop: typeof useNativeModelDrop }>(+ new URL(+ "../src/features/native-intents/use-native-drop.ts",+ import.meta.url,+ ),+ {+ "@/lib/api-base": { isTauri: true },+ "@/lib/toast": {+ toast: { error: (message: string) => errors.push(message) },+ },+ react: {+ useRef: () => optionsRef,+ useState: () => [+ overlay,+ (+ next: typeof overlay | ((prev: typeof overlay) => typeof overlay),+ ) => {+ overlay = typeof next === "function" ? next(overlay) : next;+ },+ ],+ useEffect: (effect: () => (() => void) | undefined) => {+ if (!mounted) {+ mounted = true;+ dispose = effect();+ }+ },+ },+ "./api": {+ registerNativeAttachmentPath: register,+ registerNativeModelPath: () => {+ throw new Error("unexpected model registration");+ },+ },+ "./drop-paths": dropPaths,+ "./native-drop-targets": { nativeDropTargetAt: () => null },+ "./store": { useNativeIntentStore: store },+ "@tauri-apps/api/webview": {+ getCurrentWebview: () => ({+ onDragDropEvent: (callback: typeof deliver) => {+ deliver = callback;+ installed();+ return Promise.resolve(() => {});+ },+ }),+ },+ },+ );+ hook.useNativeModelDrop(options);+ await ready;+ return {+ store: realStore,+ errors,+ get options() {+ return options;+ },+ get overlay() {+ return overlay;+ },+ dispatch: (type: string, paths: string[]) =>+ deliver({ payload: { type, paths, position: { x: 0, y: 0 } } }),+ navigate(nextView: View, nextNonce = nonce) {+ options = pageOptions(nextView, nextNonce, store, savedScopes);+ hook.useNativeModelDrop(options);+ },+ dispose: () => dispose?.(),+ };+}++for (const [label, view] of [+ ["project new chat", { mode: "project", projectId: "project-one" }],+ [+ "standalone new chat",+ { mode: "single", newThreadNonce: "standalone-draft" },+ ],+ ["existing single chat", { mode: "single", threadId: "existing-thread" }],+] as const) {+ test(`${label} accepts files and provides the queue target and drag state to its composer`, async () => {+ const h = await harness(view);+ try {+ const key = h.options.attachmentTargetKey!;+ assert.deepEqual(consumerContexts(view, key), [+ {+ component: view.mode,+ target: key,+ dragging: true,+ ownerScope: view.mode === "project" ? key : null,+ },+ ]);+ const paths = [+ "/tmp/notes.pdf",+ "/tmp/photo.png",+ "/tmp/voice.wav",+ "/tmp/movie.mp4",+ ];+ await h.dispatch("enter", paths);+ assert.deepEqual(h.overlay, { status: "attach" });+ await h.dispatch("drop", paths);+ assert.deepEqual(h.errors, []);+ const state = h.store.getState();+ assert.deepEqual(+ state.takeOpenDocumentAttachments(key).map((item) => item.id),+ paths.slice(0, 2),+ );+ assert.deepEqual(+ state.takeAudioAttachments(key).map((item) => item.id),+ [paths[2]],+ );+ assert.deepEqual(+ state.takeVideoAttachments(key).map((item) => item.id),+ [paths[3]],+ );+ assert.equal(+ state.registeringImageDrops ++ state.registeringAudioDrops ++ state.registeringVideoDrops,+ 0,+ );+ await h.dispatch("drop", ["/tmp/another-photo.png"]);+ assert.deepEqual(+ h.store+ .getState()+ .takeImageAttachments(key)+ .map((item) => item.id),+ ["/tmp/another-photo.png"],+ );+ } finally {+ h.dispose();+ }+ });+}++test("Compare rejects attachments and models before registering a path", async () => {+ let registrations = 0;+ const h = await harness(+ { mode: "compare", pairId: "comparison" },+ "draft",+ async (path) => {+ registrations += 1;+ return intent(path);+ },+ );+ try {+ await h.dispatch("enter", ["/tmp/notes.pdf"]);+ assert.equal(h.overlay.status, "invalid");+ await h.dispatch("drop", ["/tmp/notes.pdf"]);+ await h.dispatch("drop", ["/tmp/model.gguf"]);+ assert.equal(registrations, 0);+ assert.deepEqual(h.errors, [+ h.options.dropsUnsupportedReason,+ h.options.dropsUnsupportedReason,+ ]);+ } finally {+ h.dispose();+ }+});++for (const [label, nextView, nextNonce] of [+ [+ "another project",+ { mode: "project", projectId: "project-two" },+ "draft-one",+ ],+ [+ "another draft in the same project",+ { mode: "project", projectId: "project-one" },+ "draft-two",+ ],+] as const) {+ test(`an in-flight drop cannot attach to ${label}`, async () => {+ let release!: () => void;+ const registering = new Promise<void>((resolve) => {+ release = resolve;+ });+ const h = await harness(+ { mode: "project", projectId: "project-one" },+ "draft-one",+ async (path) => {+ await registering;+ return intent(path);+ },+ );+ try {+ const originalKey = h.options.attachmentTargetKey!;+ const pending = h.dispatch("drop", ["/tmp/notes.pdf"]);+ assert.equal(h.store.getState().registeringImageDrops, 1);+ h.navigate(nextView, nextNonce);+ const nextKey = h.options.attachmentTargetKey!;+ assert.notEqual(originalKey, nextKey);+ release();+ await pending;+ assert.deepEqual(+ h.store.getState().takeOpenDocumentAttachments(nextKey),+ [],+ );+ assert.deepEqual(+ h.store+ .getState()+ .takeOpenDocumentAttachments(originalKey)+ .map((item) => item.id),+ ["/tmp/notes.pdf"],+ );+ assert.deepEqual(h.errors, []);+ } finally {+ release();+ h.dispose();+ }+ });+}+++// Re-evaluate the shipped render fragment with one persistent ref, as ChatPage+// does while the same mounted runtime changes routes.+function ownerScopeRenders() {+ const start = findNode(+ (node) =>+ ts.isIfStatement(node) && node.expression.getText(source) === "projectChatShownId",+ ).getStart(source);+ const end = findNode(+ (node) =>+ ts.isVariableDeclaration(node) &&+ node.name.getText(source) === "baseAttachmentOwnerScope",+ ).parent.parent.end;+ const remembered = { current: new Map<string, string>() };+ return {+ remembered: remembered.current,+ render({+ baseView,+ baseAttachmentTargetKey,+ projectChatShownId = null,+ nativeAttachmentTargetKey = baseAttachmentTargetKey,+ }: {+ baseView: View | null;+ baseAttachmentTargetKey: string;+ projectChatShownId?: string | null;+ nativeAttachmentTargetKey?: string;+ }): string | null {+ return evaluate<string | null>(+ `${source.text.slice(start, end)} return baseAttachmentOwnerScope;`,+ {+ nativeAttachmentScopesByThread: remembered,+ baseView,+ baseAttachmentTargetKey,+ projectChatShownId,+ nativeAttachmentTargetKey,+ },+ );+ },+ };+}++test("project owners remember saved threads without binding an unsaved draft", () => {+ const h = ownerScopeRenders();+ const first = {+ baseView: { mode: "project", projectId: "first-project" } as View,+ baseAttachmentTargetKey: "project:first-project:first-draft",+ };+ assert.equal(h.render(first), first.baseAttachmentTargetKey);+ assert.equal(h.remembered.size, 0);++ assert.equal(+ h.render({ ...first, projectChatShownId: "first-thread" }),+ first.baseAttachmentTargetKey,+ );+ assert.equal(h.remembered.get("first-thread"), first.baseAttachmentTargetKey);+ assert.equal(+ h.render({+ baseView: { mode: "single", threadId: "first-thread" },+ baseAttachmentTargetKey: "single:first-thread",+ }),+ first.baseAttachmentTargetKey,+ );++ const second = {+ baseView: { mode: "project", projectId: "second-project" } as View,+ baseAttachmentTargetKey: "project:second-project:second-draft",+ projectChatShownId: "second-thread",+ };+ assert.equal(h.render(second), second.baseAttachmentTargetKey);+ assert.equal(h.remembered.get("second-thread"), second.baseAttachmentTargetKey);+ assert.equal(+ h.render({+ baseView: { mode: "single", threadId: "first-thread" },+ baseAttachmentTargetKey: "single:first-thread",+ }),+ first.baseAttachmentTargetKey,+ );+ assert.equal(h.remembered.size, 2);+});++test("Compare keeps the background project's owner while unrelated singles remain unscoped", () => {+ const h = ownerScopeRenders();+ const baseView: View = { mode: "project", projectId: "project" };+ const baseAttachmentTargetKey = "project:project:original-draft";+ h.render({ baseView, baseAttachmentTargetKey, projectChatShownId: "saved" });+ assert.equal(+ h.render({+ baseView,+ baseAttachmentTargetKey,+ nativeAttachmentTargetKey: "compare:comparison",+ }),+ baseAttachmentTargetKey,+ );+ assert.equal(h.remembered.get("saved"), baseAttachmentTargetKey);+ assert.equal(+ h.render({+ baseView: { mode: "single", threadId: "saved" },+ baseAttachmentTargetKey: "single:saved",+ nativeAttachmentTargetKey: "compare:comparison",+ }),+ baseAttachmentTargetKey,+ );+ for (const unrelated of [+ null,+ { mode: "single", threadId: "unrelated" },+ { mode: "single", newThreadNonce: "new-standalone" },+ ] as Array<View | null>) {+ assert.equal(+ h.render({+ baseView: unrelated,+ baseAttachmentTargetKey: "single:unrelated",+ }),+ null,+ );+ }+});++for (const finishInSavedChat of [true, false]) {+ const destination = finishInSavedChat ? "its thread route" : "another chat";+ test(`a saved project's drop survives registration finishing in ${destination}`, async () => {+ let release!: () => void;+ const registration = new Promise<void>((resolve) => { release = resolve; });+ const project: View = { mode: "project", projectId: "project" };+ const saved: View = { mode: "single", threadId: "saved" };+ const other: View = { mode: "single", threadId: "other" };+ const owner = ownerScopeRenders();+ const h = await harness(project, "draft", async (path) => {+ await registration;+ return intent(path);+ }, owner.remembered);+ try {+ owner.render({+ baseView: project,+ baseAttachmentTargetKey: h.options.attachmentTargetKey!,+ projectChatShownId: saved.threadId,+ });+ const drop = h.dispatch("drop", ["/tmp/notes.pdf"]);+ h.navigate(finishInSavedChat ? saved : other);+ release();+ await drop;+ const store = h.store.getState();+ if (!finishInSavedChat) {+ assert.deepEqual(store.takeOpenDocumentAttachments(h.options.attachmentTargetKey!), []);+ h.navigate(saved);+ }+ const files = store.takeOpenDocumentAttachments(h.options.attachmentTargetKey!);+ assert.deepEqual(files.map((item) => item.id), ["/tmp/notes.pdf"]);+ } finally {+ release();+ h.dispose();+ }+ });+}