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

useHandleNewThread.ts

493 lines22.3 KB

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