Open History to see the last commit
1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { availableScratchWorkspaceRoot } from "@t3tools/client-runtime/operations/projects";
3import {
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
8import type { EnvironmentId } from "@t3tools/contracts";
9
10import { stackedThreadToast, toastManager } from "~/components/ui/toast";
11import { useEnvironments } from "~/state/environments";
12import { projectEnvironment } from "~/state/projects";
13import { useAtomCommand } from "~/state/use-atom-command";
14import { useNewThreadHandler } from "./useHandleNewThread";
15
16function reportScratchFailure(title: string, error: unknown) {
17 toastManager.add(
18 stackedThreadToast({
19 type: "error",
20 title,
21 description: error instanceof Error ? error.message : "An error occurred.",
22 }),
23 );
24}
25
26export function useScratchProject() {
27 const { environments } = useEnvironments();
28 const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
29 const handleNewThread = useNewThreadHandler();
30
31 const scratchWorkspaceRootFor = (environmentId: EnvironmentId | null): string | null => {
32 const environment = environments.find((entry) => entry.environmentId === environmentId);
33 return availableScratchWorkspaceRoot(environment?.connection.phase, environment?.serverConfig);
34 };
35
36 const scratchEnvironmentId = (current: EnvironmentId | null): EnvironmentId | null => {
37 if (current !== null) return scratchWorkspaceRootFor(current) !== null ? current : null;
38 const offering = environments.filter(
39 (entry) => scratchWorkspaceRootFor(entry.environmentId) !== null,
40 );
41 return offering.length === 1 ? (offering[0]?.environmentId ?? null) : null;
42 };
43
44 const openScratchProject = async (
45 environmentId: EnvironmentId,
46 failureTitle = "Could not start without a project",
47 ): Promise<EnvironmentProject | null> => {
48 const result = await openScratch({ environmentId, input: {} });
49 if (result._tag === "Success") return result.value;
50 if (!isAtomCommandInterrupted(result)) {
51 reportScratchFailure(failureTitle, squashAtomCommandFailure(result));
52 }
53 return null;
54 };
55
56 const startScratchThread = async (environmentId: EnvironmentId) => {
57 const project = await openScratchProject(environmentId);
58 if (project) {
59 await handleNewThread(scopeProjectRef(project.environmentId, project.id)).catch(
60 (error: unknown) => reportScratchFailure("Could not start without a project", error),
61 );
62 }
63 };
64
65 return { scratchWorkspaceRootFor, scratchEnvironmentId, openScratchProject, startScratchThread };
66}