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

main
ts 60 lines 2.25 KB
Raw
1 import { useEffect, useEffectEvent, useRef, useState } from "react";
2 import type { ActiveTurnComposerAction } from "@t3tools/client-runtime/state/composer-dispatch";
3
4 export function useSubmitAfterNativeImages(props: {
5 readonly draftKey: string;
6 readonly readResetGeneration: () => number;
7 readonly blocked: boolean;
8 readonly onPasteImages: (uris: ReadonlyArray<string>) => Promise<boolean>;
9 readonly onSubmit: (followUp?: ActiveTurnComposerAction) => void;
10 }) {
11 type HeldSend = {
12 readonly draftKey: string;
13 readonly generation: number;
14 readonly followUp?: ActiveTurnComposerAction;
15 };
16 const pendingCount = useRef(0);
17 const failed = useRef(false);
18 const heldSend = useRef<HeldSend | null>(null);
19 const [releasedSend, setReleasedSend] = useState<HeldSend | null>(null);
20 const consumedSend = useRef<HeldSend | null>(null);
21 const sendReleased = useEffectEvent((held: HeldSend) => {
22 if (held.draftKey === props.draftKey && held.generation === props.readResetGeneration()) {
23 props.onSubmit(held.followUp);
24 }
25 });
26 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- submits from the render where the native images joined the draft
27 useEffect(() => {
28 if (!releasedSend || props.blocked || consumedSend.current === releasedSend) return;
29 consumedSend.current = releasedSend;
30 sendReleased(releasedSend);
31 }, [releasedSend, props.blocked]);
32 return {
33 deferSend: (followUp?: ActiveTurnComposerAction) => {
34 if (pendingCount.current === 0) return false;
35 heldSend.current = {
36 draftKey: props.draftKey,
37 generation: props.readResetGeneration(),
38 followUp,
39 };
40 return true;
41 },
42 pasteImages: (uris: ReadonlyArray<string>) => {
43 if (pendingCount.current === 0) failed.current = false;
44 pendingCount.current += 1;
45 const finish = (success: boolean) => {
46 if (!success) failed.current = true;
47 pendingCount.current -= 1;
48 if (pendingCount.current === 0) {
49 const held = heldSend.current;
50 heldSend.current = null;
51 if (held && !failed.current) setReleasedSend(held);
52 }
53 };
54 return props.onPasteImages(uris).then(finish, (error: unknown) => {
55 finish(false);
56 throw error;
57 });
58 },
59 };
60 }