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 and force "local" mode,
187 // undoing the write above.
188 setLogicalProjectDraftThreadId(
189 logicalProjectKey,
190 projectRef,
191 reusableStoredDraftThread.draftId,
192 {
193 threadId: reusableStoredDraftThread.threadId,
194 ...(workspaceContext ?? {}),
195 ...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
196 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
197 },
198 );
199 if (
200 currentRouteTarget?.kind === "draft" &&
201 currentRouteTarget.draftId === reusableStoredDraftThread.draftId
202 ) {
203 return;
204 }
205 await router.navigate({
206 to: "/draft/$draftId",
207 params: { draftId: reusableStoredDraftThread.draftId },
208 replace: options?.replace ?? false,
209 });
210 })();
211 }
212
213 if (
214 latestActiveDraftThread &&
215 currentRouteTarget?.kind === "draft" &&
216 latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
217 latestActiveDraftThread.promotedTo == null
218 ) {
219 if (
220 hasBranchOption ||
221 hasWorktreePathOption ||
222 hasEnvModeOption ||
223 hasStartFromOriginOption
224 ) {
225 setDraftThreadContext(currentRouteTarget.draftId, {
226 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
227 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
228 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
229 ...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
230 });
231 }
232 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
233 threadId: latestActiveDraftThread.threadId,
234 createdAt: latestActiveDraftThread.createdAt,
235 runtimeMode: latestActiveDraftThread.runtimeMode,
236 interactionMode: latestActiveDraftThread.interactionMode,
237 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
238 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
239 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
240 ...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
241 });
242 return Promise.resolve();
243 }
244
245 const draftId = newDraftId();
246 const threadId = newThreadId();
247 const createdAt = new Date().toISOString();
248 const initialEnvMode = options?.envMode ?? primaryServerSettings.defaultThreadEnvMode;
249 return (async () => {
250 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
251 threadId,
252 createdAt,
253 branch: options?.branch ?? null,
254 worktreePath: options?.worktreePath ?? null,
255 envMode: initialEnvMode,
256 startFromOrigin:
257 options?.startFromOrigin ??
258 resolveNewDraftStartFromOrigin({
259 envMode: initialEnvMode,
260 newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
261 }),
262 runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
263 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
264 });
265 applyStickyState(draftId);
266 if (carryModelSelection) {
267 // After sticky state so the viewed thread's exact selection
268 // (model + options like effort and context window) wins over the
269 // globally sticky one. replaceOptions: the carried selection is a
270 // complete snapshot — absent options mean "no options", not "keep
271 // whatever sticky state just wrote".
272 setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
273 }
274
275 await router.navigate({
276 to: "/draft/$draftId",
277 params: { draftId },
278 replace: options?.replace ?? false,
279 });
280 })();
281 },
282 [getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, projects, router],
283 );
284}
285
286export function useHandleNewThread() {
287 const projectOrder = useUiStateStore((store) => store.projectOrder);
288 const routeTarget = useParams({
289 strict: false,
290 select: (params) => resolveThreadRouteTarget(params),
291 });
292 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
293 const activeThread = useThread(routeThreadRef);
294 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
295 const activeDraftThread = useComposerDraftStore(() =>
296 routeTarget
297 ? routeTarget.kind === "server"
298 ? getDraftThread(routeTarget.threadRef)
299 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
300 : null,
301 );
302 const projects = useProjects();
303 const orderedProjects = useMemo(() => {
304 return orderItemsByPreferredIds({
305 items: projects,
306 preferredIds: projectOrder,
307 getId: getProjectOrderKey,
308 getPreferenceIds: (project) => [
309 getProjectOrderKey(project),
310 legacyProjectCwdPreferenceKey(project.workspaceRoot),
311 ],
312 });
313 }, [projectOrder, projects]);
314 const handleNewThread = useNewThreadHandler();
315
316 return {
317 activeDraftThread,
318 activeThread,
319 defaultProjectRef: orderedProjects[0]
320 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
321 : null,
322 handleNewThread,
323 routeThreadRef,
324 };
325}