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_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";
8import { useParams, useRouter } from "@tanstack/react-router";
9import { useCallback, useMemo } from "react";
10import {
11 composerDraftHasUserContent,
12 markPromotedDraftThreadByRef,
13 type DraftId,
14 type DraftThreadEnvMode,
15 type DraftThreadState,
16 useComposerDraftStore,
17} from "../composerDraftStore";
18import { newDraftId, newThreadId } from "../lib/utils";
19import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
20import {
21 deriveLogicalProjectKeyFromSettings,
22 getProjectOrderKey,
23 selectProjectGroupingSettings,
24} from "../logicalProject";
25import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
26import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
27import { readProjects, readThreadShell, useProjects, useThread } from "../state/entities";
28import {
29 hasExplicitComposerModelSelection,
30 resolveNewDraftStartFromOrigin,
31 resolveNewThreadModelSelectionOverride,
32} from "../lib/chatThreadActions";
33import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults";
34import { environmentServerConfigsAtom } from "../state/server";
35import { resolveThreadRouteTarget } from "../threadRoutes";
36import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
37import { useClientSettings } from "./useSettings";
38
39interface NewThreadWorkspaceOptions {
40 branch?: string | null;
41 worktreePath?: string | null;
42 envMode?: DraftThreadEnvMode;
43 startFromOrigin?: boolean;
44}
45
46// The workspace options the caller passed explicitly, shaped for the draft
47// store: absent keys stay absent so they never overwrite existing draft
48// state. Every reuse path applies exactly this set.
49function pickExplicitWorkspaceOptions(options: NewThreadWorkspaceOptions | undefined) {
50 return {
51 ...(options?.branch !== undefined ? { branch: options.branch } : {}),
52 ...(options?.worktreePath !== undefined ? { worktreePath: options.worktreePath } : {}),
53 ...(options?.envMode !== undefined ? { envMode: options.envMode } : {}),
54 ...(options?.startFromOrigin !== undefined ? { startFromOrigin: options.startFromOrigin } : {}),
55 };
56}
57
58export function useNewThreadHandler() {
59 const environmentServerConfigs = useAtomValue(environmentServerConfigsAtom);
60 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
61 const router = useRouter();
62 const getCurrentRouteTarget = useCallback(() => {
63 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
64 return resolveThreadRouteTarget(currentRouteParams);
65 }, [router]);
66
67 return useCallback(
68 (
69 projectRef: ScopedProjectRef,
70 options?: {
71 branch?: string | null;
72 worktreePath?: string | null;
73 envMode?: DraftThreadEnvMode;
74 startFromOrigin?: boolean;
75 replace?: boolean;
76 },
77 // Which draft the thread ended up in, so a caller that has something to put in it — a
78 // prepared checkout, a task to write — addresses that one rather than looking the project
79 // up again and finding whichever draft it happens to hold.
80 ): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
81 const projects = readProjects();
82 const targetServerSettings =
83 environmentServerConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
84 const {
85 getComposerDraft,
86 getDraftSessionByLogicalProjectKey,
87 getDraftSession,
88 getDraftThread,
89 applyStickyState,
90 setDraftThreadContext,
91 setLogicalProjectDraftThreadId,
92 setModelSelection,
93 } = useComposerDraftStore.getState();
94 const requestingRouteHref = router.state.location.href;
95 const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref;
96 const currentRouteTarget = getCurrentRouteTarget();
97 // A new thread carries the user's working mode from the thread being
98 // viewed. The target project's configured model still wins; interaction
99 // mode carries independently. Permissions, branch, worktree, and env mode
100 // come from configured defaults unless the caller passes them explicitly.
101 const carrySourceShell =
102 currentRouteTarget?.kind === "server"
103 ? readThreadShell(currentRouteTarget.threadRef)
104 : null;
105 const carrySourceDraft =
106 currentRouteTarget?.kind === "draft" ? getDraftSession(currentRouteTarget.draftId) : null;
107 // Composer overrides win over the persisted thread state — they are
108 // what the user currently sees in the composer controls.
109 const carrySourceComposer = currentRouteTarget
110 ? getComposerDraft(
111 currentRouteTarget.kind === "server"
112 ? currentRouteTarget.threadRef
113 : currentRouteTarget.draftId,
114 )
115 : null;
116 const composerActiveProvider = carrySourceComposer?.activeProvider ?? null;
117 const composerModelSelection = composerActiveProvider
118 ? (carrySourceComposer?.modelSelectionByProvider[composerActiveProvider] ?? null)
119 : null;
120 const carryModelSelection =
121 composerModelSelection ?? carrySourceShell?.modelSelection ?? null;
122 const carryInteractionMode =
123 carrySourceComposer?.interactionMode ??
124 carrySourceShell?.interactionMode ??
125 carrySourceDraft?.interactionMode ??
126 null;
127 const project = projects.find(
128 (candidate) =>
129 candidate.id === projectRef.projectId &&
130 candidate.environmentId === projectRef.environmentId,
131 );
132 // The resolver applies project overrides and, until the server has
133 // folded them, the aggregate's own legacy fields.
134 const projectSettings = resolveProjectSettings(
135 targetServerSettings,
136 project?.id ?? null,
137 project,
138 );
139 const projectDefaultModelSelection = projectSettings.settings.defaultModelSelection;
140 const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
141 const projectThreadEnvMode =
142 projectSettings.sources.defaultThreadEnvMode === "project"
143 ? projectSettings.settings.defaultThreadEnvMode
144 : undefined;
145 const resolveModelSelectionOverride = (destinationDraftId: DraftId) =>
146 resolveNewThreadModelSelectionOverride({
147 projectDefaultSelection: projectDefaultModelSelection ?? null,
148 carrySelection: carryModelSelection,
149 carrySourceDraftId:
150 currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null,
151 destinationDraftId,
152 });
153 // The shared resolver owns the priority order. The t3.json read is
154 // skipped entirely when a higher-priority source decides, and its
155 // query atom caches per project after the first call.
156 const resolveDefaultEnvMode = async (): Promise<DraftThreadEnvMode> => {
157 const consultProjectFile = project !== undefined && projectThreadEnvMode == null;
158 return resolveDefaultThreadEnvMode({
159 projectSetting: projectThreadEnvMode,
160 projectFile: consultProjectFile
161 ? await readT3ProjectFileDefaultThreadEnvMode(
162 project.environmentId,
163 project.workspaceRoot,
164 )
165 : null,
166 globalDefault: projectSettings.settings.defaultThreadEnvMode,
167 });
168 };
169 const logicalProjectKey = project
170 ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
171 : scopedProjectKey(projectRef);
172 const hasBranchOption = options?.branch !== undefined;
173 const hasWorktreePathOption = options?.worktreePath !== undefined;
174 const hasEnvModeOption = options?.envMode !== undefined;
175 const hasStartFromOriginOption = options?.startFromOrigin !== undefined;
176 const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
177 const storedDraftThreadRef = storedDraftThread
178 ? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId)
179 : null;
180 const reusableStoredDraftThread =
181 storedDraftThread !== null &&
182 storedDraftThread.promotedTo == null &&
183 storedDraftThreadRef !== null &&
184 readThreadShell(storedDraftThreadRef) === null
185 ? storedDraftThread
186 : null;
187 if (storedDraftThreadRef && reusableStoredDraftThread === null) {
188 markPromotedDraftThreadByRef(storedDraftThreadRef);
189 }
190 // New-thread surfaces (button, hotkeys, "/" landing, palette) only
191 // ever reuse a draft the user has NOT invested in. A draft with typed
192 // text or attachments is work in progress: it stays alive where it is
193 // (reachable from the sidebar draft rows) and this request mints a
194 // fresh draft instead — the remap in the store preserves invested
195 // drafts rather than deleting them.
196 const emptyStoredDraftThread =
197 reusableStoredDraftThread &&
198 !composerDraftHasUserContent(getComposerDraft(reusableStoredDraftThread.draftId))
199 ? reusableStoredDraftThread
200 : null;
201 const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
202 ? currentRouteTarget.kind === "server"
203 ? getDraftThread(currentRouteTarget.threadRef)
204 : getDraftSession(currentRouteTarget.draftId)
205 : null;
206 if (emptyStoredDraftThread) {
207 return (async () => {
208 const isDraftAlreadyOpen =
209 currentRouteTarget?.kind === "draft" &&
210 currentRouteTarget.draftId === emptyStoredDraftThread.draftId;
211 const hasExplicitWorkspaceOption =
212 hasBranchOption ||
213 hasWorktreePathOption ||
214 hasEnvModeOption ||
215 hasStartFromOriginOption;
216 // Resurrecting an empty stored draft must not resurrect its stale
217 // context: explicit workspace options win outright; otherwise the
218 // env context resets to the configured defaults so drafts seeded
219 // before a defaults change (or by the old carry-over behavior) stop
220 // landing on "current checkout" branches forever. When the draft is
221 // already open and no options were passed, leave its workspace
222 // context alone entirely — the user may have just picked a branch
223 // in the composer. Model selection has its own explicit-pick rule
224 // below and does not follow this guard.
225 let workspaceContext: NewThreadWorkspaceOptions | null = null;
226 if (hasExplicitWorkspaceOption) {
227 workspaceContext = pickExplicitWorkspaceOptions(options);
228 } else if (!isDraftAlreadyOpen) {
229 const defaultEnvMode = await resolveDefaultEnvMode();
230 if (routeChangedSinceRequest()) {
231 return null;
232 }
233 // The await yields. If the draft was opened (a concurrent
234 // invocation's navigation landed), promoted to a real thread,
235 // remapped away (a concurrent invocation registered a fresh
236 // draft — remapping back would evict the winner and let the
237 // store GC it), or gained content (no longer a reusable empty
238 // draft) in the meantime, this invocation is a stale loser:
239 // resetting context, remapping, or navigating would all clobber
240 // state written after the snapshot above. Bail out entirely —
241 // the winner already did this work.
242 const routeTargetNow = getCurrentRouteTarget();
243 const openedMeanwhile =
244 routeTargetNow?.kind === "draft" &&
245 routeTargetNow.draftId === emptyStoredDraftThread.draftId;
246 const promotedMeanwhile =
247 storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null;
248 const remappedMeanwhile =
249 getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !==
250 emptyStoredDraftThread.draftId;
251 const investedMeanwhile = composerDraftHasUserContent(
252 getComposerDraft(emptyStoredDraftThread.draftId),
253 );
254 if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) {
255 return null;
256 }
257 workspaceContext = {
258 branch: null,
259 worktreePath: null,
260 envMode: defaultEnvMode,
261 startFromOrigin: resolveNewDraftStartFromOrigin({
262 envMode: defaultEnvMode,
263 newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin,
264 }),
265 };
266 }
267 if (workspaceContext) {
268 setDraftThreadContext(emptyStoredDraftThread.draftId, {
269 ...workspaceContext,
270 ...(!isDraftAlreadyOpen ? { runtimeMode: defaultRuntimeMode } : {}),
271 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
272 });
273 }
274 // Model intent: an explicit human pick always stands. Seeds and
275 // legacy entries alike re-resolve here — sticky first, mirroring
276 // the mint-fresh path, then the project default or carried
277 // selection on top. This runs even when the draft is already open:
278 // without it, a changed pin could never reach the draft the user
279 // is looking at, because explicit picks are the only thing the
280 // flag protects.
281 const storedDraft = getComposerDraft(emptyStoredDraftThread.draftId);
282 const storedDraftHasExplicitModelPick = hasExplicitComposerModelSelection(storedDraft);
283 if (!storedDraftHasExplicitModelPick) {
284 applyStickyState(emptyStoredDraftThread.draftId);
285 const modelSelectionOverride = resolveModelSelectionOverride(
286 emptyStoredDraftThread.draftId,
287 );
288 if (modelSelectionOverride) {
289 // This is a complete snapshot: absent options mean "no options",
290 // not "keep the stale draft's options".
291 setModelSelection(emptyStoredDraftThread.draftId, modelSelectionOverride, {
292 replaceOptions: true,
293 });
294 }
295 }
296 // The workspace context must also ride along here: when projectRef
297 // targets a different physical member of the logical project,
298 // createDraftThreadState treats the remap as a project change and
299 // would otherwise wipe branch/worktree, undoing the write above.
300 setLogicalProjectDraftThreadId(
301 logicalProjectKey,
302 projectRef,
303 emptyStoredDraftThread.draftId,
304 {
305 threadId: emptyStoredDraftThread.threadId,
306 ...workspaceContext,
307 ...(!isDraftAlreadyOpen ? { runtimeMode: defaultRuntimeMode } : {}),
308 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
309 },
310 );
311 const opened = {
312 draftId: emptyStoredDraftThread.draftId,
313 threadId: emptyStoredDraftThread.threadId,
314 };
315 // Re-read the route: the snapshot from before the await is stale
316 // once a concurrent invocation's navigation lands, and navigating
317 // again would push a duplicate history entry.
318 const routeTargetAfterWrites = getCurrentRouteTarget();
319 if (
320 routeTargetAfterWrites?.kind === "draft" &&
321 routeTargetAfterWrites.draftId === emptyStoredDraftThread.draftId
322 ) {
323 return opened;
324 }
325 await router.navigate({
326 to: "/draft/$draftId",
327 params: { draftId: emptyStoredDraftThread.draftId },
328 replace: options?.replace ?? false,
329 });
330 return opened;
331 })();
332 }
333
334 if (
335 latestActiveDraftThread &&
336 currentRouteTarget?.kind === "draft" &&
337 latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
338 latestActiveDraftThread.promotedTo == null &&
339 // Same content rule as above: a new-thread request while viewing an
340 // invested draft mints a fresh one instead of repurposing it.
341 !composerDraftHasUserContent(getComposerDraft(currentRouteTarget.draftId))
342 ) {
343 if (
344 hasBranchOption ||
345 hasWorktreePathOption ||
346 hasEnvModeOption ||
347 hasStartFromOriginOption
348 ) {
349 setDraftThreadContext(currentRouteTarget.draftId, pickExplicitWorkspaceOptions(options));
350 }
351 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
352 threadId: latestActiveDraftThread.threadId,
353 createdAt: latestActiveDraftThread.createdAt,
354 runtimeMode: latestActiveDraftThread.runtimeMode,
355 interactionMode: latestActiveDraftThread.interactionMode,
356 ...pickExplicitWorkspaceOptions(options),
357 });
358 return Promise.resolve({
359 draftId: currentRouteTarget.draftId,
360 threadId: latestActiveDraftThread.threadId,
361 });
362 }
363
364 const draftId = newDraftId();
365 const threadId = newThreadId();
366 const createdAt = new Date().toISOString();
367 return (async () => {
368 const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode());
369 if (routeChangedSinceRequest()) {
370 return null;
371 }
372 // The await yields, so a concurrent invocation may have registered a
373 // draft for this logical project in the meantime. Registering ours
374 // too would evict that draft while its navigation is in flight —
375 // reuse the winner instead, like the synchronous path above does.
376 const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
377 if (
378 racedDraft &&
379 // Only a draft REGISTERED during the await counts as a raced
380 // winner. An invested draft this invocation deliberately declined
381 // to reuse is still mapped at this point — reusing it here would
382 // silently undo mint-fresh semantics.
383 racedDraft.draftId !== storedDraftThread?.draftId &&
384 readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null
385 ) {
386 // Same remap the reuse paths above perform: point the draft at the
387 // caller's project member and apply explicit workspace options if
388 // the caller passed any. Without explicit options the winner's
389 // context stands untouched — the winner's navigation is landing,
390 // which is the isDraftAlreadyOpen "leave it alone" case. Writing
391 // this invocation's defaults here instead would clobber the
392 // winner's explicit picks and could pair its worktreePath with a
393 // contradictory envMode.
394 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, {
395 threadId: racedDraft.threadId,
396 createdAt: racedDraft.createdAt,
397 runtimeMode: racedDraft.runtimeMode,
398 interactionMode: racedDraft.interactionMode,
399 ...pickExplicitWorkspaceOptions(options),
400 });
401 await router.navigate({
402 to: "/draft/$draftId",
403 params: { draftId: racedDraft.draftId },
404 replace: options?.replace ?? false,
405 });
406 return { draftId: racedDraft.draftId, threadId: racedDraft.threadId };
407 }
408 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
409 threadId,
410 createdAt,
411 branch: options?.branch ?? null,
412 worktreePath: options?.worktreePath ?? null,
413 envMode: initialEnvMode,
414 startFromOrigin:
415 options?.startFromOrigin ??
416 resolveNewDraftStartFromOrigin({
417 envMode: initialEnvMode,
418 newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin,
419 }),
420 runtimeMode: defaultRuntimeMode,
421 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
422 });
423 applyStickyState(draftId);
424 const modelSelectionOverride = resolveModelSelectionOverride(draftId);
425 if (modelSelectionOverride) {
426 // Project defaults and carried selections both outrank global sticky
427 // state. The project default wins when both are present.
428 setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true });
429 }
430 await router.navigate({
431 to: "/draft/$draftId",
432 params: { draftId },
433 replace: options?.replace ?? false,
434 });
435 return { draftId, threadId };
436 })();
437 },
438 [environmentServerConfigs, getCurrentRouteTarget, projectGroupingSettings, router],
439 );
440}
441
442export function useHandleNewThread() {
443 const projectOrder = useUiStateStore((store) => store.projectOrder);
444 const routeTarget = useParams({
445 strict: false,
446 select: (params) => resolveThreadRouteTarget(params),
447 });
448 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
449 const routeDraftId = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
450 const activeThread = useThread(routeThreadRef);
451 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
452 const activeDraftThread = useComposerDraftStore(() =>
453 routeTarget
454 ? routeTarget.kind === "server"
455 ? getDraftThread(routeTarget.threadRef)
456 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
457 : null,
458 );
459 const projects = useProjects();
460 const orderedProjects = useMemo(() => {
461 return orderItemsByPreferredIds({
462 items: projects,
463 preferredIds: projectOrder,
464 getId: getProjectOrderKey,
465 getPreferenceIds: (project) => [
466 getProjectOrderKey(project),
467 legacyProjectCwdPreferenceKey(project.workspaceRoot),
468 ],
469 });
470 }, [projectOrder, projects]);
471 const handleNewThread = useNewThreadHandler();
472
473 return {
474 activeDraftThread,
475 activeThread,
476 defaultProjectRef: orderedProjects[0]
477 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
478 : null,
479 handleNewThread,
480 routeDraftId,
481 routeThreadRef,
482 };
483}