Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(web): free sent and removed local images

jeffreyb4cea4c56727
diff --git a/apps/web/src/features/rooms/chat/use-composer-attachments.ts b/apps/web/src/features/rooms/chat/use-composer-attachments.ts
index 4a80e491..6083ef8d 100644
--- a/apps/web/src/features/rooms/chat/use-composer-attachments.ts
+++ b/apps/web/src/features/rooms/chat/use-composer-attachments.ts
@@ -13,7 +13,10 @@ import {
composerAttachmentStore,
} from "./composer-attachment-drafts";
import type { MessageComposerProps } from "./message-composer";
-import { decodeLocalImage } from "@/features/rooms/files/local-message-images";
+import {
+ decodeLocalImage,
+ releaseLocalImage,
+} from "@/features/rooms/files/local-message-images";
const maximumAttachmentCount = 5;
@@ -203,6 +206,7 @@ export function useComposerAttachments({
);
if (next.length === 0) attachmentIntentKeyRef.current = undefined;
updateSelectedFiles(() => next);
+ releaseLocalImage(attachment.file);
if (!idempotencyKey) return;
void onCancelAttachment?.({
attachmentClientId: attachment.clientId,
diff --git a/apps/web/src/features/rooms/chat/use-room-message-delivery.ts b/apps/web/src/features/rooms/chat/use-room-message-delivery.ts
index f316560b..777ade0d 100644
--- a/apps/web/src/features/rooms/chat/use-room-message-delivery.ts
+++ b/apps/web/src/features/rooms/chat/use-room-message-delivery.ts
@@ -5,7 +5,10 @@ import { createTeamHubIdempotencyKey } from "@/features/teamhub/teamhub-client";
import { classifyTeamHubCommandFailure } from "@/features/teamhub/teamhub-command-outcome";
import type { TeamHubMessagePresentation } from "@/features/teamhub/teamhub-runtime";
import type { TeamHubMessage } from "@/features/teamhub/teamhub-types";
-import { rememberLocalMessageImage } from "@/features/rooms/files/local-message-images";
+import {
+ releaseLocalImage,
+ rememberLocalMessageImage,
+} from "@/features/rooms/files/local-message-images";
import type { MessageComposition } from "./message-composer";
import {
@@ -405,6 +408,10 @@ export function useRoomMessageDelivery({
return;
}
setOutgoing((items) => items.filter((item) => item.clientId !== clientId));
+ // Nothing shows a canceled Message's images again.
+ for (const { file } of current.attachmentInputs ?? []) {
+ releaseLocalImage(file);
+ }
}
const stageAttachment = useCallback(
diff --git a/apps/web/src/features/rooms/files/local-message-images.test.ts b/apps/web/src/features/rooms/files/local-message-images.test.ts
new file mode 100644
index 00000000..9cb54c48
--- /dev/null
+++ b/apps/web/src/features/rooms/files/local-message-images.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import {
+ LOCAL_MESSAGE_IMAGE_LIMIT,
+ decodeLocalImage,
+ localMessageImage,
+ releaseLocalImage,
+ rememberLocalMessageImage,
+} from "./local-message-images";
+
+describe("local message images", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ function stubDecoding() {
+ let next = 0;
+ vi.spyOn(URL, "createObjectURL").mockImplementation(
+ () => `blob:image-${next++}`,
+ );
+ const revoke = vi
+ .spyOn(URL, "revokeObjectURL")
+ .mockImplementation(() => undefined);
+ vi.stubGlobal(
+ "Image",
+ class {
+ naturalHeight = 10;
+ naturalWidth = 20;
+ onload: () => void = () => undefined;
+ onerror: () => void = () => undefined;
+ set src(_url: string) {
+ queueMicrotask(() => this.onload());
+ }
+ },
+ );
+ return revoke;
+ }
+
+ it("keeps only the most recent sent images and frees the oldest", async () => {
+ const revoke = stubDecoding();
+ const sent = Array.from(
+ { length: LOCAL_MESSAGE_IMAGE_LIMIT + 1 },
+ (_, index) => new File(["x"], `${index}.png`, { type: "image/png" }),
+ );
+ const urls = await Promise.all(
+ sent.map(async (file, index) => {
+ const image = await decodeLocalImage(file);
+ rememberLocalMessageImage(`document-${index}`, file);
+ return image.url;
+ }),
+ );
+
+ expect(localMessageImage("document-0")).toBeUndefined();
+ expect(localMessageImage("document-1")).toBe(sent[1]);
+ expect(revoke).toHaveBeenCalledExactlyOnceWith(urls[0]);
+ });
+
+ it("frees a picked image that is removed, even mid-decode", async () => {
+ const revoke = stubDecoding();
+ const file = new File(["x"], "picked.png", { type: "image/png" });
+ const decoding = decodeLocalImage(file);
+ releaseLocalImage(file);
+ const image = await decoding;
+
+ expect(revoke).toHaveBeenCalledExactlyOnceWith(image.url);
+ // A later pick decodes it again with a fresh URL.
+ expect((await decodeLocalImage(file)).url).not.toBe(image.url);
+ });
+});
diff --git a/apps/web/src/features/rooms/files/local-message-images.ts b/apps/web/src/features/rooms/files/local-message-images.ts
index f5f026d1..1584390c 100644
--- a/apps/web/src/features/rooms/files/local-message-images.ts
+++ b/apps/web/src/features/rooms/files/local-message-images.ts
@@ -1,13 +1,26 @@
import { useEffect, useState } from "react";
+/**
+ * How many just-sent images keep their local file. Each pins the original
+ * file through its object URL, so an older one goes back to the download.
+ */
+export const LOCAL_MESSAGE_IMAGE_LIMIT = 24;
+
/**
* Images this browser just sent, by their Document id, so the committed
* Message shows the local file at once instead of downloading it again.
+ * Oldest first.
*/
const files = new Map<string, File>();
export function rememberLocalMessageImage(documentId: string, file: File) {
+ files.delete(documentId);
files.set(documentId, file);
+ for (const [oldestId, oldest] of files) {
+ if (files.size <= LOCAL_MESSAGE_IMAGE_LIMIT) break;
+ files.delete(oldestId);
+ if (![...files.values()].includes(oldest)) releaseLocalImage(oldest);
+ }
}
export function localMessageImage(documentId: string): File | undefined {
@@ -20,8 +33,9 @@ interface DecodedImage {
width: number;
}
-// Decoded once per file and kept for the session, so the sending row and the
-// committed row both show it at its size from their first frame.
+// Decoded once per file and kept while the file is remembered or picked, so
+// the sending row and the committed row both show it at its size from their
+// first frame.
const decoded = new WeakMap<File, Promise<DecodedImage>>();
const ready = new WeakMap<File, DecodedImage>();
@@ -31,7 +45,7 @@ export function decodeLocalImage(file: File): Promise<DecodedImage> {
if (!pending) {
const url = URL.createObjectURL(file);
const element = new Image();
- pending = new Promise<void>((resolve) => {
+ const decoding: Promise<DecodedImage> = new Promise<void>((resolve) => {
element.onload = () => resolve();
element.onerror = () => resolve();
element.src = url;
@@ -41,14 +55,29 @@ export function decodeLocalImage(file: File): Promise<DecodedImage> {
url,
width: element.naturalWidth,
};
- ready.set(file, image);
+ // Released while decoding: nothing will show it.
+ if (decoded.get(file) !== decoding) URL.revokeObjectURL(url);
+ else ready.set(file, image);
return image;
});
+ pending = decoding;
decoded.set(file, pending);
}
return pending;
}
+/**
+ * Frees a local image's object URL once nothing will show it again: a picked
+ * file removed before sending, or a sent one past the remembered limit. An
+ * image already painted keeps its pixels.
+ */
+export function releaseLocalImage(file: File) {
+ const image = ready.get(file);
+ if (image) URL.revokeObjectURL(image.url);
+ ready.delete(file);
+ decoded.delete(file);
+}
+
/**
* The size a chat image shows at: its own size, scaled down to fit 448 by
* 360 px, so the frame hugs the picture rather than letterboxing it.
diff --git a/apps/web/src/features/rooms/files/message-file-attachment.tsx b/apps/web/src/features/rooms/files/message-file-attachment.tsx
index 510006c0..84503d13 100644
--- a/apps/web/src/features/rooms/files/message-file-attachment.tsx
+++ b/apps/web/src/features/rooms/files/message-file-attachment.tsx
@@ -203,7 +203,10 @@ function MessageImage({
}) {
const { client } = useTeamHubRuntime();
const container = useRef<HTMLDivElement>(null);
- const local = useDecodedImage(localMessageImage(documentId));
+ const localFile = localMessageImage(documentId);
+ const local = useDecodedImage(localFile);
+ // A local file past the remembered limit falls back to the download.
+ const hasLocalFile = localFile !== undefined;
const [objectUrl, setObjectUrl] = useState<string>();
const [failed, setFailed] = useState(false);
@@ -214,7 +217,7 @@ function MessageImage({
const controller = new AbortController();
setObjectUrl(undefined);
setFailed(false);
- if (localMessageImage(documentId)) return;
+ if (hasLocalFile) return;
async function load() {
if (started) return;
@@ -265,7 +268,7 @@ function MessageImage({
controller.abort();
dispose();
};
- }, [client, documentId, versionId]);
+ }, [client, documentId, hasLocalFile, versionId]);
return (
// Only as wide as the image, so an own Message can align it right.