Skip to content

Modern Docker Management, Designed for Everyone

fix: containers grouped by projects split between pages (#2049)

Kyle Mendell54d159aa1e39
diff --git a/backend/internal/huma/handlers/containers.go b/backend/internal/huma/handlers/containers.go
index cb626475e..9f9ac97b9 100644
--- a/backend/internal/huma/handlers/containers.go
+++ b/backend/internal/huma/handlers/containers.go
@@ -26,10 +26,11 @@ type ContainerHandler struct {
// Paginated response
type ContainerPaginatedResponse struct {
- Success bool `json:"success"`
- Data []containertypes.Summary `json:"data"`
- Counts containertypes.StatusCounts `json:"counts"`
- Pagination base.PaginationResponse `json:"pagination"`
+ Success bool `json:"success"`
+ Data []containertypes.Summary `json:"data"`
+ Groups []containertypes.SummaryGroup `json:"groups,omitempty"`
+ Counts containertypes.StatusCounts `json:"counts"`
+ Pagination base.PaginationResponse `json:"pagination"`
}
type ListContainersInput struct {
@@ -39,6 +40,7 @@ type ListContainersInput struct {
Order string `query:"order" default:"asc" doc:"Sort direction"`
Start int `query:"start" default:"0" doc:"Start index"`
Limit int `query:"limit" default:"20" doc:"Limit"`
+ GroupBy string `query:"groupBy" doc:"Optional grouping mode (for example: project)"`
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal containers"`
Updates string `query:"updates" doc:"Filter by update status (has_update, up_to_date, error, unknown)"`
}
@@ -222,7 +224,7 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
Filters: filters,
}
- containers, paginationResp, counts, err := h.containerService.ListContainersPaginated(ctx, params, true, input.IncludeInternal)
+ result, err := h.containerService.ListContainersPaginated(ctx, params, true, input.IncludeInternal, input.GroupBy)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerListError{Err: err}).Error())
}
@@ -230,14 +232,15 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
return &ListContainersOutput{
Body: ContainerPaginatedResponse{
Success: true,
- Data: containers,
- Counts: counts,
+ Data: result.Items,
+ Groups: result.Groups,
+ Counts: result.Counts,
Pagination: base.PaginationResponse{
- TotalPages: paginationResp.TotalPages,
- TotalItems: paginationResp.TotalItems,
- CurrentPage: paginationResp.CurrentPage,
- ItemsPerPage: paginationResp.ItemsPerPage,
- GrandTotalItems: paginationResp.GrandTotalItems,
+ TotalPages: result.Pagination.TotalPages,
+ TotalItems: result.Pagination.TotalItems,
+ CurrentPage: result.Pagination.CurrentPage,
+ ItemsPerPage: result.Pagination.ItemsPerPage,
+ GrandTotalItems: result.Pagination.GrandTotalItems,
},
},
}, nil
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index e6e0d87c3..08f9ad137 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -35,6 +35,18 @@ type ContainerService struct {
settingsService *SettingsService
}
+const (
+ containerGroupByProject = "project"
+ containerNoProjectGroup = "No Project"
+)
+
+type ContainerListResult struct {
+ Items []containertypes.Summary
+ Groups []containertypes.SummaryGroup
+ Pagination pagination.Response
+ Counts containertypes.StatusCounts
+}
+
func NewContainerService(db *database.DB, eventService *EventService, dockerService *DockerClientService, imageService *ImageService, settingsService *SettingsService) *ContainerService {
return &ContainerService{
db: db,
@@ -436,15 +448,21 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
return nil
}
-func (s *ContainerService) ListContainersPaginated(ctx context.Context, params pagination.QueryParams, includeAll bool, includeInternal bool) ([]containertypes.Summary, pagination.Response, containertypes.StatusCounts, error) {
+func (s *ContainerService) ListContainersPaginated(
+ ctx context.Context,
+ params pagination.QueryParams,
+ includeAll bool,
+ includeInternal bool,
+ groupBy string,
+) (ContainerListResult, error) {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
- return nil, pagination.Response{}, containertypes.StatusCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)
+ return ContainerListResult{}, fmt.Errorf("failed to connect to Docker: %w", err)
}
containerList, err := dockerClient.ContainerList(ctx, client.ContainerListOptions{All: includeAll})
if err != nil {
- return nil, pagination.Response{}, containertypes.StatusCounts{}, fmt.Errorf("failed to list Docker containers: %w", err)
+ return ContainerListResult{}, fmt.Errorf("failed to list Docker containers: %w", err)
}
dockerContainers := containerList.Items
@@ -454,11 +472,149 @@ func (s *ContainerService) ListContainersPaginated(ctx context.Context, params p
items := s.buildContainerSummaries(dockerContainers, updateInfoMap)
config := s.buildContainerPaginationConfig()
- result := pagination.SearchOrderAndPaginate(items, params, config)
counts := s.calculateContainerStatusCounts(items)
+
+ if groupBy == containerGroupByProject {
+ ungroupedParams := params
+ ungroupedParams.Start = 0
+ ungroupedParams.Limit = -1
+
+ result := pagination.SearchOrderAndPaginate(items, ungroupedParams, config)
+ groups, paginationResp := paginateContainerProjectGroupsInternal(result, params)
+ return ContainerListResult{
+ Items: flattenContainerProjectGroupsInternal(groups),
+ Groups: groups,
+ Pagination: paginationResp,
+ Counts: counts,
+ }, nil
+ }
+
+ result := pagination.SearchOrderAndPaginate(items, params, config)
paginationResp := pagination.BuildResponseFromFilterResult(result, params)
- return result.Items, paginationResp, counts, nil
+ return ContainerListResult{
+ Items: result.Items,
+ Pagination: paginationResp,
+ Counts: counts,
+ }, nil
+}
+
+func paginateContainerProjectGroupsInternal(
+ result pagination.FilterResult[containertypes.Summary],
+ params pagination.QueryParams,
+) ([]containertypes.SummaryGroup, pagination.Response) {
+ groups := groupContainersByProjectInternal(result.Items)
+ groupedItems := flattenContainerProjectGroupsInternal(groups)
+ totalCount := len(groupedItems)
+
+ if params.Limit <= 0 {
+ return groups, pagination.Response{
+ TotalPages: 1,
+ TotalItems: int64(totalCount),
+ CurrentPage: 1,
+ ItemsPerPage: totalCount,
+ GrandTotalItems: result.TotalAvailable,
+ }
+ }
+
+ pages := partitionContainerProjectPagesInternal(groups, params.Limit)
+ requestedPage := 1
+ if params.Limit > 0 {
+ requestedPage = (params.Start / params.Limit) + 1
+ }
+
+ if requestedPage < 1 {
+ requestedPage = 1
+ }
+
+ totalPages := len(pages)
+ if totalPages == 0 {
+ totalPages = 1
+ }
+ if requestedPage > totalPages {
+ requestedPage = totalPages
+ }
+
+ pageGroups := []containertypes.SummaryGroup{}
+ if len(pages) > 0 {
+ pageGroups = pages[requestedPage-1]
+ }
+
+ return pageGroups, pagination.Response{
+ TotalPages: int64(totalPages),
+ TotalItems: int64(totalCount),
+ CurrentPage: requestedPage,
+ ItemsPerPage: params.Limit,
+ GrandTotalItems: result.TotalAvailable,
+ }
+}
+
+func groupContainersByProjectInternal(items []containertypes.Summary) []containertypes.SummaryGroup {
+ groups := make([]containertypes.SummaryGroup, 0)
+ groupIndexes := make(map[string]int)
+
+ for _, item := range items {
+ groupName := getContainerProjectNameInternal(item)
+ groupIndex, exists := groupIndexes[groupName]
+ if !exists {
+ groupIndex = len(groups)
+ groupIndexes[groupName] = groupIndex
+ groups = append(groups, containertypes.SummaryGroup{GroupName: groupName})
+ }
+
+ groups[groupIndex].Items = append(groups[groupIndex].Items, item)
+ }
+
+ return groups
+}
+
+func flattenContainerProjectGroupsInternal(groups []containertypes.SummaryGroup) []containertypes.Summary {
+ flattened := make([]containertypes.Summary, 0)
+ for _, group := range groups {
+ flattened = append(flattened, group.Items...)
+ }
+
+ return flattened
+}
+
+func partitionContainerProjectPagesInternal(groups []containertypes.SummaryGroup, limit int) [][]containertypes.SummaryGroup {
+ if len(groups) == 0 {
+ return [][]containertypes.SummaryGroup{{}}
+ }
+
+ pages := make([][]containertypes.SummaryGroup, 0)
+ currentPage := make([]containertypes.SummaryGroup, 0)
+ currentCount := 0
+
+ for _, group := range groups {
+ currentPage = append(currentPage, group)
+ currentCount += len(group.Items)
+
+ if currentCount >= limit {
+ pages = append(pages, currentPage)
+ currentPage = make([]containertypes.SummaryGroup, 0)
+ currentCount = 0
+ }
+ }
+
+ if len(currentPage) > 0 || len(pages) == 0 {
+ pages = append(pages, currentPage)
+ }
+
+ return pages
+}
+
+func getContainerProjectNameInternal(container containertypes.Summary) string {
+ if container.Labels == nil {
+ return containerNoProjectGroup
+ }
+
+ projectName := strings.TrimSpace(container.Labels["com.docker.compose.project"])
+ if projectName == "" {
+ return containerNoProjectGroup
+ }
+
+ return projectName
}
func filterInternalContainers(containers []container.Summary, includeInternal bool) []container.Summary {
diff --git a/backend/internal/services/container_service_test.go b/backend/internal/services/container_service_test.go
new file mode 100644
index 000000000..5787bbb13
--- /dev/null
+++ b/backend/internal/services/container_service_test.go
@@ -0,0 +1,86 @@
+package services
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ containertypes "github.com/getarcaneapp/arcane/types/container"
+ "github.com/stretchr/testify/require"
+)
+
+func TestPaginateContainerProjectGroupsKeepsProjectWhole(t *testing.T) {
+ items := []containertypes.Summary{
+ newGroupedContainerSummary("other-1", "other-1"),
+ newGroupedContainerSummary("other-2", "other-2"),
+ newGroupedContainerSummary("other-3", "other-3"),
+ newGroupedContainerSummary("other-4", "other-4"),
+ newGroupedContainerSummary("other-5", "other-5"),
+ newGroupedContainerSummary("other-6", "other-6"),
+ newGroupedContainerSummary("other-7", "other-7"),
+ newGroupedContainerSummary("other-8", "other-8"),
+ newGroupedContainerSummary("other-9", "other-9"),
+ newGroupedContainerSummary("other-10", "other-10"),
+ newGroupedContainerSummary("other-11", "other-11"),
+ newGroupedContainerSummary("other-12", "other-12"),
+ newGroupedContainerSummary("other-13", "other-13"),
+ newGroupedContainerSummary("other-14", "other-14"),
+ newGroupedContainerSummary("other-15", "other-15"),
+ newGroupedContainerSummary("other-16", "other-16"),
+ newGroupedContainerSummary("other-17", "other-17"),
+ newGroupedContainerSummary("other-18", "other-18"),
+ newGroupedContainerSummary("immich-server", "immich"),
+ newGroupedContainerSummary("immich-ml", "immich"),
+ newGroupedContainerSummary("immich-redis", "immich"),
+ newGroupedContainerSummary("immich-postgres", "immich"),
+ }
+
+ groupedItems, resp := paginateContainerProjectGroupsInternal(
+ pagination.FilterResult[containertypes.Summary]{Items: items, TotalCount: int64(len(items)), TotalAvailable: int64(len(items))},
+ pagination.QueryParams{PaginationParams: pagination.PaginationParams{Start: 0, Limit: 20}},
+ )
+
+ require.Len(t, groupedItems, 19)
+ require.Equal(t, int64(1), resp.TotalPages)
+ require.Equal(t, 1, resp.CurrentPage)
+ require.Equal(t, 20, resp.ItemsPerPage)
+ require.Equal(t, int64(22), resp.TotalItems)
+
+ projectCounts := make(map[string]int)
+ for _, group := range groupedItems {
+ projectCounts[group.GroupName] += len(group.Items)
+ }
+
+ require.Equal(t, 4, projectCounts["immich"])
+ require.Equal(t, 1, projectCounts["other-1"])
+ require.Equal(t, 1, projectCounts["other-18"])
+}
+
+func TestGroupContainersByProjectUsesNoProjectBucket(t *testing.T) {
+ groups := groupContainersByProjectInternal([]containertypes.Summary{
+ {ID: "1", Labels: map[string]string{"com.docker.compose.project": "alpha"}},
+ {ID: "2", Labels: map[string]string{}},
+ {ID: "3", Labels: nil},
+ })
+
+ require.Len(t, groups, 2)
+ require.Equal(t, "alpha", groups[0].GroupName)
+ require.Len(t, groups[0].Items, 1)
+ require.Equal(t, containerNoProjectGroup, groups[1].GroupName)
+ require.Len(t, groups[1].Items, 2)
+ require.Equal(t, containerNoProjectGroup, getContainerProjectNameInternal(groups[1].Items[0]))
+ require.Equal(t, containerNoProjectGroup, getContainerProjectNameInternal(groups[1].Items[1]))
+}
+
+func newGroupedContainerSummary(name string, project string) containertypes.Summary {
+ labels := map[string]string{}
+ if project != "" {
+ labels["com.docker.compose.project"] = project
+ }
+
+ return containertypes.Summary{
+ ID: name,
+ Names: []string{name},
+ Labels: labels,
+ State: "running",
+ }
+}
diff --git a/frontend/src/lib/components/arcane-table/arcane-table.svelte b/frontend/src/lib/components/arcane-table/arcane-table.svelte
index f2aaf8a6f..9a2bf9702 100644
--- a/frontend/src/lib/components/arcane-table/arcane-table.svelte
+++ b/frontend/src/lib/components/arcane-table/arcane-table.svelte
@@ -61,6 +61,7 @@
customTableView,
customSettings = $bindable<Record<string, unknown>>({}),
columnVisibility = $bindable<VisibilityState>({}),
+ groupedRows = null,
// Grouping props
groupBy,
groupIcon,
@@ -97,6 +98,7 @@
>;
customSettings?: Record<string, unknown>;
columnVisibility?: VisibilityState;
+ groupedRows?: GroupedData<TData>[] | null;
// Grouping props
groupBy?: (item: TData) => string;
groupIcon?: (groupName: string) => Component;
@@ -509,7 +511,8 @@
);
// Compute grouped rows when groupBy is provided
- const groupedRows = $derived.by((): GroupedData<TData>[] | null => {
+ const effectiveGroupedRows = $derived.by((): GroupedData<TData>[] | null => {
+ if (groupedRows) return groupedRows;
if (!groupBy) return null;
const groups = new Map<string, TData[]>();
@@ -660,7 +663,7 @@
{table}
{selectedIds}
columnsCount={columnsDef.length}
- {groupedRows}
+ groupedRows={effectiveGroupedRows}
{groupIcon}
{groupCollapsedState}
{selectionDisabled}
@@ -678,7 +681,7 @@
{table}
{mobileCard}
{mobileFieldVisibility}
- {groupedRows}
+ groupedRows={effectiveGroupedRows}
{groupIcon}
{groupCollapsedState}
onGroupToggle={handleGroupToggle}
@@ -716,7 +719,7 @@
{table}
{selectedIds}
columnsCount={columnsDef.length}
- {groupedRows}
+ groupedRows={effectiveGroupedRows}
{groupIcon}
{groupCollapsedState}
{selectionDisabled}
@@ -732,7 +735,7 @@
{table}
{mobileCard}
{mobileFieldVisibility}
- {groupedRows}
+ groupedRows={effectiveGroupedRows}
{groupIcon}
{groupCollapsedState}
onGroupToggle={handleGroupToggle}
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index 19b9c9f07..a47345571 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -3,29 +3,38 @@ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type {
ContainerStatusCounts,
ContainerSummaryDto,
+ ContainerSummaryGroupDto,
ContainerStats,
ContainerCreateRequest
} from '$lib/types/container.type';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
import { transformPaginationParams } from '$lib/utils/params.util';
-export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts>;
+export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts> & {
+ groups?: ContainerSummaryGroupDto[];
+};
+export type ContainerListRequestOptions = SearchPaginationSortRequest & {
+ groupByProject?: boolean;
+};
export class ContainerService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
- async getContainers(options?: SearchPaginationSortRequest): Promise<ContainersPaginatedResponse> {
+ async getContainers(options?: ContainerListRequestOptions): Promise<ContainersPaginatedResponse> {
const envId = await this.resolveEnvironmentId();
return this.getContainersForEnvironment(envId, options);
}
async getContainersForEnvironment(
environmentId: string,
- options?: SearchPaginationSortRequest
+ options?: ContainerListRequestOptions
): Promise<ContainersPaginatedResponse> {
const params = transformPaginationParams(options);
+ if (options?.groupByProject) {
+ params.groupBy = 'project';
+ }
const res = await this.api.get(`/environments/${environmentId}/containers`, { params });
return res.data;
}
diff --git a/frontend/src/lib/types/container.type.ts b/frontend/src/lib/types/container.type.ts
index 598f81720..667bd4f87 100644
--- a/frontend/src/lib/types/container.type.ts
+++ b/frontend/src/lib/types/container.type.ts
@@ -75,6 +75,11 @@ export interface ContainerSummaryDto extends BaseContainer {
updateInfo?: ImageUpdateInfoDto;
}
+export interface ContainerSummaryGroupDto {
+ groupName: string;
+ items: ContainerSummaryDto[];
+}
+
export interface ContainerPorts {
ip?: string;
privatePort: number;
diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelte
index 088361728..fd35aa9e3 100644
--- a/frontend/src/routes/(app)/containers/+page.svelte
+++ b/frontend/src/routes/(app)/containers/+page.svelte
@@ -9,9 +9,12 @@
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { ContainerCreateRequest, ContainerStatusCounts } from '$lib/types/container.type';
- import { createMutation, createQuery } from '@tanstack/svelte-query';
+ import { createMutation } from '@tanstack/svelte-query';
import { BoxIcon } from '$lib/icons';
import { queryKeys } from '$lib/query/query-keys';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { ContainerListRequestOptions } from '$lib/services/container-service';
+ import ContainerEnvironmentSync from './components/container-environment-sync.svelte';
let { data } = $props();
@@ -19,7 +22,10 @@
let selectedIds = $state<string[]>([]);
let isCreateDialogOpen = $state(false);
let containers = $state(untrack(() => data.containers));
+ let isRefreshing = $state(false);
const envId = $derived(environmentStore.selected?.id || '0');
+ let groupByProject = $state(false);
+ let hasSeenEnvironmentSync = $state(false);
const countsFallback: ContainerStatusCounts = {
runningContainers: 0,
@@ -27,18 +33,30 @@
totalContainers: 0
};
- const containersQuery = createQuery(() => ({
- queryKey: queryKeys.containers.list(envId, requestOptions),
- queryFn: () => containerService.getContainersForEnvironment(envId, requestOptions),
- initialData: data.containers
- }));
+ function buildRequestOptions(options: SearchPaginationSortRequest = requestOptions): ContainerListRequestOptions {
+ return {
+ ...options,
+ groupByProject
+ };
+ }
+
+ async function refreshContainers(options: ContainerListRequestOptions = buildRequestOptions()) {
+ isRefreshing = true;
+ try {
+ const next = await containerService.getContainersForEnvironment(envId, options);
+ containers = next;
+ return next;
+ } finally {
+ isRefreshing = false;
+ }
+ }
const checkUpdatesMutation = createMutation(() => ({
mutationKey: queryKeys.containers.checkUpdates(envId),
mutationFn: () => imageService.runAutoUpdate(),
onSuccess: async () => {
toast.success(m.containers_check_updates_success());
- await containersQuery.refetch();
+ await refreshContainers();
},
onError: () => {
toast.error(m.containers_check_updates_failed());
@@ -50,7 +68,7 @@
mutationFn: (options: ContainerCreateRequest) => containerService.createContainer(options),
onSuccess: async () => {
toast.success(m.common_create_success({ resource: m.resource_container() }));
- await containersQuery.refetch();
+ await refreshContainers();
isCreateDialogOpen = false;
},
onError: () => {
@@ -58,21 +76,31 @@
}
}));
- $effect(() => {
- if (containersQuery.data) {
- containers = containersQuery.data;
+ function handleEnvironmentChange() {
+ if (!hasSeenEnvironmentSync) {
+ hasSeenEnvironmentSync = true;
+ return;
}
- });
+
+ const nextOptions: SearchPaginationSortRequest = {
+ ...requestOptions,
+ pagination: {
+ page: 1,
+ limit: requestOptions.pagination?.limit ?? containers.pagination?.itemsPerPage ?? 20
+ }
+ };
+ requestOptions = nextOptions;
+ return refreshContainers(buildRequestOptions(nextOptions));
+ }
async function handleCheckForUpdates() {
await checkUpdatesMutation.mutateAsync();
}
async function refresh() {
- await containersQuery.refetch();
+ await refreshContainers();
}
- const isRefreshing = $derived(containersQuery.isFetching && !containersQuery.isPending);
const containerStatusCounts = $derived(containers.counts ?? countsFallback);
const actionButtons: ActionButton[] = $derived([
@@ -124,15 +152,26 @@
]);
</script>
+{#key envId}
+ <ContainerEnvironmentSync onActivate={handleEnvironmentChange} />
+{/key}
+
<ResourcePageLayout title={m.containers_title()} subtitle={m.containers_subtitle()} {actionButtons} {statCards}>
{#snippet mainContent()}
<ContainerTable
bind:containers
bind:selectedIds
bind:requestOptions
+ bind:groupByProject
onRefreshData={async (options) => {
- requestOptions = options;
- await containersQuery.refetch();
+ requestOptions = {
+ search: options.search,
+ pagination: options.pagination,
+ sort: options.sort,
+ filters: options.filters,
+ includeInternal: options.includeInternal
+ };
+ return refreshContainers(options);
}}
/>
{/snippet}
diff --git a/frontend/src/routes/(app)/containers/components/container-environment-sync.svelte b/frontend/src/routes/(app)/containers/components/container-environment-sync.svelte
new file mode 100644
index 000000000..40b5c222b
--- /dev/null
+++ b/frontend/src/routes/(app)/containers/components/container-environment-sync.svelte
@@ -0,0 +1,13 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+
+ let {
+ onActivate
+ }: {
+ onActivate: () => void | Promise<unknown>;
+ } = $props();
+
+ onMount(() => {
+ void onActivate();
+ });
+</script>
diff --git a/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte b/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte
new file mode 100644
index 000000000..118684bf4
--- /dev/null
+++ b/frontend/src/routes/(app)/containers/components/container-stats-sync.svelte
@@ -0,0 +1,18 @@
+<script lang="ts">
+ import type { ContainerStatsManager } from './container-stats-manager.svelte';
+
+ let {
+ statsManager,
+ envId,
+ targetIds
+ }: {
+ statsManager: ContainerStatsManager;
+ envId: string;
+ targetIds: Set<string>;
+ } = $props();
+
+ $effect(() => {
+ statsManager.envId = envId;
+ statsManager.targetIds = targetIds;
+ });
+</script>
diff --git a/frontend/src/routes/(app)/containers/container-table.actions.ts b/frontend/src/routes/(app)/containers/container-table.actions.ts
index 7ddca491f..b21d6e7e3 100644
--- a/frontend/src/routes/(app)/containers/container-table.actions.ts
+++ b/frontend/src/routes/(app)/containers/container-table.actions.ts
@@ -1,8 +1,7 @@
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { m } from '$lib/paraglide/messages';
-import { containerService } from '$lib/services/container-service';
+import { containerService, type ContainersPaginatedResponse } from '$lib/services/container-service';
import type { ContainerSummaryDto } from '$lib/types/container.type';
-import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { toast } from 'svelte-sonner';
@@ -16,9 +15,9 @@ type BulkLoadingState = {
};
type ActionDeps = {
- getRequestOptions: () => SearchPaginationSortRequest;
- setContainers: (next: Paginated<ContainerSummaryDto>) => void;
+ setContainers: (next: ContainersPaginatedResponse) => void;
setSelectedIds: (next: string[]) => void;
+ refreshContainers: () => Promise<ContainersPaginatedResponse>;
actionStatus: Record<string, ActionStatus>;
isBulkLoading: BulkLoadingState;
};
@@ -66,14 +65,14 @@ const containerActionConfigs: Record<ContainerActionKind, ContainerActionConfig>
};
export function createContainerActions({
- getRequestOptions,
setContainers,
setSelectedIds,
+ refreshContainers,
actionStatus,
isBulkLoading
}: ActionDeps) {
- const refreshContainers = async () => {
- const result = await containerService.getContainers(getRequestOptions());
+ const reloadContainers = async () => {
+ const result = await refreshContainers();
setContainers(result);
return result;
};
@@ -91,7 +90,7 @@ export function createContainerActions({
},
async onSuccess() {
toast.success(config.success());
- await refreshContainers();
+ await reloadContainers();
}
});
} catch (error) {
@@ -132,7 +131,7 @@ export function createContainerActions({
},
async onSuccess() {
toast.success(m.containers_remove_success());
- await refreshContainers();
+ await reloadContainers();
}
});
}
@@ -167,7 +166,7 @@ export function createContainerActions({
toast.info(m.image_update_up_to_date_title());
}
- await refreshContainers();
+ await reloadContainers();
} catch (error) {
console.error('Container update failed:', error);
toast.error(m.containers_update_failed({ name: containerName }));
@@ -206,7 +205,7 @@ export function createContainerActions({
toast.error(config.failure());
}
- await refreshContainers();
+ await reloadContainers();
setSelectedIds([]);
}
}
@@ -293,7 +292,7 @@ export function createContainerActions({
toast.error(m.containers_remove_failed());
}
- await refreshContainers();
+ await reloadContainers();
setSelectedIds([]);
}
}
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 559ab700f..b31f98642 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -4,7 +4,7 @@
import { Spinner } from '$lib/components/ui/spinner/index.js';
import { goto } from '$app/navigation';
import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
- import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import { format } from 'date-fns';
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
@@ -13,12 +13,17 @@
import { m } from '$lib/paraglide/messages';
import { PortBadge } from '$lib/components/badges/index.js';
import { UniversalMobileCard } from '$lib/components/arcane-table/index.js';
- import { containerService } from '$lib/services/container-service';
+ import {
+ containerService,
+ type ContainerListRequestOptions,
+ type ContainersPaginatedResponse
+ } from '$lib/services/container-service';
import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import ImageUpdateItem from '$lib/components/image-update-item.svelte';
import { PersistedState } from 'runed';
import { onMount } from 'svelte';
import { ContainerStatsManager } from './components/container-stats-manager.svelte';
+ import ContainerStatsSync from './components/container-stats-sync.svelte';
import ContainerStatsCell from './components/container-stats-cell.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import IconImage from '$lib/components/icon-image.svelte';
@@ -28,8 +33,8 @@
getActionStatusMessage,
getContainerDisplayName,
getContainerIpAddress,
+ getProjectName,
getStateBadgeVariant,
- groupContainerByProject,
parseImageRef,
type ActionStatus
} from './container-table.helpers';
@@ -54,12 +59,14 @@
containers = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
+ groupByProject = $bindable(false),
onRefreshData
}: {
- containers: Paginated<ContainerSummaryDto>;
+ containers: ContainersPaginatedResponse;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefreshData?: (options: SearchPaginationSortRequest) => Promise<void>;
+ groupByProject?: boolean;
+ onRefreshData?: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;
} = $props();
// Track action status per container ID (e.g., "starting", "stopping", "updating", "")
@@ -74,12 +81,21 @@
const statsManager = new ContainerStatsManager();
- async function refreshContainers(options: SearchPaginationSortRequest) {
+ function buildGroupedRequest(options: SearchPaginationSortRequest, grouped = groupByProject): ContainerListRequestOptions {
+ return {
+ ...options,
+ groupByProject: grouped
+ };
+ }
+
+ async function refreshContainers(options: SearchPaginationSortRequest, grouped = groupByProject) {
+ const request = buildGroupedRequest(options, grouped);
if (onRefreshData) {
- await onRefreshData(options);
- return containers;
+ const result = await onRefreshData(request);
+ containers = result;
+ return result;
}
- const result = await containerService.getContainers(options);
+ const result = await containerService.getContainers(request);
containers = result;
return result;
}
@@ -112,13 +128,13 @@
handleBulkRestart,
handleBulkRemove
} = createContainerActions({
- getRequestOptions: () => requestOptions,
setContainers: (next) => {
containers = next;
},
setSelectedIds: (next) => {
selectedIds = next;
},
+ refreshContainers: () => refreshContainers(requestOptions),
actionStatus,
isBulkLoading
});
@@ -135,6 +151,12 @@
let collapsedGroupsState = $state<PersistedState<Record<string, boolean>> | null>(null);
let collapsedGroups = $derived(collapsedGroupsState?.current ?? {});
let columnVisibility = $state<Record<string, boolean>>({});
+ const backendGroupedRows = $derived(
+ containers.groups?.map((group) => ({
+ groupName: group.groupName,
+ items: group.items
+ })) ?? null
+ );
const shouldConnect = $derived.by(() => {
const cpuVisible = columnVisibility.cpuUsage !== false;
@@ -151,11 +173,6 @@
const currentEnvId = $derived(environmentStore.selected?.id || '0');
- $effect(() => {
- statsManager.envId = currentEnvId;
- statsManager.targetIds = shouldConnect;
- });
-
onMount(() => {
collapsedGroupsState = new PersistedState<Record<string, boolean>>('container-groups-collapsed', {});
@@ -165,17 +182,34 @@
setShowInternal(persistedInternal);
}
+ const persistedGroupByProject = (customSettings.groupByProject as boolean) ?? false;
+ if (persistedGroupByProject !== groupByProject) {
+ groupByProject = persistedGroupByProject;
+ }
+
+ if (persistedGroupByProject) {
+ const nextOptions: SearchPaginationSortRequest = {
+ ...requestOptions,
+ pagination: { page: 1, limit: getCurrentLimit() }
+ };
+ requestOptions = nextOptions;
+ void refreshContainers(nextOptions, true);
+ }
+
return () => {
statsManager.destroy();
};
});
- let groupByProject = $derived.by(() => {
- return (customSettings.groupByProject as boolean) ?? false;
- });
-
function setGroupByProject(value: boolean) {
customSettings = { ...customSettings, groupByProject: value };
+ groupByProject = value;
+ const nextOptions: SearchPaginationSortRequest = {
+ ...requestOptions,
+ pagination: { page: 1, limit: getCurrentLimit() }
+ };
+ requestOptions = nextOptions;
+ void refreshContainers(nextOptions, value);
}
function toggleGroup(groupName: string) {
@@ -279,8 +313,14 @@
function getGroupIcon(_groupName: string) {
return ProjectsIcon;
}
+
+ function getGroupName(item: ContainerSummaryDto): string {
+ return getProjectName(item);
+ }
</script>
+<ContainerStatsSync {statsManager} envId={currentEnvId} targetIds={shouldConnect} />
+
{#snippet IPAddressCell({ item }: { item: ContainerSummaryDto })}
{@const ip = getContainerIpAddress(item)}
<span class="font-mono text-sm">{ip ?? m.common_na()}</span>
@@ -633,7 +673,8 @@
rowActions={RowActions}
mobileCard={ContainerMobileCardSnippet}
customViewOptions={CustomViewOptions}
- groupBy={groupByProject ? groupContainerByProject : undefined}
+ groupedRows={groupByProject ? backendGroupedRows : null}
+ groupBy={groupByProject && !backendGroupedRows ? getGroupName : undefined}
groupIcon={groupByProject ? getGroupIcon : undefined}
groupCollapsedState={collapsedGroups}
onGroupToggle={toggleGroup}
diff --git a/tests/spec/container-grouped-pagination.spec.ts b/tests/spec/container-grouped-pagination.spec.ts
new file mode 100644
index 000000000..cccdb2570
--- /dev/null
+++ b/tests/spec/container-grouped-pagination.spec.ts
@@ -0,0 +1,171 @@
+import { expect, test } from "@playwright/test";
+
+type MockContainer = {
+ id: string;
+ names: string[];
+ image: string;
+ imageId: string;
+ command: string;
+ created: number;
+ labels: Record<string, string>;
+ state: string;
+ status: string;
+ ports: [];
+ hostConfig: { networkMode: string };
+ networkSettings: { networks: Record<string, unknown> };
+ mounts: [];
+};
+
+function createContainer(id: string, name: string, project: string, created: number): MockContainer {
+ return {
+ id,
+ names: [`/${name}`],
+ image: `${project || "misc"}:latest`,
+ imageId: `image-${id}`,
+ command: "",
+ created,
+ labels: project ? { "com.docker.compose.project": project } : {},
+ state: "running",
+ status: "Up 5 minutes",
+ ports: [],
+ hostConfig: { networkMode: "default" },
+ networkSettings: { networks: {} },
+ mounts: [],
+ };
+}
+
+function buildContainersResponse(containers: MockContainer[], start: number, limit: number) {
+ const safeLimit = limit > 0 ? limit : containers.length;
+ const pageItems = limit === -1 ? containers : containers.slice(start, start + safeLimit);
+ const currentPage = limit > 0 ? Math.floor(start / safeLimit) + 1 : 1;
+ const totalPages = limit > 0 ? Math.max(1, Math.ceil(containers.length / safeLimit)) : 1;
+ const itemsPerPage = limit === -1 ? containers.length : safeLimit;
+
+ return {
+ success: true,
+ data: pageItems,
+ counts: {
+ runningContainers: containers.length,
+ stoppedContainers: 0,
+ totalContainers: containers.length,
+ },
+ pagination: {
+ totalPages,
+ totalItems: containers.length,
+ currentPage,
+ itemsPerPage,
+ grandTotalItems: containers.length,
+ },
+ };
+}
+
+test("grouped containers do not split the same project across pages", async ({ page, context }) => {
+ await page.addInitScript(() => {
+ localStorage.removeItem("arcane-container-table");
+ localStorage.setItem("container-groups-collapsed", JSON.stringify({ immich: false }));
+ localStorage.removeItem("collapsible-cards-expanded");
+ });
+
+ let groupedMockPayload:
+ | {
+ groups: Array<{ groupName: string; items: MockContainer[] }>;
+ }
+ | undefined;
+
+ const otherContainers = Array.from({ length: 18 }, (_, index) => {
+ const project = `other-${index + 1}`;
+ return createContainer(`other-${index + 1}`, `${project}-service`, project, 1_000 - index);
+ });
+
+ const immichContainers = [
+ createContainer("immich-1", "immich-server", "immich", 900),
+ createContainer("immich-2", "immich-machine-learning", "immich", 899),
+ createContainer("immich-3", "immich-redis", "immich", 898),
+ createContainer("immich-4", "immich-postgres", "immich", 897),
+ ];
+
+ const allContainers = [...otherContainers, ...immichContainers];
+
+ await context.route("**/containers**", async (route) => {
+ if (route.request().method() !== "GET") {
+ await route.continue();
+ return;
+ }
+
+ const url = new URL(route.request().url());
+ if (!/^\/api\/environments\/[^/]+\/containers$/.test(url.pathname)) {
+ await route.continue();
+ return;
+ }
+
+ const start = Number(url.searchParams.get("start") ?? "0");
+ const limit = Number(url.searchParams.get("limit") ?? "20");
+ const groupBy = url.searchParams.get("groupBy");
+
+ if (groupBy === "project") {
+ groupedMockPayload = {
+ groups: [
+ {
+ groupName: "immich",
+ items: immichContainers,
+ },
+ ...otherContainers.slice(0, 18).map((container, index) => ({
+ groupName: `other-${index + 1}`,
+ items: [container],
+ })),
+ ],
+ };
+
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ success: true,
+ data: [...immichContainers, ...otherContainers.slice(0, 18)],
+ groups: groupedMockPayload.groups,
+ counts: {
+ runningContainers: allContainers.length,
+ stoppedContainers: 0,
+ totalContainers: allContainers.length,
+ },
+ pagination: {
+ totalPages: 1,
+ totalItems: allContainers.length,
+ currentPage: 1,
+ itemsPerPage: 20,
+ grandTotalItems: allContainers.length,
+ },
+ }),
+ });
+ return;
+ }
+
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(buildContainersResponse(allContainers, start, limit)),
+ });
+ });
+
+ await page.goto("/containers");
+ await page.waitForLoadState("networkidle");
+
+ await page.setViewportSize({ width: 1440, height: 900 });
+
+ await page.getByRole("button", { name: "View" }).click();
+ await page.getByRole("menuitemcheckbox", { name: "Group by Project" }).click();
+ await page.keyboard.press("Escape");
+
+ await expect.poll(() => groupedMockPayload?.groups.find((group) => group.groupName === "immich")?.items.length ?? 0).toBe(4);
+
+ const immichGroupRow = page.locator("table tbody tr").filter({ has: page.getByText("immich", { exact: true }) });
+
+ await expect(immichGroupRow).toHaveCount(1);
+ await expect(immichGroupRow).toContainText("immich");
+ await expect(immichGroupRow).toContainText("(4)");
+
+ await expect(page.getByRole("link", { name: "immich-server", exact: true })).toBeVisible();
+ await expect(page.getByRole("link", { name: "immich-machine-learning", exact: true })).toBeVisible();
+ await expect(page.getByRole("link", { name: "immich-redis", exact: true })).toBeVisible();
+ await expect(page.getByRole("link", { name: "immich-postgres", exact: true })).toBeVisible();
+});
diff --git a/types/container/container.go b/types/container/container.go
index dd1c8fa4a..920009ac8 100644
--- a/types/container/container.go
+++ b/types/container/container.go
@@ -634,6 +634,19 @@ type Summary struct {
UpdateInfo *imagetypes.UpdateInfo `json:"updateInfo,omitempty"`
}
+// SummaryGroup represents a group of container summaries.
+type SummaryGroup struct {
+ // GroupName is the group label, such as a compose project name.
+ //
+ // Required: true
+ GroupName string `json:"groupName"`
+
+ // Items contains the container summaries in the group.
+ //
+ // Required: true
+ Items []Summary `json:"items"`
+}
+
// Details represents detailed container information.
type Details struct {
// ID is the unique identifier of the container.