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