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