Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 scopedProjectKey,
4 scopeProjectRef,
5 scopeThreadRef,
6} from "@t3tools/client-runtime/environment";
7import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
8import { useParams, useRouter } from "@tanstack/react-router";
9import { useCallback, useMemo } from "react";
10import {
11 markPromotedDraftThreadByRef,
12 type DraftThreadEnvMode,
13 type DraftThreadState,
14 useComposerDraftStore,
15} from "../composerDraftStore";
16import { newDraftId, newThreadId } from "../lib/utils";
17import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
18import {
19 deriveLogicalProjectKeyFromSettings,
20 getProjectOrderKey,
21 selectProjectGroupingSettings,
22} from "../logicalProject";
23import { readThreadShell, useProjects, useThread } from "../state/entities";
24import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
25import { primaryServerSettingsAtom } from "../state/server";
26import { resolveThreadRouteTarget } from "../threadRoutes";
27import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
28import { useClientSettings } from "./useSettings";
29
30export function useNewThreadHandler() {
31 const projects = useProjects();
32 // New-thread defaults are a user preference, and the settings UI only ever
33 // edits the primary environment's settings.json. Reading the target
34 // environment's own settings here would silently reset remote projects to
35 // the decoded defaults ("local" mode, current branch), since nothing can
36 // set those values on a remote server.
37 const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);
38 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
39 const router = useRouter();
40 const getCurrentRouteTarget = useCallback(() => {
41 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
42 return resolveThreadRouteTarget(currentRouteParams);
43 }, [router]);
44
45 return useCallback(
46 (
47 projectRef: ScopedProjectRef,
48 options?: {
49 branch?: string | null;
50 worktreePath?: string | null;
51 envMode?: DraftThreadEnvMode;
52 startFromOrigin?: boolean;
53 replace?: boolean;
54 },
55 ): Promise<void> => {
56 const {
57 getComposerDraft,
58 getDraftSessionByLogicalProjectKey,
59 getDraftSession,
60 getDraftThread,
61 applyStickyState,
62 setDraftThreadContext,
63 setLogicalProjectDraftThreadId,
64 setModelSelection,
65 } = useComposerDraftStore.getState();
66 const currentRouteTarget = getCurrentRouteTarget();
67 // A new thread carries the user's *working mode* from the thread being
68 // viewed: model (including options like reasoning effort and context
69 // window), permission mode, and interaction mode. Branch, worktree, and
70 // env mode never carry implicitly — those come from the configured
71 // defaults unless the caller passes them explicitly.
72 const carrySourceShell =
73 currentRouteTarget?.kind === "server"
74 ? readThreadShell(currentRouteTarget.threadRef)
75 : null;
76 const carrySourceDraft =
77 currentRouteTarget?.kind === "draft" ? getDraftSession(currentRouteTarget.draftId) : null;
78 // Composer overrides win over the persisted thread state — they are
79 // what the user currently sees in the composer controls.
80 const carrySourceComposer = currentRouteTarget
81 ? getComposerDraft(
82 currentRouteTarget.kind === "server"
83 ? currentRouteTarget.threadRef
84 : currentRouteTarget.draftId,
85 )
86 : null;
87 const composerActiveProvider = carrySourceComposer?.activeProvider ?? null;
88 const composerModelSelection = composerActiveProvider
89 ? (carrySourceComposer?.modelSelectionByProvider[composerActiveProvider] ?? null)
90 : null;
91 const carryModelSelection =
92 composerModelSelection ?? carrySourceShell?.modelSelection ?? null;
93 const carryRuntimeMode =
94 carrySourceComposer?.runtimeMode ??
95 carrySourceShell?.runtimeMode ??
96 carrySourceDraft?.runtimeMode ??
97 null;
98 const carryInteractionMode =
99 carrySourceComposer?.interactionMode ??
100 carrySourceShell?.interactionMode ??
101 carrySourceDraft?.interactionMode ??
102 null;
103 const project = projects.find(
104 (candidate) =>
105 candidate.id === projectRef.projectId &&
106 candidate.environmentId === projectRef.environmentId,
107 );
108 const logicalProjectKey = project
109 ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
110 : scopedProjectKey(projectRef);
111 const hasBranchOption = options?.branch !== undefined;
112 const hasWorktreePathOption = options?.worktreePath !== undefined;
113 const hasEnvModeOption = options?.envMode !== undefined;
114 const hasStartFromOriginOption = options?.startFromOrigin !== undefined;
115 const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
116 const storedDraftThreadRef = storedDraftThread
117 ? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId)
118 : null;
119 const reusableStoredDraftThread =
120 storedDraftThreadRef && readThreadShell(storedDraftThreadRef) !== null
121 ? null
122 : storedDraftThread;
123 if (storedDraftThreadRef && reusableStoredDraftThread === null) {
124 markPromotedDraftThreadByRef(storedDraftThreadRef);
125 }
126 const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
127 ? currentRouteTarget.kind === "server"
128 ? getDraftThread(currentRouteTarget.threadRef)
129 : getDraftSession(currentRouteTarget.draftId)
130 : null;
131 if (reusableStoredDraftThread) {
132 return (async () => {
133 const isDraftAlreadyOpen =
134 currentRouteTarget?.kind === "draft" &&
135 currentRouteTarget.draftId === reusableStoredDraftThread.draftId;
136 const hasExplicitWorkspaceOption =
137 hasBranchOption ||
138 hasWorktreePathOption ||
139 hasEnvModeOption ||
140 hasStartFromOriginOption;
141 // Resurrecting a stored draft must not resurrect its stale context:
142 // explicit workspace options win outright; otherwise the env context
143 // resets to the configured defaults so drafts seeded before a
144 // defaults change (or by the old carry-over behavior) stop landing
145 // on "current checkout" branches forever. Composer text is
146 // preserved. When the draft is already open and no options were
147 // passed, leave it alone entirely — the user may have just picked a
148 // branch in the composer.
149 const defaultEnvMode = primaryServerSettings.defaultThreadEnvMode;
150 const workspaceContext = hasExplicitWorkspaceOption
151 ? {
152 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
153 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
154 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
155 ...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
156 }
157 : isDraftAlreadyOpen
158 ? null
159 : {
160 branch: null,
161 worktreePath: null,
162 envMode: defaultEnvMode,
163 startFromOrigin: resolveNewDraftStartFromOrigin({
164 envMode: defaultEnvMode,
165 newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
166 }),
167 };
168 if (workspaceContext) {
169 setDraftThreadContext(reusableStoredDraftThread.draftId, {
170 ...workspaceContext,
171 ...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
172 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
173 });
174 if (carryModelSelection) {
175 // The carried selection is a complete snapshot of the viewed
176 // thread's model state: absent options mean "no options", not
177 // "keep the stale draft's options".
178 setModelSelection(reusableStoredDraftThread.draftId, carryModelSelection, {
179 replaceOptions: true,
180 });
181 }
182 }
183 // The workspace context must also ride along here: when projectRef
184 // targets a different physical member of the logical project,
185 // createDraftThreadState treats the remap as a project change and
186 // would otherwise wipe branch/worktree, undoing the write above.
187 setLogicalProjectDraftThreadId(
188 logicalProjectKey,
189 projectRef,
190 reusableStoredDraftThread.draftId,
191 {
192 threadId: reusableStoredDraftThread.threadId,
193 ...workspaceContext,
194 ...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
195 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
196 },
197 );
198 if (
199 currentRouteTarget?.kind === "draft" &&
200 currentRouteTarget.draftId === reusableStoredDraftThread.draftId
201 ) {
202 return;
203 }
204 await router.navigate({
205 to: "/draft/$draftId",
206 params: { draftId: reusableStoredDraftThread.draftId },
207 replace: options?.replace ?? false,
208 });
209 })();
210 }
211
212 if (
213 latestActiveDraftThread &&
214 currentRouteTarget?.kind === "draft" &&
215 latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
216 latestActiveDraftThread.promotedTo == null
217 ) {
218 if (
219 hasBranchOption ||
220 hasWorktreePathOption ||
221 hasEnvModeOption ||
222 hasStartFromOriginOption
223 ) {
224 setDraftThreadContext(currentRouteTarget.draftId, {
225 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
226 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
227 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
228 ...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
229 });
230 }
231 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
232 threadId: latestActiveDraftThread.threadId,
233 createdAt: latestActiveDraftThread.createdAt,
234 runtimeMode: latestActiveDraftThread.runtimeMode,
235 interactionMode: latestActiveDraftThread.interactionMode,
236 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
237 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
238 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
239 ...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
240 });
241 return Promise.resolve();
242 }
243
244 const draftId = newDraftId();
245 const threadId = newThreadId();
246 const createdAt = new Date().toISOString();
247 const initialEnvMode = options?.envMode ?? primaryServerSettings.defaultThreadEnvMode;
248 return (async () => {
249 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
250 threadId,
251 createdAt,
252 branch: options?.branch ?? null,
253 worktreePath: options?.worktreePath ?? null,
254 envMode: initialEnvMode,
255 startFromOrigin:
256 options?.startFromOrigin ??
257 resolveNewDraftStartFromOrigin({
258 envMode: initialEnvMode,
259 newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
260 }),
261 runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
262 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
263 });
264 applyStickyState(draftId);
265 if (carryModelSelection) {
266 // After sticky state so the viewed thread's exact selection
267 // (model + options like effort and context window) wins over the
268 // globally sticky one. replaceOptions: the carried selection is a
269 // complete snapshot — absent options mean "no options", not "keep
270 // whatever sticky state just wrote".
271 setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
272 }
273
274 await router.navigate({
275 to: "/draft/$draftId",
276 params: { draftId },
277 replace: options?.replace ?? false,
278 });
279 })();
280 },
281 [getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, projects, router],
282 );
283}
284
285export function useHandleNewThread() {
286 const projectOrder = useUiStateStore((store) => store.projectOrder);
287 const routeTarget = useParams({
288 strict: false,
289 select: (params) => resolveThreadRouteTarget(params),
290 });
291 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
292 const activeThread = useThread(routeThreadRef);
293 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
294 const activeDraftThread = useComposerDraftStore(() =>
295 routeTarget
296 ? routeTarget.kind === "server"
297 ? getDraftThread(routeTarget.threadRef)
298 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
299 : null,
300 );
301 const projects = useProjects();
302 const orderedProjects = useMemo(() => {
303 return orderItemsByPreferredIds({
304 items: projects,
305 preferredIds: projectOrder,
306 getId: getProjectOrderKey,
307 getPreferenceIds: (project) => [
308 getProjectOrderKey(project),
309 legacyProjectCwdPreferenceKey(project.workspaceRoot),
310 ],
311 });
312 }, [projectOrder, projects]);
313 const handleNewThread = useNewThreadHandler();
314
315 return {
316 activeDraftThread,
317 activeThread,
318 defaultProjectRef: orderedProjects[0]
319 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
320 : null,
321 handleNewThread,
322 routeThreadRef,
323 };
324}