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

useHandleNewThread.ts

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