Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-project-actions.ts

174 lines7.7 KB

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 { isModelSelectionUnavailable } from "../../lib/modelOptions";
23import { useAtomCommand } from "../../state/use-atom-command";
24import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts";
25import { setPendingConnectionError } from "../../state/use-remote-environment-registry";
26import { validateProjectThreadCreation } from "./projectThreadCreationValidation";
27import { appAtomRegistry } from "../../state/atom-registry";
28import { serverEnvironment } from "../../state/server";
29import { resolveProviderInteractionMode } from "./legacy-plan-mode";
30​
31export function useCreateProjectThread() {
32 const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
33​
34 return useCallback(
35 async (input: {
36 readonly project: EnvironmentProject;
37 readonly modelSelection: ModelSelection;
38 readonly envMode: "local" | "worktree";
39 readonly branch: string | null;
40 readonly worktreePath: string | null;
41 readonly startFromOrigin?: boolean;
42 readonly runtimeMode: RuntimeMode;
43 readonly interactionMode: ProviderInteractionMode;
44 readonly initialMessageText: string;
45 readonly initialAttachments: ReadonlyArray<DraftComposerAttachment>;
46 readonly onAttachmentsUploaded: (
47 attachments: ReadonlyArray<DraftComposerAttachment>,
48 ) => Promise<void>;
49 /** Reuse identifiers from a queued pending task instead of minting new ones. */
50 readonly turnMetadata?: TurnCommandMetadata;
51 }) => {
52 const metadata = input.turnMetadata ?? makeTurnCommandMetadata();
53 const threadId = ThreadId.make(metadata.threadId);
54 const initialMessageText = input.initialMessageText.trim();
55​
56 const validationError = validateProjectThreadCreation({
57 environmentId: input.project.environmentId,
58 projectId: input.project.id,
59 environmentMode: input.envMode,
60 branch: input.branch,
61 initialMessageText,
62 });
63 if (validationError !== null) {
64 setPendingConnectionError(validationError.message);
65 return AsyncResult.failure(Cause.fail(validationError));
66 }
67​
68 const validateLiveFileAttachments = (
69 attachments: ReadonlyArray<DraftComposerAttachment>,
70 ): string | null =>
71 validateDraftFileAttachments({
72 attachments,
73 serverConfig: appAtomRegistry.get(
74 serverEnvironment.configValueAtom(input.project.environmentId),
75 ),
76 });
77 const initialAttachmentError = validateLiveFileAttachments(input.initialAttachments);
78 if (initialAttachmentError !== null) {
79 setPendingConnectionError(initialAttachmentError);
80 return AsyncResult.failure(Cause.fail(new Error(initialAttachmentError)));
81 }
82​
83 let prepared: Awaited<ReturnType<typeof prepareTurnAttachments>>;
84 try {
85 // If persisting the references into the draft throws, the owner call
86 // deletes the pending uploads it minted before rethrowing.
87 prepared = await prepareTurnAttachments({
88 environmentId: input.project.environmentId,
89 attachments: input.initialAttachments,
90 supportsImageUploads:
91 appAtomRegistry.get(serverEnvironment.configValueAtom(input.project.environmentId))
92 ?.environment.capabilities.attachmentUploads === true,
93 persistUploadedReferences: async (draftAttachments) => {
94 await input.onAttachmentsUploaded(draftAttachments);
95 return "persisted";
96 },
97 });
98 } catch (error) {
99 const message = error instanceof Error ? error.message : "An attachment could not upload.";
100 setPendingConnectionError(message);
101 return AsyncResult.failure(Cause.fail(new Error(message)));
102 }
103 if (prepared.status !== "ready") {
104 const message = "The attachments are no longer available.";
105 setPendingConnectionError(message);
106 return AsyncResult.failure(Cause.fail(new Error(message)));
107 }
108​
109 const preparedAttachmentError = validateLiveFileAttachments(prepared.draftAttachments);
110 if (preparedAttachmentError !== null) {
111 setPendingConnectionError(preparedAttachmentError);
112 return AsyncResult.failure(Cause.fail(new Error(preparedAttachmentError)));
113 }
114​
115 const serverConfig = appAtomRegistry.get(
116 serverEnvironment.configValueAtom(input.project.environmentId),
117 );
118 const providerError = !serverConfig
119 ? "Provider settings are still loading. Try again."
120 : isModelSelectionUnavailable(serverConfig, input.modelSelection)
121 ? "Antigravity model unavailable. Open model settings to finish setup or choose another model."
122 : null;
123 if (providerError !== null) {
124 setPendingConnectionError(providerError);
125 return AsyncResult.failure(Cause.fail(new Error(providerError)));
126 }
127 const provider = serverConfig?.providers.find(
128 (candidate) => candidate.instanceId === input.modelSelection.instanceId,
129 );
130​
131 const result = await startTurn({
132 environmentId: input.project.environmentId,
133 input: buildProjectThreadStartTurnInput({
134 projectId: input.project.id,
135 projectCwd: input.project.workspaceRoot,
136 threadId: metadata.threadId,
137 commandId: metadata.commandId,
138 messageId: metadata.messageId,
139 createdAt: metadata.createdAt,
140 text: initialMessageText,
141 attachments: input.initialAttachments,
142 uploadedAttachments: prepared.attachments,
143 modelSelection: input.modelSelection,
144 runtimeMode: input.runtimeMode,
145 interactionMode: resolveProviderInteractionMode(provider, input.interactionMode),
146 workspaceMode: input.envMode,
147 branch: input.branch,
148 worktreePath: input.worktreePath,
149 startFromOrigin: input.startFromOrigin ?? false,
150 worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
151 }),
152 });
153 if (AsyncResult.isFailure(result)) {
154 const error = Cause.squash(result.cause);
155 setPendingConnectionError(
156 error instanceof Error ? error.message : "The task could not be started.",
157 );
158 return AsyncResult.failure(result.cause);
159 }
160 // The started turn holds its own copy of the bytes; a failed delete is
161 // surfaced without failing the started task.
162 await prepared.releaseUploads().catch((error) => {
163 console.warn("[project-thread] could not delete consumed pending uploads", error);
164 });
165 setPendingConnectionError(null);
166 scheduleUnusedComposerAttachmentCleanup(input.initialAttachments);
167​
168 return mapAtomCommandResult(result, () =>
169 scopeThreadRef(input.project.environmentId, threadId),
170 );
171 },
172 [startTurn],
173 );