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

useHandleNewThread.ts

467 lines21.4 KB

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