Open History to see the last commit
1import { useCallback } from "react";
2
3import { scopeThreadRef } from "@t3tools/client-runtime/environment";
4import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
5import { mapAtomCommandResult } from "@t3tools/client-runtime/state/runtime";
6import {
7 ThreadId,
8 type ModelSelection,
9 type ProviderInteractionMode,
10 type RuntimeMode,
11} from "@t3tools/contracts";
12import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
13import * as Cause from "effect/Cause";
14import { AsyncResult } from "effect/unstable/reactivity";
15
16import { threadEnvironment } from "../../state/threads";
17import type { DraftComposerAttachment } from "../../lib/composerImages";
18import { prepareTurnAttachments, validateDraftFileAttachments } from "../../lib/attachmentUpload";
19import { makeTurnCommandMetadata, type TurnCommandMetadata } from "../../lib/commandMetadata";
20import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
21import { randomHex } from "../../lib/uuid";
22import { useAtomCommand } from "../../state/use-atom-command";
23import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts";
24import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
25import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
26import { appAtomRegistry } from "../../state/atom-registry";
27import { serverEnvironment } from "../../state/server";
28
29export function useCreateProjectThread() {
30 const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
31
32 return useCallback(
33 async (input: {
34 readonly project: EnvironmentProject;
35 readonly modelSelection: ModelSelection;
36 readonly envMode: "local" | "worktree";
37 readonly branch: string | null;
38 readonly worktreePath: string | null;
39 readonly startFromOrigin?: boolean;
40 readonly runtimeMode: RuntimeMode;
41 readonly interactionMode: ProviderInteractionMode;
42 readonly initialMessageText: string;
43 readonly initialAttachments: ReadonlyArray<DraftComposerAttachment>;
44 readonly onAttachmentsUploaded: (
45 attachments: ReadonlyArray<DraftComposerAttachment>,
46 ) => Promise<void>;
47 /** Reuse identifiers from a queued pending task instead of minting new ones. */
48 readonly turnMetadata?: TurnCommandMetadata;
49 }) => {
50 const metadata = input.turnMetadata ?? makeTurnCommandMetadata();
51 const threadId = ThreadId.make(metadata.threadId);
52 const initialMessageText = input.initialMessageText.trim();
53
54 const validationError = validateProjectThreadCreation({
55 environmentId: input.project.environmentId,
56 projectId: input.project.id,
57 environmentMode: input.envMode,
58 branch: input.branch,
59 initialMessageText,
60 });
61 if (validationError !== null) {
62 setPendingConnectionError(validationError.message);
63 return AsyncResult.failure(Cause.fail(validationError));
64 }
65
66 const validateLiveFileAttachments = (
67 attachments: ReadonlyArray<DraftComposerAttachment>,
68 ): string | null =>
69 validateDraftFileAttachments({
70 attachments,
71 serverConfig: appAtomRegistry.get(
72 serverEnvironment.configValueAtom(input.project.environmentId),
73 ),
74 });
75 const initialAttachmentError = validateLiveFileAttachments(input.initialAttachments);
76 if (initialAttachmentError !== null) {
77 setPendingConnectionError(initialAttachmentError);
78 return AsyncResult.failure(Cause.fail(new Error(initialAttachmentError)));
79 }
80
81 let prepared: Awaited<ReturnType<typeof prepareTurnAttachments>>;
82 try {
83 // If persisting the references into the draft throws, the owner call
84 // deletes the pending uploads it minted before rethrowing.
85 prepared = await prepareTurnAttachments({
86 environmentId: input.project.environmentId,
87 attachments: input.initialAttachments,
88 supportsImageUploads:
89 appAtomRegistry.get(serverEnvironment.configValueAtom(input.project.environmentId))
90 ?.environment.capabilities.attachmentUploads === true,
91 persistUploadedReferences: async (draftAttachments) => {
92 await input.onAttachmentsUploaded(draftAttachments);
93 return "persisted";
94 },
95 });
96 } catch (error) {
97 const message = error instanceof Error ? error.message : "An attachment could not upload.";
98 setPendingConnectionError(message);
99 return AsyncResult.failure(Cause.fail(new Error(message)));
100 }
101 if (prepared.status !== "ready") {
102 const message = "The attachments are no longer available.";
103 setPendingConnectionError(message);
104 return AsyncResult.failure(Cause.fail(new Error(message)));
105 }
106
107 const preparedAttachmentError = validateLiveFileAttachments(prepared.draftAttachments);
108 if (preparedAttachmentError !== null) {
109 setPendingConnectionError(preparedAttachmentError);
110 return AsyncResult.failure(Cause.fail(new Error(preparedAttachmentError)));
111 }
112
113 const result = await startTurn({
114 environmentId: input.project.environmentId,
115 input: buildProjectThreadStartTurnInput({
116 projectId: input.project.id,
117 projectCwd: input.project.workspaceRoot,
118 threadId: metadata.threadId,
119 commandId: metadata.commandId,
120 messageId: metadata.messageId,
121 createdAt: metadata.createdAt,
122 text: initialMessageText,
123 attachments: input.initialAttachments,
124 uploadedAttachments: prepared.attachments,
125 modelSelection: input.modelSelection,
126 runtimeMode: input.runtimeMode,
127 interactionMode: input.interactionMode,
128 workspaceMode: input.envMode,
129 branch: input.branch,
130 worktreePath: input.worktreePath,
131 startFromOrigin: input.startFromOrigin ?? false,
132 worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
133 }),
134 });
135 if (AsyncResult.isFailure(result)) {
136 const error = Cause.squash(result.cause);
137 setPendingConnectionError(
138 error instanceof Error ? error.message : "The task could not be started.",
139 );
140 return AsyncResult.failure(result.cause);
141 }
142 // The started turn holds its own copy of the bytes; a failed delete is
143 // surfaced without failing the started task.
144 await prepared.releaseUploads().catch((error) => {
145 console.warn("[project-thread] could not delete consumed pending uploads", error);
146 });
147 setPendingConnectionError(null);
148 scheduleUnusedComposerAttachmentCleanup(input.initialAttachments);
149
150 return mapAtomCommandResult(result, () =>
151 scopeThreadRef(input.project.environmentId, threadId),
152 );
153 },
154 [startTurn],
155 );
156}