Skip to content

Commit 4bbe134

Browse files
committed
fix(web): keep thread references on their machine
1 parent 468ade3 commit 4bbe134

5 files changed

Lines changed: 167 additions & 2 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@ import {
393393
previewAnnotationContextReference,
394394
reviewCommentContextLabel,
395395
terminalContextReference,
396+
threadContextsBelongToEnvironment,
396397
} from "../lib/composerContextRecords";
397398
import { type ReviewCommentContext } from "../reviewCommentContext";
398399
import { environmentCatalog } from "../connection/catalog";
@@ -1800,6 +1801,9 @@ export default function ChatView(props: ChatViewProps) {
18001801
const draft = store.getComposerDraft(composerDraftTarget);
18011802
return (draft?.images.length ?? 0) > 0 || (draft?.files.length ?? 0) > 0;
18021803
});
1804+
const composerHasThreadContexts = useComposerDraftStore(
1805+
(store) => (store.getComposerDraft(composerDraftTarget)?.threadContexts.length ?? 0) > 0,
1806+
);
18031807
// Anything beyond the prompt text: attachments, terminal or element contexts, annotations.
18041808
const composerHasNonPromptContent = useComposerDraftStore((store) => {
18051809
const draft = store.getComposerDraft(composerDraftTarget);
@@ -2851,7 +2855,14 @@ export default function ChatView(props: ChatViewProps) {
28512855
projectGroupingSettings,
28522856
);
28532857
const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);
2854-
if (storedDraftSession) {
2858+
if (
2859+
storedDraftSession &&
2860+
threadContextsBelongToEnvironment(
2861+
useComposerDraftStore.getState().getComposerDraft(storedDraftSession.draftId)
2862+
?.threadContexts ?? [],
2863+
activeProjectRef.environmentId,
2864+
)
2865+
) {
28552866
setDraftThreadContext(storedDraftSession.draftId, input);
28562867
setLogicalProjectDraftThreadId(
28572868
logicalProjectKey,
@@ -3036,6 +3047,7 @@ export default function ChatView(props: ChatViewProps) {
30363047
canAutoBalanceEnvironments &&
30373048
loadBalancingSettings.loadBalancingEnabled &&
30383049
draftThread?.environmentSelection !== "manual" &&
3050+
!composerHasThreadContexts &&
30393051
(!composerHasAttachments || Boolean(draftThread?.loadBalancedEnvironmentId)) &&
30403052
(!draftThread?.branch || draftThread.environmentSelection === "auto") &&
30413053
!draftThread?.worktreePath,
@@ -4387,6 +4399,14 @@ export default function ChatView(props: ChatViewProps) {
43874399
]);
43884400
const onAutoEnvironment = useCallback(() => {
43894401
if (envLocked || !draftId) return;
4402+
if (useComposerDraftStore.getState().getComposerDraft(draftId)?.threadContexts.length) {
4403+
toastManager.add({
4404+
type: "warning",
4405+
title: "Keep thread references on this machine",
4406+
description: "Remove thread references before choosing automatic routing.",
4407+
});
4408+
return;
4409+
}
43904410
if (composerHasAttachments) {
43914411
toastManager.add({
43924412
type: "warning",
@@ -4443,6 +4463,22 @@ export default function ChatView(props: ChatViewProps) {
44434463
(env) => env.environmentId === nextEnvironmentId,
44444464
);
44454465
if (!target) return;
4466+
const referencesAllowTarget = () => {
4467+
if (
4468+
threadContextsBelongToEnvironment(
4469+
useComposerDraftStore.getState().getComposerDraft(draftId)?.threadContexts ?? [],
4470+
target.environmentId,
4471+
)
4472+
)
4473+
return true;
4474+
toastManager.add({
4475+
type: "warning",
4476+
title: "Keep thread references on their machine",
4477+
description: "Remove thread references before switching to another machine.",
4478+
});
4479+
return false;
4480+
};
4481+
if (!referencesAllowTarget()) return;
44464482
const request = { environmentId: target.environmentId };
44474483
environmentChangeRef.current = request;
44484484
setIsEnvironmentChanging(false);
@@ -4457,6 +4493,7 @@ export default function ChatView(props: ChatViewProps) {
44574493
currentDraft.projectId !== originalDraft.projectId
44584494
)
44594495
return;
4496+
if (!referencesAllowTarget()) return;
44604497
const projectRef = scopeProjectRef(target.environmentId, project.id);
44614498
if (activeProjectIsScratch) {
44624499
// Scratch projects are machine-local, so move their logical mapping too.
@@ -8739,6 +8776,15 @@ export default function ChatView(props: ChatViewProps) {
87398776
notifyDirectAnnotationAttached();
87408777
return;
87418778
}
8779+
if (!threadContextsBelongToEnvironment(sendCtx.threadContexts, environmentId)) {
8780+
toastManager.add({
8781+
type: "warning",
8782+
title: "Thread references are on another machine",
8783+
description:
8784+
"Choose the machine that owns these threads, or remove their references before sending.",
8785+
});
8786+
return;
8787+
}
87428788
const multipleModelSelections = sendCtx.multipleModelSelections;
87438789
if (
87448790
multipleModelSelections !== null &&

‎apps/web/src/components/chat/DraftHeroHeadline.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { primaryServerKeybindingsAtom } from "~/state/server";
1414
import { useScratchProject } from "~/hooks/useScratchProject";
1515
import { useClientSettings } from "~/hooks/useSettings";
1616
import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
17+
import { threadContextsBelongToEnvironment } from "~/lib/composerContextRecords";
1718
import {
1819
deriveLogicalProjectKeyFromSettings,
1920
selectProjectGroupingSettings,
@@ -40,6 +41,7 @@ import {
4041
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
4142
import { InlineButton } from "../ui/button";
4243
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
44+
import { toastManager } from "../ui/toast";
4345

4446
// Menu value for "No project"; real entries are keyed by logical project key.
4547
const NO_PROJECT_VALUE = "no-project";
@@ -179,12 +181,22 @@ export function DraftHeroHeadline({
179181
if (!draftId) {
180182
return;
181183
}
184+
const currentDraft = getComposerDraft(draftId);
185+
if (
186+
!threadContextsBelongToEnvironment(currentDraft?.threadContexts ?? [], project.environmentId)
187+
) {
188+
toastManager.add({
189+
type: "warning",
190+
title: "Keep thread references on their machine",
191+
description: "Remove thread references before switching to another machine.",
192+
});
193+
return;
194+
}
182195
latestTargetRef.current = {
183196
draftId,
184197
activeProjectKey: logicalProjectKey,
185198
scratchTargetEnvironmentId: project.environmentId,
186199
};
187-
const currentDraft = getComposerDraft(draftId);
188200
setLogicalProjectDraftThreadId(
189201
logicalProjectKey,
190202
scopeProjectRef(project.environmentId, project.id),

‎apps/web/src/composerDraftStore.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1879,6 +1879,86 @@ describe("composerDraftStore project draft thread mapping", () => {
18791879
expect(store.getComposerDraft(draftId)?.prompt).toBe("keep this prompt");
18801880
});
18811881

1882+
it.each(["manual", "auto"] as const)(
1883+
"keeps referenced threads readable during %s machine selection, including stale selections",
1884+
(environmentSelection) => {
1885+
const store = useComposerDraftStore.getState();
1886+
const reference = threadContextRecord(
1887+
scopeThreadRef(TEST_ENVIRONMENT_ID, otherThreadId),
1888+
"Reference conversation",
1889+
);
1890+
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
1891+
store.setPrompt(draftId, "Use this context");
1892+
store.addThreadContexts(draftId, [reference]);
1893+
const before = useComposerDraftStore.getState();
1894+
1895+
store.setDraftThreadContext(draftId, {
1896+
projectRef: remoteProjectRef,
1897+
environmentSelection,
1898+
loadBalancedEnvironmentId:
1899+
environmentSelection === "auto" ? OTHER_TEST_ENVIRONMENT_ID : null,
1900+
});
1901+
1902+
expect(store.getDraftThread(draftId)).toEqual(before.draftThreadsByThreadKey[draftId]);
1903+
expect(store.getComposerDraft(draftId)).toEqual(before.draftsByThreadKey[draftId]);
1904+
1905+
store.setThreadContexts(draftId, []);
1906+
store.setDraftThreadContext(draftId, { projectRef: remoteProjectRef });
1907+
expect(store.getDraftThread(draftId)?.environmentId).toBe(OTHER_TEST_ENVIRONMENT_ID);
1908+
expect(store.getComposerDraft(draftId)?.prompt).toBe("Use this context");
1909+
},
1910+
);
1911+
1912+
it("protects referenced threads when a logical project or Scratch draft is remapped", () => {
1913+
const store = useComposerDraftStore.getState();
1914+
const reference = threadContextRecord(
1915+
scopeThreadRef(TEST_ENVIRONMENT_ID, otherThreadId),
1916+
"Reference conversation",
1917+
);
1918+
store.setLogicalProjectDraftThreadId("scratch-local", projectRef, draftId, { threadId });
1919+
store.addThreadContexts(draftId, [reference]);
1920+
const before = useComposerDraftStore.getState();
1921+
1922+
store.setLogicalProjectDraftThreadId("scratch-remote", remoteProjectRef, draftId);
1923+
1924+
expect(useComposerDraftStore.getState()).toBe(before);
1925+
expect(store.getDraftSessionByLogicalProjectKey("scratch-local")?.draftId).toBe(draftId);
1926+
expect(store.getDraftSessionByLogicalProjectKey("scratch-remote")).toBeNull();
1927+
1928+
store.setLogicalProjectDraftThreadId("scratch-local", otherProjectRef, draftId);
1929+
expect(store.getDraftThread(draftId)?.projectId).toBe(otherProjectId);
1930+
expect(store.getComposerDraft(draftId)?.threadContexts).toEqual([reference]);
1931+
1932+
store.setThreadContexts(draftId, []);
1933+
store.setLogicalProjectDraftThreadId("scratch-remote", remoteProjectRef, draftId);
1934+
expect(store.getDraftThread(draftId)?.environmentId).toBe(OTHER_TEST_ENVIRONMENT_ID);
1935+
expect(store.getDraftSessionByLogicalProjectKey("scratch-local")).toBeNull();
1936+
});
1937+
1938+
it("can return a persisted mismatched reference to its source machine", () => {
1939+
const store = useComposerDraftStore.getState();
1940+
const reference = threadContextRecord(
1941+
scopeThreadRef(TEST_ENVIRONMENT_ID, otherThreadId),
1942+
"Reference conversation",
1943+
);
1944+
store.setProjectDraftThreadId(remoteProjectRef, draftId, { threadId });
1945+
store.addThreadContexts(draftId, [reference]);
1946+
const merge = useComposerDraftStore.persist.getOptions().merge!;
1947+
useComposerDraftStore.setState(
1948+
merge(
1949+
JSON.parse(
1950+
JSON.stringify(partializeComposerDraftStoreState(useComposerDraftStore.getState())),
1951+
),
1952+
useComposerDraftStore.getInitialState(),
1953+
),
1954+
);
1955+
1956+
store.setDraftThreadContext(draftId, { projectRef });
1957+
1958+
expect(store.getDraftThread(draftId)?.environmentId).toBe(TEST_ENVIRONMENT_ID);
1959+
expect(store.getComposerDraft(draftId)?.threadContexts).toEqual([reference]);
1960+
});
1961+
18821962
it("clears branch and worktree but keeps env mode when changing a draft thread project ref", () => {
18831963
const store = useComposerDraftStore.getState();
18841964
store.setProjectDraftThreadId(projectRef, draftId, {

‎apps/web/src/composerDraftStore.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ import {
7070
reviewCommentContextReference,
7171
terminalContextReference,
7272
threadContextReference,
73+
threadContextsBelongToEnvironment,
7374
} from "./lib/composerContextRecords";
7475
import { create } from "zustand";
7576
import { persist, type PersistStorage, type StorageValue } from "zustand/middleware";
@@ -2716,6 +2717,15 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
27162717
}
27172718
set((state) => {
27182719
const existingThread = state.draftThreadsByThreadKey[draftId];
2720+
if (
2721+
existingThread?.environmentId !== projectRef.environmentId &&
2722+
!threadContextsBelongToEnvironment(
2723+
state.draftsByThreadKey[draftId]?.threadContexts ?? EMPTY_THREAD_CONTEXTS,
2724+
projectRef.environmentId,
2725+
)
2726+
) {
2727+
return state;
2728+
}
27192729
const previousThreadKeyForLogicalProject =
27202730
state.logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
27212731
const nextDraftThread = createDraftThreadState(
@@ -2830,6 +2840,16 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
28302840
environmentId: existing.environmentId,
28312841
projectId: existing.projectId,
28322842
};
2843+
// Resource checks and Scratch creation can finish after a reference was attached.
2844+
if (
2845+
nextProjectRef.environmentId !== existing.environmentId &&
2846+
!threadContextsBelongToEnvironment(
2847+
state.draftsByThreadKey[threadKey]?.threadContexts ?? EMPTY_THREAD_CONTEXTS,
2848+
nextProjectRef.environmentId,
2849+
)
2850+
) {
2851+
return state;
2852+
}
28332853
if (
28342854
nextProjectRef.projectId.length === 0 ||
28352855
nextProjectRef.environmentId.length === 0

‎apps/web/src/lib/composerContextRecords.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,13 @@ export function threadContextReference(record: ThreadContextRecord): ComposerCon
166166
return { kind: "thread", contextId: record.contextId, label: record.label };
167167
}
168168

169+
export function threadContextsBelongToEnvironment(
170+
records: ReadonlyArray<ThreadContextRecord>,
171+
environmentId: EnvironmentId,
172+
): boolean {
173+
return records.every((record) => record.environmentId === environmentId);
174+
}
175+
169176
export function threadContextRecord(ref: ScopedThreadRef, title: string): ThreadContextRecord {
170177
const label = sanitizeComposerContextLabel(title, "thread");
171178
return {

0 commit comments

Comments
 (0)