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