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

use-project-actions.ts

153 lines6.6 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 { 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 persistUploadedReferences: async (draftAttachments) => {
89 await input.onAttachmentsUploaded(draftAttachments);
90 return "persisted";
91 },
92 });
93 } catch (error) {
94 const message = error instanceof Error ? error.message : "An attachment could not upload.";
95 setPendingConnectionError(message);
96 return AsyncResult.failure(Cause.fail(new Error(message)));
97 }
98 if (prepared.status !== "ready") {
99 const message = "The attachments are no longer available.";
100 setPendingConnectionError(message);
101 return AsyncResult.failure(Cause.fail(new Error(message)));
102 }
103​
104 const preparedAttachmentError = validateLiveFileAttachments(prepared.draftAttachments);
105 if (preparedAttachmentError !== null) {
106 setPendingConnectionError(preparedAttachmentError);
107 return AsyncResult.failure(Cause.fail(new Error(preparedAttachmentError)));
108 }
109​
110 const result = await startTurn({
111 environmentId: input.project.environmentId,
112 input: buildProjectThreadStartTurnInput({
113 projectId: input.project.id,
114 projectCwd: input.project.workspaceRoot,
115 threadId: metadata.threadId,
116 commandId: metadata.commandId,
117 messageId: metadata.messageId,
118 createdAt: metadata.createdAt,
119 text: initialMessageText,
120 attachments: input.initialAttachments,
121 uploadedAttachments: prepared.attachments,
122 modelSelection: input.modelSelection,
123 runtimeMode: input.runtimeMode,
124 interactionMode: input.interactionMode,
125 workspaceMode: input.envMode,
126 branch: input.branch,
127 worktreePath: input.worktreePath,
128 startFromOrigin: input.startFromOrigin ?? false,
129 worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
130 }),
131 });
132 if (AsyncResult.isFailure(result)) {
133 const error = Cause.squash(result.cause);
134 setPendingConnectionError(
135 error instanceof Error ? error.message : "The task could not be started.",
136 );
137 return AsyncResult.failure(result.cause);
138 }
139 // The started turn holds its own copy of the bytes; a failed delete is
140 // surfaced without failing the started task.
141 await prepared.releaseUploads().catch((error) => {
142 console.warn("[project-thread] could not delete consumed pending uploads", error);
143 });
144 setPendingConnectionError(null);
145 scheduleUnusedComposerAttachmentCleanup(input.initialAttachments);
146​
147 return mapAtomCommandResult(result, () =>
148 scopeThreadRef(input.project.environmentId, threadId),
149 );
150 },
151 [startTurn],
152 );