Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/disk-usage-improvement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Disk usage: diagnóstico e correções

Data: 2026-10-22

## Problema

Cada serviço tem uma partição persistente (`Partitions/service-<id>` ou
`Partitions/sandbox-<id>`) com Cache HTTP, Code Cache, GPUCache, Service Worker e
IndexedDB. Nada limita esse crescimento e o botão "Clear cache" só limpava o cache HTTP.

## Medições

Perfil novo, 4 serviços (WhatsApp, Telegram, Slack, Gmail), depois de fechar:

- total 42 MB · WhatsApp 28 MB (Service Worker 16 MB + Cache HTTP 9,4 MB)
- `session.clearCache()` sozinho (comportamento antigo do botão): 42 → 23 MB
- `clearStorageData({cachestorage, serviceworkers, shadercache})`: 42 → 26 MB
- os dois juntos: **42 → 6,7 MB (−84%)**, preservando IndexedDB e cookies

Teste de integração com o handler compilado (build real, partição de serviço):

- antes 27,6 MB → depois 2,4 MB · **25,1 MB recuperados (91%)**

## Correções aplicadas

1. `src/helpers/partition-helpers.ts` (novo): resolução pura da partição do serviço
(sandbox vs. própria), validação de partição persistente e detecção de partições
órfãs. Coberto por 19 testes.
2. `clear-cache` agora recebe a partição resolvida pelo renderer, valida e limpa
**cache HTTP + CacheStorage + Service Workers + shader cache**. Cookies,
localStorage e IndexedDB não são tocados (sem logout, sem perder histórico).
3. `clear-storage-data` também aceita a partição (usado na exclusão de serviço).
4. Exclusão de serviço remove a partição do serviço e, quando ele era o último do
grupo, a partição do sandbox.
5. Varredura de partições órfãs na inicialização, disparada quando a lista de
serviços carrega (guardada contra lista vazia) — cobre o caso de serviço excluído
em outra máquina com sync.
6. "Clear all cache" passa a usar a mesma detecção de órfãs (inclui sandbox).

## Verificação

- `pnpm test`: 18 suites, 161 testes (159 ok, 2 skipped) — 19 novos
- `pnpm typecheck`: ok
- `pnpm lint` (`--max-warnings 0`): ok
- AppImage reconstruído e iniciado sob Xvfb sem crash

## Risco e comportamento

- "Clear cache" passa a descartar também o CacheStorage/Service Worker: o serviço
recarrega assets na próxima abertura (esperado), sem novo login.
- A limpeza de IndexedDB saiu do "clear cache" e ficou restrita à exclusão do
serviço. Antes, limpar cache podia deslogar WhatsApp/Slack.
- A varredura de órfãs nunca roda com lista de serviços vazia (falha de API não
apaga partições válidas).
1 change: 1 addition & 0 deletions src/@types/stores.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export interface AppStore extends TypedStore {
get(key: string): any;
getAppCacheSizeRequest: () => void;
healthCheckRequest: () => void;
sandboxServices: { id: string; name: string; services: string[] }[];
isClearingAllCache: () => void;
isAppMuted: boolean;
isFocused: () => void;
Expand Down
4 changes: 2 additions & 2 deletions src/api/ServicesApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default class ServicesApi {
return this.server.reorderService(data);
}

clearCache(serviceId: string) {
return this.local.clearCache(serviceId);
clearCache(serviceId: string, partition?: string) {
return this.local.clearCache(serviceId, partition);
}
}
17 changes: 2 additions & 15 deletions src/api/server/LocalApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,7 @@ export default class LocalApi {
});
}

async clearCache(serviceId: string | null = null) {
const targetsToClear = {
storages: [
'filesystem',
'indexdb',
'shadercache',
'serviceworkers',
'cachestorage',
],
};
await ipcRenderer.invoke('clear-storage-data', {
serviceId,
targetsToClear,
});
return ipcRenderer.invoke('clear-cache', { serviceId });
async clearCache(serviceId: string | null = null, partition?: string) {
return ipcRenderer.invoke('clear-cache', { serviceId, partition });
}
}
12 changes: 9 additions & 3 deletions src/api/server/ServerApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ import {
loadRecipeConfig,
} from '../../helpers/recipe-helpers';

import { removeServicePartitionDirectory } from '../../helpers/service-helpers';
import {
getPartitionForService,
removeServiceAndSandboxPartitions,
} from '../../helpers/service-helpers';

const debug = require('../../preload-safe-debug')('Ferdium:ServerApi');

Expand Down Expand Up @@ -328,12 +331,15 @@ export default class ServerApi {
// a corrupt IndexedDB database (for example WhatsApp's login database)
// while filesystem cleanup is deferred until the next app start.
try {
await ipcRenderer.invoke('clear-storage-data', { serviceId: id });
await ipcRenderer.invoke('clear-storage-data', {
serviceId: id,
partition: getPartitionForService(id),
});
} catch (error) {
debug('Unable to clear service storage before partition removal', error);
}

removeServicePartitionDirectory(id, true);
removeServiceAndSandboxPartitions(id);

debug('ServerApi::deleteService resolves', data);
return data;
Expand Down
60 changes: 51 additions & 9 deletions src/electron/ipc-api/sessionStorage.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,52 @@
import { type Session, ipcMain, session } from 'electron';
import {
type ClearStorageDataOptions,
type Session,
ipcMain,
session,
} from 'electron';
import { TODOS_PARTITION_ID } from '../../config';
import {
REGENERABLE_CACHE_STORAGES,
isValidPersistPartition,
} from '../../helpers/partition-helpers';

const debug = require('../../preload-safe-debug')(
'Ferdium:ipcApi:sessionStorage',
);

const deduceSession = (serviceId: string | undefined | null): Session => {
if (!serviceId) return session.defaultSession;
type SessionTarget = {
serviceId?: string | null;
partition?: string | null;
};

const resolveSession = ({ serviceId, partition }: SessionTarget): Session => {
if (serviceId === TODOS_PARTITION_ID)
return session.fromPartition(TODOS_PARTITION_ID);

// The renderer resolves whether the service lives in a sandbox partition;
// the value is validated here so it can never address anything outside the
// app's own persistent partitions.
if (isValidPersistPartition(partition))
return session.fromPartition(partition);

if (!serviceId) return session.defaultSession;

return session.fromPartition(`persist:service-${serviceId}`);
};

export default async () => {
ipcMain.handle(
'clear-storage-data',
async (_event, { serviceId, targetsToClear }) => {
async (
_event,
{
serviceId,
partition,
targetsToClear,
}: SessionTarget & { targetsToClear?: ClearStorageDataOptions },
) => {
try {
const serviceSession = deduceSession(serviceId);
const serviceSession = resolveSession({ serviceId, partition });
serviceSession.flushStorageData();
if (targetsToClear) {
debug('Clearing targets:', targetsToClear);
Expand All @@ -33,8 +60,23 @@ export default async () => {
}
},
);
ipcMain.handle('clear-cache', (_event, { serviceId }) => {
const serviceSession = deduceSession(serviceId);
return serviceSession.clearCache();
});

ipcMain.handle(
'clear-cache',
async (_event, { serviceId, partition }: SessionTarget) => {
const serviceSession = resolveSession({ serviceId, partition });

// The HTTP cache and the caches kept outside it (service worker,
// CacheStorage, shader cache) are cleared by different APIs. Only the
// second one reclaims the bulk of a service's disk usage, so both run.
// Cookies, localStorage and IndexedDB are intentionally untouched.
await serviceSession.clearCache();
await serviceSession.clearStorageData({
storages: [
...REGENERABLE_CACHE_STORAGES,
] as ClearStorageDataOptions['storages'],
});
serviceSession.flushStorageData();
},
);
};
80 changes: 80 additions & 0 deletions src/helpers/partition-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
export interface SandboxLike {
id: string;
services: string[];
}

export const SERVICE_PARTITION_PREFIX = 'persist:service-';
export const SANDBOX_PARTITION_PREFIX = 'persist:sandbox-';

// Storages that only hold data rebuilt on demand. Clearing them reclaims disk
// without dropping cookies, localStorage or IndexedDB (i.e. without logging the
// user out of the service or discarding its message database).
export const REGENERABLE_CACHE_STORAGES = [
'cachestorage',
'serviceworkers',
'shadercache',
] as const;

const PERSIST_PARTITION_PATTERN = /^persist:[\w.-]+$/;

export const isValidPersistPartition = (
partition: unknown,
): partition is string =>
typeof partition === 'string' &&
PERSIST_PARTITION_PATTERN.test(partition) &&
!partition.includes('..');

export const findSandboxForService = (
sandboxes: SandboxLike[],
serviceId: string,
): SandboxLike | undefined =>
sandboxes.find(
sandbox =>
Array.isArray(sandbox.services) && sandbox.services.includes(serviceId),
);

/**
* A service lives in its sandbox partition when it belongs to a sandbox group,
* otherwise in its own partition. Must stay in sync with ServiceWebview.tsx.
*/
export const getServicePartition = ({
sandboxes,
serviceId,
fallbackPartition,
useSandboxes = true,
}: {
sandboxes: SandboxLike[];
serviceId: string;
fallbackPartition?: string;
useSandboxes?: boolean;
}): string => {
if (useSandboxes) {
const sandbox = findSandboxForService(sandboxes, serviceId);
if (sandbox) {
return `${SANDBOX_PARTITION_PREFIX}${sandbox.id}`;
}
}

return fallbackPartition || `${SERVICE_PARTITION_PREFIX}${serviceId}`;
};

/**
* Partition directories under `Partitions/` that no longer belong to any
* service or sandbox. They are left behind when a service is deleted while its
* session is locked, or when a sandbox is dropped.
*/
export const findOrphanPartitionDirectories = (
directories: string[],
{ serviceIds, sandboxIds }: { serviceIds: string[]; sandboxIds: string[] },
): string[] => {
const known = new Set<string>([
...serviceIds.map(id => `service-${id}`),
...sandboxIds.map(id => `sandbox-${id}`),
]);

return directories.filter(
directory =>
(directory.startsWith('service-') || directory.startsWith('sandbox-')) &&
!known.has(directory),
);
};
48 changes: 48 additions & 0 deletions src/helpers/service-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import {
} from 'fs-extra';
import { userDataPath } from '../environment-remote';

import {
findSandboxForService,
getServicePartition,
type SandboxLike,
} from './partition-helpers';

const RETRYABLE_PARTITION_REMOVAL_ERROR_CODES = new Set([
'EACCES',
'EBUSY',
Expand Down Expand Up @@ -144,6 +150,48 @@ export async function getServiceIdsFromPartitions(): Promise<string[]> {
return files.filter(n => n !== '__chrome_extension');
}

/**
* Sandboxes are stored on disk (config/sandboxes.json) and are also needed by
* the renderer paths that run before the stores are populated (e.g. service
* deletion), so they are read directly instead of going through the store.
*/
export const readSandboxes = (): SandboxLike[] => {
try {
const data = readJsonSync(userDataPath('config', 'sandboxes.json'));
return Array.isArray(data) ? data : [];
} catch {
return [];
}
};

export const getPartitionForService = (
serviceId: string,
fallbackPartition?: string,
useSandboxes = true,
): string =>
getServicePartition({
sandboxes: readSandboxes(),
serviceId,
fallbackPartition,
useSandboxes,
});

/**
* Removes every partition owned by a service. A sandbox partition is shared by
* all services in the group, so it is only removed when this was the last one.
*/
export const removeServiceAndSandboxPartitions = (serviceId: string): void => {
removeServicePartitionDirectory(serviceId, true);

const sandbox = findSandboxForService(readSandboxes(), serviceId);
const remainingServices =
sandbox?.services.filter(id => id !== serviceId) ?? [];

if (sandbox && remainingServices.length === 0) {
removeServicePartitionDirectory(`sandbox-${sandbox.id}`);
}
};

// Persistent Electron sessions can keep files open for the lifetime of the app.
// ServerApi imports this helper before service webviews are created, so this is
// the earliest safe point in the renderer startup to remove partitions that
Expand Down
Loading