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