TypeScript
refactor(web): the archived threads settings page lives in its own file (#22666)
Julius Marminge0b91504aba9d
diff --git a/apps/web/src/components/settings/ArchivedThreadsPanel.tsx b/apps/web/src/components/settings/ArchivedThreadsPanel.tsxnew file mode 100644index 00000000000..8aacb39c503--- /dev/null+++ b/apps/web/src/components/settings/ArchivedThreadsPanel.tsx@@ -0,0 +1,287 @@+import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis";+import { Spinner } from "~/components/ui/spinner";+import { ArchiveIcon, ArchiveX } from "lucide-react";+import { type ScopedThreadRef } from "@t3tools/contracts";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { presentThreadShell } from "@t3tools/client-runtime/state/shell";+import {+ isAtomCommandInterrupted,+ settlePromise,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { useSettingsScope } from "./SettingsScopeContext";+import { useThreadActions } from "../../hooks/useThreadActions";+import { readLocalApi } from "../../localApi";+import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";+import { RelativeTime } from "../RelativeTime";+import { Button } from "../ui/button";+import { stackedThreadToast, toastManager } from "../ui/toast";+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";+import { searchableSetting } from "./settingsSearch";+import { ProjectFavicon } from "../ProjectFavicon";++export function ArchivedThreadsPanel() {+ const { scope, groups: projectGroups, environments } = useSettingsScope();+ const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();+ const {+ snapshots: archivedSnapshots,+ error: archiveError,+ isLoading: isLoadingArchive,+ refresh: refreshArchivedThreads,+ } = useArchivedThreadSnapshots(scope.environmentIds);++ const { groups: archivedGroups, hasMultipleEnvironments } = (() => {+ const selectedProjectKeys =+ scope.kind === "project" || scope.kind === "checkout"+ ? new Set(scope.members.map((member) => `${member.environmentId}:${member.id}`))+ : null;+ const projectsByEnvironmentAndId = new Map(+ archivedSnapshots.flatMap(({ environmentId, snapshot }) =>+ snapshot.projects+ .filter(+ (project) =>+ selectedProjectKeys === null ||+ selectedProjectKeys.has(`${environmentId}:${project.id}`),+ )+ .map(+ (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const,+ ),+ ),+ );+ const environmentLabels = new Map(+ environments.map((environment) => {+ const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments);+ return [environment.environmentId, secondary ? `${primary} (${secondary})` : primary];+ }),+ );+ const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>+ snapshot.threads.map((thread) => ({+ ...presentThreadShell(environmentId, thread),+ environmentLabel: environmentLabels.get(environmentId) ?? environmentId,+ })),+ );+ const hasMultipleEnvironments =+ new Set(+ threads+ .filter((thread) =>+ projectsByEnvironmentAndId.has(`${thread.environmentId}:${thread.projectId}`),+ )+ .map((thread) => thread.environmentId),+ ).size > 1;+ const logicalGroupsByProjectKey = new Map(+ projectGroups.flatMap((group) =>+ group.memberProjectRefs.map(+ (member) => [`${member.environmentId}:${member.projectId}`, group] as const,+ ),+ ),+ );++ const archivedProjects = Array.from(projectsByEnvironmentAndId.values());+ const groups = new Map<+ string,+ {+ readonly project: (typeof archivedProjects)[number];+ readonly title: string;+ readonly threads: Array<(typeof threads)[number]>;+ }+ >();+ for (const project of archivedProjects) {+ const projectThreads: Array<(typeof threads)[number]> = [];+ for (const thread of threads) {+ if (thread.projectId === project.id && thread.environmentId === project.environmentId) {+ projectThreads.push(thread);+ }+ }+ if (projectThreads.length > 0) {+ const physicalProjectKey = `${project.environmentId}:${project.id}` as const;+ const logicalGroup = hasMultipleEnvironments+ ? logicalGroupsByProjectKey.get(physicalProjectKey)+ : undefined;+ const groupKey = logicalGroup?.projectKey ?? physicalProjectKey;+ const group = groups.get(groupKey);+ if (group) {+ group.threads.push(...projectThreads);+ } else {+ groups.set(groupKey, {+ project,+ title: logicalGroup?.displayName ?? project.title,+ threads: projectThreads,+ });+ }+ }+ }+ const sortedGroups = Array.from(groups, ([key, group]) => ({+ ...group,+ key,+ threads: group.threads.toSorted((left, right) => {+ const leftKey = left.archivedAt ?? left.createdAt;+ const rightKey = right.archivedAt ?? right.createdAt;+ return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);+ }),+ }));+ return { groups: sortedGroups, hasMultipleEnvironments };+ })();++ const handleArchivedThreadContextMenu = async (+ threadRef: ScopedThreadRef,+ position: { x: number; y: number },+ ) => {+ const api = readLocalApi();+ if (!api) return;+ const clicked = await api.contextMenu.show(+ [+ { id: "unarchive", label: "Unarchive" },+ { id: "delete", label: "Delete", destructive: true },+ ],+ position,+ );++ if (clicked === "unarchive") {+ const result = await unarchiveThread(threadRef);+ if (result._tag === "Success") {+ refreshArchivedThreads();+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Failed to unarchive thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ return;+ }++ if (clicked === "delete") {+ const result = await confirmAndDeleteThread(threadRef);+ if (result._tag === "Success") {+ refreshArchivedThreads();+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Failed to delete thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ }+ };++ return (+ <SettingsPageContainer>+ {archivedGroups.length === 0 ? (+ <SettingsSection+ id={isLoadingArchive ? undefined : searchableSetting("archive").id}+ title={searchableSetting("archive").title}+ >+ <SettingsRow+ title={+ <span className="inline-flex items-center gap-2">+ {isLoadingArchive ? (+ <Spinner size="sm" tone="muted" />+ ) : (+ <ArchiveIcon className="size-3.5 text-muted-foreground" />+ )}+ {isLoadingArchive+ ? "Loading archived threads"+ : archiveError+ ? "Could not load archived threads"+ : "No archived threads"}+ </span>+ }+ description={+ isLoadingArchive+ ? "Checking connected environments."+ : (archiveError ?? "Archived threads will appear here.")+ }+ />+ </SettingsSection>+ ) : (+ archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => (+ <SettingsSection+ key={key}+ id={index === 0 ? searchableSetting("archive").id : undefined}+ title={title}+ icon={<ProjectFavicon project={project} />}+ >+ {projectThreads.map((thread) => (+ <SettingsRow+ key={`${thread.environmentId}:${thread.id}`}+ onContextMenu={(event) => {+ event.preventDefault();+ void (async () => {+ const result = await settlePromise(() =>+ handleArchivedThreadContextMenu(+ scopeThreadRef(thread.environmentId, thread.id),+ {+ x: event.clientX,+ y: event.clientY,+ },+ ),+ );+ if (result._tag === "Failure") {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Archived thread action failed",+ description:+ error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ })();+ }}+ title={thread.title}+ description={+ <span className={hasMultipleEnvironments ? "block truncate" : undefined}>+ {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null}+ Archived <RelativeTime timestamp={thread.archivedAt ?? thread.createdAt} />+ {" \u00b7 Created "}+ <RelativeTime timestamp={thread.createdAt} />+ </span>+ }+ control={+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="shrink-0"+ onClick={() => {+ void (async () => {+ const result = await unarchiveThread(+ scopeThreadRef(thread.environmentId, thread.id),+ );+ if (result._tag === "Success") {+ refreshArchivedThreads();+ return;+ }+ if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Failed to unarchive thread",+ description:+ error instanceof Error ? error.message : "An error occurred.",+ }),+ );+ }+ })();+ }}+ >+ <ArchiveX className="size-3.5" />+ <span>Unarchive</span>+ </Button>+ }+ />+ ))}+ </SettingsSection>+ ))+ )}+ </SettingsPageContainer>+ );+}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex 16c6ff3fb89..f3defe2113c 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -1,10 +1,8 @@import { SettingsGroup } from "./SettingsGroup";-import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis";import { useScopedSettingsWriteAllowed } from "./useScopedSettings";-import { Spinner } from "~/components/ui/spinner";import { NotificationSettings } from "./NotificationSettings";import { PRIVACY_POLICY_URL } from "../../legalLinks";-import { ArchiveIcon, ArchiveX, CheckIcon, ChevronRightIcon, SettingsIcon } from "lucide-react";+import { CheckIcon, ChevronRightIcon, SettingsIcon } from "lucide-react";import { Link, useNavigate } from "@tanstack/react-router";import type { CSSProperties, ReactNode } from "react";import { useEffect, useEffectEvent, useRef, useState } from "react";@@ -13,16 +11,8 @@ import {type DesktopUpdateChannel,ProviderDriverKind,type ProviderInstanceId,- type ScopedThreadRef,type SidebarProjectGroupingMode,} from "@t3tools/contracts";-import { scopeThreadRef } from "@t3tools/client-runtime/environment";-import { presentThreadShell } from "@t3tools/client-runtime/state/shell";-import {- isAtomCommandInterrupted,- settlePromise,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";import {DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE,DEFAULT_UNIFIED_SETTINGS,@@ -89,7 +79,6 @@ import {import { useScopedModelDisabledReason } from "./useScopedModelAvailability";import { useSettingsScope } from "./SettingsScopeContext";import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";-import { useThreadActions } from "../../hooks/useThreadActions";import { useDesktopUpdateState } from "../../state/desktopUpdate";import {getCustomModelOptionsByInstance,@@ -105,8 +94,6 @@ import { ensureLocalApi, readLocalApi } from "../../localApi";import { isMacPlatform } from "../../lib/utils";import { useEnvironmentProviders } from "../../state/environments";import { EMPTY_SERVER_PROVIDERS } from "../../state/server";-import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";-import { RelativeTime } from "../RelativeTime";import { Button } from "../ui/button";import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";import {@@ -171,7 +158,6 @@ import {useSettingsSearchTargetId,} from "./settingsLayout";import { searchableSetting } from "./settingsSearch";-import { ProjectFavicon } from "../ProjectFavicon";import { PanelAnimationsPreview } from "./PanelAnimationsPreview";const ENVIRONMENT_IDENTIFICATION_LABELS: Record<EnvironmentIdentificationMode, string> = {@@ -3351,269 +3337,3 @@ export function GeneralSettingsPanel() {</SettingsPageContainer>);}--export function ArchivedThreadsPanel() {- const { scope, groups: projectGroups, environments } = useSettingsScope();- const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();- const {- snapshots: archivedSnapshots,- error: archiveError,- isLoading: isLoadingArchive,- refresh: refreshArchivedThreads,- } = useArchivedThreadSnapshots(scope.environmentIds);-- const { groups: archivedGroups, hasMultipleEnvironments } = (() => {- const selectedProjectKeys =- scope.kind === "project" || scope.kind === "checkout"- ? new Set(scope.members.map((member) => `${member.environmentId}:${member.id}`))- : null;- const projectsByEnvironmentAndId = new Map(- archivedSnapshots.flatMap(({ environmentId, snapshot }) =>- snapshot.projects- .filter(- (project) =>- selectedProjectKeys === null ||- selectedProjectKeys.has(`${environmentId}:${project.id}`),- )- .map(- (project) => [`${environmentId}:${project.id}`, { ...project, environmentId }] as const,- ),- ),- );- const environmentLabels = new Map(- environments.map((environment) => {- const { primary, secondary } = settingsScopeEnvironmentLabels(environment, environments);- return [environment.environmentId, secondary ? `${primary} (${secondary})` : primary];- }),- );- const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>- snapshot.threads.map((thread) => ({- ...presentThreadShell(environmentId, thread),- environmentLabel: environmentLabels.get(environmentId) ?? environmentId,- })),- );- const hasMultipleEnvironments =- new Set(- threads- .filter((thread) =>- projectsByEnvironmentAndId.has(`${thread.environmentId}:${thread.projectId}`),- )- .map((thread) => thread.environmentId),- ).size > 1;- const logicalGroupsByProjectKey = new Map(- projectGroups.flatMap((group) =>- group.memberProjectRefs.map(- (member) => [`${member.environmentId}:${member.projectId}`, group] as const,- ),- ),- );-- const archivedProjects = Array.from(projectsByEnvironmentAndId.values());- const groups = new Map<- string,- {- readonly project: (typeof archivedProjects)[number];- readonly title: string;- readonly threads: Array<(typeof threads)[number]>;- }- >();- for (const project of archivedProjects) {- const projectThreads: Array<(typeof threads)[number]> = [];- for (const thread of threads) {- if (thread.projectId === project.id && thread.environmentId === project.environmentId) {- projectThreads.push(thread);- }- }- if (projectThreads.length > 0) {- const physicalProjectKey = `${project.environmentId}:${project.id}` as const;- const logicalGroup = hasMultipleEnvironments- ? logicalGroupsByProjectKey.get(physicalProjectKey)- : undefined;- const groupKey = logicalGroup?.projectKey ?? physicalProjectKey;- const group = groups.get(groupKey);- if (group) {- group.threads.push(...projectThreads);- } else {- groups.set(groupKey, {- project,- title: logicalGroup?.displayName ?? project.title,- threads: projectThreads,- });- }- }- }- const sortedGroups = Array.from(groups, ([key, group]) => ({- ...group,- key,- threads: group.threads.toSorted((left, right) => {- const leftKey = left.archivedAt ?? left.createdAt;- const rightKey = right.archivedAt ?? right.createdAt;- return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);- }),- }));- return { groups: sortedGroups, hasMultipleEnvironments };- })();-- const handleArchivedThreadContextMenu = async (- threadRef: ScopedThreadRef,- position: { x: number; y: number },- ) => {- const api = readLocalApi();- if (!api) return;- const clicked = await api.contextMenu.show(- [- { id: "unarchive", label: "Unarchive" },- { id: "delete", label: "Delete", destructive: true },- ],- position,- );-- if (clicked === "unarchive") {- const result = await unarchiveThread(threadRef);- if (result._tag === "Success") {- refreshArchivedThreads();- } else if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to unarchive thread",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- }- return;- }-- if (clicked === "delete") {- const result = await confirmAndDeleteThread(threadRef);- if (result._tag === "Success") {- refreshArchivedThreads();- } else if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to delete thread",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- }- }- };-- return (- <SettingsPageContainer>- {archivedGroups.length === 0 ? (- <SettingsSection- id={isLoadingArchive ? undefined : searchableSetting("archive").id}- title={searchableSetting("archive").title}- >- <SettingsRow- title={- <span className="inline-flex items-center gap-2">- {isLoadingArchive ? (- <Spinner size="sm" tone="muted" />- ) : (- <ArchiveIcon className="size-3.5 text-muted-foreground" />- )}- {isLoadingArchive- ? "Loading archived threads"- : archiveError- ? "Could not load archived threads"- : "No archived threads"}- </span>- }- description={- isLoadingArchive- ? "Checking connected environments."- : (archiveError ?? "Archived threads will appear here.")- }- />- </SettingsSection>- ) : (- archivedGroups.map(({ key, project, title, threads: projectThreads }, index) => (- <SettingsSection- key={key}- id={index === 0 ? searchableSetting("archive").id : undefined}- title={title}- icon={<ProjectFavicon project={project} />}- >- {projectThreads.map((thread) => (- <SettingsRow- key={`${thread.environmentId}:${thread.id}`}- onContextMenu={(event) => {- event.preventDefault();- void (async () => {- const result = await settlePromise(() =>- handleArchivedThreadContextMenu(- scopeThreadRef(thread.environmentId, thread.id),- {- x: event.clientX,- y: event.clientY,- },- ),- );- if (result._tag === "Failure") {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Archived thread action failed",- description:- error instanceof Error ? error.message : "An error occurred.",- }),- );- }- })();- }}- title={thread.title}- description={- <span className={hasMultipleEnvironments ? "block truncate" : undefined}>- {hasMultipleEnvironments ? `${thread.environmentLabel} · ` : null}- Archived <RelativeTime timestamp={thread.archivedAt ?? thread.createdAt} />- {" \u00b7 Created "}- <RelativeTime timestamp={thread.createdAt} />- </span>- }- control={- <Button- type="button"- variant="outline"- size="sm"- className="shrink-0"- onClick={() => {- void (async () => {- const result = await unarchiveThread(- scopeThreadRef(thread.environmentId, thread.id),- );- if (result._tag === "Success") {- refreshArchivedThreads();- return;- }- if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to unarchive thread",- description:- error instanceof Error ? error.message : "An error occurred.",- }),- );- }- })();- }}- >- <ArchiveX className="size-3.5" />- <span>Unarchive</span>- </Button>- }- />- ))}- </SettingsSection>- ))- )}- </SettingsPageContainer>- );-}diff --git a/apps/web/src/routes/settings.archived.tsx b/apps/web/src/routes/settings.archived.tsxindex 3ad690afc02..b411f6440af 100644--- a/apps/web/src/routes/settings.archived.tsx+++ b/apps/web/src/routes/settings.archived.tsx@@ -1,6 +1,6 @@import { createFileRoute } from "@tanstack/react-router";-import { ArchivedThreadsPanel } from "../components/settings/SettingsPanels";+import { ArchivedThreadsPanel } from "../components/settings/ArchivedThreadsPanel";export const Route = createFileRoute("/settings/archived")({component: ArchivedThreadsPanel,