The best way to control Claude Code, Codex and more from any computer or phone

main
ts 484 lines 16.5 KB
Raw
1 import * as Dialog from "../components/ui/Dialog";
2 import { msg } from "gt-react-native";
3 import { m } from "../i18n/messages";
4 import { useServerConfigs } from "./entities";
5 import {
6 questionAttachmentDraftKey,
7 questionAttachmentDraftPrefix,
8 questionAttachmentPreparationAtom,
9 } from "./question-attachments";
10 import {
11 appendUnsentQuestionAttachments,
12 resolveQuestionImagePreparations,
13 } from "./question-attachment-preparation";
14 import { scopedThreadKey } from "../lib/scopedEntities";
15 import {
16 clearComposerDraft,
17 composerDraftsAtom,
18 questionAttachmentDraftsAtom,
19 } from "./use-composer-drafts";
20 import {
21 composerAttachmentUploadsAtom,
22 composerAttachmentUploadBlockReason,
23 composerAttachmentsStillUploading,
24 } from "./composer-attachment-uploads";
25 import { useAtomValue } from "@effect/atom-react";
26 import { useRef, useState } from "react";
27
28 import {
29 type EnvironmentId,
30 type ProviderApprovalDecision,
31 type RuntimeRequestId,
32 type ThreadId,
33 } from "@t3tools/contracts";
34 import {
35 type PendingThreadRequests,
36 type ThreadUserInputQuestion,
37 onThreadRequestsResolved,
38 pruneResolvedUserInputDrafts,
39 resolvedQuestionDraftKeys,
40 seedUserInputDraftAnswers,
41 userInputDraftKey,
42 } from "@t3tools/client-runtime/state/thread-requests";
43 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
44 import { Atom } from "effect/reactivity";
45
46 import { environmentThreadDetails, threadEnvironment } from "./threads";
47 import {
48 buildPendingUserInputAnswers,
49 setPendingUserInputCustomAnswer,
50 togglePendingUserInputOptionSelection,
51 type PendingUserInputDraftAnswer,
52 } from "@t3tools/client-runtime/state/pending-user-input";
53 import { appAtomRegistry } from "./atom-registry";
54 import { useSelectedThreadPendingRequests } from "./use-thread-detail";
55 import { useThreadSelection } from "./use-thread-selection";
56 import { useAtomCommand } from "./use-atom-command";
57 import { readEnvironmentScope } from "./session";
58
59 const EMPTY_PENDING_REQUESTS: PendingThreadRequests = { approvals: [], userInputs: [] };
60
61 const userInputDraftsByRequestKeyAtom = Atom.make<
62 Record<string, Record<string, PendingUserInputDraftAnswer>>
63 >({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
64
65 // Writes start from the suggested answer the user was looking at.
66 function seededDraft(
67 drafts: Record<string, PendingUserInputDraftAnswer> | undefined,
68 question: ThreadUserInputQuestion,
69 ): PendingUserInputDraftAnswer | undefined {
70 return seedUserInputDraftAnswers([question], drafts ?? {})[question.id];
71 }
72
73 function setUserInputDraftOption(
74 requestKey: string,
75 question: ThreadUserInputQuestion,
76 value: string,
77 ): void {
78 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
79 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
80 ...current,
81 [requestKey]: {
82 ...current[requestKey],
83 [question.id]: togglePendingUserInputOptionSelection(
84 question,
85 seededDraft(current[requestKey], question),
86 value,
87 ),
88 },
89 });
90 }
91
92 function setUserInputDraftCustomAnswer(
93 requestKey: string,
94 question: ThreadUserInputQuestion,
95 customAnswer: string,
96 ): void {
97 const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
98 appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
99 ...current,
100 [requestKey]: {
101 ...current[requestKey],
102 [question.id]: setPendingUserInputCustomAnswer(
103 question,
104 seededDraft(current[requestKey], question),
105 customAnswer,
106 ),
107 },
108 });
109 }
110
111 /** Drops a thread's answer and attachment drafts for every request outside `pendingRequestIds`. */
112 function pruneResolvedRequestDrafts(
113 environmentId: EnvironmentId,
114 threadId: ThreadId,
115 pendingRequestIds: ReadonlyArray<RuntimeRequestId>,
116 unansweredRequestIds: ReadonlyArray<RuntimeRequestId> = [],
117 ): void {
118 const drafts = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
119 const prunedDrafts = pruneResolvedUserInputDrafts(
120 drafts,
121 environmentId,
122 threadId,
123 pendingRequestIds,
124 );
125 if (prunedDrafts !== drafts) appAtomRegistry.set(userInputDraftsByRequestKeyAtom, prunedDrafts);
126
127 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
128 const attachmentDrafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix));
129 const counts = { ...appAtomRegistry.get(questionAttachmentPreparationAtom) };
130 let changed = false;
131 const resolved = resolvedQuestionDraftKeys(
132 new Set([...Object.keys(attachmentDrafts), ...Object.keys(counts)]),
133 prefix,
134 pendingRequestIds,
135 );
136 const discard = new Set(resolvedQuestionDraftKeys(resolved, prefix, unansweredRequestIds));
137 const threadKey = scopedThreadKey(environmentId, threadId);
138 for (const key of resolved) {
139 resolveQuestionImagePreparations(key, discard.has(key) ? null : threadKey);
140 if (attachmentDrafts[key]) clearComposerDraft(key);
141 if (key in counts) {
142 delete counts[key];
143 changed = true;
144 }
145 }
146 if (changed) appAtomRegistry.set(questionAttachmentPreparationAtom, counts);
147 }
148
149 /**
150 * Stop cancels an open question and a provider timeout expires it; neither sent
151 * its attachments, so they move to the thread's own draft before pruning.
152 */
153 function returnUnsentAttachmentsToThreadDraft(
154 environmentId: EnvironmentId,
155 threadId: ThreadId,
156 unansweredRequestIds: ReadonlyArray<RuntimeRequestId>,
157 ): void {
158 if (unansweredRequestIds.length === 0) return;
159 const prefix = questionAttachmentDraftPrefix(environmentId, threadId);
160 const drafts = appAtomRegistry.get(questionAttachmentDraftsAtom(prefix));
161 const otherRequestKeys = new Set(
162 resolvedQuestionDraftKeys(Object.keys(drafts), prefix, unansweredRequestIds),
163 );
164 const attachments = Object.entries(drafts).flatMap(([key, draft]) =>
165 otherRequestKeys.has(key) ? [] : draft.attachments,
166 );
167 appendUnsentQuestionAttachments(scopedThreadKey(environmentId, threadId), attachments);
168 }
169
170 // Resolution can come from anywhere: another device, an interrupt, the turn
171 // ending, or a reload over drafts for requests that resolved meanwhile.
172 onThreadRequestsResolved(({ environmentId, threadId, pendingRequestIds, unansweredRequestIds }) => {
173 returnUnsentAttachmentsToThreadDraft(environmentId, threadId, unansweredRequestIds);
174 pruneResolvedRequestDrafts(environmentId, threadId, pendingRequestIds, unansweredRequestIds);
175 });
176
177 /**
178 * Drops `answeredRequestId`'s drafts as soon as the server accepts the
179 * response, before the projection push that resolves it lands.
180 */
181 function collectAnsweredRequestDrafts(
182 environmentId: EnvironmentId,
183 threadId: ThreadId,
184 answeredRequestId: RuntimeRequestId,
185 ) {
186 const current = appAtomRegistry.get(
187 environmentThreadDetails.pendingRequestsAtom({ environmentId, threadId }),
188 );
189 // Missing detail is not resolution.
190 if (current === null) return;
191 pruneResolvedRequestDrafts(
192 environmentId,
193 threadId,
194 [...current.approvals, ...current.userInputs]
195 .map((request) => request.requestId)
196 .filter((requestId) => requestId !== answeredRequestId),
197 );
198 }
199
200 export function useSelectedThreadRequests() {
201 const respondToApproval = useAtomCommand(
202 threadEnvironment.respondToApproval,
203 "thread approval response",
204 );
205 const respondToUserInput = useAtomCommand(
206 threadEnvironment.respondToUserInput,
207 "thread user input response",
208 );
209 const dismissUserInput = useAtomCommand(
210 threadEnvironment.dismissUserInput,
211 "thread user input dismissal",
212 );
213 const { selectedThread: selectedThreadShell } = useThreadSelection();
214 const pendingRequests = useSelectedThreadPendingRequests();
215 const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
216 const userInputResponsesInFlight = useRef(new Set<string>());
217 const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
218 const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
219
220 const activePendingApprovals = pendingRequests?.approvals ?? EMPTY_PENDING_REQUESTS.approvals;
221 const activePendingApproval = activePendingApprovals[0] ?? null;
222 const activePendingUserInputs = pendingRequests?.userInputs ?? EMPTY_PENDING_REQUESTS.userInputs;
223 const activePendingUserInput = activePendingUserInputs[0] ?? null;
224 const questionServerConfigs = useServerConfigs();
225 const attachmentDrafts = useAtomValue(
226 questionAttachmentDraftsAtom(
227 selectedThreadShell
228 ? questionAttachmentDraftPrefix(selectedThreadShell.environmentId, selectedThreadShell.id)
229 : "",
230 ),
231 );
232 const preparationCounts = useAtomValue(questionAttachmentPreparationAtom);
233 const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
234 // Suggested answers are shown until the user edits them; only edits are stored.
235 const activePendingUserInputAnswerDrafts =
236 activePendingUserInput && selectedThreadShell
237 ? seedUserInputDraftAnswers(
238 activePendingUserInput.questions,
239 userInputDraftsByRequestKey[
240 userInputDraftKey(
241 selectedThreadShell.environmentId,
242 selectedThreadShell.id,
243 activePendingUserInput.requestId,
244 )
245 ] ?? {},
246 )
247 : {};
248 const activePendingUserInputDrafts =
249 activePendingUserInput && selectedThreadShell
250 ? Object.fromEntries(
251 activePendingUserInput.questions.map((question) => {
252 const key = questionAttachmentDraftKey(
253 selectedThreadShell.environmentId,
254 selectedThreadShell.id,
255 activePendingUserInput.requestId,
256 question.id,
257 );
258 const attachments = attachmentDrafts[key]?.attachments ?? [];
259 const uploadInput = {
260 environmentId: selectedThreadShell.environmentId,
261 attachments,
262 serverConfig: questionServerConfigs.get(selectedThreadShell.environmentId) ?? null,
263 states: uploadStates,
264 };
265 return [
266 question.id,
267 {
268 ...activePendingUserInputAnswerDrafts[question.id],
269 attachmentCount: attachments.length,
270 attachmentsBlocked:
271 (attachments.length > 0 &&
272 questionServerConfigs.get(selectedThreadShell.environmentId) === undefined) ||
273 (preparationCounts[key] ?? 0) > 0 ||
274 composerAttachmentsStillUploading(uploadInput) ||
275 composerAttachmentUploadBlockReason({
276 ...uploadInput,
277 connected: true,
278 }) !== null,
279 },
280 ];
281 }),
282 )
283 : {};
284 const activePendingUserInputAnswers = activePendingUserInput
285 ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingUserInputDrafts)
286 : null;
287
288 const onSelectUserInputOption = (
289 requestId: RuntimeRequestId,
290 question: ThreadUserInputQuestion,
291 value: string,
292 ) => {
293 if (!selectedThreadShell) {
294 return;
295 }
296
297 const requestKey = userInputDraftKey(
298 selectedThreadShell.environmentId,
299 selectedThreadShell.id,
300 requestId,
301 );
302 setUserInputDraftOption(requestKey, question, value);
303 };
304
305 const onChangeUserInputCustomAnswer = (
306 requestId: RuntimeRequestId,
307 questionId: string,
308 customAnswer: string,
309 ) => {
310 const question = activePendingUserInputs
311 .find((request) => request.requestId === requestId)
312 ?.questions.find((entry) => entry.id === questionId);
313 if (!selectedThreadShell || !question) {
314 return;
315 }
316
317 const requestKey = userInputDraftKey(
318 selectedThreadShell.environmentId,
319 selectedThreadShell.id,
320 requestId,
321 );
322 setUserInputDraftCustomAnswer(requestKey, question, customAnswer);
323 };
324
325 const onRespondToApproval = async (
326 requestId: RuntimeRequestId,
327 decision: ProviderApprovalDecision,
328 feedback?: string,
329 ) => {
330 if (
331 !selectedThreadShell ||
332 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
333 ) {
334 return;
335 }
336 if (
337 activePendingApprovals.find((approval) => approval.requestId === requestId)
338 ?.responseCapability !== "live"
339 ) {
340 return;
341 }
342
343 setRespondingApprovalId(requestId);
344 const result = await respondToApproval({
345 environmentId: selectedThreadShell.environmentId,
346 input: {
347 threadId: selectedThreadShell.id,
348 requestId,
349 decision,
350 ...(feedback === undefined ? {} : { feedback }),
351 },
352 });
353 setRespondingApprovalId((current) => (current === requestId ? null : current));
354 return result;
355 };
356
357 const onSubmitUserInput = async () => {
358 if (
359 !selectedThreadShell ||
360 !activePendingUserInput ||
361 activePendingUserInput.responseCapability === "not_resumable" ||
362 !activePendingUserInputAnswers ||
363 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
364 ) {
365 return;
366 }
367
368 const responseKey = questionAttachmentDraftKey(
369 selectedThreadShell.environmentId,
370 selectedThreadShell.id,
371 activePendingUserInput.requestId,
372 "",
373 );
374 if (userInputResponsesInFlight.current.has(responseKey)) return;
375 const attachmentsByQuestionId = new Map<
376 string,
377 import("@t3tools/contracts").UserInputAttachments[string]
378 >();
379 for (const question of activePendingUserInput.questions) {
380 const key = questionAttachmentDraftKey(
381 selectedThreadShell.environmentId,
382 selectedThreadShell.id,
383 activePendingUserInput.requestId,
384 question.id,
385 );
386 if ((appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0) return;
387 const attachments = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments ?? [];
388 if (attachments.length === 0) continue;
389 if (
390 attachments.some(
391 (attachment) =>
392 !attachment.uploadedAttachmentId ||
393 attachment.uploadEnvironmentId !== selectedThreadShell.environmentId,
394 )
395 ) {
396 Dialog.alert(
397 m(msg("Attachments are not ready")),
398 m(msg("Wait for uploads to finish, or retry failed uploads.")),
399 );
400 return;
401 }
402 attachmentsByQuestionId.set(
403 question.id,
404 attachments.map((attachment) => ({
405 type: attachment.type,
406 id: attachment.uploadedAttachmentId!,
407 name: attachment.name,
408 mimeType: attachment.mimeType,
409 sizeBytes: attachment.sizeBytes,
410 })),
411 );
412 }
413 userInputResponsesInFlight.current.add(responseKey);
414 setRespondingUserInputId(activePendingUserInput.requestId);
415 const result = await respondToUserInput({
416 environmentId: selectedThreadShell.environmentId,
417 input: {
418 threadId: selectedThreadShell.id,
419 requestId: activePendingUserInput.requestId,
420 answers: activePendingUserInputAnswers,
421 ...(attachmentsByQuestionId.size > 0
422 ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) }
423 : {}),
424 },
425 });
426 userInputResponsesInFlight.current.delete(responseKey);
427 setRespondingUserInputId((current) =>
428 current === activePendingUserInput.requestId ? null : current,
429 );
430 if (result._tag === "Success") {
431 collectAnsweredRequestDrafts(
432 selectedThreadShell.environmentId,
433 selectedThreadShell.id,
434 activePendingUserInput.requestId,
435 );
436 }
437 return result;
438 };
439
440 const onDismissUserInput = async () => {
441 if (
442 !selectedThreadShell ||
443 !activePendingUserInput ||
444 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
445 ) {
446 return;
447 }
448
449 setRespondingUserInputId(activePendingUserInput.requestId);
450 const result = await dismissUserInput({
451 environmentId: selectedThreadShell.environmentId,
452 input: {
453 threadId: selectedThreadShell.id,
454 requestId: activePendingUserInput.requestId,
455 },
456 });
457 setRespondingUserInputId((current) =>
458 current === activePendingUserInput.requestId ? null : current,
459 );
460 if (result._tag === "Success") {
461 collectAnsweredRequestDrafts(
462 selectedThreadShell.environmentId,
463 selectedThreadShell.id,
464 activePendingUserInput.requestId,
465 );
466 }
467 return result;
468 };
469
470 return {
471 activePendingApproval,
472 activePendingApprovals,
473 activePendingUserInput,
474 activePendingUserInputDrafts,
475 activePendingUserInputAnswers,
476 respondingApprovalId,
477 respondingUserInputId,
478 onRespondToApproval,
479 onSelectUserInputOption,
480 onChangeUserInputCustomAnswer,
481 onSubmitUserInput,
482 onDismissUserInput,
483 };
484 }