Open History to see the last commit
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;
39}
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 };
51}
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 storedDraftThreadRef && readThreadShell(storedDraftThreadRef) !== null
193 ? null
194 : storedDraftThread;
195 if (storedDraftThreadRef && reusableStoredDraftThread === null) {
196 markPromotedDraftThreadByRef(storedDraftThreadRef);
197 }
198 // New-thread surfaces (button, hotkeys, "/" landing, palette) only
199 // ever reuse a draft the user has NOT invested in. A draft with typed
200 // text or attachments is work in progress: it stays alive where it is
201 // (reachable from the sidebar draft rows) and this request mints a
202 // fresh draft instead — the remap in the store preserves invested
203 // drafts rather than deleting them.
204 const emptyStoredDraftThread =
205 reusableStoredDraftThread &&
206 !composerDraftHasUserContent(getComposerDraft(reusableStoredDraftThread.draftId))
207 ? reusableStoredDraftThread
208 : null;
209 const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
210 ? currentRouteTarget.kind === "server"
211 ? getDraftThread(currentRouteTarget.threadRef)
212 : getDraftSession(currentRouteTarget.draftId)
213 : null;
214 if (emptyStoredDraftThread) {
215 return (async () => {
216 const isDraftAlreadyOpen =
217 currentRouteTarget?.kind === "draft" &&
218 currentRouteTarget.draftId === emptyStoredDraftThread.draftId;
219 const hasExplicitWorkspaceOption =
220 hasBranchOption ||
221 hasWorktreePathOption ||
222 hasEnvModeOption ||
223 hasStartFromOriginOption;
224 // Resurrecting an empty stored draft must not resurrect its stale
225 // context: explicit workspace options win outright; otherwise the
226 // env context resets to the configured defaults so drafts seeded
227 // before a defaults change (or by the old carry-over behavior) stop
228 // landing on "current checkout" branches forever. When the draft is
229 // already open and no options were passed, leave it alone entirely —
230 // the user may have just picked a branch in the composer.
231 let workspaceContext: NewThreadWorkspaceOptions | null = null;
232 if (hasExplicitWorkspaceOption) {
233 workspaceContext = pickExplicitWorkspaceOptions(options);
234 } else if (!isDraftAlreadyOpen) {
235 const defaultEnvMode = await resolveDefaultEnvMode();
236 // The await yields. If the draft was opened (a concurrent
237 // invocation's navigation landed), promoted to a real thread,
238 // remapped away (a concurrent invocation registered a fresh
239 // draft — remapping back would evict the winner and let the
240 // store GC it), or gained content (no longer a reusable empty
241 // draft) in the meantime, this invocation is a stale loser:
242 // resetting context, remapping, or navigating would all clobber
243 // state written after the snapshot above. Bail out entirely —
244 // the winner already did this work.
245 const routeTargetNow = getCurrentRouteTarget();
246 const openedMeanwhile =
247 routeTargetNow?.kind === "draft" &&
248 routeTargetNow.draftId === emptyStoredDraftThread.draftId;
249 const promotedMeanwhile =
250 storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null;
251 const remappedMeanwhile =
252 getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !==
253 emptyStoredDraftThread.draftId;
254 const investedMeanwhile = composerDraftHasUserContent(
255 getComposerDraft(emptyStoredDraftThread.draftId),
256 );
257 if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) {
258 return null;
259 }
260 workspaceContext = {
261 branch: null,
262 worktreePath: null,
263 envMode: defaultEnvMode,
264 startFromOrigin: resolveNewDraftStartFromOrigin({
265 envMode: defaultEnvMode,
266 newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
267 }),
268 };
269 }
270 if (workspaceContext) {
271 setDraftThreadContext(emptyStoredDraftThread.draftId, {
272 ...workspaceContext,
273 ...(carryRuntimeMode ? { runtimeMode: carryRuntimeMode } : {}),
274 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
275 });
276 if (carryModelSelection) {
277 // The carried selection is a complete snapshot of the viewed
278 // thread's model state: absent options mean "no options", not
279 // "keep the stale draft's options".
280 setModelSelection(emptyStoredDraftThread.draftId, carryModelSelection, {
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 carryComposerContentTo(emptyStoredDraftThread.draftId);
301 const opened = {
302 draftId: emptyStoredDraftThread.draftId,
303 threadId: emptyStoredDraftThread.threadId,
304 };
305 // Re-read the route: the snapshot from before the await is stale
306 // once a concurrent invocation's navigation lands, and navigating
307 // again would push a duplicate history entry.
308 const routeTargetAfterWrites = getCurrentRouteTarget();
309 if (
310 routeTargetAfterWrites?.kind === "draft" &&
311 routeTargetAfterWrites.draftId === emptyStoredDraftThread.draftId
312 ) {
313 return opened;
314 }
315 await router.navigate({
316 to: "/draft/$draftId",
317 params: { draftId: emptyStoredDraftThread.draftId },
318 replace: options?.replace ?? false,
319 });
320 return opened;
321 })();
322 }
323
324 if (
325 latestActiveDraftThread &&
326 currentRouteTarget?.kind === "draft" &&
327 latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
328 latestActiveDraftThread.promotedTo == null &&
329 // Same content rule as above: a new-thread request while viewing an
330 // invested draft mints a fresh one instead of repurposing it.
331 !composerDraftHasUserContent(getComposerDraft(currentRouteTarget.draftId))
332 ) {
333 if (
334 hasBranchOption ||
335 hasWorktreePathOption ||
336 hasEnvModeOption ||
337 hasStartFromOriginOption
338 ) {
339 setDraftThreadContext(currentRouteTarget.draftId, pickExplicitWorkspaceOptions(options));
340 }
341 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
342 threadId: latestActiveDraftThread.threadId,
343 createdAt: latestActiveDraftThread.createdAt,
344 runtimeMode: latestActiveDraftThread.runtimeMode,
345 interactionMode: latestActiveDraftThread.interactionMode,
346 ...pickExplicitWorkspaceOptions(options),
347 });
348 return Promise.resolve({
349 draftId: currentRouteTarget.draftId,
350 threadId: latestActiveDraftThread.threadId,
351 });
352 }
353
354 const draftId = newDraftId();
355 const threadId = newThreadId();
356 const createdAt = new Date().toISOString();
357 return (async () => {
358 const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode());
359 // The await yields, so a concurrent invocation may have registered a
360 // draft for this logical project in the meantime. Registering ours
361 // too would evict that draft while its navigation is in flight —
362 // reuse the winner instead, like the synchronous path above does.
363 const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
364 if (
365 racedDraft &&
366 // Only a draft REGISTERED during the await counts as a raced
367 // winner. An invested draft this invocation deliberately declined
368 // to reuse is still mapped at this point — reusing it here would
369 // silently undo mint-fresh semantics.
370 racedDraft.draftId !== storedDraftThread?.draftId &&
371 readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null
372 ) {
373 // Same remap the reuse paths above perform: point the draft at the
374 // caller's project member and apply explicit workspace options if
375 // the caller passed any. Without explicit options the winner's
376 // context stands untouched — the winner's navigation is landing,
377 // which is the isDraftAlreadyOpen "leave it alone" case. Writing
378 // this invocation's defaults here instead would clobber the
379 // winner's explicit picks and could pair its worktreePath with a
380 // contradictory envMode.
381 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, {
382 threadId: racedDraft.threadId,
383 createdAt: racedDraft.createdAt,
384 runtimeMode: racedDraft.runtimeMode,
385 interactionMode: racedDraft.interactionMode,
386 ...pickExplicitWorkspaceOptions(options),
387 });
388 carryComposerContentTo(racedDraft.draftId);
389 await router.navigate({
390 to: "/draft/$draftId",
391 params: { draftId: racedDraft.draftId },
392 replace: options?.replace ?? false,
393 });
394 return { draftId: racedDraft.draftId, threadId: racedDraft.threadId };
395 }
396 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
397 threadId,
398 createdAt,
399 branch: options?.branch ?? null,
400 worktreePath: options?.worktreePath ?? null,
401 envMode: initialEnvMode,
402 startFromOrigin:
403 options?.startFromOrigin ??
404 resolveNewDraftStartFromOrigin({
405 envMode: initialEnvMode,
406 newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,
407 }),
408 runtimeMode: carryRuntimeMode ?? DEFAULT_RUNTIME_MODE,
409 ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}),
410 });
411 applyStickyState(draftId);
412 if (carryModelSelection) {
413 // After sticky state so the viewed thread's exact selection
414 // (model + options like effort and context window) wins over the
415 // globally sticky one. replaceOptions: the carried selection is a
416 // complete snapshot — absent options mean "no options", not "keep
417 // whatever sticky state just wrote".
418 setModelSelection(draftId, carryModelSelection, { replaceOptions: true });
419 }
420 carryComposerContentTo(draftId);
421
422 await router.navigate({
423 to: "/draft/$draftId",
424 params: { draftId },
425 replace: options?.replace ?? false,
426 });
427 return { draftId, threadId };
428 })();
429 },
430 [getCurrentRouteTarget, primaryServerSettings, projectGroupingSettings, projects, router],
431 );
432}
433
434export function useHandleNewThread() {
435 const projectOrder = useUiStateStore((store) => store.projectOrder);
436 const routeTarget = useParams({
437 strict: false,
438 select: (params) => resolveThreadRouteTarget(params),
439 });
440 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
441 const activeThread = useThread(routeThreadRef);
442 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
443 const activeDraftThread = useComposerDraftStore(() =>
444 routeTarget
445 ? routeTarget.kind === "server"
446 ? getDraftThread(routeTarget.threadRef)
447 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
448 : null,
449 );
450 const projects = useProjects();
451 const orderedProjects = useMemo(() => {
452 return orderItemsByPreferredIds({
453 items: projects,
454 preferredIds: projectOrder,
455 getId: getProjectOrderKey,
456 getPreferenceIds: (project) => [
457 getProjectOrderKey(project),
458 legacyProjectCwdPreferenceKey(project.workspaceRoot),
459 ],
460 });
461 }, [projectOrder, projects]);
462 const handleNewThread = useNewThreadHandler();
463
464 return {
465 activeDraftThread,
466 activeThread,
467 defaultProjectRef: orderedProjects[0]
468 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
469 : null,
470 handleNewThread,
471 routeThreadRef,
472 };
473}