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

useHandleNewThread.ts

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