TypeScript
fix(web): changing projects no longer creates a draft (#9097)
Exotic3b3465f2a9db
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 2783f3266d6..a475230fe82 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -7367,6 +7367,7 @@ function ChatViewContent(props: ChatViewProps) {}><DraftHeroHeadline+ draftId={draftId}activeProjectRef={activeProjectRef}activeProjectTitle={activeProject?.title ?? null}/>diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsxindex 57f9d779225..04bbeb6ce49 100644--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx@@ -1,11 +1,13 @@+import type { DraftId } from "~/composerDraftStore";+import { useComposerDraftStore } from "~/composerDraftStore";import type { ScopedProjectRef } from "@t3tools/contracts";import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";import { FolderPlusIcon } from "lucide-react";import { useCallback, useMemo } from "react";import { openCommandPalette } from "~/commandPaletteBus";-import { useNewThreadHandler } from "~/hooks/useHandleNewThread";import { useClientSettings } from "~/hooks/useSettings";+import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";import { selectProjectGroupingSettings } from "~/logicalProject";import {buildSidebarProjectPickerEntries,@@ -26,11 +28,13 @@ import {import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";interface DraftHeroHeadlineProps {+ readonly draftId: DraftId | null;readonly activeProjectRef: ScopedProjectRef | null;readonly activeProjectTitle: string | null;}export function DraftHeroHeadline({+ draftId,activeProjectRef,activeProjectTitle,}: DraftHeroHeadlineProps) {@@ -40,7 +44,12 @@ export function DraftHeroHeadline({const primaryEnvironmentId = usePrimaryEnvironmentId();const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);const projectSortOrder = useClientSettings((settings) => settings.sidebarProjectSortOrder);- const handleNewThread = useNewThreadHandler();+ const setLogicalProjectDraftThreadId = useComposerDraftStore(+ (store) => store.setLogicalProjectDraftThreadId,+ );+ const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);+ const applyStickyState = useComposerDraftStore((store) => store.applyStickyState);+ const setModelSelection = useComposerDraftStore((store) => store.setModelSelection);const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);const environmentLabelById = useMemo(@@ -126,12 +135,26 @@ export function DraftHeroHeadline({return;}const project = entry.targetProject;- // Changing the repo of a draft moves the typed content along:- // the user started writing in the wrong project, not a new task.- void handleNewThread(scopeProjectRef(project.environmentId, project.id), {- replace: true,- carryComposerContent: true,- });+ if (!draftId) {+ return;+ }+ // Project selection changes the target of the open draft in+ // place. The prompt stays in the same composer session, so the+ // sidebar only gets a draft row if the user later navigates away.+ const currentDraft = getComposerDraft(draftId);+ setLogicalProjectDraftThreadId(+ entry.group.projectKey,+ scopeProjectRef(project.environmentId, project.id),+ draftId,+ );+ if (!hasExplicitComposerModelSelection(currentDraft)) {+ applyStickyState(draftId);+ if (project.defaultModelSelection) {+ setModelSelection(draftId, project.defaultModelSelection, {+ replaceOptions: true,+ });+ }+ }}}>{projectPickerEntries.map(({ group }) => {diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex ac797529308..4e8e9d200bf 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -636,167 +636,6 @@ describe("composerDraftStore file attachments", () => {});});-describe("composerDraftStore moveComposerPromptAndImages", () => {- const sourceDraftId = DraftId.make("draft-move-source");- const destinationDraftId = DraftId.make("draft-move-destination");- let originalRevokeObjectUrl: typeof URL.revokeObjectURL;- let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;-- beforeEach(() => {- resetComposerDraftStore();- originalRevokeObjectUrl = URL.revokeObjectURL;- revokeSpy = vi.fn();- URL.revokeObjectURL = revokeSpy;- });-- afterEach(() => {- URL.revokeObjectURL = originalRevokeObjectUrl;- });-- it("moves prompt and images to the destination without revoking preview URLs", () => {- const store = useComposerDraftStore.getState();- store.setPrompt(sourceDraftId, "fix the login redirect");- store.addImages(sourceDraftId, [makeImage({ id: "img-move", previewUrl: "blob:move" })]);-- store.moveComposerPromptAndImages(sourceDraftId, destinationDraftId);-- expect(draftByKey(sourceDraftId)).toBeUndefined();- const destination = draftByKey(destinationDraftId);- expect(destination?.prompt).toBe("fix the login redirect");- expect(destination?.images.map((image) => image.id)).toEqual(["img-move"]);- expect(revokeSpy).not.toHaveBeenCalled();- });-- it("keeps session-bound contexts on the source and strips their placeholders from the moved prompt", () => {- const sourceThreadId = ThreadId.make("thread-move-source");- const sourceThreadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, sourceThreadId);- const store = useComposerDraftStore.getState();- store.addTerminalContext(sourceThreadRef, makeTerminalContext({ id: "ctx-stay" }));- store.setPrompt(sourceThreadRef, `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER} explain this error`);-- store.moveComposerPromptAndImages(sourceThreadRef, destinationDraftId);-- const source = draftFor(sourceThreadId, TEST_ENVIRONMENT_ID);- expect(source?.terminalContexts.map((context) => context.id)).toEqual(["ctx-stay"]);- expect(source?.prompt).toBe(INLINE_TERMINAL_CONTEXT_PLACEHOLDER);- expect(draftByKey(destinationDraftId)?.prompt).toBe(" explain this error");- });-- it("keeps hydrated file references on their original environment", () => {- const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-file-source"));- const destinationRef = scopeThreadRef(- OTHER_TEST_ENVIRONMENT_ID,- ThreadId.make("thread-file-destination"),- );- const store = useComposerDraftStore.getState();- store.setPrompt(sourceRef, "review the report");- store.addFiles(sourceRef, [- {- ...makeFile("file-hydrated"),- file: null,- uploadedAttachmentId: "pending-report-pdf",- uploadEnvironmentId: TEST_ENVIRONMENT_ID,- },- ]);-- store.moveComposerPromptAndImages(sourceRef, destinationRef);-- expect(store.getComposerDraft(sourceRef)?.files.map((file) => file.id)).toEqual([- "file-hydrated",- ]);- expect(store.getComposerDraft(destinationRef)?.files).toEqual([]);- expect(store.getComposerDraft(destinationRef)?.prompt).toBe("review the report");- });-- it("moves files across environments when the original browser file remains available", () => {- const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-file-source"));- const destinationRef = scopeThreadRef(- OTHER_TEST_ENVIRONMENT_ID,- ThreadId.make("thread-file-destination"),- );- const store = useComposerDraftStore.getState();- store.addFiles(sourceRef, [- {- ...makeFile("file-local"),- uploadedAttachmentId: "pending-source-env",- uploadEnvironmentId: TEST_ENVIRONMENT_ID,- },- ]);-- store.moveComposerPromptAndImages(sourceRef, destinationRef);-- expect(store.getComposerDraft(sourceRef)).toBeNull();- const moved = store.getComposerDraft(destinationRef)?.files;- expect(moved?.map((file) => file.id)).toEqual(["file-local"]);- // The source-environment upload is unreachable from the destination; the- // move drops it so the destination upload can mint its own.- expect(moved?.[0]?.uploadedAttachmentId).toBeUndefined();- expect(moved?.[0]?.uploadEnvironmentId).toBeUndefined();- });-- it("does not duplicate a file the destination already holds", () => {- const sourceRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("thread-dup-source"));- const destinationRef = scopeThreadRef(- TEST_ENVIRONMENT_ID,- ThreadId.make("thread-dup-destination"),- );- const store = useComposerDraftStore.getState();- // Same metadata key on both sides; the ids differ.- store.addFiles(sourceRef, [makeFile("file-copy-a")]);- store.addFiles(destinationRef, [makeFile("file-copy-b")]);-- store.moveComposerPromptAndImages(sourceRef, destinationRef);-- expect(store.getComposerDraft(destinationRef)?.files.map((file) => file.id)).toEqual([- "file-copy-b",- ]);- expect(store.getComposerDraft(sourceRef)?.files.map((file) => file.id)).toEqual([- "file-copy-a",- ]);- });-- it("keeps overflow attachments on the source when the destination is nearly full", () => {- const store = useComposerDraftStore.getState();- store.addImages(- destinationDraftId,- Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1 }, (_, index) =>- makeImage({- id: `destination-${index}`,- name: `destination-${index}.png`,- previewUrl: `blob:destination-${index}`,- }),- ),- );- store.addImages(sourceDraftId, [- makeImage({ id: "source-first", name: "first.png", previewUrl: "blob:first" }),- makeImage({ id: "source-second", name: "second.png", previewUrl: "blob:second" }),- ]);- store.addFiles(sourceDraftId, [makeFile("source-file")]);-- store.moveComposerPromptAndImages(sourceDraftId, destinationDraftId);-- expect(store.getComposerDraft(destinationDraftId)?.images).toHaveLength(- PROVIDER_SEND_TURN_MAX_ATTACHMENTS,- );- expect(store.getComposerDraft(destinationDraftId)?.files).toEqual([]);- expect(store.getComposerDraft(sourceDraftId)?.images.map((image) => image.id)).toEqual([- "source-second",- ]);- expect(store.getComposerDraft(sourceDraftId)?.files.map((file) => file.id)).toEqual([- "source-file",- ]);- });-- it("is a no-op when source and destination are the same target", () => {- const store = useComposerDraftStore.getState();- store.setPrompt(sourceDraftId, "keep me");-- store.moveComposerPromptAndImages(sourceDraftId, sourceDraftId);-- expect(draftByKey(sourceDraftId)?.prompt).toBe("keep me");- });-});-describe("composerDraftStore syncPersistedAttachments", () => {const threadId = ThreadId.make("thread-sync-persisted");const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId);@@ -1275,6 +1114,18 @@ describe("composerDraftStore project draft thread mapping", () => {});});+ it("removes a draft's previous project mapping when retargeted in place", () => {+ const store = useComposerDraftStore.getState();+ store.setProjectDraftThreadId(projectRef, draftId, { threadId });+ store.setPrompt(draftId, "keep this prompt");++ store.setProjectDraftThreadId(otherProjectRef, draftId, { threadId });++ expect(store.getDraftThreadByProjectRef(projectRef)).toBeNull();+ expect(store.getDraftThreadByProjectRef(otherProjectRef)?.draftId).toBe(draftId);+ expect(store.getComposerDraft(draftId)?.prompt).toBe("keep this prompt");+ });+it("rotates a failed bootstrap thread id without losing its draft", () => {const store = useComposerDraftStore.getState();const retryThreadId = ThreadId.make("thread-retry");@@ -1704,6 +1555,30 @@ describe("composerDraftStore project draft thread mapping", () => {});});+ it("clears stale upload metadata when retargeting a draft to another environment", () => {+ const store = useComposerDraftStore.getState();+ const hydratedFile: ComposerFileAttachment = {+ ...makeFile("file-cross-environment"),+ file: null,+ uploadedAttachmentId: "local-environment-upload",+ uploadEnvironmentId: TEST_ENVIRONMENT_ID,+ };++ store.setProjectDraftThreadId(projectRef, draftId, { threadId });+ store.addFiles(draftId, [hydratedFile]);++ store.setProjectDraftThreadId(remoteProjectRef, draftId, { threadId });++ const file = store.getComposerDraft(draftId)?.files[0];+ expect(file).toMatchObject({+ id: hydratedFile.id,+ file: null,+ });+ expect(file?.uploadedAttachmentId).toBeUndefined();+ expect(file?.uploadEnvironmentId).toBeUndefined();+ expect(file && composerFileNeedsReattach(file)).toBe(true);+ });+it("clears branch and worktree but keeps env mode when changing a draft thread project ref", () => {const store = useComposerDraftStore.getState();store.setProjectDraftThreadId(projectRef, draftId, {diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.tsindex 886c89071d1..fe1dab19976 100644--- a/apps/web/src/composerDraftStore.ts+++ b/apps/web/src/composerDraftStore.ts@@ -45,7 +45,6 @@ import {type TerminalContextDraft,ensureInlineTerminalContextPlaceholders,normalizeTerminalContextText,- stripInlineTerminalContextPlaceholders,} from "./lib/terminalContext";import {type ElementContextDraft,@@ -116,6 +115,29 @@ export function composerFileNeedsReattach(file: ComposerFileAttachment): booleanreturn file.file === null && file.uploadedAttachmentId === undefined;}+function clearStaleFileUploadMetadata(+ draft: ComposerThreadDraftState,+ environmentId: EnvironmentId,+): ComposerThreadDraftState {+ let changed = false;+ const files = draft.files.map((file) => {+ if (+ (file.uploadedAttachmentId === undefined && file.uploadEnvironmentId === undefined) ||+ file.uploadEnvironmentId === environmentId+ ) {+ return file;+ }++ changed = true;+ const nextFile = { ...file };+ delete nextFile.uploadedAttachmentId;+ delete nextFile.uploadEnvironmentId;+ return nextFile;+ });++ return changed ? { ...draft, files } : draft;+}+export const PersistedComposerFileAttachment = Schema.Struct({id: Schema.String,name: Schema.String,@@ -435,7 +457,11 @@ interface ComposerDraftStoreState {getDraftThread: (threadRef: ComposerThreadTarget) => DraftThreadState | null;listDraftThreadKeys: () => string[];hasDraftThreadsInEnvironment: (environmentId: EnvironmentId) => boolean;- /** Creates or updates the draft session tracked for a logical project. */+ /**+ * Creates or updates the draft session tracked for a logical project.+ * Reassigning an existing draft removes its previous logical-project+ * mapping so one session cannot resolve from two projects.+ */setLogicalProjectDraftThreadId: (logicalProjectKey: string,projectRef: ScopedProjectRef,@@ -606,13 +632,6 @@ interface ComposerDraftStoreState {* prompt stash. Session-bound context stays in the source draft.*/clearComposerPromptAndImages: (threadRef: ComposerThreadTarget) => void;- /**- * Moves prompt text and transferable attachments into another composer.- * Attachments over the destination limit and uploaded files that belong to- * another environment stay in the source draft. Terminal and element- * context, preview annotations, and review comments also stay in the source.- */- moveComposerPromptAndImages: (from: ComposerThreadTarget, to: ComposerThreadTarget) => void;}export interface EffectiveComposerModelState {@@ -2515,18 +2534,53 @@ const composerDraftStore = create<ComposerDraftStoreState>()(options,);const hasSameLogicalMapping = previousThreadKeyForLogicalProject === draftId;- if (hasSameLogicalMapping && draftThreadsEqual(existingThread, nextDraftThread)) {+ const hasNoStaleMappingsForDraft = Object.entries(+ state.logicalProjectDraftThreadKeyByLogicalProjectKey,+ ).every(+ ([logicalKey, mappedDraftId]) =>+ mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,+ );+ if (+ hasSameLogicalMapping &&+ hasNoStaleMappingsForDraft &&+ draftThreadsEqual(existingThread, nextDraftThread)+ ) {return state;}- const nextLogicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> = {- ...state.logicalProjectDraftThreadKeyByLogicalProjectKey,- [normalizedLogicalProjectKey]: draftId,- };+ // A draft session belongs to one logical project at a time. When+ // an open draft is retargeted in place, remove any old mapping+ // for that same draft so the previous project cannot resolve it.+ const nextLogicalProjectDraftThreadKeyByLogicalProjectKey: Record<string, string> =+ Object.fromEntries(+ Object.entries(state.logicalProjectDraftThreadKeyByLogicalProjectKey).filter(+ ([logicalKey, mappedDraftId]) =>+ mappedDraftId !== draftId || logicalKey === normalizedLogicalProjectKey,+ ),+ );+ nextLogicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey] =+ draftId;const nextDraftThreadsByThreadKey: Record<string, DraftThreadState> = {...state.draftThreadsByThreadKey,[draftId]: nextDraftThread,};+ const existingDraft = state.draftsByThreadKey[draftId];let nextDraftsByThreadKey = state.draftsByThreadKey;+ if (+ existingThread &&+ existingThread.environmentId !== projectRef.environmentId &&+ existingDraft !== undefined+ ) {+ const nextDraft = clearStaleFileUploadMetadata(+ existingDraft,+ projectRef.environmentId,+ );+ if (nextDraft !== existingDraft) {+ nextDraftsByThreadKey = {+ ...state.draftsByThreadKey,+ [draftId]: nextDraft,+ };+ }+ }const previousDraftThread =previousThreadKeyForLogicalProject === undefined? undefined@@ -2550,7 +2604,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()() {delete nextDraftThreadsByThreadKey[previousThreadKeyForLogicalProject];if (state.draftsByThreadKey[previousThreadKeyForLogicalProject] !== undefined) {- nextDraftsByThreadKey = { ...state.draftsByThreadKey };+ nextDraftsByThreadKey = { ...nextDraftsByThreadKey };delete nextDraftsByThreadKey[previousThreadKeyForLogicalProject];}}@@ -3805,117 +3859,6 @@ const composerDraftStore = create<ComposerDraftStoreState>()(return { draftsByThreadKey: nextDraftsByThreadKey };});},- moveComposerPromptAndImages: (from, to) => {- const fromKey = resolveComposerDraftKey(get(), from) ?? "";- const toKey = resolveComposerDraftKey(get(), to) ?? "";- if (fromKey.length === 0 || toKey.length === 0 || fromKey === toKey) {- return;- }- set((state) => {- const source = state.draftsByThreadKey[fromKey];- if (!source) {- return state;- }- const destination = state.draftsByThreadKey[toKey] ?? createEmptyThreadDraft();- const destinationEnvironmentId =- typeof to === "string"- ? (state.draftThreadsByThreadKey[toKey]?.environmentId ??- parseScopedThreadKey(toKey)?.environmentId ??- null)- : to.environmentId;- // A file the destination already holds (same id, or same- // metadata key) stays behind instead of duplicating there.- const destinationFileIds = new Set(destination.files.map((file) => file.id));- const destinationFileKeys = new Set(destination.files.map(composerFileDedupKey));- const transferableFiles = source.files.filter(- (file) =>- (file.file !== null || file.uploadEnvironmentId === destinationEnvironmentId) &&- !destinationFileIds.has(file.id) &&- !destinationFileKeys.has(composerFileDedupKey(file)),- );- const remainingAttachmentSlots = Math.max(- 0,- PROVIDER_SEND_TURN_MAX_ATTACHMENTS -- destination.images.length -- destination.files.length,- );- const movedImages = source.images.slice(0, remainingAttachmentSlots);- const movedImageIds = new Set(movedImages.map((image) => image.id));- const retainedImages = source.images.filter((image) => !movedImageIds.has(image.id));- const movedFiles = transferableFiles- .slice(0, remainingAttachmentSlots - movedImages.length)- .map((file) => {- // A byte-backed file moving across environments re-uploads at- // the destination. Keeping the source-environment upload id- // would mark it uploaded after a reload with no local bytes- // and no valid upload anywhere the destination can reach. The- // upload queue keeps the source upload as fallback, then- // deletes it after the destination upload succeeds. Abandoned- // uploads still expire through the server sweep.- if (- file.file === null ||- file.uploadEnvironmentId === undefined ||- file.uploadEnvironmentId === destinationEnvironmentId- ) {- return file;- }- const { uploadedAttachmentId: _a, uploadEnvironmentId: _e, ...rest } = file;- return rest;- });- const movedFileIds = new Set(movedFiles.map((file) => file.id));- const retainedFiles = source.files.filter((file) => !movedFileIds.has(file.id));- // Inline placeholders reference the source's terminal contexts,- // which stay behind; re-anchor the moved prompt to whatever- // contexts the destination already holds.- const movedPrompt = ensureInlineTerminalContextPlaceholders(- stripInlineTerminalContextPlaceholders(source.prompt),- destination.terminalContexts.length,- );- const nextDestination: ComposerThreadDraftState = {- ...destination,- prompt: movedPrompt,- images: [...destination.images, ...movedImages],- files: [...destination.files, ...movedFiles],- nonPersistedImageIds: [- ...destination.nonPersistedImageIds,- ...source.nonPersistedImageIds.filter((imageId) => movedImageIds.has(imageId)),- ],- persistedAttachments: [- ...destination.persistedAttachments,- ...source.persistedAttachments.filter((attachment) =>- movedImageIds.has(attachment.id),- ),- ],- };- // Same clearing shape as clearComposerPromptAndImages, but the- // preview URLs are NOT revoked: the images moved and their blobs- // are still referenced from the destination.- const nextSource: ComposerThreadDraftState = {- ...source,- prompt: ensureInlineTerminalContextPlaceholders("", source.terminalContexts.length),- images: retainedImages,- files: retainedFiles,- nonPersistedImageIds: source.nonPersistedImageIds.filter(- (imageId) => !movedImageIds.has(imageId),- ),- persistedAttachments: source.persistedAttachments.filter(- (attachment) => !movedImageIds.has(attachment.id),- ),- };- const nextDraftsByThreadKey = { ...state.draftsByThreadKey };- if (shouldRemoveDraft(nextSource)) {- delete nextDraftsByThreadKey[fromKey];- } else {- nextDraftsByThreadKey[fromKey] = nextSource;- }- if (shouldRemoveDraft(nextDestination)) {- delete nextDraftsByThreadKey[toKey];- } else {- nextDraftsByThreadKey[toKey] = nextDestination;- }- return { draftsByThreadKey: nextDraftsByThreadKey };- });- },};},{diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.tsindex 78e17a76b37..438cda84c62 100644--- a/apps/web/src/hooks/useHandleNewThread.ts+++ b/apps/web/src/hooks/useHandleNewThread.ts@@ -25,6 +25,7 @@ import {import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";import { readThreadShell, useProjects, useThread } from "../state/entities";import {+ hasExplicitComposerModelSelection,resolveNewDraftStartFromOrigin,resolveNewThreadModelSelectionOverride,} from "../lib/chatThreadActions";@@ -33,7 +34,6 @@ import { primaryServerSettingsAtom } from "../state/server";import { resolveThreadRouteTarget } from "../threadRoutes";import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";import { useClientSettings } from "./useSettings";-import { toastManager } from "../components/ui/toast";interface NewThreadWorkspaceOptions {branch?: string | null;@@ -78,14 +78,6 @@ export function useNewThreadHandler() {envMode?: DraftThreadEnvMode;startFromOrigin?: boolean;replace?: boolean;- /**- * Move the viewed draft's typed content and transferable attachments into the- * draft this request lands on. Set by the draft repo picker: the- * user started writing in the wrong project and the text should- * follow them. Explicit new-thread surfaces leave this unset and- * keep mint-fresh semantics.- */- carryComposerContent?: boolean;},// Which draft the thread ended up in, so a caller that has something to put in it — a// prepared checkout, a task to write — addresses that one rather than looking the project@@ -97,7 +89,6 @@ export function useNewThreadHandler() {getDraftSession,getDraftThread,applyStickyState,- moveComposerPromptAndImages,setDraftThreadContext,setLogicalProjectDraftThreadId,setModelSelection,@@ -138,39 +129,6 @@ export function useNewThreadHandler() {carrySourceShell?.interactionMode ??carrySourceDraft?.interactionMode ??null;- // Content only moves when the caller opted in and the user is looking- // at a draft. The content check happens at move time, not here: the- // paths below await, and text typed during those awaits must still- // come along.- const carryContentSourceDraftId =- options?.carryComposerContent === true && currentRouteTarget?.kind === "draft"- ? currentRouteTarget.draftId- : null;- const carryComposerContentTo = (destinationDraftId: DraftId) => {- if (- carryContentSourceDraftId &&- carryContentSourceDraftId !== destinationDraftId &&- // Never clobber a destination the user already invested in — the- // move overwrites the destination prompt, so a concurrent repo- // change that carried content first must win.- !composerDraftHasUserContent(getComposerDraft(destinationDraftId)) &&- composerDraftHasUserContent(getComposerDraft(carryContentSourceDraftId))- ) {- moveComposerPromptAndImages(carryContentSourceDraftId, destinationDraftId);- // The move caps at the destination's free slots and skips- // duplicates, so images and files can both stay behind.- const remainingDraft = getComposerDraft(carryContentSourceDraftId);- const remainingCount =- (remainingDraft?.files.length ?? 0) + (remainingDraft?.images.length ?? 0);- if (remainingCount > 0) {- toastManager.add({- type: "warning",- title: `${remainingCount} attachment${remainingCount === 1 ? " stayed" : "s stayed"} in the original draft`,- description: "Return to the original draft or attach the files again.",- });- }- }- };const project = projects.find((candidate) =>candidate.id === projectRef.projectId &&@@ -310,11 +268,7 @@ export function useNewThreadHandler() {// is looking at, because explicit picks are the only thing the// flag protects.const storedDraft = getComposerDraft(emptyStoredDraftThread.draftId);- const storedActiveSelection = storedDraft?.activeProvider- ? storedDraft.modelSelectionByProvider[storedDraft.activeProvider]- : undefined;- const storedDraftHasExplicitModelPick =- Boolean(storedActiveSelection) && storedDraft?.modelSelectionExplicit === true;+ const storedDraftHasExplicitModelPick = hasExplicitComposerModelSelection(storedDraft);if (!storedDraftHasExplicitModelPick) {applyStickyState(emptyStoredDraftThread.draftId);const modelSelectionOverride = resolveModelSelectionOverride(@@ -343,7 +297,6 @@ export function useNewThreadHandler() {...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),},);- carryComposerContentTo(emptyStoredDraftThread.draftId);const opened = {draftId: emptyStoredDraftThread.draftId,threadId: emptyStoredDraftThread.threadId,@@ -431,7 +384,6 @@ export function useNewThreadHandler() {interactionMode: racedDraft.interactionMode,...pickExplicitWorkspaceOptions(options),});- carryComposerContentTo(racedDraft.draftId);await router.navigate({to: "/draft/$draftId",params: { draftId: racedDraft.draftId },@@ -461,8 +413,6 @@ export function useNewThreadHandler() {// state. The project default wins when both are present.setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true });}- carryComposerContentTo(draftId);-await router.navigate({to: "/draft/$draftId",params: { draftId },diff --git a/apps/web/src/lib/attachmentUploadQueue.test.ts b/apps/web/src/lib/attachmentUploadQueue.test.tsindex 9f754baf500..d7b30e452aa 100644--- a/apps/web/src/lib/attachmentUploadQueue.test.ts+++ b/apps/web/src/lib/attachmentUploadQueue.test.ts@@ -1,5 +1,4 @@-import { scopeThreadRef } from "@t3tools/client-runtime/environment";-import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { EnvironmentId } from "@t3tools/contracts";import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import {@@ -326,83 +325,6 @@ describe("attachmentUploadQueue", () => {}});- it("persists a pending upload on the same-environment draft that receives its file", async () => {- const source = scopeThreadRef(firstEnvironment, ThreadId.make("thread-background-move-source"));- const destination = scopeThreadRef(- firstEnvironment,- ThreadId.make("thread-background-move-destination"),- );- const file = makeFile("background-move");- const store = useComposerDraftStore.getState();- store.addFiles(source, [file]);-- try {- startAttachmentUpload({- environmentId: firstEnvironment,- image: file,- draftTarget: source,- });- await Promise.resolve();- store.moveComposerPromptAndImages(source, destination);- const sourceAfterMove = store.getComposerDraft(source);-- // The destination never starts the existing job again. Its completion- // must find the file in current store state instead of the captured row.- const settled = awaitAttachmentUploads([file.id]);- TestXmlHttpRequest.requests[0]!.complete();- await settled;-- expect(store.getComposerDraft(source)).toEqual(sourceAfterMove);- expect(store.getComposerDraft(destination)?.files).toMatchObject([- {- id: file.id,- uploadedAttachmentId: "pending-environment-1-background-move.pdf",- uploadEnvironmentId: firstEnvironment,- },- ]);- } finally {- store.clearComposerContent(source);- store.clearComposerContent(destination);- }- });-- it("does not stamp an old-environment upload after its file moves environments", async () => {- const source = scopeThreadRef(- firstEnvironment,- ThreadId.make("thread-cross-environment-source"),- );- const destination = scopeThreadRef(- secondEnvironment,- ThreadId.make("thread-cross-environment-destination"),- );- const file = makeFile("cross-environment-move");- const store = useComposerDraftStore.getState();- store.addFiles(source, [file]);-- try {- startAttachmentUpload({- environmentId: firstEnvironment,- image: file,- draftTarget: source,- });- await Promise.resolve();- store.moveComposerPromptAndImages(source, destination);-- const settled = awaitAttachmentUploads([file.id]);- TestXmlHttpRequest.requests[0]!.complete();- await settled;-- expect(store.getComposerDraft(source)).toBeNull();- const movedFile = store.getComposerDraft(destination)?.files[0];- expect(movedFile?.id).toBe(file.id);- expect(movedFile?.uploadedAttachmentId).toBeUndefined();- expect(movedFile?.uploadEnvironmentId).toBeUndefined();- } finally {- store.clearComposerContent(source);- store.clearComposerContent(destination);- }- });-it("verifies an uploaded file reference before restoring it", async () => {const file: ComposerFileAttachment = {...makeFile("restored"),@@ -849,90 +771,6 @@ describe("attachmentUploadQueue", () => {});});- it("releases a moved file's source upload only after its destination upload succeeds", async () => {- const source = scopeThreadRef(firstEnvironment, ThreadId.make("thread-file-move-source"));- const destination = scopeThreadRef(- secondEnvironment,- ThreadId.make("thread-file-move-destination"),- );- const file = makeFile("moved-report");- const store = useComposerDraftStore.getState();- store.addFiles(source, [file]);-- try {- startAttachmentUpload({- environmentId: firstEnvironment,- image: file,- draftTarget: source,- });- await Promise.resolve();- let settled = awaitAttachmentUploads([file.id]);- TestXmlHttpRequest.requests[0]!.complete();- await settled;-- const sourceAttachmentId = store.getComposerDraft(source)?.files[0]?.uploadedAttachmentId;- expect(sourceAttachmentId).toBe("pending-environment-1-moved-report.pdf");-- store.moveComposerPromptAndImages(source, destination);- const movedFile = store.getComposerDraft(destination)?.files[0];- expect(movedFile).toMatchObject({- id: file.id,- file: file.file,- });- expect(movedFile?.uploadedAttachmentId).toBeUndefined();- expect(movedFile?.uploadEnvironmentId).toBeUndefined();-- startAttachmentUpload({- environmentId: secondEnvironment,- image: movedFile!,- draftTarget: destination,- });- await Promise.resolve();-- const sourceDeletesBeforeDestinationUpload = mocks.runAtomCommand.mock.calls.filter(- ([, command, target]) =>- command === mocks.removeUpload &&- (- target as {- readonly environmentId: EnvironmentId;- readonly input: { readonly attachmentId: string };- }- ).environmentId === firstEnvironment &&- (target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===- sourceAttachmentId,- );- expect(sourceDeletesBeforeDestinationUpload).toEqual([]);-- settled = awaitAttachmentUploads([file.id]);- TestXmlHttpRequest.requests[1]!.complete();- await settled;-- const sourceDeletesAfterDestinationUpload = mocks.runAtomCommand.mock.calls.filter(- ([, command, target]) =>- command === mocks.removeUpload &&- (- target as {- readonly environmentId: EnvironmentId;- readonly input: { readonly attachmentId: string };- }- ).environmentId === firstEnvironment &&- (target as { readonly input: { readonly attachmentId: string } }).input.attachmentId ===- sourceAttachmentId,- );- expect(sourceDeletesAfterDestinationUpload).toHaveLength(1);- expect(store.getComposerDraft(destination)?.files).toMatchObject([- {- id: file.id,- uploadedAttachmentId: "pending-environment-2-moved-report.pdf",- uploadEnvironmentId: secondEnvironment,- },- ]);- } finally {- store.clearComposerContent(source);- store.clearComposerContent(destination);- }- });-it("does not let stalled uploads block another environment", async () => {const images = ["image-a", "image-b", "image-c", "image-d"].map(makeImage);for (const image of images) {diff --git a/apps/web/src/lib/chatThreadActions.test.ts b/apps/web/src/lib/chatThreadActions.test.tsindex ee555231e43..c145404a74e 100644--- a/apps/web/src/lib/chatThreadActions.test.ts+++ b/apps/web/src/lib/chatThreadActions.test.ts@@ -8,6 +8,7 @@ import {import { describe, expect, it, vi } from "vite-plus/test";import {resolveThreadActionProjectRef,+ hasExplicitComposerModelSelection,resolveNewDraftStartFromOrigin,resolveNewThreadModelSelectionOverride,startNewThreadFromContext,@@ -37,6 +38,22 @@ function createContext(overrides: Partial<ChatThreadActionContext> = {}): ChatTh}describe("chatThreadActions", () => {+ it("only treats an active stored selection marked explicit as an explicit pick", () => {+ const draft = {+ activeProvider: PROJECT_DEFAULT_SELECTION.instanceId,+ modelSelectionByProvider: {+ [PROJECT_DEFAULT_SELECTION.instanceId]: PROJECT_DEFAULT_SELECTION,+ },+ modelSelectionExplicit: true,+ };++ expect(hasExplicitComposerModelSelection(draft)).toBe(true);+ expect(hasExplicitComposerModelSelection({ ...draft, modelSelectionExplicit: false })).toBe(+ false,+ );+ expect(hasExplicitComposerModelSelection({ ...draft, activeProvider: null })).toBe(false);+ });+it("does not carry a non-explicit model from the destination draft back into itself", () => {expect(resolveNewThreadModelSelectionOverride({diff --git a/apps/web/src/lib/chatThreadActions.ts b/apps/web/src/lib/chatThreadActions.tsindex 4336fa5a825..c14a26d03d1 100644--- a/apps/web/src/lib/chatThreadActions.ts+++ b/apps/web/src/lib/chatThreadActions.ts@@ -5,7 +5,12 @@ import type {ProjectId,ScopedProjectRef,} from "@t3tools/contracts";-import type { DraftThreadEnvMode } from "../composerDraftStore";+import type { ComposerThreadDraftState, DraftThreadEnvMode } from "../composerDraftStore";++type ComposerModelSelectionState = Pick<+ ComposerThreadDraftState,+ "activeProvider" | "modelSelectionByProvider" | "modelSelectionExplicit"+>;interface ThreadContextLike {environmentId: EnvironmentId;@@ -51,6 +56,18 @@ export function resolveNewThreadModelSelectionOverride(input: {);}+export function hasExplicitComposerModelSelection(+ draft: ComposerModelSelectionState | null | undefined,+): boolean {+ const activeProvider = draft?.activeProvider;+ return (+ draft?.modelSelectionExplicit === true &&+ activeProvider !== null &&+ activeProvider !== undefined &&+ draft.modelSelectionByProvider[activeProvider] !== undefined+ );+}+export function resolveThreadActionProjectRef(context: ChatThreadActionContext,): ScopedProjectRef | null {