Open History to see the last commit
1import { scopedProjectKey, scopeProjectRef } from "@workbench/client-runtime";
2import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@workbench/contracts";
3import { useParams, useRouter } from "@tanstack/react-router";
4import { useCallback, useMemo } from "react";
5import { useShallow } from "zustand/react/shallow";
6import {
7 type DraftThreadEnvMode,
8 type DraftThreadState,
9 useComposerDraftStore,
10} from "../composerDraftStore";
11import { newDraftId, newThreadId } from "../lib/utils";
12import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
13import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
14import { selectProjectsAcrossEnvironments, useStore } from "../store";
15import { createThreadSelectorByRef } from "../storeSelectors";
16import { resolveThreadRouteTarget } from "../threadRoutes";
17import { useUiStateStore } from "../uiStateStore";
18import { useSettings } from "./useSettings";
19
20function useNewThreadState() {
21 const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
22 const projectGroupingSettings = useSettings((settings) => ({
23 sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
24 sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
25 }));
26 const router = useRouter();
27 const getCurrentRouteTarget = useCallback(() => {
28 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
29 return resolveThreadRouteTarget(currentRouteParams);
30 }, [router]);
31
32 return useCallback(
33 (
34 projectRef: ScopedProjectRef,
35 options?: {
36 branch?: string | null;
37 worktreePath?: string | null;
38 envMode?: DraftThreadEnvMode;
39 },
40 ): Promise<void> => {
41 const {
42 getDraftSessionByLogicalProjectKey,
43 getDraftSession,
44 getDraftThread,
45 applyStickyState,
46 setDraftThreadContext,
47 setLogicalProjectDraftThreadId,
48 } = useComposerDraftStore.getState();
49 const currentRouteTarget = getCurrentRouteTarget();
50 const project = projects.find(
51 (candidate) =>
52 candidate.id === projectRef.projectId &&
53 candidate.environmentId === projectRef.environmentId,
54 );
55 const logicalProjectKey = project
56 ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
57 : scopedProjectKey(projectRef);
58 const hasBranchOption = options?.branch !== undefined;
59 const hasWorktreePathOption = options?.worktreePath !== undefined;
60 const hasEnvModeOption = options?.envMode !== undefined;
61 const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
62 const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
63 ? currentRouteTarget.kind === "server"
64 ? getDraftThread(currentRouteTarget.threadRef)
65 : getDraftSession(currentRouteTarget.draftId)
66 : null;
67 if (storedDraftThread) {
68 return (async () => {
69 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
70 setDraftThreadContext(storedDraftThread.draftId, {
71 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
72 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
73 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
74 });
75 }
76 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, storedDraftThread.draftId, {
77 threadId: storedDraftThread.threadId,
78 });
79 if (
80 currentRouteTarget?.kind === "draft" &&
81 currentRouteTarget.draftId === storedDraftThread.draftId
82 ) {
83 return;
84 }
85 await router.navigate({
86 to: "/draft/$draftId",
87 params: { draftId: storedDraftThread.draftId },
88 });
89 })();
90 }
91
92 if (
93 latestActiveDraftThread &&
94 currentRouteTarget?.kind === "draft" &&
95 latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
96 latestActiveDraftThread.promotedTo == null
97 ) {
98 if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
99 setDraftThreadContext(currentRouteTarget.draftId, {
100 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
101 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
102 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
103 });
104 }
105 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
106 threadId: latestActiveDraftThread.threadId,
107 createdAt: latestActiveDraftThread.createdAt,
108 runtimeMode: latestActiveDraftThread.runtimeMode,
109 interactionMode: latestActiveDraftThread.interactionMode,
110 ...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
111 ...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
112 ...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
113 });
114 return Promise.resolve();
115 }
116
117 const draftId = newDraftId();
118 const threadId = newThreadId();
119 const createdAt = new Date().toISOString();
120 return (async () => {
121 setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
122 threadId,
123 createdAt,
124 branch: options?.branch ?? null,
125 worktreePath: options?.worktreePath ?? null,
126 envMode: options?.envMode ?? "local",
127 runtimeMode: DEFAULT_RUNTIME_MODE,
128 });
129 applyStickyState(draftId);
130
131 await router.navigate({
132 to: "/draft/$draftId",
133 params: { draftId },
134 });
135 })();
136 },
137 [getCurrentRouteTarget, projectGroupingSettings, router, projects],
138 );
139}
140
141export function useNewThreadHandler() {
142 const handleNewThread = useNewThreadState();
143
144 return {
145 handleNewThread,
146 };
147}
148
149export function useHandleNewThread() {
150 const projectOrder = useUiStateStore((store) => store.projectOrder);
151 const routeTarget = useParams({
152 strict: false,
153 select: (params) => resolveThreadRouteTarget(params),
154 });
155 const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
156 const activeThread = useStore(
157 useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
158 );
159 const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
160 const activeDraftThread = useComposerDraftStore(() =>
161 routeTarget
162 ? routeTarget.kind === "server"
163 ? getDraftThread(routeTarget.threadRef)
164 : useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
165 : null,
166 );
167 const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
168 const orderedProjects = useMemo(() => {
169 return orderItemsByPreferredIds({
170 items: projects,
171 preferredIds: projectOrder,
172 getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
173 });
174 }, [projectOrder, projects]);
175 const handleNewThread = useNewThreadState();
176
177 return {
178 activeDraftThread,
179 activeThread,
180 defaultProjectRef: orderedProjects[0]
181 ? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
182 : null,
183 handleNewThread,
184 routeThreadRef,
185 };
186}