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

main
ts 378 lines 14.3 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3 import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
4 import { openGuestShareDialog } from "../components/chat/guestShareDialogState";
5 import {
6 type AtomCommandResult,
7 isAtomCommandInterrupted,
8 settlePromise,
9 squashAtomCommandFailure,
10 } from "@t3tools/client-runtime/state/runtime";
11 import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
12 import {
13 AuthOrchestrationOperateScope,
14 type ScopedThreadRef,
15 type ThreadId,
16 } from "@t3tools/contracts";
17 import { useRouter } from "@tanstack/react-router";
18 import { msg } from "gt-react";
19
20 import { pickSnoozePreset, resolveSnoozePresets } from "../components/Sidebar.snooze";
21 import {
22 buildThreadActionMenuItems,
23 threadActionRequiresOperate,
24 type ThreadActionMenuId,
25 } from "../components/threadActionMenu.logic";
26 import { titleRegenerationToast } from "../components/threadTitleRegenerationToast";
27 import { stackedThreadToast, toastManager } from "../components/ui/toast";
28 import { copyThreadReference } from "../lib/copyThreadReference";
29 import { m } from "../i18n/messages";
30 import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
31 import { threadEnvironment } from "../state/threads";
32 import { useOrchestrationCommand } from "../state/use-orchestration-command";
33 import { readEnvironmentScope } from "../state/session";
34 import {
35 readEnvironmentServerConfigLoaded,
36 readEnvironmentSupportsAutoSettleOptOut,
37 readThreadShell,
38 useProjects,
39 } from "../state/entities";
40 import { usePrimaryEnvironmentId } from "../state/environments";
41 import { readLocalApi } from "../localApi";
42 import { configuredHostedAppUrl } from "../hostedPairing";
43 import {
44 deriveLogicalProjectKeyFromSettings,
45 derivePhysicalProjectKey,
46 selectProjectGroupingSettings,
47 } from "@t3tools/client-runtime/state/project-grouping";
48 import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
49 import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
50 import { useCopyToClipboard } from "./useCopyToClipboard";
51 import { useNewThreadHandler } from "./useHandleNewThread";
52 import { useClientSettings } from "./useSettings";
53 import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions";
54
55 function failureToast(title: string, error: unknown) {
56 toastManager.add(
57 stackedThreadToast({
58 type: "error",
59 title,
60 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
61 }),
62 );
63 }
64
65 export function useThreadActionMenu(input: {
66 readonly threadRef: ScopedThreadRef | null;
67 readonly projectCwd: string | null;
68 readonly onStartRename: () => void;
69 readonly onFind?: ((threadRef: ScopedThreadRef) => void) | undefined;
70 readonly canShareWithGuest: boolean;
71 }) {
72 const { threadRef, projectCwd, onStartRename, onFind, canShareWithGuest } = input;
73 const router = useRouter();
74 const projects = useProjects();
75 const primaryEnvironmentId = usePrimaryEnvironmentId();
76 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
77 const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
78 projects,
79 settings: projectGroupingSettings,
80 primaryEnvironmentId,
81 });
82 const {
83 settleThread,
84 unsettleThread,
85 snoozeThread,
86 unsnoozeThread,
87 pinThread,
88 confirmAndUnpinThread,
89 setThreadAutoSettle,
90 archiveThread,
91 deleteThread,
92 markThreadUnread,
93 turnThreadIntoProject,
94 } = useThreadActions();
95 const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, {
96 reportFailure: false,
97 });
98 const handleNewThread = useNewThreadHandler();
99 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
100 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
101 const timestampFormat = useClientSettings((s) => s.timestampFormat);
102 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
103 onError: (error) => failureToast(m(msg("Failed to copy path")), error),
104 });
105 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
106 target: {
107 target: "branch name",
108 unavailableMessage: msg("Clipboard API is unavailable while copying branch name."),
109 failureMessage: msg("Failed to copy branch name to the clipboard."),
110 },
111 onError: (error) => failureToast(m(msg("Failed to copy branch")), error),
112 });
113 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
114 onError: (error) => failureToast(m(msg("Failed to copy thread ID")), error),
115 });
116
117 const openMenu = (position: { x: number; y: number }) => {
118 if (threadRef === null) return;
119 void (async () => {
120 const api = readLocalApi();
121 if (!api) return;
122 const thread = readThreadShell(threadRef);
123 if (!thread) {
124 failureToast(
125 m(msg("Thread actions unavailable")),
126 new Error(m(msg("This thread has not loaded yet."))),
127 );
128 return;
129 }
130 const now = new Date();
131 const configLoaded = readEnvironmentServerConfigLoaded(threadRef.environmentId);
132 const supports = {
133 settlement: configLoaded,
134 autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId),
135 snooze: configLoaded,
136 pinning: configLoaded,
137 titleRegeneration: configLoaded,
138 };
139 const isRegeneratingTitle = thread.titleRegeneration != null;
140 const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId);
141 const items = buildThreadActionMenuItems({
142 canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
143 canFind: onFind !== undefined,
144 branch: thread.branch ?? null,
145 projectFilter: null,
146 isPinned: thread.pinnedAt != null,
147 isSettled: supports.settlement && thread.settledOverride === "settled",
148 autoSettleEnabled: thread.autoSettleDisabledAt == null,
149 isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
150 canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
151 isRegeneratingTitle,
152 isRunning: !threadRuntimeCanArchive(thread.runtime),
153 supports,
154 snoozePresets,
155 canShareWithGuest,
156 canTurnIntoProject: canTurnThreadIntoProject(threadRef),
157 });
158 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
159 if (clicked._tag === "Failure" || clicked.value === null) return;
160 const action: ThreadActionMenuId = clicked.value;
161 if (
162 threadActionRequiresOperate(action) &&
163 !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)
164 ) {
165 failureToast(
166 m(msg("Thread action unavailable")),
167 new Error(m(msg("This connection cannot change threads."))),
168 );
169 return;
170 }
171 if (action.startsWith("snooze:")) {
172 const preset =
173 action === "snooze:custom"
174 ? await requestCustomSnooze()
175 : pickSnoozePreset(
176 snoozePresets,
177 action.slice("snooze:".length),
178 timestampFormat,
179 threadRef.environmentId,
180 );
181 if (!preset) return;
182 const result = await snoozeThread(threadRef, preset.snoozedUntil);
183 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
184 failureToast(m(msg("Failed to snooze thread")), squashAtomCommandFailure(result));
185 }
186 return;
187 }
188 const reportFailure = async (
189 title: string,
190 run: () => Promise<AtomCommandResult<unknown, unknown>>,
191 ) => {
192 const result = await run();
193 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
194 failureToast(title, squashAtomCommandFailure(result));
195 }
196 };
197 switch (action) {
198 case "find":
199 onFind?.(threadRef);
200 return;
201 case "project-settings": {
202 const project = projects.find(
203 (candidate) =>
204 candidate.environmentId === thread.environmentId && candidate.id === thread.projectId,
205 );
206 if (!project) return;
207 const projectKey =
208 logicalProjectKeyByPhysicalKey.get(derivePhysicalProjectKey(project)) ??
209 deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings);
210 void router.navigate({
211 to: "/projects/$projectKey",
212 params: { projectKey },
213 });
214 return;
215 }
216 case "new-thread-on-branch": {
217 const result = await settlePromise(() =>
218 handleNewThread(scopeProjectRef(threadRef.environmentId, thread.projectId), {
219 branch: thread.branch,
220 worktreePath: thread.worktreePath,
221 envMode: thread.worktreePath ? "worktree" : "local",
222 startFromOrigin: false,
223 }),
224 );
225 if (result._tag === "Failure") {
226 failureToast(m(msg("Could not create thread")), squashAtomCommandFailure(result));
227 }
228 return;
229 }
230 case "settle":
231 await reportFailure(m(msg("Failed to settle thread")), () => settleThread(threadRef));
232 return;
233 case "unsettle":
234 await reportFailure(m(msg("Failed to un-settle thread")), () =>
235 unsettleThread(threadRef),
236 );
237 return;
238 case "unsnooze":
239 await reportFailure(m(msg("Failed to wake thread")), () => unsnoozeThread(threadRef));
240 return;
241 case "pin":
242 await reportFailure(m(msg("Failed to pin thread")), () => pinThread(threadRef));
243 return;
244 case "unpin": {
245 await reportFailure(m(msg("Failed to unpin thread")), () =>
246 confirmAndUnpinThread(threadRef),
247 );
248 return;
249 }
250 case "auto-settle:enabled":
251 case "auto-settle:disabled":
252 await reportFailure(m(msg("Failed to update auto-settle")), () =>
253 setThreadAutoSettle(threadRef, action === "auto-settle:enabled"),
254 );
255 return;
256 case "rename":
257 onStartRename();
258 return;
259 case "regenerate-title": {
260 if (isRegeneratingTitle) return;
261 const toast = titleRegenerationToast([
262 await regenerateThreadTitle({
263 environmentId: threadRef.environmentId,
264 input: { threadId: threadRef.threadId },
265 }),
266 ]);
267 if (toast) toastManager.add(toast);
268 return;
269 }
270 case "mark-unread":
271 markThreadUnread(threadRef);
272 return;
273 case "share-guest":
274 openGuestShareDialog(threadRef);
275 return;
276 case "turn-into-project": {
277 const result = await turnThreadIntoProject(threadRef);
278 if (result._tag === "Success") {
279 toastManager.add({
280 type: "success",
281 title: m(msg("Project created")),
282 description: thread.title,
283 });
284 } else if (!isAtomCommandInterrupted(result)) {
285 failureToast(
286 m(msg("Could not turn thread into a project")),
287 squashAtomCommandFailure(result),
288 );
289 }
290 return;
291 }
292 case "copy-path": {
293 const workspacePath = thread.worktreePath ?? projectCwd;
294 if (!workspacePath) {
295 toastManager.add(
296 stackedThreadToast({
297 type: "error",
298 title: m(msg("Path unavailable")),
299 description: m(msg("This thread does not have a workspace path to copy.")),
300 }),
301 );
302 return;
303 }
304 copyPathToClipboard(workspacePath, { path: workspacePath });
305 return;
306 }
307 case "copy-branch":
308 if (thread.branch) {
309 copyBranchToClipboard(thread.branch, { branch: thread.branch });
310 }
311 return;
312 case "copy-thread":
313 void copyThreadReference(
314 threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl(), m),
315 );
316 return;
317 case "copy-thread-id":
318 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
319 return;
320 case "archive": {
321 if (confirmThreadArchive) {
322 const confirmed = await settlePromise(() =>
323 api.dialogs.confirm(m(msg('Archive thread "{title}"?', { title: thread.title }))),
324 );
325 if (confirmed._tag === "Failure" || !confirmed.value) return;
326 }
327 let didArchive = false;
328 const result = await archiveThread(threadRef, {
329 onArchived: () => {
330 didArchive = true;
331 },
332 });
333 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
334 failureToast(
335 didArchive
336 ? m(msg("Thread archived, but navigation failed"))
337 : m(msg("Failed to archive thread")),
338 squashAtomCommandFailure(result),
339 );
340 }
341 return;
342 }
343 case "delete": {
344 if (confirmThreadDelete) {
345 const confirmed = await settlePromise(() =>
346 api.dialogs.confirm(
347 [
348 m(msg('Delete thread "{title}"?', { title: thread.title })),
349 m(msg("This permanently clears conversation history for this thread.")),
350 ].join("\n"),
351 { variant: "destructive" },
352 ),
353 );
354 if (confirmed._tag === "Failure" || !confirmed.value) return;
355 }
356 const deleted = await deleteThread(threadRef);
357 if (
358 deleted._tag === "Failure" &&
359 !isAtomCommandInterrupted(deleted) &&
360 // A missing thread means cleanup failed after deletion; deleteThread already toasted that failure.
361 readThreadShell(threadRef) !== null
362 ) {
363 failureToast(m(msg("Failed to delete thread")), squashAtomCommandFailure(deleted));
364 }
365 return;
366 }
367 default:
368 return;
369 }
370 })();
371 };
372
373 const closeMenu = () => {
374 void readLocalApi()?.contextMenu.close();
375 };
376
377 return { openMenu, closeMenu };
378 }