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