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