Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat(mobile): record source and size of offline copies (#3173)

Mohamed Bassem108255ad92be
diff --git a/apps/mobile/lib/offlineLibrary.test.ts b/apps/mobile/lib/offlineLibrary.test.ts
new file mode 100644
index 00000000..628bb717
--- /dev/null
+++ b/apps/mobile/lib/offlineLibrary.test.ts
@@ -0,0 +1,96 @@
+import superjson from "superjson";
+import { describe, expect, it, vi } from "vitest";
+
+import type { createFakeMMKV } from "./testing/fakeMmkv";
+import {
+ getOfflineLibraryItems,
+ OFFLINE_LIBRARY_SCHEMA_VERSION,
+ reconcileOfflineLibrary,
+ saveOfflineArticle,
+} from "./offlineLibrary";
+import { linkBookmark } from "./testing/bookmarks";
+
+const { instances } = vi.hoisted(() => ({
+ instances: new Map<string, ReturnType<typeof createFakeMMKV>>(),
+}));
+
+vi.mock("react-native-mmkv", async () => {
+ const { createFakeMMKV } = await import("./testing/fakeMmkv");
+ return {
+ createMMKV: ({ id }: { id: string }) => {
+ const storage = createFakeMMKV();
+ instances.set(id, storage);
+ return storage;
+ },
+ useMMKVString: vi.fn(),
+ };
+});
+
+function save(scope: string, id: string) {
+ const bookmark = linkBookmark(id);
+ saveOfflineArticle(scope, {
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: id,
+ savedAt: 1,
+ bookmark,
+ });
+}
+
+describe("offline library", () => {
+ it("treats copies saved before automatic downloads as manual", () => {
+ const scope = "legacy";
+ save(scope, "a");
+ const storage = instances.get("karakeep-offline-library");
+ const manifestKey = storage
+ ?.getAllKeys()
+ .find((key) => key.startsWith("manifest:") && key.endsWith(scope));
+ if (!storage || !manifestKey) {
+ throw new Error("manifest not written");
+ }
+ // What an older version of the app wrote.
+ storage.set(
+ manifestKey,
+ superjson.stringify([
+ { bookmarkId: "a", savedAt: 1, displayTitle: "Bookmark a" },
+ ]),
+ );
+
+ expect(getOfflineLibraryItems(scope)).toEqual([
+ expect.objectContaining({
+ bookmarkId: "a",
+ source: "manual",
+ }),
+ ]);
+ expect(getOfflineLibraryItems(scope)[0].byteSize).toBeUndefined();
+
+ reconcileOfflineLibrary(scope);
+ expect(getOfflineLibraryItems(scope)[0].byteSize).toBeGreaterThan(0);
+ });
+
+ it("keeps accounts apart", () => {
+ save("first", "a");
+ save("second", "b");
+ reconcileOfflineLibrary("first");
+
+ expect(
+ getOfflineLibraryItems("first").map((item) => item.bookmarkId),
+ ).toEqual(["a"]);
+ expect(
+ getOfflineLibraryItems("second").map((item) => item.bookmarkId),
+ ).toEqual(["b"]);
+ });
+
+ it("records where a copy came from", () => {
+ saveOfflineArticle(
+ "source",
+ {
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: "a",
+ savedAt: 1,
+ bookmark: linkBookmark("a"),
+ },
+ "auto",
+ );
+ expect(getOfflineLibraryItems("source")[0].source).toBe("auto");
+ });
+});
diff --git a/apps/mobile/lib/offlineLibrary.ts b/apps/mobile/lib/offlineLibrary.ts
index 59e2e95c..7c95b3a9 100644
--- a/apps/mobile/lib/offlineLibrary.ts
+++ b/apps/mobile/lib/offlineLibrary.ts
@@ -47,12 +47,50 @@ const zOfflineLibraryItem = z.object({
savedAt: z.number(),
displayTitle: z.string(),
url: z.string().optional(),
+ // Copies saved before automatic downloads existed were all explicit saves.
+ source: z.enum(["manual", "auto"]).default("manual"),
+ // Approximate on-disk footprint. Missing on older copies until reconciled.
+ byteSize: z.number().optional(),
});
const zOfflineLibraryManifest = z.array(zOfflineLibraryItem);
export type OfflineArticle = z.infer<typeof zOfflineArticle>;
export type OfflineLibraryItem = z.infer<typeof zOfflineLibraryItem>;
+export type OfflineArticleSource = OfflineLibraryItem["source"];
+
+// Covers the manifest entry and MMKV's per-key bookkeeping.
+const PER_ARTICLE_OVERHEAD_BYTES = 512;
+
+// Counting instead of encoding: bodies with inlined images run to megabytes,
+// and this only needs the length.
+function utf8ByteLength(value: string) {
+ let bytes = 0;
+ for (let index = 0; index < value.length; index++) {
+ const code = value.charCodeAt(index);
+ if (code < 0x80) {
+ bytes += 1;
+ } else if (code < 0x800) {
+ bytes += 2;
+ } else if (code >= 0xd800 && code <= 0xdbff) {
+ bytes += 4;
+ index++;
+ } else {
+ bytes += 3;
+ }
+ }
+ return bytes;
+}
+
+// What saving this bookmark would cost, before it is saved. Matches what
+// saveOfflineArticle records closely enough to plan evictions with.
+export function estimateOfflineArticleSize(
+ bookmark: OfflineArticle["bookmark"],
+) {
+ return (
+ utf8ByteLength(superjson.stringify(bookmark)) + PER_ARTICLE_OVERHEAD_BYTES
+ );
+}
function encodeKeyPart(value: string) {
return encodeURIComponent(value);
@@ -241,7 +279,11 @@ function restoreKey(key: string, raw: string | undefined) {
}
}
-export function saveOfflineArticle(scope: string, article: OfflineArticle) {
+export function saveOfflineArticle(
+ scope: string,
+ article: OfflineArticle,
+ source: OfflineArticleSource = "manual",
+) {
const parsed = zOfflineArticle.safeParse(article);
const split = parsed.success
? splitArticleContent(parsed.data.bookmark)
@@ -263,23 +305,25 @@ export function saveOfflineArticle(scope: string, article: OfflineArticle) {
const currentContentRaw = offlineLibraryStorage.getString(bodyKey);
try {
+ let byteSize = PER_ARTICLE_OVERHEAD_BYTES;
if (split.htmlContent !== undefined) {
- offlineLibraryStorage.set(
- bodyKey,
- superjson.stringify({
- schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
- bookmarkId: parsed.data.bookmarkId,
- htmlContent: split.htmlContent,
- }),
- );
+ const rawContent = superjson.stringify({
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: parsed.data.bookmarkId,
+ htmlContent: split.htmlContent,
+ });
+ offlineLibraryStorage.set(bodyKey, rawContent);
+ byteSize += utf8ByteLength(rawContent);
} else {
offlineLibraryStorage.remove(bodyKey);
}
- offlineLibraryStorage.set(
- key,
- superjson.stringify({ ...parsed.data, bookmark: split.bookmark }),
- );
+ const rawArticle = superjson.stringify({
+ ...parsed.data,
+ bookmark: split.bookmark,
+ });
+ offlineLibraryStorage.set(key, rawArticle);
+ byteSize += utf8ByteLength(rawArticle);
const stored = readOfflineArticle(scope, article.bookmarkId);
const storedContent = readOfflineArticleContent(scope, article.bookmarkId);
@@ -294,6 +338,8 @@ export function saveOfflineArticle(scope: string, article: OfflineArticle) {
savedAt: parsed.data.savedAt,
displayTitle: getDisplayTitle(parsed.data.bookmark),
...(sourceUrl ? { url: sourceUrl } : {}),
+ source,
+ byteSize,
};
writeManifest(scope, [
item,
@@ -307,6 +353,21 @@ export function saveOfflineArticle(scope: string, article: OfflineArticle) {
}
}
+const TRIM_DELAY = 2_000;
+let trimTimeout: ReturnType<typeof setTimeout> | undefined;
+
+// MMKV never shrinks its file on its own. Removals tend to come in bursts
+// (evictions, "remove all"), so trim once they settle.
+function scheduleTrim() {
+ if (trimTimeout !== undefined) {
+ clearTimeout(trimTimeout);
+ }
+ trimTimeout = setTimeout(() => {
+ trimTimeout = undefined;
+ offlineLibraryStorage.trim();
+ }, TRIM_DELAY);
+}
+
export function removeOfflineArticle(scope: string, bookmarkId: string) {
const current = parseManifest(
offlineLibraryStorage.getString(manifestKey(scope)),
@@ -317,6 +378,7 @@ export function removeOfflineArticle(scope: string, bookmarkId: string) {
);
offlineLibraryStorage.remove(articleKey(scope, bookmarkId));
offlineLibraryStorage.remove(contentKey(scope, bookmarkId));
+ scheduleTrim();
}
export function removeAllOfflineArticles(scope: string) {
@@ -329,10 +391,12 @@ export function removeAllOfflineArticles(scope: string) {
offlineLibraryStorage.remove(key);
}
}
+ scheduleTrim();
}
export function clearOfflineLibrary() {
offlineLibraryStorage.clearAll();
+ scheduleTrim();
}
function subscribeToOfflineLibrary(onStoreChange: () => void) {
@@ -354,6 +418,20 @@ export function useOfflineLibrarySize() {
);
}
+export function getOfflineLibraryItems(scope: string) {
+ return parseManifestMemoized(
+ offlineLibraryStorage.getString(manifestKey(scope)),
+ );
+}
+
+function measureStoredArticle(key: string, bodyKey: string) {
+ return (
+ PER_ARTICLE_OVERHEAD_BYTES +
+ utf8ByteLength(offlineLibraryStorage.getString(key) ?? "") +
+ utf8ByteLength(offlineLibraryStorage.getString(bodyKey) ?? "")
+ );
+}
+
export function reconcileOfflineLibrary(scope: string) {
const current = parseManifest(
offlineLibraryStorage.getString(manifestKey(scope)),
@@ -369,7 +447,11 @@ export function reconcileOfflineLibrary(scope: string) {
// Presence is checked by key rather than by parsing: this runs over the
// whole library, and the bodies are the thing worth not reading.
if (article && isRenderableArticle(article, storedKeys.has(bodyKey))) {
- validItems.push(item);
+ validItems.push(
+ item.byteSize === undefined
+ ? { ...item, byteSize: measureStoredArticle(key, bodyKey) }
+ : item,
+ );
validKeys.add(key);
if (storedKeys.has(bodyKey)) {
validKeys.add(bodyKey);
@@ -380,6 +462,7 @@ export function reconcileOfflineLibrary(scope: string) {
}
}
+ let removedAny = validItems.length !== current.length;
for (const key of storedKeys) {
if (
(key.startsWith(articlePrefix(scope)) ||
@@ -387,10 +470,14 @@ export function reconcileOfflineLibrary(scope: string) {
!validKeys.has(key)
) {
offlineLibraryStorage.remove(key);
+ removedAny = true;
}
}
writeManifest(scope, validItems);
+ if (removedAny) {
+ scheduleTrim();
+ }
}
// Metadata only — the article body is not read. Use useOfflineArticleContent
diff --git a/apps/mobile/lib/testing/bookmarks.ts b/apps/mobile/lib/testing/bookmarks.ts
new file mode 100644
index 00000000..bb048aca
--- /dev/null
+++ b/apps/mobile/lib/testing/bookmarks.ts
@@ -0,0 +1,63 @@
+import type { ZBookmark } from "@karakeep/shared/types/bookmarks";
+import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
+
+function bareBookmark(id: string, createdAt: number) {
+ return {
+ id,
+ createdAt: new Date(createdAt),
+ modifiedAt: new Date(createdAt),
+ title: `Bookmark ${id}`,
+ archived: false,
+ favourited: false,
+ taggingStatus: null,
+ summarizationStatus: null,
+ embeddingStatus: null,
+ userId: "user",
+ tags: [],
+ assets: [],
+ };
+}
+
+export function linkBookmark(
+ id: string,
+ {
+ createdAt = 0,
+ htmlContent = `<p>${id}</p>`,
+ crawlStatus = "success",
+ url = `https://example.com/${id}`,
+ }: {
+ createdAt?: number;
+ htmlContent?: string | null;
+ crawlStatus?: "success" | "failure" | "pending";
+ url?: string;
+ } = {},
+): ZBookmark {
+ return {
+ ...bareBookmark(id, createdAt),
+ content: {
+ type: BookmarkTypes.LINK,
+ url,
+ htmlContent,
+ crawlStatus,
+ crawledAt: new Date(createdAt),
+ },
+ };
+}
+
+export function textBookmark(id: string, createdAt = 0): ZBookmark {
+ return {
+ ...bareBookmark(id, createdAt),
+ content: { type: BookmarkTypes.TEXT, text: `Text ${id}` },
+ };
+}
+
+export function assetBookmark(id: string, createdAt = 0): ZBookmark {
+ return {
+ ...bareBookmark(id, createdAt),
+ content: {
+ type: BookmarkTypes.ASSET,
+ assetType: "pdf",
+ assetId: `asset-${id}`,
+ },
+ };
+}
diff --git a/apps/mobile/lib/testing/fakeMmkv.ts b/apps/mobile/lib/testing/fakeMmkv.ts
new file mode 100644
index 00000000..1ac82b98
--- /dev/null
+++ b/apps/mobile/lib/testing/fakeMmkv.ts
@@ -0,0 +1,36 @@
+// In-memory stand-in for an MMKV instance, for tests.
+export function createFakeMMKV() {
+ const values = new Map<string, string>();
+ const listeners = new Set<(key: string) => void>();
+ const notify = (key: string) => {
+ for (const listener of listeners) {
+ listener(key);
+ }
+ };
+
+ return {
+ getString: (key: string) => values.get(key),
+ set: (key: string, value: string) => {
+ values.set(key, value);
+ notify(key);
+ },
+ remove: (key: string) => {
+ const removed = values.delete(key);
+ if (removed) {
+ notify(key);
+ }
+ return removed;
+ },
+ getAllKeys: () => [...values.keys()],
+ clearAll: () => {
+ const keys = [...values.keys()];
+ values.clear();
+ keys.forEach(notify);
+ },
+ trim: () => undefined,
+ addOnValueChangedListener: (listener: (key: string) => void) => {
+ listeners.add(listener);
+ return { remove: () => listeners.delete(listener) };
+ },
+ };
+}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 466752d1..1f90152b 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -17,7 +17,8 @@
"format:fix": "oxfmt --ignore-path=../../.gitignore --ignore-path=./.gitignore .",
"lint": "oxlint --ignore-path=../../.gitignore .",
"lint:fix": "oxlint --ignore-path=../../.gitignore . --fix",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run"
},
"dependencies": {
"@emoji-mart/data": "^1.1.2",
@@ -97,7 +98,8 @@
"@types/react": "19.2.15",
"ajv": "latest",
"tailwindcss": "^3.4.1",
- "typescript": "^5.9"
+ "typescript": "^5.9",
+ "vitest": "^4.1.11"
},
"expo": {
"install": {
diff --git a/apps/mobile/vitest.config.mts b/apps/mobile/vitest.config.mts
new file mode 100644
index 00000000..54842321
--- /dev/null
+++ b/apps/mobile/vitest.config.mts
@@ -0,0 +1,11 @@
+/// <reference types="vitest" />
+
+import { defineConfig } from "vitest/config";
+
+// Only the platform-independent logic is unit tested; native modules are
+// mocked per test file.
+export default defineConfig({
+ test: {
+ include: ["lib/**/*.test.ts"],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index acbc7a23..fc627843 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -565,6 +565,9 @@ importers:
typescript:
specifier: ^5.9
version: 5.9.3
+ vitest:
+ specifier: ^4.1.11
apps/web:
dependencies: