fix: feature-base-refactoring (#297)

* docs: add AGENTS.md with feature-based architecture conventions

Defines the target src/ structure, feature list, naming conventions
(kebab-case, file type patterns), import direction rules, and
feature boundary guidelines for the planned big-bang refactor.

* docs: add features/channel/ to architecture conventions

Generic channel UI (card, modal, form) goes to features/channel/.
Provider-specific sub-folders: channel/notifications/ and channel/storages/.

* refactor: move event emitter to lib/, project service to db/services/, dedup use-mobile hook

* fix: remove unused auth import in db/services/project.ts

* refactor: migrate wrappers/common to components/common (flat)

* fix: remove dead commented-out code from button-with-loading.tsx

* refactor: merge features/browser into features/theme, flatten upload/updates, migrate statistics

* refactor: migrate wrappers/auth to features/auth

Move all auth components and forms from src/components/wrappers/auth/
into src/features/auth/ with flat kebab-case naming. Handle extra
reset-password-form.tsx and differing reset-password-schema.ts by
copying them as reset-password-page-form.tsx and reset-password-page.schema.ts.

* refactor: remove dead auth files and fix zPassword schema

Delete reset-password-section.tsx and reset-password-page-form.tsx (zero consumers).
Fix reset-password-page.schema.ts to import zPassword from @/lib/zod.

* refactor: migrate wrappers/dashboard/common to features/layout, rename Header.tsx to header.tsx

* fix: decouple layout from theme/updates cross-feature imports

Use slot props (actions, updateNotification) so app/ composes
ModeToggle and UpdateNotification into Header and AppSidebar.
Delete dead side-bar-logo.tsx (zero consumers).

* refactor: merge features/keys into features/agents, flatten sub-dirs, migrate agent wrappers

- Merge src/features/keys/keys.action.ts into src/features/agents/
- Flatten src/features/agents/components/ and hooks/ into feature root
- Migrate all src/components/wrappers/dashboard/agent/ files into src/features/agents/
- Update all import paths across app/ and src/ accordingly
- Fix broken code-snippet import in agent-key-modal.tsx (was pointing to non-existent wrappers path)

* fix: move github-releases to lib/, remove dead code and unused imports

Move GitHub release fetch logic from features/updates/github.ts to
lib/github-releases.ts so both features/updates and features/agents
can import it without cross-feature imports.
Remove commented-out impersonation block from agent-database-card.tsx.
Remove unused imports (CopyButton, Terminal, Key, Info).

* refactor: flatten features/projects/components, migrate project wrappers

Move project.dialog/form out of sub-dir, migrate project-card, project-database-card, and delete-project button/action from wrappers into features/projects/. Update all import paths across src/ and app/. Leave wrappers/dashboard/projects/database/ untouched for Task 10.

* fix: extract DatabaseCard to components/common, remove cross-feature import

DatabaseCard was imported by both features/projects and features/agents,
violating the no-cross-feature-import rule. Extract to components/common/
database-card.tsx so both features import from the shared layer.
Also tighten extendedProps type and remove commented-out maxCount prop.

* refactor: migrate all database/backup/restore/health UI to features/database

Consolidates ~40 files from 5 source locations (features/dashboard/backup,
features/dashboard/restore, wrappers/dashboard/backup, wrappers/dashboard/database,
wrappers/dashboard/health, wrappers/dashboard/projects/database) into the new
flat features/database directory with kebab-case filenames and updated @/ imports.

* fix: remove dead restore-form files and console.log from health-grid

Delete restore-form.tsx (186 lines all commented-out, zero consumers)
and restore-form.schema.ts (only a commented import).
Remove console.log(logs) from getOldestLog helper in health-grid.tsx.

Cross-feature imports (database→storages for dispatchStorage/storeBackupFiles)
are accepted as known architectural coupling — storage dispatch is called from
database server actions at runtime and cannot route through app/ props.

* refactor: migrate wrappers/admin/users to features/users, fix table-colums typo

* fix: fix relative imports, string interpolation, and console.error in users feature

Replace relative imports with @/ aliases in user-actions-cell.tsx and
admin-user-edit-modal.tsx. Fix string interpolation bug in dialog title
(was regular string, now template literal). Remove console.error from
admin-user-change-role-modal.tsx.

* refactor: migrate wrappers/profile to features/profile, fix profile-apperance typo

* fix: remove console.error calls and ts-ignore in profile feature

Remove console.error from profile-account.tsx, 2fa-form.tsx (x2).
Replace @ts-ignore on fileInput.onchange with typed cast in avatar-with-upload.tsx.

* refactor: rename features/organization to features/organizations, migrate all org wrappers

Moves 37 org-related files from features/organization/, features/dashboard/,
hooks/, wrappers/admin/organizations/, wrappers/admin/channels/organization/,
and wrappers/dashboard/organization/ into a flat features/organizations/ feature
directory. Updates all import paths codebase-wide. Fixes @ts-ignore and removes
unused @better-fetch/fetch import in admin-organization-form.

* fix: remove console.error, @ts-ignore, and unused destructures in features/organizations

* refactor: migrate wrappers/organization/migration to features/migration

Move all 5 migration files to src/features/migration/, update internal
imports to @/features/migration/ absolute paths, remove console.log,
and delete src/components/wrappers/dashboard/organization/ entirely.

* refactor: migrate wrappers/admin/settings to features/settings

Move all 14 settings files (email, notification, storage, s3) from
wrappers/dashboard/admin/settings/ into features/settings/, rewriting
imports, replacing @ts-ignore with @ts-expect-error, and renaming error
params to _error where applicable.

* refactor: rename notifications files to kebab convention, migrate notification logs

- Rename dispatch.ts/helpers.ts/types.ts to notifications.*.ts
- Migrate notification logs components from wrappers/dashboard/admin/notifications/logs/ to features/notifications/
- Fix all import paths across codebase and in providers/
- Remove unused useRouter import, replace @ts-ignore with @ts-expect-error
- Delete src/components/wrappers/dashboard/admin/notifications/

* refactor: rename storages dispatch/helpers/types to kebab convention

- Rename dispatch.ts/helpers.ts/types.ts to storages.*.ts
- Fix all import paths across codebase and in providers/
- Fix relative ../types and ../../types imports in all storage providers to absolute @/ paths
- Replace @ts-ignore with @ts-expect-error, remove console.debug/console.error

* refactor: create features/channel with generic UI and notifications/storages provider sub-folders

Consolidates 4 source locations into src/features/channel/:
- components/wrappers/dashboard/admin/channels/ → features/channel/ (11 generic UI files)
- features/notifications/providers/ → features/channel/notifications/ (9 backend + 18 form files)
- features/storages/providers/ → features/channel/storages/ (backend + forms)

The two conflicting google-drive/helpers.ts files (client helpers vs OAuth action)
are kept separate: helpers.ts and google-drive-refresh.action.ts.

Rewrites all imports codebase-wide to point to new locations.
Removes console.log/console.error calls, upgrades @ts-ignore to @ts-expect-error.

* fix: remove console.error from local storage provider

* fix: multi-select.tsx scroll issue

* fix: multi-select.tsx scroll issue
This commit is contained in:
Charles GTE
2026-05-24 17:09:12 +02:00
committed by GitHub
parent 4fadfcfaf2
commit 3fa0f9b76d
330 changed files with 627 additions and 1120 deletions
+145
View File
@@ -0,0 +1,145 @@
"use client";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {Copy, Check, Eye, EyeOff} from "lucide-react";
import {useState} from "react";
import {copyToClipboardWithMeta} from "@/components/common/copy-button";
import {Card, CardContent, CardDescription, CardHeader, CardTitle} from "@/components/ui/card";
export type AgentCardKeyProps = {
edgeKey: string;
agentName: string;
};
export const AgentCardKey = ({edgeKey, agentName}: AgentCardKeyProps) => {
const [isCopiedKey, setIsCopiedKey] = useState(false);
const [isCopiedCommand, setIsCopiedCommand] = useState(false);
const [isVisible, setIsVisible] = useState(false);
const command = `portabase agent "${agentName}" --key ${edgeKey}`;
const maskedKey = "••••••••••••••••••••••••••••••••";
const handleCopy = async (text: string, setter: (v: boolean) => void) => {
await copyToClipboardWithMeta(text);
setter(true);
};
return (
<div className="flex flex-col gap-4 py-2">
<Card className="border-muted/60 shadow-none py-0">
<CardHeader className="px-4 pt-4">
<CardTitle className="text-sm font-semibold flex items-center gap-2 uppercase tracking-tight">
CLI Setup
</CardTitle>
<CardDescription className="text-xs leading-relaxed">
To setup your agent using the CLI, copy the command below and paste it in your terminal.
Make sure you have the PortaBase CLI installed. If not, you can <a href="https://portabase.io/docs/cli" target="_blank" className="underline hover:text-primary">install it here</a>.
</CardDescription>
</CardHeader>
<CardContent className="px-4 pb-4 space-y-4">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Input
readOnly
value={isVisible ? command : `portabase agent "${agentName}" --key ${maskedKey}`}
onFocus={(e) => {
setIsVisible(true);
handleCopy(command, setIsCopiedCommand);
e.currentTarget.select();
}}
onClick={(e) => e.currentTarget.select()}
onBlur={() => {
setIsVisible(false);
setIsCopiedCommand(false);
}}
className="font-mono text-xs bg-muted/30 h-10 pr-10 cursor-pointer"
/>
<Button
variant="ghost"
size="icon"
onClick={(e) => {
e.stopPropagation();
setIsVisible(!isVisible);
}}
className="absolute right-1 top-1.5 h-7 w-7"
type="button"
>
{isVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</Button>
</div>
<Button
variant="outline"
onClick={() => handleCopy(command, setIsCopiedCommand)}
className="shrink-0 gap-2 h-10 px-4"
type="button"
>
{isCopiedCommand ? (
<><Check className="h-4 w-4 text-green-500" /></>
) : (
<><Copy className="h-4 w-4" /></>
)}
</Button>
</div>
</CardContent>
</Card>
<Card className="border-muted/60 shadow-none py-0">
<CardHeader className="px-4 pt-4">
<CardTitle className="text-sm font-semibold flex items-center gap-2 uppercase tracking-tight">
Manual Setup
</CardTitle>
<CardDescription className="text-xs leading-relaxed">
Use this key to manually configure your agent in your configuration file.
If you need help for manual configuration, you can follow our guide in the <a href="https://portabase.io/docs" target="_blank" className="underline hover:text-primary">documentation</a>.
</CardDescription>
</CardHeader>
<CardContent className="px-4 pb-4 space-y-4">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Input
readOnly
value={isVisible ? edgeKey : maskedKey}
onFocus={(e) => {
setIsVisible(true);
handleCopy(edgeKey, setIsCopiedKey);
e.currentTarget.select();
}}
onClick={(e) => e.currentTarget.select()}
onBlur={() => {
setIsVisible(false);
setIsCopiedKey(false);
}}
className="font-mono text-xs bg-muted/30 h-10 pr-10 cursor-pointer"
/>
<Button
variant="ghost"
size="icon"
onClick={(e) => {
e.stopPropagation();
setIsVisible(!isVisible);
}}
className="absolute right-1 top-1.5 h-7 w-7 hover:bg-transparent"
type="button"
>
{isVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</Button>
</div>
<Button
variant="outline"
onClick={() => handleCopy(edgeKey, setIsCopiedKey)}
className="shrink-0 gap-2 h-10 px-4 "
type="button"
>
{isCopiedKey ? (
<><Check className="h-4 w-4 text-green-500" /></>
) : (
<><Copy className="h-4 w-4" /></>
)}
</Button>
</div>
</CardContent>
</Card>
</div>
);
};
+121
View File
@@ -0,0 +1,121 @@
"use client";
import {useState} from "react";
import Link from "next/link";
import {Card} from "@/components/ui/card";
import {ConnectionIndicator} from "@/components/common/connection-indicator";
import {formatDateLastContact} from "@/utils/date-formatting";
import {AgentWith} from "@/db/schema/08_agent";
import {Activity, ChevronRight, Copy, Check, Fingerprint, Server, Database, AlertCircle} from "lucide-react";
import {Badge} from "@/components/ui/badge";
import {truncateWords} from "@/utils/text";
import {useIsMobile} from "@/hooks/use-mobile";
import {Tooltip, TooltipContent, TooltipTrigger} from "@/components/ui/tooltip";
import {useAgentUpdateCheck} from "@/features/agents/use-agent-update-check";
export type agentCardProps = {
data: AgentWith;
organizationView?: boolean;
};
export const AgentCard = (props: agentCardProps) => {
const {data: agent} = props;
const isMobile = useIsMobile();
const [isCopied, setIsCopied] = useState(false);
const {newRelease, isUpdateAvailable} = useAgentUpdateCheck(agent.version);
const handleCopy = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
navigator.clipboard.writeText(agent.id);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
return (
<Link
href={props.organizationView ? `/dashboard/settings/agents/${agent.id}`: `/dashboard/agents/${agent.id}`}
className="group block transition-all duration-200 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-xl"
>
<Card className="flex flex-row items-center p-4 gap-5 transition-all border-border/50 bg-card hover:bg-accent/50 hover:border-primary/50 group-hover:shadow-md overflow-hidden">
<div className="relative w-12 h-12 p-2.5 bg-background rounded-xl border border-border/50 shadow-sm flex items-center justify-center group-hover:border-primary/30 transition-all duration-300 group-hover:scale-105 shrink-0">
<Server className="w-6 h-6 text-foreground/80 group-hover:text-primary transition-colors" />
</div>
<div className="flex-1 min-w-0 flex flex-col gap-1.5">
<div className="flex items-center gap-3">
<h3 className="text-lg font-black text-foreground group-hover:text-primary transition-colors truncate tracking-tight ">
{isMobile ? truncateWords(agent.name, 2) : agent.name}
</h3>
{agent.version && (
<div className="flex items-center gap-2">
<Badge variant="secondary" className="h-5 px-1.5 text-[10px] font-bold tracking-wider">
v{agent.version}
</Badge>
{agent.healthErrorCount && (
<Badge variant="destructive" className="h-5 px-1.5 text-[10px] font-bold tracking-wider">
down
</Badge>
)}
{isUpdateAvailable && (
<Tooltip>
<TooltipTrigger asChild>
<div className="flex items-center justify-center w-5 h-5 bg-yellow-500/10 rounded-full border border-yellow-500/20 text-yellow-600">
<AlertCircle className="w-3 h-3" />
</div>
</TooltipTrigger>
<TooltipContent>
<p>Update available: {newRelease?.tag_name}</p>
</TooltipContent>
</Tooltip>
)}
</div>
)}
</div>
<div className="flex items-center gap-4 text-muted-foreground group-hover:text-foreground transition-colors">
<div className="hidden sm:flex items-center gap-1.5 min-w-0">
<Fingerprint className="w-3.5 h-3.5 shrink-0" />
<span className="font-mono text-xs font-bold truncate opacity-80">
{agent.id}
</span>
<button
onClick={handleCopy}
className="ml-0.5 p-1 hover:bg-muted rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 z-10"
title="Copy ID"
>
{isCopied ? <Check className="w-3 h-3 text-green-500" /> : <Copy className="w-3 h-3" />}
</button>
</div>
<div className="flex items-center gap-1.5 shrink-0">
<Database className="w-3.5 h-3.5" />
<span className="text-xs font-bold uppercase tracking-tight opacity-80">
{agent.databases?.length ?? 0} DBs
</span>
</div>
</div>
</div>
<div className="flex items-center gap-4 shrink-0">
<div className="hidden sm:flex flex-col items-end gap-1 text-right">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground/70">Last Contact</span>
<div className="flex items-center gap-1.5">
<Activity className="w-3.5 h-3.5 text-muted-foreground" />
<span className="text-xs font-bold uppercase tracking-tight">
{formatDateLastContact(agent.lastContact)}
</span>
</div>
</div>
<div className="scale-110">
<ConnectionIndicator date={agent.lastContact}/>
</div>
<ChevronRight className="w-5 h-5 text-muted-foreground group-hover:text-primary group-hover:translate-x-1 transition-all" />
</div>
</Card>
</Link>
);
};
+127
View File
@@ -0,0 +1,127 @@
"use client"
import {Card, CardContent, CardHeader, CardTitle} from "@/components/ui/card";
import {Server} from "lucide-react";
import {formatDateLastContact} from "@/utils/date-formatting";
import {AgentCardKey} from "@/features/agents/agent-card-key";
import {AgentWithDatabases} from "@/db/schema/08_agent";
import {useQuery} from "@tanstack/react-query";
import {getAgentAction} from "@/features/agents/agents.action";
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import {Separator} from "@/components/ui/separator";
import {Badge} from "@/components/ui/badge";
import {CardsWithPagination} from "@/components/common/cards-with-pagination";
import {AgentDatabaseCard} from "@/features/agents/agent-database-card";
import {HealthCheckGraph} from "@/features/database/health-grid";
import {HealthcheckLog} from "@/db/schema/15_healthcheck-log";
type AgentContentPageProps = {
edgeKey: string;
agent: AgentWithDatabases
}
export const AgentContentPage = ({edgeKey, agent: initialAgent}: AgentContentPageProps) => {
const {data} = useQuery({
queryKey: ["agent-data", initialAgent.id],
queryFn: async () => {
const result = await getAgentAction(initialAgent.id);
return result?.data;
},
initialData: {
data: initialAgent,
health: []
},
staleTime: 0,
gcTime: 0,
refetchInterval: 1000,
});
const agent = data?.data ?? initialAgent;
const agentHealthLogs: HealthcheckLog[] = data?.health ?? [];
return (
<div className="space-y-10">
<div className="flex flex-col sm:flex-row sm:justify-between gap-6 ">
<Card className="w-full sm:w-auto flex-1 transition-all border-border/50 bg-card ">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle
className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Databases</CardTitle>
<Server className="h-4 w-4 text-muted-foreground opacity-50"/>
</CardHeader>
<CardContent>
<div className="text-3xl font-bold tracking-tight">{agent.databases.length}</div>
<p className="text-xs text-muted-foreground mt-1">Linked resources</p>
</CardContent>
</Card>
<Card className="w-full sm:w-auto flex-1 transition-all border-border/50 bg-card ">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">Last
contact</CardTitle>
<Server className="h-4 w-4 text-muted-foreground opacity-50"/>
</CardHeader>
<CardContent>
<div
className="text-3xl font-bold tracking-tight">{formatDateLastContact(agent.lastContact)}</div>
<p className="text-xs text-muted-foreground mt-1">Status heartbeat</p>
</CardContent>
</Card>
</div>
{agent.lastContact && (
<HealthCheckGraph logs={agentHealthLogs}/>
)}
<div className="space-y-6">
<Accordion type="single" collapsible defaultValue={!agent.lastContact ? "registration" : undefined}>
<AccordionItem value="registration"
className="border rounded-xl px-6 bg-card shadow-sm overflow-hidden transition-all duration-300">
<AccordionTrigger className="hover:no-underline py-4 group">
<div className="flex items-center gap-3">
<span className="text-xl font-bold tracking-tight">Registration & Setup</span>
{!agent.lastContact && (
<Badge variant="outline"
className="bg-orange-500/10 text-orange-600 border-orange-500/20 animate-pulse">
Action Required
</Badge>
)}
</div>
</AccordionTrigger>
<AccordionContent className="pb-6 pt-2 border-t border-dashed">
<AgentCardKey
edgeKey={edgeKey}
agentName={agent.name}
/>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
{agent.databases.length > 0 && (
<div className="space-y-6">
<div className="flex items-center justify-between px-1">
<div className="space-y-1">
<h2 className="text-2xl font-bold tracking-tight">Managed Databases</h2>
<p className="text-sm text-muted-foreground">
Resources currently connected to this agent.
</p>
</div>
</div>
<Separator className="opacity-50"/>
<CardsWithPagination
cardsPerPage={4}
numberOfColumns={2}
data={agent.databases}
cardItem={AgentDatabaseCard}
/>
</div>
)}
</div>
)
}
@@ -0,0 +1,14 @@
"use client";
import {Database} from "@/db/schema/07_database";
import {DatabaseCard} from "@/components/common/database-card";
export type agentDatabaseCardProps = {
data: Database;
};
export const AgentDatabaseCard = (props: agentDatabaseCardProps) => {
const {data: database} = props;
return <DatabaseCard withDetails={false} data={database}/>;
};
@@ -0,0 +1,79 @@
"use client"
import {ColumnDef} from "@tanstack/react-table"
import {Database} from "@/db/schema/07_database"
import Image from "next/image"
import {ConnectionIndicator} from "@/components/common/connection-indicator"
import {formatDateLastContact} from "@/utils/date-formatting"
import Link from "next/link"
import {Button} from "@/components/ui/button"
import {ChevronRight} from "lucide-react"
export const agentDatabaseColumns: ColumnDef<Database>[] = [
{
accessorKey: "dbms",
header: "Type",
cell: ({row}) => (
<div className="flex items-center justify-center w-8 h-8 p-1.5 bg-muted/50 rounded-lg border border-border/50">
<Image
src={`/images/${row.original.dbms}.png`}
alt={row.original.dbms}
width={20}
height={20}
className="object-contain"
/>
</div>
)
},
{
accessorKey: "name",
header: "Name",
cell: ({row}) => (
<div className="flex flex-col">
<span className="font-bold text-sm">{row.original.name}</span>
<span className="text-[10px] text-muted-foreground font-mono truncate max-w-[150px]">
{row.original.agentDatabaseId}
</span>
</div>
)
},
{
accessorKey: "lastContact",
header: "Last Contact",
cell: ({row}) => (
<div className="flex flex-col">
<span className="text-xs">
{formatDateLastContact(row.original.lastContact)}
</span>
</div>
)
},
{
id: "status",
header: "Status",
cell: ({row}) => (
<div className="flex justify-center w-full">
<ConnectionIndicator date={row.original.lastContact} />
</div>
)
},
{
id: "actions",
header: () => null,
cell: ({row}) => {
const href = row.original.projectId
? `/dashboard/projects/${row.original.projectId}/database/${row.original.id}`
: "#";
return (
<div className="flex justify-end">
<Button variant="ghost" size="icon" asChild className="hover:bg-accent group">
<Link href={href}>
<ChevronRight className="h-4 w-4 text-muted-foreground group-hover:text-foreground transition-transform group-hover:translate-x-0.5" />
</Link>
</Button>
</div>
)
}
}
]
@@ -0,0 +1,63 @@
"use client";
import {Trash2} from "lucide-react";
import {ButtonWithConfirm} from "@/components/common/button-with-confirm";
import {useMutation} from "@tanstack/react-query";
import {useRouter} from "next/navigation";
import {toast} from "sonner";
import {deleteAgentAction} from "@/features/agents/agent-delete.action";
import {useIsMobile} from "@/hooks/use-mobile";
export type ButtonDeleteAgentProps = {
text?: string,
agentId: string,
organizationId?: string
organizationIds?: string[]
};
export const ButtonDeleteAgent = (props: ButtonDeleteAgentProps) => {
const router = useRouter();
const isMobile = useIsMobile();
const mutation = useMutation({
mutationFn: () => deleteAgentAction({agentId: props.agentId, organizationId: props.organizationId, organizationIds: props.organizationIds}),
onSuccess: async (result: any) => {
if (result.data?.success) {
toast.success(result.data.actionSuccess.message);
router.push(props.organizationId ? "/dashboard/settings?tab=agents" : "/dashboard/agents");
} else {
toast.error(result.data.actionError.message || "Unknown error occurred.");
}
},
});
return (
<ButtonWithConfirm
title={props.text ? props.text : ""}
description="Are you sure you want to remove this agent? This action cannot be undone."
button={{
main: {
text: props.text ? !isMobile ? props.text : "" : "",
variant: "outline",
icon: <Trash2 color="red"/>,
},
confirm: {
className: "w-full",
text: "Delete",
icon: <Trash2/>,
variant: "destructive",
onClick: () => {
mutation.mutate();
},
},
cancel: {
className: "w-full",
text: "Cancel",
icon: <Trash2/>,
variant: "outline",
},
}}
isPending={mutation.isPending}
/>
);
};
+137
View File
@@ -0,0 +1,137 @@
"use server";
import {z} from "zod";
import {v4 as uuidv4} from "uuid";
import {ServerActionResult} from "@/types/action-type";
import {and, eq, inArray} from "drizzle-orm";
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {Agent} from "@/db/schema/08_agent";
import {userAction} from "@/lib/safe-actions/actions";
import {zString} from "@/lib/zod";
import {withUpdatedAt} from "@/db/utils";
export const deleteAgentAction = userAction
.schema(
z.object({
agentId: zString(),
organizationId: zString().optional(),
organizationIds: z.array(z.string()).optional()
})
)
.action(async ({parsedInput}): Promise<ServerActionResult<Agent>> => {
const {agentId, organizationId, organizationIds} = parsedInput;
try {
let projectIds: string[] = [];
const uuid = uuidv4();
if (organizationId) {
await db
.delete(drizzleDb.schemas.organizationAgent)
.where(
and(
eq(drizzleDb.schemas.organizationAgent.organizationId, organizationId),
eq(drizzleDb.schemas.organizationAgent.agentId, agentId)
)
);
const organization = await db.query.organization.findFirst({
where: eq(drizzleDb.schemas.organization.id, organizationId),
with: {
projects: true,
}
});
projectIds = organization?.projects?.map(project => project.id) ?? [];
} else if (organizationIds) {
const organizationsToRemoveDetails = await db.query.organization.findMany({
where: inArray(drizzleDb.schemas.organization.id, organizationIds),
with: {
projects: true
}
});
projectIds = organizationsToRemoveDetails.flatMap(org =>
org.projects.map(project => project.id)
);
}
if (projectIds?.length > 0) {
const databases = await db.query.database.findMany({
where: (db, {inArray}) => inArray(db.projectId, projectIds),
columns: {id: true}
});
const databaseIds = databases.map(d => d.id);
await db
.update(drizzleDb.schemas.database)
.set(withUpdatedAt({
backupPolicy: null,
projectId: null
}))
.where(inArray(drizzleDb.schemas.database.projectId, projectIds))
.execute();
await db.delete(drizzleDb.schemas.retentionPolicy)
.where(inArray(drizzleDb.schemas.retentionPolicy.databaseId, databaseIds))
.execute();
await db.delete(drizzleDb.schemas.alertPolicy)
.where(inArray(drizzleDb.schemas.alertPolicy.databaseId, databaseIds))
.execute();
await db.delete(drizzleDb.schemas.storagePolicy)
.where(inArray(drizzleDb.schemas.storagePolicy.databaseId, databaseIds))
.execute();
}
const updatedAgent = await db
.update(drizzleDb.schemas.agent)
.set(withUpdatedAt({
isArchived: true,
slug: uuid,
deletedAt: new Date()
}))
.where(eq(drizzleDb.schemas.agent.id, agentId))
.returning();
if (!updatedAgent[0]) {
return {
success: false,
actionError: {
message: "Agent not found or update failed",
status: 404,
messageParams: {agentId: agentId},
},
};
}
return {
success: true,
value: updatedAgent[0],
actionSuccess: {
message: "Agent has been successfully deleted.",
messageParams: {projectId: agentId},
},
};
} catch (error) {
return {
success: false,
actionError: {
message: "Failed to delete agent.",
status: 500,
cause: error instanceof Error ? error.message : "Unknown error",
messageParams: {agentId: agentId},
},
};
}
});
@@ -7,16 +7,16 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {AgentForm} from "@/features/agents/components/agent.form";
import {AgentForm} from "@/features/agents/agent-form";
import {Button, buttonVariants} from "@/components/ui/button";
import {Plus} from "lucide-react";
import {GearIcon} from "@radix-ui/react-icons";
import {EmptyStatePlaceholder} from "@/components/wrappers/common/empty-state-placeholder";
import {EmptyStatePlaceholder} from "@/components/common/empty-state-placeholder";
import {useState} from "react";
import {useRouter} from "next/navigation";
import {OrganizationWithMembers} from "@/db/schema/03_organization";
import {Tabs, TabsContent, TabsList, TabsTrigger} from "@/components/ui/tabs";
import {AgentOrganisationForm} from "@/features/agents/components/agent-organizations.form";
import {AgentOrganisationForm} from "@/features/agents/agent-organizations.form";
import {AgentWith} from "@/db/schema/08_agent";
type AgentDialogProps = {
+45
View File
@@ -0,0 +1,45 @@
"use client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, DialogClose } from "@/components/ui/dialog";
import { generateEdgeKey } from "@/utils/edge_key";
import { PropsWithChildren } from "react";
import { getServerUrl } from "@/utils/get-server-url";
import { CodeSnippet } from "@/components/common/code-snippet";
import {Agent} from "@/db/schema/08_agent";
export type agentRegistrationDialogProps = PropsWithChildren<{
agent: Agent;
}>;
export function AgentModalKey(props: agentRegistrationDialogProps) {
const edge_key = generateEdgeKey(getServerUrl(), props.agent.id);
const command = `portabase agent "${props.agent.name}" --key ${edge_key}`;
return (
<Dialog>
<DialogTrigger asChild>{props.children}</DialogTrigger>
<DialogContent className="sm:max-w-[425px] w-full">
<DialogHeader>
<DialogTitle>Agent Connection</DialogTitle>
</DialogHeader>
<div className="sm:max-w-[375px] w-full space-y-4">
<CodeSnippet
title="Installation Command"
code={command}
/>
<CodeSnippet
title="Agent Key (Manual)"
code={edge_key}
/>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">Close</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -3,13 +3,13 @@
import {useRouter} from "next/navigation";
import {useMutation} from "@tanstack/react-query";
import {Form, FormControl, FormField, FormItem, useZodForm} from "@/components/ui/form";
import {ButtonWithLoading} from "@/components/wrappers/common/button/button-with-loading";
import {ButtonWithLoading} from "@/components/common/button-with-loading";
import {OrganizationWithMembers} from "@/db/schema/03_organization";
import {MultiSelect} from "@/components/wrappers/common/multiselect/multi-select";
import {MultiSelect} from "@/components/common/multi-select";
import {toast} from "sonner";
import {AgentWith} from "@/db/schema/08_agent";
import {AgentOrganizationSchema, AgentOrganizationType} from "@/features/agents/components/agent-organizations.schema";
import {updateAgentOrganizationsAction} from "@/features/agents/components/agent-organizations.action";
import {AgentOrganizationSchema, AgentOrganizationType} from "@/features/agents/agent-organizations.schema";
import {updateAgentOrganizationsAction} from "@/features/agents/agent-organizations.action";
type AgentOrganisationFormProps = {
+56
View File
@@ -0,0 +1,56 @@
"use server"
import fs from "node:fs";
import {env} from "@/env.mjs";
import path from "path";
/**
* Get Public server key content
*/
export async function getPublicServerKeyContent() {
try {
const keyPath = path.join(env.PRIVATE_PATH, '/keys/server_public.pem')
return fs.readFileSync(keyPath, "utf8");
} catch (error: any) {
console.error("Error :", error);
return {
success: false,
message: `An error occurred while getting public server key`,
};
}
}
/**
* Get Master server key
*/
export async function getMasterServerKeyContent() {
try {
const keyPath = path.join(env.PRIVATE_PATH, '/keys/master_key.bin')
return fs.readFileSync(keyPath);
} catch (error: any) {
console.error("Error :", error);
return {
success: false,
message: `An error occurred while getting master server key`,
};
}
}
export async function downloadMasterKeyAction() {
try {
const keyPath = path.join(env.PRIVATE_PATH, "keys/master_key.bin");
const fileBuffer = fs.readFileSync(keyPath);
return {
success: true,
data: fileBuffer.toString("base64"),
};
} catch (error) {
return {
success: false,
message: "Unable to download master key",
};
}
}
@@ -1,7 +1,7 @@
"use client";
import {useQuery} from "@tanstack/react-query";
import {getNewAgentRelease} from "@/features/updates/services/github";
import {getNewAgentRelease} from "@/lib/github-releases";
export const useAgentUpdateCheck = (currentVersion?: string | null) => {
const {data: newRelease, isLoading} = useQuery({