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

useHandleNewThread.ts

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