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

main
ts 178 lines 6.67 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import {
3 type AtomCommandResult,
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6 } from "@t3tools/client-runtime/state/runtime";
7 import { msg } from "gt-react";
8 import { create } from "zustand";
9
10 import { stackedThreadToast, toastManager } from "../components/ui/toast";
11 import { m, type MessageResolver } from "../i18n/messages";
12 import { shortcutLabelForCommand } from "../keybindings";
13 import { announce, cancelAnnouncement } from "../lib/announce";
14 import { appAtomRegistry } from "../rpc/atomRegistry";
15 import { primaryServerKeybindingsAtom } from "../state/server";
16 import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
17
18 type UndoOptions = {
19 action: "Settled" | "Snoozed" | "Unpinned" | "Archived" | "Discarded";
20 undo: () => Promise<AtomCommandResult<unknown, unknown>>;
21 failureTitle: string;
22 claim: ReturnType<typeof ThreadUndo.begin>;
23 commit?: () => void;
24 };
25
26 type UndoNotice = {
27 action: UndoOptions["action"];
28 count: number;
29 undo: () => Promise<void>;
30 };
31
32 export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
33
34 const SUMMARY = {
35 Settled: msg("Settled {count, plural, one {{count} thread} other {{count} threads}}"),
36 Snoozed: msg("Snoozed {count, plural, one {{count} thread} other {{count} threads}}"),
37 Unpinned: msg("Unpinned {count, plural, one {{count} thread} other {{count} threads}}"),
38 Archived: msg("Archived {count, plural, one {{count} thread} other {{count} threads}}"),
39 Discarded: msg("Discarded {count, plural, one {{count} draft} other {{count} drafts}}"),
40 } satisfies Record<UndoOptions["action"], string>;
41
42 const UNDONE = {
43 Settled: msg("Undid settle of {count, plural, one {{count} thread} other {{count} threads}}"),
44 Snoozed: msg("Undid snooze of {count, plural, one {{count} thread} other {{count} threads}}"),
45 Unpinned: msg("Undid unpin of {count, plural, one {{count} thread} other {{count} threads}}"),
46 Archived: msg("Undid archive of {count, plural, one {{count} thread} other {{count} threads}}"),
47 Discarded: msg("Undid discard of {count, plural, one {{count} draft} other {{count} drafts}}"),
48 } satisfies Record<UndoOptions["action"], string>;
49
50 function threadUndoNoticeSummary(notice: Pick<UndoNotice, "action" | "count">): string {
51 return m(SUMMARY[notice.action], { count: notice.count });
52 }
53
54 /** Components pass `useMessages()` so the label follows a language switch. */
55 export function threadUndoLabel(
56 keybindings: Parameters<typeof shortcutLabelForCommand>[0],
57 resolve: MessageResolver = m,
58 ) {
59 const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
60 return shortcut ? resolve(msg("{shortcut} to undo", { shortcut })) : resolve(msg("Undo"));
61 }
62
63 let announcedSummary: string | null = null;
64
65 // A live region that mounts already filled is skipped by screen readers, and settling
66 // usually moves focus to the next thread at the same moment, so the notice is announced
67 // separately from the alert that shows it.
68 function setNotice(notice: UndoNotice | null) {
69 useThreadUndoNotice.setState({ notice });
70 const summary = notice ? threadUndoNoticeSummary(notice) : null;
71 if (summary === announcedSummary) return;
72 announcedSummary = summary;
73 if (summary) {
74 const label = threadUndoLabel(appAtomRegistry.get(primaryServerKeybindingsAtom));
75 announce(m(msg("{summary}, {label}", { summary, label })), "thread-undo-notice");
76 } else {
77 cancelAnnouncement("thread-undo-notice");
78 }
79 }
80
81 let liveUndos: UndoOptions[] = [];
82 let expiry: ReturnType<typeof setTimeout> | undefined;
83 // A new notice owns mod+z even inside a text field, until the user presses
84 // another key or edits text. After that, mod+z is the field's own undo again.
85 let shortcutClaimed = false;
86
87 function refreshNotice() {
88 const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
89 liveUndos = liveUndos.filter((entry) => !stale.includes(entry));
90 for (const entry of stale) entry.commit?.();
91 const latest = liveUndos.at(-1);
92 if (!latest) {
93 clearTimeout(expiry);
94 setNotice(null);
95 return;
96 }
97 const group: UndoOptions[] = [];
98 for (let index = liveUndos.length - 1; index >= 0; index--) {
99 const entry = liveUndos[index]!;
100 if (entry.action !== latest.action) break;
101 group.push(entry);
102 }
103 setNotice({
104 action: latest.action,
105 count: group.length,
106 undo: async () => {
107 const current = group.filter((entry) => liveUndos.includes(entry) && entry.claim.isCurrent());
108 liveUndos = liveUndos.filter((entry) => !group.includes(entry));
109 // Claim before awaiting to prevent repeated actions restoring a group twice.
110 for (const entry of current) entry.claim.finish();
111 refreshNotice();
112 let undone = 0;
113 await Promise.all(
114 current.map(async ({ undo, failureTitle }) => {
115 const reportFailure = (error: unknown) => {
116 toastManager.add(
117 stackedThreadToast({
118 type: "error",
119 title: failureTitle,
120 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
121 }),
122 );
123 };
124 try {
125 const result = await undo();
126 if (result._tag === "Success") undone++;
127 else if (!isAtomCommandInterrupted(result)) {
128 reportFailure(squashAtomCommandFailure(result));
129 }
130 } catch (error) {
131 reportFailure(error);
132 }
133 }),
134 );
135 // Failures already raise a toast, so only what was actually restored is spoken.
136 if (undone > 0) {
137 announce(m(UNDONE[latest.action], { count: undone }));
138 }
139 },
140 });
141 }
142
143 ThreadUndo.subscribe(refreshNotice);
144
145 export function undoLatestThreadAction(): boolean {
146 const notice = useThreadUndoNotice.getState().notice;
147 if (!notice) return false;
148 void notice.undo();
149 return true;
150 }
151
152 /** Whether mod+z should undo the notice's actions even while a text field is focused. */
153 export function threadUndoClaimsShortcut(): boolean {
154 return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
155 }
156
157 /** Called on any other keypress or text edit; hands mod+z back to text fields. */
158 export function releaseThreadUndoShortcut() {
159 shortcutClaimed = false;
160 }
161
162 /** Shows one compact confirmation for the currently undoable thread actions. */
163 export function showThreadUndoNotice(options: UndoOptions) {
164 if (!options.claim.isCurrent()) return;
165 liveUndos.push(options);
166 shortcutClaimed = true;
167 refreshNotice();
168 clearTimeout(expiry);
169 expiry = setTimeout(() => {
170 const expired = liveUndos;
171 liveUndos = [];
172 for (const { claim, commit } of expired) {
173 claim.finish();
174 commit?.();
175 }
176 refreshNotice();
177 }, 5_000);
178 }