Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useHandleNewThread.ts

542 lines24.4 KB

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