The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { m as resolveMessage } from "~/i18n/messages"; |
| 3 | import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis"; |
| 4 | import { Spinner } from "~/components/ui/spinner"; |
| 5 | import { ArchiveIcon, ArchiveX, Trash2Icon } from "lucide-react"; |
| 6 | import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; |
| 7 | import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 8 | import { |
| 9 | type AtomCommandResult, |
| 10 | isAtomCommandInterrupted, |
| 11 | settlePromise, |
| 12 | squashAtomCommandFailure, |
| 13 | } from "@t3tools/client-runtime/state/runtime"; |
| 14 | import { useSettingsScope } from "./SettingsScopeContext"; |
| 15 | import { useThreadActions } from "../../hooks/useThreadActions"; |
| 16 | import { readLocalApi } from "../../localApi"; |
| 17 | import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; |
| 18 | import { RelativeTime } from "../RelativeTime"; |
| 19 | import { Button } from "../ui/button"; |
| 20 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 21 | import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; |
| 22 | import { useSearchableSetting } from "./settingsSearch"; |
| 23 | import { ProjectFavicon } from "../ProjectFavicon"; |
| 24 | |
| 25 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 26 | import { useRef, useState } from "react"; |
| 27 | import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; |
| 28 | |
| 29 | const ARCHIVE_ACTIONS = [ |
| 30 | { |
| 31 | action: "unarchive", |
| 32 | label: msg("Unarchive"), |
| 33 | threadLabel: msg("Unarchive {title}"), |
| 34 | failureTitle: msg("Failed to unarchive thread"), |
| 35 | Icon: ArchiveX, |
| 36 | }, |
| 37 | { |
| 38 | action: "delete", |
| 39 | label: msg("Delete", { $context: "verb, deletes a thread" }), |
| 40 | threadLabel: msg("Delete {title}"), |
| 41 | failureTitle: msg("Failed to delete thread"), |
| 42 | Icon: Trash2Icon, |
| 43 | }, |
| 44 | ] as const; |
| 45 | type ArchiveAction = (typeof ARCHIVE_ACTIONS)[number]["action"]; |
| 46 | |
| 47 | export function ArchivedThreadsPanel() { |
| 48 | const searchableSetting = useSearchableSetting(); |
| 49 | const gt = useGT(); |
| 50 | const m = useMessages(); |
| 51 | const { scope, groups: projectGroups, environments } = useSettingsScope(); |
| 52 | const { unarchiveThread, confirmAndDeleteThread } = useThreadActions(); |
| 53 | const pendingActionsRef = useRef(new Set<string>()); |
| 54 | const [pendingKeys, setPendingKeys] = useState<ReadonlySet<string>>(() => new Set()); |
| 55 | const { |
| 56 | snapshots: archivedSnapshots, |
| 57 | error: archiveError, |
| 58 | isLoading: isLoadingArchive, |
| 59 | refresh: refreshArchivedThreads, |
| 60 | } = useArchivedThreadSnapshots(scope.environmentIds); |
| 61 | |
| 62 | const { groups: archivedGroups, hasMultipleEnvironments } = (() => { |
| 63 | const selectedProjectKeys = |
| 64 | scope.kind === "project" || scope.kind === "checkout" |
| 65 | ? new Set(scope.members.map((member) => `${member.environmentId}:${member.id}`)) |
| 66 | : null; |
| 67 | const projectsByEnvironmentAndId = new Map( |
| 68 | archivedSnapshots.flatMap(({ environmentId, snapshot }) => |
| 69 | snapshot.projects |
| 70 | .filter( |
| 71 | (project) => |
| 72 | selectedProjectKeys === null || |
| 73 | selectedProjectKeys.has(`${environmentId}:${project.id}`), |
| 74 | ) |
| 75 | .map( |
| 76 | (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const, |
| 77 | ), |
| 78 | ), |
| 79 | ); |
| 80 | const environmentLabels = new Map( |
| 81 | environments.map((environment) => { |
| 82 | const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments); |
| 83 | return [environment.environmentId, secondary ? `${primary} (${secondary})` : primary]; |
| 84 | }), |
| 85 | ); |
| 86 | const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) => |
| 87 | snapshot.threads.map((thread) => ({ |
| 88 | ...presentThreadShell(environmentId, thread), |
| 89 | environmentLabel: environmentLabels.get(environmentId) ?? environmentId, |
| 90 | })), |
| 91 | ); |
| 92 | const hasMultipleEnvironments = |
| 93 | new Set( |
| 94 | threads |
| 95 | .filter((thread) => |
| 96 | projectsByEnvironmentAndId.has(`${thread.environmentId}:${thread.projectId}`), |
| 97 | ) |
| 98 | .map((thread) => thread.environmentId), |
| 99 | ).size > 1; |
| 100 | const logicalGroupsByProjectKey = new Map( |
| 101 | projectGroups.flatMap((group) => |
| 102 | group.memberProjectRefs.map( |
| 103 | (member) => [`${member.environmentId}:${member.projectId}`, group] as const, |
| 104 | ), |
| 105 | ), |
| 106 | ); |
| 107 | |
| 108 | const archivedProjects = Array.from(projectsByEnvironmentAndId.values()); |
| 109 | const groups = new Map< |
| 110 | string, |
| 111 | { |
| 112 | readonly project: (typeof archivedProjects)[number]; |
| 113 | readonly title: string; |
| 114 | readonly threads: Array<(typeof threads)[number]>; |
| 115 | } |
| 116 | >(); |
| 117 | for (const project of archivedProjects) { |
| 118 | const projectThreads: Array<(typeof threads)[number]> = []; |
| 119 | for (const thread of threads) { |
| 120 | if (thread.projectId === project.id && thread.environmentId === project.environmentId) { |
| 121 | projectThreads.push(thread); |
| 122 | } |
| 123 | } |
| 124 | if (projectThreads.length > 0) { |
| 125 | const physicalProjectKey = `${project.environmentId}:${project.id}` as const; |
| 126 | const logicalGroup = hasMultipleEnvironments |
| 127 | ? logicalGroupsByProjectKey.get(physicalProjectKey) |
| 128 | : undefined; |
| 129 | const groupKey = logicalGroup?.projectKey ?? physicalProjectKey; |
| 130 | const group = groups.get(groupKey); |
| 131 | if (group) { |
| 132 | group.threads.push(...projectThreads); |
| 133 | } else { |
| 134 | groups.set(groupKey, { |
| 135 | project, |
| 136 | title: logicalGroup?.displayName ?? project.title, |
| 137 | threads: projectThreads, |
| 138 | }); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | const sortedGroups = Array.from(groups, ([key, group]) => ({ |
| 143 | ...group, |
| 144 | key, |
| 145 | threads: group.threads.toSorted((left, right) => { |
| 146 | const leftKey = left.archivedAt ?? left.createdAt; |
| 147 | const rightKey = right.archivedAt ?? right.createdAt; |
| 148 | return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); |
| 149 | }), |
| 150 | })); |
| 151 | return { groups: sortedGroups, hasMultipleEnvironments }; |
| 152 | })(); |
| 153 | |
| 154 | type ArchivedThread = (typeof archivedGroups)[number]["threads"][number]; |
| 155 | |
| 156 | const reportFailure = (result: AtomCommandResult<unknown, unknown> | null, title: string) => { |
| 157 | if (result?._tag !== "Failure" || isAtomCommandInterrupted(result)) return; |
| 158 | const error = squashAtomCommandFailure(result); |
| 159 | toastManager.add( |
| 160 | stackedThreadToast({ |
| 161 | type: "error", |
| 162 | title, |
| 163 | description: |
| 164 | error instanceof Error |
| 165 | ? (thrownErrorMessage(error, resolveMessage) ?? error.message) |
| 166 | : gt("An error occurred."), |
| 167 | }), |
| 168 | ); |
| 169 | }; |
| 170 | |
| 171 | const handleThreadAction = async (action: ArchiveAction, thread: ArchivedThread) => { |
| 172 | const target = scopeThreadRef(thread.environmentId, thread.id); |
| 173 | const key = scopedThreadKey(target); |
| 174 | // Context menus can outlive their render, so checks and cleanup use the live set. |
| 175 | const pending = pendingActionsRef.current; |
| 176 | if (pending.has(key)) return; |
| 177 | pending.add(key); |
| 178 | setPendingKeys(new Set(pending)); |
| 179 | const result = await settlePromise(async () => { |
| 180 | const result = await (action === "unarchive" |
| 181 | ? unarchiveThread(target) |
| 182 | : confirmAndDeleteThread(target, thread.title)); |
| 183 | if (result._tag === "Success") refreshArchivedThreads(); |
| 184 | return result; |
| 185 | }).finally(() => { |
| 186 | pending.delete(key); |
| 187 | setPendingKeys(new Set(pending)); |
| 188 | }); |
| 189 | reportFailure( |
| 190 | result._tag === "Failure" ? result : result.value, |
| 191 | m(ARCHIVE_ACTIONS.find((entry) => entry.action === action)!.failureTitle), |
| 192 | ); |
| 193 | }; |
| 194 | |
| 195 | const handleContextMenu = async (thread: ArchivedThread, position: { x: number; y: number }) => { |
| 196 | const pending = pendingActionsRef.current; |
| 197 | if (pending.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)))) return; |
| 198 | const result = await settlePromise(async () => { |
| 199 | const clicked = await readLocalApi()?.contextMenu.show( |
| 200 | ARCHIVE_ACTIONS.map(({ action, label }) => ({ |
| 201 | id: action, |
| 202 | label: m(label), |
| 203 | destructive: action === "delete", |
| 204 | })), |
| 205 | position, |
| 206 | ); |
| 207 | if (clicked === "unarchive" || clicked === "delete") |
| 208 | await handleThreadAction(clicked, thread); |
| 209 | }); |
| 210 | reportFailure(result, gt("Archived thread action failed")); |
| 211 | }; |
| 212 | |
| 213 | return ( |
| 214 | <SettingsPageContainer> |
| 215 | {archivedGroups.length === 0 ? ( |
| 216 | <SettingsSection |
| 217 | id={isLoadingArchive ? undefined : searchableSetting("archive").id} |
| 218 | title={searchableSetting("archive").title} |
| 219 | > |
| 220 | <SettingsRow |
| 221 | title={ |
| 222 | <span className="inline-flex items-center gap-2"> |
| 223 | {isLoadingArchive ? ( |
| 224 | <Spinner size="sm" tone="muted" /> |
| 225 | ) : ( |
| 226 | <ArchiveIcon className="size-3.5 text-muted-foreground" /> |
| 227 | )} |
| 228 | {isLoadingArchive |
| 229 | ? gt("Loading archived threads") |
| 230 | : archiveError |
| 231 | ? gt("Could not load archived threads") |
| 232 | : gt("No archived threads")} |
| 233 | </span> |
| 234 | } |
| 235 | description={ |
| 236 | isLoadingArchive |
| 237 | ? gt("Checking connected environments.") |
| 238 | : (archiveError ?? gt("Archived threads will appear here.")) |
| 239 | } |
| 240 | /> |
| 241 | </SettingsSection> |
| 242 | ) : ( |
| 243 | archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => ( |
| 244 | <SettingsSection |
| 245 | key={key} |
| 246 | id={index === 0 ? searchableSetting("archive").id : undefined} |
| 247 | title={title} |
| 248 | icon={<ProjectFavicon project={project} />} |
| 249 | > |
| 250 | {projectThreads.map((thread) => { |
| 251 | const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); |
| 252 | return ( |
| 253 | <SettingsRow |
| 254 | key={`${thread.environmentId}:${thread.id}`} |
| 255 | onContextMenu={(event) => { |
| 256 | event.preventDefault(); |
| 257 | void handleContextMenu(thread, { x: event.clientX, y: event.clientY }); |
| 258 | }} |
| 259 | title={thread.title} |
| 260 | description={ |
| 261 | <span className={hasMultipleEnvironments ? "block truncate" : undefined}> |
| 262 | {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null} |
| 263 | <T> |
| 264 | Archived <RelativeTime timestamp={thread.archivedAt ?? thread.createdAt} /> |
| 265 | {" \u00b7 Created "} |
| 266 | <RelativeTime timestamp={thread.createdAt} /> |
| 267 | </T> |
| 268 | </span> |
| 269 | } |
| 270 | control={ |
| 271 | <div className="flex shrink-0 items-center gap-2"> |
| 272 | {ARCHIVE_ACTIONS.map(({ action, label, threadLabel, Icon }) => ( |
| 273 | <Tooltip key={action}> |
| 274 | <TooltipTrigger |
| 275 | render={ |
| 276 | <Button |
| 277 | type="button" |
| 278 | variant={action === "delete" ? "destructive-outline" : "outline"} |
| 279 | size="icon-sm" |
| 280 | aria-label={m(threadLabel, { title: thread.title })} |
| 281 | disabled={pendingKeys.has(threadKey)} |
| 282 | onClick={() => void handleThreadAction(action, thread)} |
| 283 | /> |
| 284 | } |
| 285 | > |
| 286 | <Icon className="size-3.5" /> |
| 287 | </TooltipTrigger> |
| 288 | <TooltipPopup>{m(label)}</TooltipPopup> |
| 289 | </Tooltip> |
| 290 | ))} |
| 291 | </div> |
| 292 | } |
| 293 | /> |
| 294 | ); |
| 295 | })} |
| 296 | </SettingsSection> |
| 297 | )) |
| 298 | )} |
| 299 | </SettingsPageContainer> |
| 300 | ); |
| 301 | } |