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

main
ts 108 lines 3.89 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { msg } from "gt-react-native";
3 import { useEffect } from "react";
4 import { AppState } from "react-native";
5 import * as Atom from "effect/reactivity/Atom";
6 import * as Schema from "effect/Schema";
7 import { appAtomRegistry } from "../../state/atom-registry";
8 import { writeFileAtomically } from "../../lib/atomic-file";
9 import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";
10 import {
11 EMPTY_REVIEW_DRAFT,
12 ReviewDraftDocument,
13 pullRequestReviewKey,
14 type ReviewDraft,
15 } from "./pullRequestReviewDrafts";
16 import type { PullRequestParams } from "./usePullRequestDiff";
17 import { m } from "../../i18n/messages";
18
19 const state = Atom.make<{
20 drafts: Record<string, ReviewDraft>;
21 ready: boolean;
22 error: string | null;
23 }>({ drafts: {}, ready: false, error: null }).pipe(Atom.keepAlive);
24 const decodeDocument = Schema.decodeUnknownSync(ReviewDraftDocument);
25 const queue = new SerializedAsyncQueue();
26 let loading: Promise<void> | null = null;
27 let timer: ReturnType<typeof setTimeout> | null = null;
28 let savedDrafts: Record<string, ReviewDraft> | null = null;
29 async function draftFile() {
30 const { Directory, File, Paths } = await import("expo-file-system");
31 const directory = new Directory(Paths.document, "pull-request-drafts");
32 directory.create({ idempotent: true, intermediates: true });
33 return new File(directory, "drafts.json");
34 }
35 function load() {
36 if (loading) return loading;
37 loading = (async () => {
38 try {
39 const file = await draftFile();
40 const drafts = file.exists ? decodeDocument(JSON.parse(await file.text())).drafts : {};
41 savedDrafts = drafts;
42 appAtomRegistry.set(state, { drafts, ready: true, error: null });
43 } catch {
44 appAtomRegistry.set(state, {
45 ...appAtomRegistry.get(state),
46 error: m(msg("Could not restore review drafts. Reopen this screen to retry.")),
47 });
48 loading = null;
49 }
50 })();
51 return loading;
52 }
53 async function persist() {
54 if (timer) clearTimeout(timer);
55 timer = null;
56 await queue.run(async () => {
57 const current = appAtomRegistry.get(state);
58 if (!current.ready || current.drafts === savedDrafts) return;
59 try {
60 const drafts = Object.fromEntries(
61 Object.entries(current.drafts).filter(
62 ([, draft]) => draft.summary || draft.comment || draft.comments.length,
63 ),
64 );
65 await writeFileAtomically(await draftFile(), JSON.stringify({ version: 1, drafts }));
66 savedDrafts = current.drafts;
67 if (appAtomRegistry.get(state).error)
68 appAtomRegistry.set(state, { ...appAtomRegistry.get(state), error: null });
69 } catch {
70 appAtomRegistry.set(state, {
71 ...appAtomRegistry.get(state),
72 error: m(msg("Drafts are kept in this session, but could not be saved on this device.")),
73 });
74 }
75 });
76 }
77 export function usePullRequestReviewDraft(params: PullRequestParams) {
78 const snapshot = useAtomValue(state);
79 const key = pullRequestReviewKey(params);
80 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads review drafts from disk and persists them when AppState leaves active and on unmount
81 useEffect(() => {
82 void load();
83 const listener = AppState.addEventListener("change", (phase) => {
84 if (phase !== "active") void persist();
85 });
86 return () => {
87 listener.remove();
88 void persist();
89 };
90 }, []);
91 const update = (transform: (current: ReviewDraft) => ReviewDraft) => {
92 const current = appAtomRegistry.get(state);
93 if (!current.ready) return;
94 appAtomRegistry.set(state, {
95 ...current,
96 drafts: { ...current.drafts, [key]: transform(current.drafts[key] ?? EMPTY_REVIEW_DRAFT) },
97 });
98 if (timer) clearTimeout(timer);
99 timer = setTimeout(() => void persist(), 200);
100 };
101 return {
102 draft: snapshot.drafts[key] ?? EMPTY_REVIEW_DRAFT,
103 ready: snapshot.ready,
104 error: snapshot.error,
105 update,
106 flush: persist,
107 };
108 }