Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

perf(attachments): lazy-load inline images with reserved dimensions (MUL-8182) (#9453)

Jiayuan Zhang4c70f3600b57
diff --git a/.github/workflows/ui-performance.yml b/.github/workflows/ui-performance.yml
index 4b11c2da8c..a0c4c2faca 100644
--- a/.github/workflows/ui-performance.yml
+++ b/.github/workflows/ui-performance.yml
@@ -19,6 +19,13 @@ on:
head:
description: "Head ref (branch, tag or SHA)"
required: true
+ scenario:
+ description: "Scenario to measure"
+ type: choice
+ options:
+ - typing-under-live-runs
+ - image-thread
+ default: typing-under-live-runs
# Read-only and without secrets: it builds and runs whatever refs it is given.
permissions:
@@ -56,7 +63,7 @@ jobs:
run: pnpm exec playwright install --with-deps chromium
- name: Compare
- run: node scripts/perf-compare.mjs --base "${{ inputs.base }}" --head "${{ inputs.head }}" --out perf-report
+ run: node scripts/perf-compare.mjs --base "${{ inputs.base }}" --head "${{ inputs.head }}" --out perf-report --scenario "${{ inputs.scenario }}"
- name: Publish to the job summary
if: always()
diff --git a/e2e/perf/README.md b/e2e/perf/README.md
index ae2d86531d..ce2aceda87 100644
--- a/e2e/perf/README.md
+++ b/e2e/perf/README.md
@@ -85,6 +85,33 @@ success, on failure and on cancellation.
The ordinary e2e suite ignores this directory; it needs a production build and
a machine that is not busy doing anything else.
+The image-heavy thread scenario (MUL-8182) types a comment while a long thread
+of large screenshots loads in the viewport. Image responses are held until the
+first keystroke, so fetching, decoding and laying out the images all land in
+the measured window, which runs with the CPU throttled 4× — a fast workstation
+absorbs this page without dropping a frame. It reports keydown-to-next-frame
+p95/max, keystrokes over 16.7 ms, long tasks, layout shift, mounted images,
+and fetched bytes. This frame measurement is not INP. It shares the report path with the live-runs scenario, so it only
+runs when selected:
+
+```bash
+PERF_SCENARIO=image-thread pnpm exec playwright test --config=playwright.perf.config.ts image-heavy-thread.spec.ts
+node scripts/perf-compare.mjs --base origin/main --head HEAD --out perf-report --scenario image-thread
+```
+
+For a review comparison, set `PERF_SCREENSHOT_PATH` to a real 2880×1800 PNG
+(kept locally, outside Git; `PERF_SCREENSHOT_ALT_PATH` optionally alternates a
+second screenshot), `PERF_IMAGE_MODE=known|missing|none`, and
+`PERF_IMAGE_POSITION=start|loaded`. All modes keep the same 37 comments.
+The `loaded` position scrolls through every image before typing at the thread
+bottom. The `missing` mode omits dimensions to represent existing attachments;
+its 16:10 placeholder can shift when the true aspect ratio becomes known.
+`none` is the no-image control. Defaults use generated pixels for CI.
+
+Use `PERF_REPEATS=3` with `perf-compare.mjs` to retain every sample in
+`base.json` / `head.json` and report the median of each numeric metric.
+Use a separate output directory per mode/position.
+
The floating-chat lifetime regression runs against the same production build:
```bash
diff --git a/e2e/perf/fixtures/image-heavy-thread.ts b/e2e/perf/fixtures/image-heavy-thread.ts
new file mode 100644
index 0000000000..ef6879aff9
--- /dev/null
+++ b/e2e/perf/fixtures/image-heavy-thread.ts
@@ -0,0 +1,166 @@
+/**
+ * Fixture for the image-heavy thread scenario (MUL-8182).
+ *
+ * One long thread with identical text across known-size, missing-size, and
+ * no-image modes. PERF_SCREENSHOT_PATH supplies a real 2880x1800 PNG locally;
+ * CI defaults to deterministic synthetic pixels. Both refs use the same bytes.
+ */
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { deflateSync } from "node:zlib";
+
+export const FIXTURE_VERSION = "2.0.0";
+export const IMAGE_MODE = process.env.PERF_IMAGE_MODE ?? "known";
+export const POSITION = process.env.PERF_IMAGE_POSITION ?? "start";
+
+export const WORKSPACE_SLUG = "perf";
+export const WORKSPACE_ID = "11111111-1111-4111-8111-111111111111";
+export const USER_ID = "22222222-2222-4222-8222-222222222222";
+export const ISSUE_ID = "33333333-3333-4333-8333-333333333333";
+export const ISSUE_IDENTIFIER = "PERF-1";
+
+export const REPLY_COMMENT_COUNT = 36;
+/** Every fourth reply carries a second screenshot. */
+export const IMAGE_COUNT = 1 + REPLY_COMMENT_COUNT + Math.ceil(REPLY_COMMENT_COUNT / 4);
+/** A desktop screenshot at 2x. */
+export const ORIGINAL = { width: 2880, height: 1800 };
+export const TYPING_TEXT = "abcdefghijklmnopqrstuvwxyz".repeat(7).slice(0, 172);
+export const KEY_DELAY_MS = 25;
+export const MEDIA_PREFIX = "/uploads/perf/";
+
+const uuid = (prefix: string, n: number) =>
+ `${prefix}${String(n).padStart(4, "0")}-4444-4444-8444-444444444444`.slice(0, 36);
+
+export const commentIds = Array.from({ length: 1 + REPLY_COMMENT_COUNT }, (_, i) => uuid("cccc", i));
+export const rootCommentId = commentIds[0]!;
+
+const at = (offsetSeconds: number) =>
+ new Date(Date.UTC(2026, 9, 1, 0, 0, 0) + offsetSeconds * 1000).toISOString();
+
+function attachment(commentId: string, n: number) {
+ const id = uuid("eeee", n);
+ const key = `${MEDIA_PREFIX}${id}.png`;
+ return {
+ id,
+ workspace_id: WORKSPACE_ID,
+ issue_id: ISSUE_ID,
+ comment_id: commentId,
+ chat_session_id: null,
+ chat_message_id: null,
+ uploader_type: "member",
+ uploader_id: USER_ID,
+ filename: `screenshot-${n}.png`,
+ url: key,
+ download_url: key,
+ markdown_url: key,
+ content_type: "image/png",
+ size_bytes: 4_000_000,
+ ...(IMAGE_MODE === "known" ? ORIGINAL : {}),
+ created_at: at(n),
+ };
+}
+
+export function buildTimelineEntries() {
+ let image = 0;
+ return commentIds.map((id, index) => {
+ const files = Array.from({ length: index > 0 && index % 4 === 1 ? 2 : 1 }, () => attachment(id, image++));
+ if (IMAGE_MODE === "none") files.length = 0;
+ const prose = Array.from(
+ { length: 3 },
+ (_, p) => `Paragraph ${p + 1} of comment ${index}: what changed, and the screenshot that shows it.`,
+ );
+ return {
+ type: "comment" as const,
+ id,
+ actor_type: "user" as const,
+ actor_id: USER_ID,
+ created_at: at(index * 60),
+ updated_at: at(index * 60),
+ issue_id: ISSUE_ID,
+ parent_id: index === 0 ? null : rootCommentId,
+ content: [...prose, ...files.map((f) => `![${f.filename}](${f.url})`)].join("\n\n"),
+ resolved_at: null,
+ reactions: [],
+ attachments: files,
+ source_task_id: null,
+ };
+ });
+}
+
+function crc32(bytes: Buffer): number {
+ let crc = ~0;
+ for (const byte of bytes) {
+ crc ^= byte;
+ for (let k = 0; k < 8; k += 1) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1));
+ }
+ return ~crc >>> 0;
+}
+
+function chunk(type: string, data: Buffer): Buffer {
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(data.length);
+ const body = Buffer.concat([Buffer.from(type, "ascii"), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(body));
+ return Buffer.concat([length, body, crc]);
+}
+
+/**
+ * A screenshot-like RGB PNG: flat panels with text-like noise rows, so it
+ * compresses roughly the way a UI capture does and decodes at full size.
+ */
+function screenshotPNG(width: number, height: number): Buffer {
+ const stride = width * 3 + 1;
+ const raw = Buffer.alloc(stride * height);
+ let seed = 0x12345678;
+ for (let y = 0; y < height; y += 1) {
+ raw[y * stride] = 0;
+ const textRow = Math.floor(y / 12) % 3 === 1;
+ for (let x = 0; x < width; x += 1) {
+ const panel = (Math.floor(x / 300) + Math.floor(y / 250)) % 4;
+ let v = 235 - panel * 18;
+ if (textRow && x % 300 > 24 && x % 300 < 260) {
+ seed = (seed * 1664525 + 1013904223) >>> 0;
+ if (seed >>> 30 === 0) v = 40;
+ }
+ const o = y * stride + 1 + x * 3;
+ raw[o] = v;
+ raw[o + 1] = v;
+ raw[o + 2] = Math.min(255, v + 10);
+ }
+ }
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width, 0);
+ header.writeUInt32BE(height, 4);
+ header[8] = 8;
+ header[9] = 2;
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk("IHDR", header),
+ chunk("IDAT", deflateSync(raw, { level: 6 })),
+ chunk("IEND", Buffer.alloc(0)),
+ ]);
+}
+
+let media: { original: Buffer; alternate?: Buffer } | undefined;
+export function mediaBytes(): { original: Buffer; alternate?: Buffer } {
+ media ??= {
+ original: process.env.PERF_SCREENSHOT_PATH
+ ? readFileSync(process.env.PERF_SCREENSHOT_PATH)
+ : screenshotPNG(ORIGINAL.width, ORIGINAL.height),
+ alternate: process.env.PERF_SCREENSHOT_ALT_PATH ? readFileSync(process.env.PERF_SCREENSHOT_ALT_PATH) : undefined,
+ };
+ if ([media.original, media.alternate].filter((b): b is Buffer => !!b).some((b) => b.readUInt32BE(16) !== ORIGINAL.width || b.readUInt32BE(20) !== ORIGINAL.height)) {
+ throw new Error("PERF_SCREENSHOT_PATH must be a 2880x1800 PNG screenshot");
+ }
+ return media;
+}
+
+export function fixtureDigest(): { version: string; sha256: string; bytes: number } {
+ const { original, alternate } = mediaBytes();
+ const hash = createHash("sha256")
+ .update(JSON.stringify({ version: FIXTURE_VERSION, timeline: buildTimelineEntries(), typing: TYPING_TEXT, position: POSITION }))
+ .update(original)
+ .update(alternate ?? Buffer.alloc(0));
+ return { version: FIXTURE_VERSION, sha256: hash.digest("hex").slice(0, 16), bytes: original.length + (alternate?.length ?? 0) };
+}
diff --git a/e2e/perf/image-heavy-thread.spec.ts b/e2e/perf/image-heavy-thread.spec.ts
new file mode 100644
index 0000000000..1df69a2031
--- /dev/null
+++ b/e2e/perf/image-heavy-thread.spec.ts
@@ -0,0 +1,430 @@
+/**
+ * Comment typing beside an image-heavy thread (MUL-8182).
+ *
+ * A long thread of replies that each carry a large screenshot sits in the
+ * viewport while the reader types a comment. Every inline image that mounts
+ * is fetched, decoded at full size and laid out on the main thread, and an
+ * image without a reserved box shifts everything below it when it lands.
+ *
+ * Image responses are held until the first keystroke, so the images arrive,
+ * decode and lay out while the user is typing — the moment the report
+ * measures. Like the live-runs scenario, only HTTP and the WebSocket are
+ * synthetic; the page, the composer and the CSS are the real build.
+ *
+ * Select it with `PERF_SCENARIO=image-thread` (perf-compare's
+ * `--scenario image-thread` sets it): the live-runs scenario writes the same
+ * report path, and the two must not overwrite each other.
+ */
+import { expect, test, type Page } from "@playwright/test";
+import { writeFileSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import * as fx from "./fixtures/image-heavy-thread";
+
+test.skip(process.env.PERF_SCENARIO !== "image-thread", "set PERF_SCENARIO=image-thread to run");
+test.setTimeout(300_000);
+const SCENARIO_LIMIT_MS = 60_000;
+const SETUP_LIMIT_MS = 120_000;
+/** CPU slowdown for the measured window only (setup runs at full speed). */
+const CPU_THROTTLE = 4;
+
+test.use({
+ viewport: { width: 1280, height: 720 },
+ locale: "en-US",
+ colorScheme: "light",
+ serviceWorkers: "block",
+});
+
+const workspace = {
+ id: fx.WORKSPACE_ID, name: "Perf", slug: fx.WORKSPACE_SLUG,
+ description: null, context: null,
+ settings: { github_enabled: false }, repos: [],
+ issue_prefix: "PERF", avatar_url: null,
+ created_at: "2026-09-01T00:00:00Z", updated_at: "2026-09-01T00:00:00Z",
+};
+
+const me = {
+ id: fx.USER_ID, name: "Perf User", email: "[email protected]", avatar_url: null,
+ language: null, onboarded_at: "2026-09-01T00:00:00Z",
+ onboarding_questionnaire: { source: "other" },
+ created_at: "2026-09-01T00:00:00Z", updated_at: "2026-09-01T00:00:00Z",
+};
+
+const issue = {
+ id: fx.ISSUE_ID, workspace_id: fx.WORKSPACE_ID, number: 1,
+ identifier: fx.ISSUE_IDENTIFIER, title: "Image-heavy thread",
+ description: "Performance scenario fixture.", status: "in_progress",
+ status_category: "in_progress", status_name: "In Progress", priority: "none",
+ assignee_type: null, assignee_id: null, creator_type: "user", creator_id: fx.USER_ID,
+ parent_issue_id: null, project_id: null, position: 0,
+ start_date: null, due_date: null, stage: null, metadata: {}, properties: {},
+ labels: [], reactions: [],
+ created_at: "2026-09-01T00:00:00Z", updated_at: "2026-09-01T00:00:00Z",
+};
+
+function responseFor(pathname: string): unknown | undefined {
+ switch (pathname) {
+ case "/api/config": return { feature_flags: {}, allow_signup: true };
+ case "/api/me": return me;
+ case "/api/workspaces": return [workspace];
+ case "/api/client-usage": return {};
+ case "/api/issue-view-preferences": return { prefs: { hidden: [], order: [] } };
+ case "/api/issue-views": case "/api/agent-run-counts": case "/api/agent-activity-30d": return [];
+ case "/api/skills": return { skills: [], total: 0 };
+ case "/api/autopilots": return { autopilots: [], total: 0 };
+ case "/api/issues/unread": return { items: [], next_cursor: null };
+ case "/api/inbox/archived/page": return { items: [], next_cursor: null };
+ case `/api/inbox/issues/${fx.ISSUE_ID}/read`: return { count: 0 };
+ case "/api/agents": case "/api/runtimes": case "/api/squads":
+ case "/api/agent-task-snapshot": case "/api/invitations": case "/api/inbox":
+ case "/api/inbox/unread-summary": case "/api/pins": case "/api/chat/sessions":
+ return [];
+ case "/api/chat/pending-tasks/has-any": return { has_pending: false };
+ case `/api/workspaces/${fx.WORKSPACE_ID}/members`: return [];
+ case "/api/projects": return { projects: [], total: 0 };
+ case "/api/issues": return { issues: [], total: 0 };
+ case "/api/issue-statuses": return { statuses: [] };
+ case "/api/properties": return { properties: [], total: 0 };
+ case "/api/quick-actions": return { quick_actions: [] };
+ case "/api/assignee-frequency": return [];
+ case "/api/labels": return { labels: [], total: 0 };
+ case "/api/issue-workflows": return { workflows: [], total: 0 };
+ case `/api/issues/${fx.ISSUE_ID}/system-wakeups`: return [];
+ case `/api/issues/${fx.ISSUE_ID}/duplicates`: return { duplicate_of: null, duplicates: [] };
+ case `/api/issues/${fx.ISSUE_ID}/comments/trigger-preview`:
+ return { agents: [], blocked: [] };
+ case "/api/issues/child-progress": return { progress: [] };
+ case `/api/issues/${fx.ISSUE_IDENTIFIER}`:
+ case `/api/issues/${fx.ISSUE_ID}`: return issue;
+ case `/api/issues/${fx.ISSUE_ID}/timeline`: return fx.buildTimelineEntries();
+ case `/api/issues/${fx.ISSUE_ID}/task-runs`:
+ case `/api/issues/${fx.ISSUE_ID}/subscribers`:
+ case `/api/issues/${fx.ISSUE_ID}/wakeups`:
+ case `/api/issues/${fx.ISSUE_ID}/attachments`: return [];
+ case `/api/issues/${fx.ISSUE_ID}/labels`: return { labels: [] };
+ case `/api/issues/${fx.ISSUE_ID}/children`: return { issues: [] };
+ case `/api/issues/${fx.ISSUE_ID}/pull-requests`: return { pull_requests: [] };
+ default: return undefined;
+ }
+}
+
+/**
+ * The local search copy syncs in the background on every page and is not part
+ * of this one's cost, so it is declined rather than seeded.
+ */
+const DECLINED = new Set(["/api/search-index/manifest"]);
+
+const nextFrame = (page: Page) =>
+ page.evaluate(() => new Promise<void>((done) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => done()));
+ }));
+
+function emit(report: Record<string, unknown>) {
+ const out = process.env.PERF_REPORT_PATH;
+ if (out) {
+ mkdirSync(dirname(resolve(out)), { recursive: true });
+ let samples: Record<string, unknown>[] = [];
+ try { samples = JSON.parse(readFileSync(resolve(out), "utf8")).samples ?? []; } catch { /* first sample */ }
+ samples.push(report);
+ const combined: Record<string, unknown> = { ...report, samples };
+ for (const key of Object.keys(report)) {
+ if (typeof report[key] !== "number") continue;
+ const values = samples.map((sample) => sample[key]).filter((v): v is number => typeof v === "number").sort((a, b) => a - b);
+ combined[key] = values[Math.floor(values.length / 2)];
+ }
+ combined.status = samples.every((sample) => sample.status === "ok") ? "ok" : "invalid";
+ writeFileSync(resolve(out), JSON.stringify(combined, null, 2));
+ }
+ test.info().annotations.push({ type: "perf", description: JSON.stringify(report) });
+ // eslint-disable-next-line no-console
+ console.log(`PERF_REPORT ${JSON.stringify(report)}`);
+}
+
+test("comment typing stays responsive beside an image-heavy thread", async ({ page, context, baseURL }) => {
+ const origin = new URL(baseURL ?? "http://localhost:3000").origin;
+ const unknownRequests: string[] = [];
+ const pageErrors: string[] = [];
+ const external: string[] = [];
+ const served = { originals: 0, bytes: 0 };
+ const media = fx.mediaBytes();
+
+ page.on("pageerror", (error) => pageErrors.push(error.message));
+ await page.emulateMedia({ colorScheme: "light", reducedMotion: "no-preference" });
+ await context.addCookies([
+ { name: "multica_logged_in", value: "1", url: origin },
+ { name: "last_workspace_slug", value: fx.WORKSPACE_SLUG, url: origin },
+ ]);
+ await context.addInitScript(() => {
+ window.localStorage.setItem("multica:chat:floatingChatEnabled", "false");
+ });
+ await context.addInitScript(() => {
+ const tasks: number[] = [];
+ let shift = 0;
+ const keyFrames: number[] = [];
+ document.addEventListener("keydown", (event) => {
+ if (event.key.length !== 1) return;
+ requestAnimationFrame(() => keyFrames.push(performance.now() - event.timeStamp));
+ });
+
+ const w = window as unknown as Record<string, unknown>;
+ w.__perfLongTasks = tasks;
+ w.__perfKeyFrames = keyFrames;
+ w.__perfShift = () => shift;
+ w.__perfReset = () => {
+ longTasks.takeRecords();
+ shifts.takeRecords();
+ tasks.length = 0;
+ keyFrames.length = 0;
+ shift = 0;
+ };
+ const longTasks = new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) tasks.push(entry.duration);
+ });
+ longTasks.observe({ type: "longtask", buffered: true });
+ // Typing is recent input, so `hadRecentInput` would excuse every shift in
+ // the window; the reader still sees each one.
+ const shifts = new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) shift += (entry as unknown as { value: number }).value;
+ });
+ shifts.observe({ type: "layout-shift", buffered: true });
+ w.__perfDrain = () => {
+ for (const entry of longTasks.takeRecords()) tasks.push(entry.duration);
+ for (const entry of shifts.takeRecords()) shift += (entry as unknown as { value: number }).value;
+ };
+ });
+
+ let releaseMedia!: () => void;
+ const mediaGate = new Promise<void>((done) => { releaseMedia = done; });
+ await context.route("**/*", async (route) => {
+ const url = new URL(route.request().url());
+ if (url.origin !== origin) {
+ external.push(url.href);
+ return route.abort();
+ }
+ if (url.pathname.startsWith(fx.MEDIA_PREFIX)) {
+ await mediaGate;
+ const index = Number(/eeee(\d+)/.exec(url.pathname)?.[1] ?? 0);
+ const body = index % 2 && media.alternate ? media.alternate : media.original;
+ served.originals += 1;
+ served.bytes += body.length;
+ return route.fulfill({ status: 200, contentType: "image/png", body });
+ }
+ if (!url.pathname.startsWith("/api/")) return route.continue();
+ if (DECLINED.has(url.pathname)) {
+ return route.fulfill({ status: 404, contentType: "application/json", body: "{}" });
+ }
+ const body = responseFor(url.pathname);
+ if (body === undefined) {
+ unknownRequests.push(`${route.request().method()} ${url.pathname}${url.search}`);
+ return route.fulfill({ status: 404, contentType: "application/json", body: "{}" });
+ }
+ return route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(body) });
+ });
+ await context.routeWebSocket((url) => url.pathname === "/ws", (ws) => {
+ ws.onMessage(() => {});
+ });
+
+ const setupDeadline = Date.now() + SETUP_LIMIT_MS;
+ const setupLeft = () => Math.max(1, setupDeadline - Date.now());
+ const failSetup = (stage: string) => emit({
+ status: "invalid",
+ invalid: [`setup did not complete: ${stage}`],
+ fixture: fx.fixtureDigest(),
+ page_errors: pageErrors,
+ unmocked_requests: unknownRequests,
+ external_requests: external,
+ typing_elapsed_ms: null,
+ scenario_elapsed_ms: null,
+ });
+
+ // ---- 1. Load, and put the thread in the viewport ---------------------------
+ await page.goto(`${origin}/${fx.WORKSPACE_SLUG}/issues/${fx.ISSUE_IDENTIFIER}`, {
+ waitUntil: "domcontentloaded", timeout: setupLeft(),
+ });
+ const root = page.locator(`[id="comment-${fx.rootCommentId}"]`);
+ try {
+ await expect(root).toBeVisible({ timeout: setupLeft() });
+ // Every build mounts at least the root and the latest reply.
+ await expect(page.locator(`[id="comment-${fx.commentIds.at(-1)}"]`)).toBeAttached({ timeout: setupLeft() });
+ } catch (error) { failSetup("the thread never rendered"); throw error; }
+ await page.evaluate(() => document.fonts?.ready);
+ // Scroll the thread's replies into view: the scroll parent is the nearest
+ // ancestor that scrolls.
+ await root.evaluate((el) => {
+ let scroller: HTMLElement | null = el.parentElement;
+ while (scroller && !/(auto|scroll)/.test(getComputedStyle(scroller).overflowY)) {
+ scroller = scroller.parentElement;
+ }
+ if (!scroller) throw new Error("no scroll container");
+ const offset = el.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+ scroller.scrollTop += offset + 200;
+ });
+ await nextFrame(page);
+
+ // Load every image in sequence before the second scenario's typing window.
+ // This exercises the decoded images that remain mounted within a long thread.
+ if (fx.POSITION === "loaded") {
+ releaseMedia();
+ if (fx.IMAGE_MODE !== "none") {
+ const images = page.locator(`img[src^="${fx.MEDIA_PREFIX}"]`);
+ const count = await images.count();
+ for (let i = 0; i < count; i += 1) {
+ const image = images.nth(i);
+ await image.scrollIntoViewIfNeeded();
+ await expect.poll(() => image.evaluate((img) => (img as HTMLImageElement).complete)).toBe(true);
+ }
+ expect(await images.evaluateAll((nodes) => nodes.every((img) => (img as HTMLImageElement).complete))).toBe(true);
+ }
+ await page.locator(`[id="comment-${fx.commentIds.at(-1)}"]`).scrollIntoViewIfNeeded();
+ await nextFrame(page);
+ }
+
+ // ---- 2. Focus the composer -------------------------------------------------
+ const shell = page.getByTestId("comment-composer-shell");
+ await expect(shell).toBeVisible();
+ const composer = await page
+ .locator('div:has(> [data-testid="comment-composer-shell"])')
+ .first()
+ .elementHandle();
+ if (!composer) throw new Error("comment composer container not found");
+ await shell.click();
+ const editor = await composer.waitForSelector('.ProseMirror[contenteditable="true"]', {
+ timeout: setupLeft(),
+ });
+ await editor.click();
+ expect(await editor.evaluate((node) => node === document.activeElement)).toBe(true);
+ expect((await editor.innerText()).trim()).toBe("");
+
+ const cdp = await context.newCDPSession(page);
+ await cdp.send("Performance.enable");
+ const readMetrics = async () => {
+ const { metrics } = await cdp.send("Performance.getMetrics");
+ return Object.fromEntries(metrics.map((m) => [m.name, m.value]));
+ };
+ // A fast workstation absorbs this page without a dropped frame; the stall
+ // was reported from ordinary laptops. Same factor on both builds.
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: CPU_THROTTLE });
+ const before = await readMetrics();
+ await page.evaluate(() => (window as unknown as { __perfReset: () => void }).__perfReset());
+
+ // ---- 3. Release the images and type at the same time -----------------------
+ const startedAt = Date.now();
+ releaseMedia();
+ const typing = page.keyboard.type(fx.TYPING_TEXT, { delay: fx.KEY_DELAY_MS });
+ typing.catch(() => {});
+ const remainingMs = () => Math.max(0, startedAt + SCENARIO_LIMIT_MS - Date.now());
+ let timedOutAt: string | null = null;
+ async function beforeDeadline<T>(work: Promise<T>, label: string): Promise<boolean> {
+ const budget = remainingMs();
+ if (budget <= 0) { timedOutAt ??= label; return false; }
+ let timer: NodeJS.Timeout | undefined;
+ const expired = new Promise<false>((done) => { timer = setTimeout(() => done(false), budget); });
+ const finished = await Promise.race([work.then(() => true, () => false), expired]);
+ clearTimeout(timer);
+ if (!finished) timedOutAt ??= label;
+ return finished;
+ }
+
+ let typingElapsedMs: number | null = null;
+ if (await beforeDeadline(typing, "keystrokes")) {
+ const verified = await beforeDeadline(
+ expect.poll(async () => (await editor.innerText()).trim(), { timeout: remainingMs() })
+ .toBe(fx.TYPING_TEXT),
+ "editor content",
+ );
+ if (verified) {
+ await beforeDeadline(nextFrame(page), "paint");
+ typingElapsedMs = Date.now() - startedAt;
+ }
+ }
+
+ // Settled once every image that is in or near the viewport has painted.
+ let scenarioElapsedMs: number | null = null;
+ if (!timedOutAt) {
+ const settled = await beforeDeadline(
+ page.waitForFunction((prefix) => [...document.images]
+ .filter((img) => img.currentSrc.includes(prefix))
+ .filter((img) => {
+ const r = img.getBoundingClientRect();
+ return r.bottom > -800 && r.top < window.innerHeight + 800;
+ })
+ .every((img) => img.complete), fx.MEDIA_PREFIX, { timeout: remainingMs() }),
+ "images",
+ );
+ if (settled) {
+ await beforeDeadline(nextFrame(page), "final paint");
+ scenarioElapsedMs = Date.now() - startedAt;
+ }
+ }
+ const abortedAfterMs = timedOutAt ? Date.now() - startedAt : null;
+
+ // ---- 4. Collect ------------------------------------------------------------
+ const COLLECT_BUDGET_MS = 20_000;
+ const collect = async <T>(work: Promise<T>, fallback: T): Promise<T> => {
+ let timer: NodeJS.Timeout | undefined;
+ const expired = new Promise<T>((done) => { timer = setTimeout(() => done(fallback), COLLECT_BUDGET_MS); });
+ const value = await Promise.race([work.catch(() => fallback), expired]);
+ clearTimeout(timer);
+ return value;
+ };
+ const observed = await collect(page.evaluate((prefix) => {
+ const w = window as unknown as {
+ __perfDrain: () => void; __perfLongTasks: number[]; __perfShift: () => number; __perfKeyFrames: number[];
+ };
+ w.__perfDrain();
+ return {
+ longTasks: [...w.__perfLongTasks],
+ shift: w.__perfShift(),
+ keyFrames: [...w.__perfKeyFrames],
+ mounted: [...document.images].filter((img) => img.src.includes(prefix)).length,
+ };
+ }, fx.MEDIA_PREFIX), { longTasks: [] as number[], keyFrames: [] as number[], shift: 0, mounted: 0 });
+ const after = await collect(readMetrics(), {} as Record<string, number>);
+ const metricsRead = Object.keys(after).length > 0;
+ const deltaMs = (name: string) =>
+ metricsRead ? Math.round(((after[name] ?? 0) - (before[name] ?? 0)) * 1000) : null;
+
+ const invalid: string[] = [];
+ if (unknownRequests.length) invalid.push(`unmocked requests: ${unknownRequests.join(", ")}`);
+ if (external.length) invalid.push(`external requests: ${external.join(", ")}`);
+ if (pageErrors.length) invalid.push(`page errors: ${pageErrors.join(" | ")}`);
+ if (!timedOutAt && !metricsRead) invalid.push("performance metrics unavailable");
+ if (!timedOutAt && fx.IMAGE_MODE !== "none" && served.originals === 0) invalid.push("no image was requested");
+ if (observed.keyFrames.length !== fx.TYPING_TEXT.length) invalid.push("missing keydown frame samples");
+ const status = timedOutAt ? "timeout" : invalid.length ? "invalid" : "ok";
+
+ const longTasks = observed.longTasks;
+ emit({
+ status, invalid,
+ scenario: "image-thread",
+ image_mode: fx.IMAGE_MODE,
+ position: fx.POSITION,
+ real_screenshot: !!process.env.PERF_SCREENSHOT_PATH,
+ keystrokes_over_frame: observed.keyFrames.filter((ms) => ms > 1000 / 60).length,
+ key_frame_p95_ms: Math.round([...observed.keyFrames].sort((a, b) => a - b)[Math.ceil(observed.keyFrames.length * 0.95) - 1] ?? 0),
+ key_frame_max_ms: Math.round(Math.max(0, ...observed.keyFrames)),
+ timed_out_at: timedOutAt,
+ aborted_after_ms: abortedAfterMs,
+ fixture: fx.fixtureDigest(),
+ typing_elapsed_ms: typingElapsedMs,
+ scenario_elapsed_ms: scenarioElapsedMs,
+ recalc_style_ms: deltaMs("RecalcStyleDuration"),
+ layout_ms: deltaMs("LayoutDuration"),
+ task_ms: deltaMs("TaskDuration"),
+ long_task_count: longTasks.length,
+ long_task_total_ms: Math.round(longTasks.reduce((sum, t) => sum + t, 0)),
+ long_task_max_ms: Math.round(Math.max(0, ...longTasks)),
+ layout_shift: Math.round(observed.shift * 1000) / 1000,
+ images_mounted: observed.mounted,
+ originals_served: served.originals,
+ image_bytes_served: served.bytes,
+ dom_nodes: metricsRead ? Math.round(after.Nodes ?? 0) : null,
+ js_heap_mb: metricsRead ? Math.round((after.JSHeapUsedSize ?? 0) / 1e6) : null,
+ cpu_throttle: CPU_THROTTLE,
+ typed_chars: fx.TYPING_TEXT.length,
+ node_version: process.version,
+ browser_version: page.context().browser()?.version() ?? "unknown",
+ });
+
+ expect(invalid, invalid.join(" | ")).toEqual([]);
+ expect(timedOutAt, `scenario exceeded ${SCENARIO_LIMIT_MS}ms while waiting for ${timedOutAt}`).toBeNull();
+});
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index fe65ed34f1..dfad578fc4 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1674,6 +1674,26 @@ describe("ApiClient", () => {
});
});
+ describe("attachment dimensions", () => {
+ it.each([
+ [{ width: 3200, height: 2000 }, [3200, 2000]],
+ [{ width: "wide", height: -1 }, [undefined, undefined]],
+ [{ width: null, height: 0.5 }, [undefined, undefined]],
+ [{}, [undefined, undefined]],
+ ])("preserves the attachment with optional metadata %j", async (metadata, expected) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(
+ JSON.stringify({
+ id: "att-1", filename: "shot.png", url: "/uploads/shot.png",
+ download_url: "/uploads/shot.png", ...metadata,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ )));
+ const att = await new ApiClient("https://api.example.test").getAttachment("att-1");
+ expect(att.id).toBe("att-1");
+ expect([att.width, att.height]).toEqual(expected);
+ });
+ });
+
describe("getAttachmentTextContent", () => {
it("returns body text and the original content type from the X-* header", async () => {
vi.stubGlobal(
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index abfeb46f0b..5b3b0ef3ec 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -979,8 +979,14 @@ const ReactionSchema = z.object({
// Nested attachments embedded in timeline/comment responses stay lenient on
// purpose: a single malformed attachment must not knock the whole timeline
// into the fallback `[]`.
+const AttachmentImageFields = {
+ width: z.number().int().positive().optional().catch(undefined),
+ height: z.number().int().positive().optional().catch(undefined),
+};
+
const AttachmentSchema = z.object({
id: z.string(),
+ ...AttachmentImageFields,
}).loose();
const ChatQuickActionSchema = z.object({
@@ -1046,6 +1052,9 @@ export const AttachmentResponseSchema = z.object({
filename: z.string(),
chat_session_id: z.string().nullable().optional(),
chat_message_id: z.string().nullable().optional(),
+ // Image metadata is optional and degrades on its own: a malformed value
+ // means "unknown dimensions", never a lost attachment.
+ ...AttachmentImageFields,
}).loose();
export const EMPTY_ATTACHMENT: Attachment = {
diff --git a/packages/core/types/attachment.ts b/packages/core/types/attachment.ts
index 10ee54621d..f7757600da 100644
--- a/packages/core/types/attachment.ts
+++ b/packages/core/types/attachment.ts
@@ -46,4 +46,10 @@ export interface Attachment {
content_type: string;
size_bytes: number;
created_at: string;
+ /**
+ * An image's displayed pixel size, so a body can reserve its box before the
+ * image loads. Absent for other files and for older uploads.
+ */
+ width?: number;
+ height?: number;
}
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
index 7cb24cc1ee..216836405f 100644
--- a/packages/views/editor/attachment.test.tsx
+++ b/packages/views/editor/attachment.test.tsx
@@ -788,6 +788,69 @@ describe("Attachment — image dispatch", () => {
});
});
+describe("Attachment — lazy images and reserved box (MUL-8182)", () => {
+ it("loads the original lazily in the recorded box", () => {
+ const att = makeRecord({ width: 3200, height: 2000 });
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ const img = document.querySelector("img")!;
+ expect(img.getAttribute("src")).toBe(att.download_url);
+ expect(img.getAttribute("loading")).toBe("lazy");
+ expect(img.getAttribute("decoding")).toBe("async");
+ expect(img.getAttribute("width")).toBe("3200");
+ const figure = img.closest(".image-figure") as HTMLElement;
+ expect(figure.hasAttribute("data-sized")).toBe(true);
+ expect(figure.hasAttribute("data-pending")).toBe(false);
+ expect(figure.style.getPropertyValue("--image-width")).toBe("3200px");
+ expect(figure.style.getPropertyValue("--image-aspect")).toBe("1.6");
+ });
+
+ it("takes dimensions from the resolved record for markdown images", () => {
+ const att = makeRecord({ width: 1170, height: 2532 });
+ resolverState.attachments = [att];
+ renderWithQuery(<Attachment attachment={{ kind: "url", url: att.url, filename: "", forceKind: "image" }} />);
+ expect(document.querySelector("img")?.getAttribute("height")).toBe("2532");
+ });
+
+ it("ignores malformed dimensions on an unparsed record", () => {
+ const att = makeRecord({ width: -1, height: "big" as unknown as number });
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ expect(document.querySelector("img")?.hasAttribute("width")).toBe(false);
+ });
+
+ it("holds an unknown-size placeholder until load or error", () => {
+ const att = makeRecord();
+ renderWithQuery(<Attachment attachment={{ kind: "record", attachment: att }} />);
+ const img = document.querySelector("img")!;
+ const figure = img.closest(".image-figure") as HTMLElement;
+ expect(figure.hasAttribute("data-pending")).toBe(true);
+ fireEvent.load(img);
+ expect(figure.hasAttribute("data-pending")).toBe(false);
+ expect(img.hasAttribute("data-loaded")).toBe(true);
+ });
+
+ it("restores the placeholder when a reused image changes source", () => {
+ const att = makeRecord();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ const { rerender } = render(
+ <QueryClientProvider client={client}>
+ <Attachment attachment={{ kind: "record", attachment: att }} />
+ </QueryClientProvider>,
+ );
+ fireEvent.load(document.querySelector("img")!);
+ rerender(
+ <QueryClientProvider client={client}>
+ <Attachment attachment={{
+ kind: "record",
+ attachment: { ...att, id: "att-2", download_url: "https://cdn.example.test/second.png" },
+ }} />
+ </QueryClientProvider>,
+ );
+ expect(document.querySelector(".image-figure")?.hasAttribute("data-pending")).toBe(true);
+ });
+});
+
describe("Attachment — html dispatch", () => {
// An HTML file is a file (MUL-7649): the row opens it in the viewer, and
// nothing is fetched to embed it inline.
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index 787653890c..d15eac53af 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -33,7 +33,7 @@ import {
Maximize2,
Trash2,
} from "@multica/ui/icons";
-import type { ReactNode } from "react";
+import { useCallback, useState, type CSSProperties, type ReactNode } from "react";
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
@@ -53,6 +53,7 @@ import {
import { useDownloadAttachment } from "./use-download-attachment";
import { AttachmentCard, AttachmentFileCard } from "./attachment-card";
import { canOpenPreview, getPreviewKind, type PreviewKind } from "./utils/preview";
+import { imageDimensions } from "./utils/image-metadata";
import "./styles/attachment.css";
// Public API
@@ -121,6 +122,17 @@ interface Normalized {
height?: number;
}
+function recordImageFields(
+ record: AttachmentRecord | undefined,
+): Pick<Normalized, "width" | "height"> {
+ if (!record) return {};
+ const dims = imageDimensions(record);
+ return {
+ width: dims?.width,
+ height: dims?.height,
+ };
+}
+
function normalize(
input: AttachmentInput,
resolve: (url: string) => AttachmentRecord | undefined,
@@ -137,9 +149,12 @@ function normalize(
attachmentId: input.attachment.id,
record: input.attachment,
uploading: false,
+ ...recordImageFields(input.attachment),
};
}
const record = input.url ? resolve(input.url) : undefined;
+ const fromRecord = recordImageFields(record);
+ const ownSize = input.width !== undefined || input.height !== undefined;
return {
filename: input.filename || record?.filename || "",
contentType: input.contentType || record?.content_type || "",
@@ -170,8 +185,8 @@ function normalize(
attachmentId: record?.id,
record,
uploading: !!input.uploading,
- width: input.width,
- height: input.height,
+ width: ownSize ? input.width : fromRecord.width,
+ height: ownSize ? input.height : fromRecord.height,
};
}
@@ -481,6 +496,24 @@ function ImageAttachmentView({
// cursor: zoom-in }` keys off this same flag for the cursor affordance.
const clickable = !editable && !uploading;
+ // An image that has not loaded has no size of its own (the figure shrinks
+ // to it), so its box is reserved up front: from its pixel size when known,
+ // otherwise as a fixed-ratio placeholder. Once anything has painted the box
+ // follows the image.
+ const [loadedSrc, setLoadedSrc] = useState<string | null>(null);
+ const loaded = !!src && loadedSrc === src;
+ const imgRef = useCallback((img: HTMLImageElement | null) => {
+ if (img?.complete && img.naturalWidth > 0) setLoadedSrc(src);
+ }, [src]);
+ const sized = !!width && !!height;
+ const pending = !loaded && !sized && !uploading;
+ const sizeStyle = sized
+ ? ({
+ "--image-width": `${width}px`,
+ "--image-aspect": `${width! / height!}`,
+ } as CSSProperties)
+ : undefined;
+
// DOM mirrors the original ReadonlyImage (span-only chain so it stays
// valid HTML5 when rendered inside a markdown <p>). In editor surfaces
// the NodeViewWrapper still emits its own outer .image-node div around
@@ -494,16 +527,25 @@ function ImageAttachmentView({
className,
)}
data-clickable={clickable || undefined}
+ data-sized={sized || undefined}
+ data-pending={pending || undefined}
+ style={sizeStyle}
contentEditable={false}
onClick={clickable ? onView : undefined}
>
<img
+ ref={imgRef}
src={src || undefined}
alt={alt}
width={width}
height={height}
+ loading="lazy"
+ decoding="async"
+ data-loaded={loaded || undefined}
className={cn("image-content", uploading && "image-uploading")}
draggable={false}
+ onLoad={() => setLoadedSrc(src)}
+ onError={() => setLoadedSrc(src)}
/>
{!uploading && src && (
<span
diff --git a/packages/views/editor/styles/attachment.css b/packages/views/editor/styles/attachment.css
index 6c20bba5b0..8e02a6ff03 100644
--- a/packages/views/editor/styles/attachment.css
+++ b/packages/views/editor/styles/attachment.css
@@ -44,6 +44,43 @@
box-shadow: 0 0 0 1px var(--border);
}
+/* Reserved box. An unloaded <img> lays out at 0×0 inside the shrink-to-fit
+ figure even with width/height attributes, so the figure carries the size:
+ an image with a known pixel size (--image-width, --image-aspect) gets the
+ box it will render at; one without gets a fixed-ratio placeholder until it
+ loads. Without a box, every unloaded image sits in the viewport at once and
+ lazy loading can't defer any of them. */
+.image-figure[data-sized] {
+ width: min(var(--image-width), 100%);
+}
+
+.image-figure.image-standalone[data-sized] {
+ width: min(var(--image-width), 100%, 36rem * var(--image-aspect));
+}
+
+.image-figure[data-sized] .image-content {
+ width: 100%;
+ aspect-ratio: var(--image-aspect);
+}
+
+.image-figure[data-pending] {
+ display: block;
+}
+
+.image-figure.image-standalone[data-pending] {
+ width: 20rem;
+ max-width: 100%;
+}
+
+.image-figure[data-pending] .image-content {
+ width: 100%;
+ aspect-ratio: 16 / 10;
+}
+
+.image-content:not([data-loaded]) {
+ background-color: var(--muted);
+}
+
.image-uploading {
opacity: 0.5;
animation: rte-upload-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
diff --git a/packages/views/editor/utils/image-metadata.ts b/packages/views/editor/utils/image-metadata.ts
new file mode 100644
index 0000000000..d9f72cacca
--- /dev/null
+++ b/packages/views/editor/utils/image-metadata.ts
@@ -0,0 +1,19 @@
+import type { Attachment } from "@multica/core/types";
+
+// Some attachment lists reach the renderer without a schema pass, so the
+// optional image fields are checked here rather than trusted.
+
+function pixelSize(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) && value > 0
+ ? Math.round(value)
+ : undefined;
+}
+
+/** The image's displayed pixel size, when the server recorded it. */
+export function imageDimensions(
+ record: Pick<Attachment, "width" | "height">,
+): { width: number; height: number } | undefined {
+ const width = pixelSize(record.width);
+ const height = pixelSize(record.height);
+ return width && height ? { width, height } : undefined;
+}
diff --git a/scripts/perf-compare.mjs b/scripts/perf-compare.mjs
index d7f4cf236d..314f6ef259 100755
--- a/scripts/perf-compare.mjs
+++ b/scripts/perf-compare.mjs
@@ -12,7 +12,11 @@
* One sample per ref is a report, not a verdict. A difference near the noise
* floor means "run it again by hand", not "regression".
*
- * node scripts/perf-compare.mjs --base <ref> --head <ref> [--out <dir>]
+ * node scripts/perf-compare.mjs --base <ref> --head <ref> [--out <dir>] [--scenario <name>]
+ *
+ * `--scenario` picks the measurement: `typing-under-live-runs` (default) or
+ * `image-thread` (MUL-8182). Both write the same report path, so one run
+ * measures exactly one of them.
*/
import { execFileSync, spawn } from "node:child_process";
import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync } from "node:fs";
@@ -29,8 +33,33 @@ const flag = (name, fallback) => {
const baseRef = flag("base");
const headRef = flag("head", "HEAD");
const outDir = resolve(flag("out", join(repoRoot, "perf-report")));
-if (!baseRef) {
- console.error("usage: node scripts/perf-compare.mjs --base <ref> [--head <ref>] [--out <dir>]");
+const buildCache = join(repoRoot, ".turbo", "perf-build-cache");
+const SCENARIOS = {
+ "typing-under-live-runs": {
+ title: "Comment typing under live runs (MUL-7227)",
+ spec: "typing-under-live-runs.spec.ts",
+ metrics: [],
+ },
+ "image-thread": {
+ title: "Comment typing beside an image-heavy thread (MUL-8182)",
+ spec: "image-heavy-thread.spec.ts",
+ metrics: [
+ ["layout_shift", "Layout shift (sum)"],
+ ["images_mounted", "Images mounted"],
+ ["originals_served", "Originals fetched"],
+ ["keystrokes_over_frame", "Keystrokes over 16.7 ms"],
+ ["key_frame_p95_ms", "Keydown to frame p95 (ms)"],
+ ["image_bytes_served", "Image bytes fetched"],
+ ["js_heap_mb", "JS heap (MB)"],
+ ],
+ },
+};
+const scenarioName = flag("scenario", "typing-under-live-runs");
+const scenario = SCENARIOS[scenarioName];
+if (!baseRef || !scenario) {
+ console.error(
+ `usage: node scripts/perf-compare.mjs --base <ref> [--head <ref>] [--out <dir>] [--scenario ${Object.keys(SCENARIOS).join("|")}]`,
+ );
process.exit(2);
}
@@ -200,7 +229,7 @@ async function measure(ref, label) {
const buildStart = Date.now();
const buildLog = execFileSync(
"pnpm",
- ["exec", "turbo", "build", "--filter=@multica/web"],
+ ["exec", "turbo", "build", "--filter=@multica/web", `--cache-dir=${buildCache}`],
{ cwd: checkout, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] },
);
process.stdout.write(buildLog);
@@ -228,12 +257,14 @@ async function measure(ref, label) {
const measureStart = Date.now();
let scenarioExit = 0;
try {
- run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts", "typing-under-live-runs.spec.ts"], {
+ run("pnpm", ["exec", "playwright", "test", "--config=playwright.perf.config.ts",
+ `--repeat-each=${process.env.PERF_REPEATS ?? "1"}`, ...(scenario.spec ? [scenario.spec] : [])], {
cwd: repoRoot,
env: {
...process.env,
PLAYWRIGHT_BASE_URL: `http://127.0.0.1:${port}`,
PERF_REPORT_PATH: reportPath,
+ PERF_SCENARIO: scenarioName,
},
});
} catch (error) {
@@ -281,7 +312,7 @@ const METRICS = [
function markdown(base, head) {
const usable = base.status === "ok" && head.status === "ok";
- const rows = METRICS.map(([key, label]) => {
+ const rows = [...METRICS, ...scenario.metrics].map(([key, label]) => {
const a = base[key];
const b = head[key];
if (typeof a !== "number" || typeof b !== "number") return `| ${label} | ${a ?? "—"} | ${b ?? "—"} | — | — |`;
@@ -292,10 +323,10 @@ function markdown(base, head) {
const timing = (r) =>
`install ${r.timings_s.install}s · build ${r.timings_s.build}s${r.build_cached ? " (restored from cache — not a real build)" : ""} · start ${r.timings_s.start}s · measure ${r.timings_s.measure}s`;
return [
- "## Comment typing under live runs (MUL-7227)",
+ `## ${scenario.title}`,
"",
usable
- ? "One sample per ref. This is a report, not a merge gate — read a small difference as noise until a second run says otherwise."
+ ? `${head.samples?.length ?? 1} sample(s) per ref; numeric metrics are medians. This is a report, not a merge gate — small differences may be noise.`
: `**Not a usable comparison.** base: \`${base.status}\`, head: \`${head.status}\`.`,
"",
"| Metric | base | head | Δ | ratio |",
diff --git a/server/internal/handler/attachment_dimensions_test.go b/server/internal/handler/attachment_dimensions_test.go
new file mode 100644
index 0000000000..f1dcebf4b8
--- /dev/null
+++ b/server/internal/handler/attachment_dimensions_test.go
@@ -0,0 +1,78 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "image"
+ "image/png"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestUploadFileImageDimensions(t *testing.T) {
+ store := &mockStorage{}
+ originalStorage, originalSigner := testHandler.Storage, testHandler.CFSigner
+ testHandler.Storage, testHandler.CFSigner = store, nil
+ t.Cleanup(func() { testHandler.Storage, testHandler.CFSigner = originalStorage, originalSigner })
+
+ var imageBytes bytes.Buffer
+ if err := png.Encode(&imageBytes, image.NewRGBA(image.Rect(0, 0, 80, 40))); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ filename string
+ data []byte
+ image bool
+ }{
+ {"shot.png", imageBytes.Bytes(), true},
+ {"notes.txt", []byte("notes"), false},
+ } {
+ t.Run(tc.filename, func(t *testing.T) {
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ part, err := writer.CreateFormFile("file", tc.filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := part.Write(tc.data); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", &body)
+ req.Header.Set("Content-Type", writer.FormDataContentType())
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ var response AttachmentResponse
+ testutil.Call(t, testHandler.UploadFile, req).Want(http.StatusOK).JSON(&response)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), "DELETE FROM attachment WHERE id = $1", response.ID)
+ })
+ stored, err := testHandler.Queries.GetAttachment(context.Background(), db.GetAttachmentParams{
+ ID: parseUUID(response.ID), WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.image {
+ if response.Width == nil || *response.Width != 80 || response.Height == nil || *response.Height != 40 {
+ t.Fatalf("response dimensions = %v/%v", response.Width, response.Height)
+ }
+ if !stored.Width.Valid || stored.Width.Int32 != 80 || !stored.Height.Valid || stored.Height.Int32 != 40 {
+ t.Fatalf("stored dimensions = %v/%v", stored.Width, stored.Height)
+ }
+ } else if response.Width != nil || response.Height != nil || stored.Width.Valid || stored.Height.Valid {
+ t.Fatal("non-image acquired dimensions")
+ }
+ })
+ }
+ if len(store.files) != 2 {
+ t.Fatalf("stored %d objects, want two originals", len(store.files))
+ }
+}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index b9a040e984..9959e55e02 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -18,6 +18,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/imagemetadata"
"github.com/multica-ai/multica/server/internal/storage"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -99,6 +100,9 @@ type AttachmentResponse struct {
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
CreatedAt string `json:"created_at"`
+ // Displayed image dimensions, absent for non-images and older uploads.
+ Width *int32 `json:"width,omitempty"`
+ Height *int32 `json:"height,omitempty"`
}
// attachmentURLMode selects how DownloadURL is rendered on a response.
@@ -171,6 +175,9 @@ func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode)
if h.CFSigner != nil && mode != attachmentURLModeStable {
resp.DownloadURL = h.CFSigner.SignedURL(a.Url, time.Now().Add(h.attachmentDownloadURLTTL()))
}
+ if a.Width.Valid && a.Height.Valid {
+ resp.Width, resp.Height = &a.Width.Int32, &a.Height.Int32
+ }
if a.IssueID.Valid {
s := uuidToString(a.IssueID)
resp.IssueID = &s
@@ -551,6 +558,10 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
params.ChatSessionID = task.ChatSessionID
}
+ if dimensions, ok := imagemetadata.Dimensions(data); ok {
+ params.Width = pgtype.Int4{Int32: dimensions.Width, Valid: true}
+ params.Height = pgtype.Int4{Int32: dimensions.Height, Valid: true}
+ }
link, err := h.Storage.Upload(r.Context(), key, data, contentType, header.Filename)
if err != nil {
slog.Error("file upload failed", "error", err)
diff --git a/server/internal/imagemetadata/dimensions.go b/server/internal/imagemetadata/dimensions.go
new file mode 100644
index 0000000000..022aa2b816
--- /dev/null
+++ b/server/internal/imagemetadata/dimensions.go
@@ -0,0 +1,101 @@
+// Package imagemetadata reads image headers without decoding pixel data.
+package imagemetadata
+
+import (
+ "bytes"
+ "encoding/binary"
+ "image"
+ _ "image/gif"
+ _ "image/jpeg"
+ _ "image/png"
+ "math"
+)
+
+type Size struct {
+ Width int32
+ Height int32
+}
+
+// Dimensions returns the size displayed by browsers, including JPEG orientation.
+// Unsupported or malformed files simply retain the unknown-size placeholder.
+func Dimensions(data []byte) (Size, bool) {
+ cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > math.MaxInt32 || cfg.Height > math.MaxInt32 {
+ return Size{}, false
+ }
+ width, height := int32(cfg.Width), int32(cfg.Height)
+ if format == "jpeg" && jpegOrientation(data) >= 5 {
+ width, height = height, width
+ }
+ return Size{Width: width, Height: height}, true
+}
+
+func jpegOrientation(data []byte) int {
+ if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {
+ return 1
+ }
+ for offset := 2; offset+4 <= len(data); {
+ if data[offset] != 0xff {
+ break
+ }
+ marker := data[offset+1]
+ if marker == 0xff {
+ offset++
+ continue
+ }
+ if marker == 0xda || marker == 0xd9 {
+ break
+ }
+ length := int(binary.BigEndian.Uint16(data[offset+2:]))
+ end := offset + 2 + length
+ if length < 2 || end > len(data) {
+ break
+ }
+ payload := data[offset+4 : end]
+ if marker == 0xe1 && bytes.HasPrefix(payload, []byte("Exif\x00\x00")) {
+ return tiffOrientation(payload[6:])
+ }
+ offset = end
+ }
+ return 1
+}
+
+func tiffOrientation(data []byte) int {
+ if len(data) < 8 {
+ return 1
+ }
+ var order binary.ByteOrder
+ switch string(data[:2]) {
+ case "II":
+ order = binary.LittleEndian
+ case "MM":
+ order = binary.BigEndian
+ default:
+ return 1
+ }
+ if order.Uint16(data[2:4]) != 42 {
+ return 1
+ }
+ offset := uint64(order.Uint32(data[4:8]))
+ if offset < 8 || offset+2 > uint64(len(data)) {
+ return 1
+ }
+ count := int(order.Uint16(data[offset:]))
+ for i := 0; i < count; i++ {
+ entry := offset + 2 + uint64(i)*12
+ if entry+12 > uint64(len(data)) {
+ return 1
+ }
+ if order.Uint16(data[entry:]) != 0x0112 {
+ continue
+ }
+ if order.Uint16(data[entry+2:]) != 3 || order.Uint32(data[entry+4:]) != 1 {
+ return 1
+ }
+ if value := int(order.Uint16(data[entry+8:])); value >= 1 && value <= 8 {
+ return value
+ }
+ return 1
+ }
+ return 1
+}
diff --git a/server/internal/imagemetadata/dimensions_test.go b/server/internal/imagemetadata/dimensions_test.go
new file mode 100644
index 0000000000..246a63e80c
--- /dev/null
+++ b/server/internal/imagemetadata/dimensions_test.go
@@ -0,0 +1,103 @@
+package imagemetadata
+
+import (
+ "bytes"
+ "encoding/binary"
+ "hash/crc32"
+ "image"
+ "image/color"
+ "image/gif"
+ "image/jpeg"
+ "image/png"
+ "testing"
+)
+
+func TestDimensions(t *testing.T) {
+ img := image.NewRGBA(image.Rect(0, 0, 80, 40))
+ for name, encode := range map[string]func(*bytes.Buffer) error{
+ "png": func(b *bytes.Buffer) error { return png.Encode(b, img) },
+ "jpeg": func(b *bytes.Buffer) error { return jpeg.Encode(b, img, nil) },
+ "gif": func(b *bytes.Buffer) error {
+ return gif.Encode(b, image.NewPaletted(img.Rect, color.Palette{color.White}), nil)
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ var b bytes.Buffer
+ if err := encode(&b); err != nil {
+ t.Fatal(err)
+ }
+ if size, ok := Dimensions(b.Bytes()); !ok || size != (Size{80, 40}) {
+ t.Fatalf("Dimensions = %+v, %v", size, ok)
+ }
+ })
+ }
+ for _, data := range [][]byte{nil, []byte("not an image"), []byte("\x89PNG\r\n\x1a\n")} {
+ if size, ok := Dimensions(data); ok || size != (Size{}) {
+ t.Fatalf("invalid file returned %+v, %v", size, ok)
+ }
+ }
+}
+
+func TestDimensionsReadsHeaderWithoutPixelDecode(t *testing.T) {
+ // A valid IHDR with no pixel data is sufficient, even for huge images.
+ header := make([]byte, 13)
+ binary.BigEndian.PutUint32(header, 100000)
+ binary.BigEndian.PutUint32(header[4:], 50000)
+ header[8], header[9] = 8, 2
+ chunk := append([]byte("IHDR"), header...)
+ data := append([]byte("\x89PNG\r\n\x1a\n"), 0, 0, 0, 13)
+ data = append(data, chunk...)
+ data = binary.BigEndian.AppendUint32(data, crc32.ChecksumIEEE(chunk))
+ if _, err := png.Decode(bytes.NewReader(data)); err == nil {
+ t.Fatal("fixture must not contain decodable pixels")
+ }
+ if size, ok := Dimensions(data); !ok || size != (Size{100000, 50000}) {
+ t.Fatalf("Dimensions = %+v, %v", size, ok)
+ }
+}
+
+func TestDimensionsJPEGOrientation(t *testing.T) {
+ var b bytes.Buffer
+ if err := jpeg.Encode(&b, image.NewRGBA(image.Rect(0, 0, 80, 40)), nil); err != nil {
+ t.Fatal(err)
+ }
+ for _, order := range []binary.ByteOrder{binary.BigEndian, binary.LittleEndian} {
+ for orientation := uint16(1); orientation <= 8; orientation++ {
+ tiff := make([]byte, 26)
+ copy(tiff, "MM")
+ if order == binary.LittleEndian {
+ copy(tiff, "II")
+ }
+ order.PutUint16(tiff[2:], 42)
+ order.PutUint32(tiff[4:], 8)
+ order.PutUint16(tiff[8:], 1)
+ order.PutUint16(tiff[10:], 0x0112)
+ order.PutUint16(tiff[12:], 3)
+ order.PutUint32(tiff[14:], 1)
+ order.PutUint16(tiff[18:], orientation)
+ payload := append([]byte("Exif\x00\x00"), tiff...)
+ data := append([]byte{0xff, 0xd8, 0xff, 0xe1}, byte((len(payload)+2)>>8), byte(len(payload)+2))
+ data = append(data, payload...)
+ data = append(data, b.Bytes()[2:]...)
+ want := Size{80, 40}
+ if orientation >= 5 {
+ want = Size{40, 80}
+ }
+ if size, ok := Dimensions(data); !ok || size != want {
+ t.Fatalf("orientation %d: got %+v, %v; want %+v", orientation, size, ok, want)
+ }
+ }
+ }
+}
+
+func TestMalformedEXIFFallsBack(t *testing.T) {
+ for _, data := range [][]byte{
+ nil, []byte("Exif"),
+ []byte("MM\x00\x2a\xff\xff\xff\xff"),
+ []byte("II\x2a\x00\x08\x00\x00\x00\xff\xff"),
+ } {
+ if got := tiffOrientation(data); got != 1 {
+ t.Fatalf("orientation = %d", got)
+ }
+ }
+}
diff --git a/server/migrations/615_attachment_image_dimensions.down.sql b/server/migrations/615_attachment_image_dimensions.down.sql
new file mode 100644
index 0000000000..34346dbdcf
--- /dev/null
+++ b/server/migrations/615_attachment_image_dimensions.down.sql
@@ -0,0 +1,3 @@
+ALTER TABLE attachment
+ DROP COLUMN IF EXISTS width,
+ DROP COLUMN IF EXISTS height;
diff --git a/server/migrations/615_attachment_image_dimensions.up.sql b/server/migrations/615_attachment_image_dimensions.up.sql
new file mode 100644
index 0000000000..9966ea42db
--- /dev/null
+++ b/server/migrations/615_attachment_image_dimensions.up.sql
@@ -0,0 +1,4 @@
+-- Nullable metadata preserves compatibility with older servers and uploads.
+ALTER TABLE attachment
+ ADD COLUMN width integer,
+ ADD COLUMN height integer;
diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.go
index 1b117a9fad..ad95d81795 100644
--- a/server/pkg/db/generated/attachment.sql.go
+++ b/server/pkg/db/generated/attachment.sql.go
@@ -82,13 +82,15 @@ const createAttachment = `-- name: CreateAttachment :one
WITH inserted AS (
INSERT INTO attachment (
id, workspace_id, issue_id, comment_id, chat_session_id, task_id, source_context_id,
- uploader_type, uploader_id, filename, url, content_type, size_bytes
+ uploader_type, uploader_id, filename, url, content_type, size_bytes,
+ width, height
)
VALUES (
$1, $2, $9, $10, $11, $12, $13,
- $3, $4, $5, $6, $7, $8
+ $3, $4, $5, $6, $7, $8,
+ $14, $15
)
- RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id
+ RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height
), bumped_issue AS (
UPDATE issue
SET revision = revision + 1
@@ -100,7 +102,7 @@ WITH inserted AS (
WHERE id IN (SELECT comment_id FROM inserted WHERE comment_id IS NOT NULL)
RETURNING revision
)
-SELECT inserted.id, inserted.workspace_id, inserted.issue_id, inserted.comment_id, inserted.uploader_type, inserted.uploader_id, inserted.filename, inserted.url, inserted.content_type, inserted.size_bytes, inserted.created_at, inserted.chat_session_id, inserted.chat_message_id, inserted.task_id, inserted.source_context_id,
+SELECT inserted.id, inserted.workspace_id, inserted.issue_id, inserted.comment_id, inserted.uploader_type, inserted.uploader_id, inserted.filename, inserted.url, inserted.content_type, inserted.size_bytes, inserted.created_at, inserted.chat_session_id, inserted.chat_message_id, inserted.task_id, inserted.source_context_id, inserted.width, inserted.height,
COALESCE((SELECT revision FROM bumped_issue), 0)::bigint AS issue_revision,
COALESCE((SELECT revision FROM bumped_comment), 0)::bigint AS comment_revision
FROM inserted
@@ -120,6 +122,8 @@ type CreateAttachmentParams struct {
ChatSessionID pgtype.UUID `json:"chat_session_id"`
TaskID pgtype.UUID `json:"task_id"`
SourceContextID pgtype.UUID `json:"source_context_id"`
+ Width pgtype.Int4 `json:"width"`
+ Height pgtype.Int4 `json:"height"`
}
type CreateAttachmentRow struct {
@@ -138,6 +142,8 @@ type CreateAttachmentRow struct {
ChatMessageID pgtype.UUID `json:"chat_message_id"`
TaskID pgtype.UUID `json:"task_id"`
SourceContextID pgtype.UUID `json:"source_context_id"`
+ Width pgtype.Int4 `json:"width"`
+ Height pgtype.Int4 `json:"height"`
IssueRevision int64 `json:"issue_revision"`
CommentRevision int64 `json:"comment_revision"`
}
@@ -157,6 +163,8 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
arg.ChatSessionID,
arg.TaskID,
arg.SourceContextID,
+ arg.Width,
+ arg.Height,
)
var i CreateAttachmentRow
err := row.Scan(
@@ -175,6 +183,8 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
&i.IssueRevision,
&i.CommentRevision,
)
@@ -190,7 +200,7 @@ INSERT INTO attachment (
$4, $5, $6,
$7, $8, $9
)
-RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id
+RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height
`
type CreateSourceContextAttachmentParams struct {
@@ -234,6 +244,8 @@ func (q *Queries) CreateSourceContextAttachment(ctx context.Context, arg CreateS
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
)
return i, err
}
@@ -282,7 +294,7 @@ const deleteAttachmentsBySourceContext = `-- name: DeleteAttachmentsBySourceCont
DELETE FROM attachment
WHERE workspace_id = $1
AND source_context_id = $2
-RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id
+RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height
`
type DeleteAttachmentsBySourceContextParams struct {
@@ -315,6 +327,8 @@ func (q *Queries) DeleteAttachmentsBySourceContext(ctx context.Context, arg Dele
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -376,7 +390,7 @@ SET chat_message_id = NULL
WHERE chat_message_id IN (
SELECT id FROM chat_message WHERE chat_message.task_id = $1 AND role = 'user'
)
-RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id
+RETURNING id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height
`
// When an empty chat task is cancelled, its user message is deleted. The
@@ -409,6 +423,8 @@ func (q *Queries) DetachAttachmentsFromUserChatMessageByTask(ctx context.Context
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -421,7 +437,7 @@ func (q *Queries) DetachAttachmentsFromUserChatMessageByTask(ctx context.Context
}
const getAttachment = `-- name: GetAttachment :one
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE id = $1 AND workspace_id = $2
`
@@ -449,12 +465,14 @@ func (q *Queries) GetAttachment(ctx context.Context, arg GetAttachmentParams) (A
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
)
return i, err
}
const getAttachmentByIDOnly = `-- name: GetAttachmentByIDOnly :one
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE id = $1
`
@@ -483,6 +501,8 @@ func (q *Queries) GetAttachmentByIDOnly(ctx context.Context, id pgtype.UUID) (At
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
)
return i, err
}
@@ -661,7 +681,7 @@ func (q *Queries) ListAttachmentURLsByIssueOrComments(ctx context.Context, issue
}
const listAttachmentsByChatMessage = `-- name: ListAttachmentsByChatMessage :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE chat_message_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -696,6 +716,8 @@ func (q *Queries) ListAttachmentsByChatMessage(ctx context.Context, arg ListAtta
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -708,7 +730,7 @@ func (q *Queries) ListAttachmentsByChatMessage(ctx context.Context, arg ListAtta
}
const listAttachmentsByChatMessageIDs = `-- name: ListAttachmentsByChatMessageIDs :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE chat_message_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -743,6 +765,8 @@ func (q *Queries) ListAttachmentsByChatMessageIDs(ctx context.Context, arg ListA
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -755,7 +779,7 @@ func (q *Queries) ListAttachmentsByChatMessageIDs(ctx context.Context, arg ListA
}
const listAttachmentsByComment = `-- name: ListAttachmentsByComment :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE comment_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -790,6 +814,8 @@ func (q *Queries) ListAttachmentsByComment(ctx context.Context, arg ListAttachme
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -802,7 +828,7 @@ func (q *Queries) ListAttachmentsByComment(ctx context.Context, arg ListAttachme
}
const listAttachmentsByCommentIDs = `-- name: ListAttachmentsByCommentIDs :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE comment_id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -837,6 +863,8 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -849,7 +877,7 @@ func (q *Queries) ListAttachmentsByCommentIDs(ctx context.Context, arg ListAttac
}
const listAttachmentsByIDs = `-- name: ListAttachmentsByIDs :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE id = ANY($1::uuid[]) AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -884,6 +912,8 @@ func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsB
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -896,7 +926,7 @@ func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsB
}
const listAttachmentsByIssue = `-- name: ListAttachmentsByIssue :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at ASC
`
@@ -931,6 +961,8 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -943,7 +975,7 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment
}
const listAttachmentsBySourceContext = `-- name: ListAttachmentsBySourceContext :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE workspace_id = $1
AND source_context_id = $2
ORDER BY created_at ASC, id ASC
@@ -979,6 +1011,8 @@ func (q *Queries) ListAttachmentsBySourceContext(ctx context.Context, arg ListAt
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -1018,7 +1052,7 @@ func (q *Queries) ListSourceContextAttachmentURLsByWorkspace(ctx context.Context
}
const listSourceContextCommentAttachments = `-- name: ListSourceContextCommentAttachments :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE workspace_id = $1
AND issue_id = $2
AND comment_id = ANY($3::uuid[])
@@ -1059,6 +1093,8 @@ func (q *Queries) ListSourceContextCommentAttachments(ctx context.Context, arg L
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -1071,7 +1107,7 @@ func (q *Queries) ListSourceContextCommentAttachments(ctx context.Context, arg L
}
const listSourceContextIssueAttachments = `-- name: ListSourceContextIssueAttachments :many
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE workspace_id = $1
AND issue_id = $2
AND comment_id IS NULL
@@ -1112,6 +1148,8 @@ func (q *Queries) ListSourceContextIssueAttachments(ctx context.Context, arg Lis
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
); err != nil {
return nil, err
}
@@ -1124,7 +1162,7 @@ func (q *Queries) ListSourceContextIssueAttachments(ctx context.Context, arg Lis
}
const lockAttachmentRow = `-- name: LockAttachmentRow :one
-SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id FROM attachment
+SELECT id, workspace_id, issue_id, comment_id, uploader_type, uploader_id, filename, url, content_type, size_bytes, created_at, chat_session_id, chat_message_id, task_id, source_context_id, width, height FROM attachment
WHERE id = $1 AND workspace_id = $2
FOR UPDATE
`
@@ -1157,6 +1195,8 @@ func (q *Queries) LockAttachmentRow(ctx context.Context, arg LockAttachmentRowPa
&i.ChatMessageID,
&i.TaskID,
&i.SourceContextID,
+ &i.Width,
+ &i.Height,
)
return i, err
}
diff --git a/server/pkg/db/generated/attachment_row.go b/server/pkg/db/generated/attachment_row.go
index 3a4a74c350..f2119f5446 100644
--- a/server/pkg/db/generated/attachment_row.go
+++ b/server/pkg/db/generated/attachment_row.go
@@ -18,5 +18,7 @@ func (r CreateAttachmentRow) Attachment() Attachment {
ChatSessionID: r.ChatSessionID,
ChatMessageID: r.ChatMessageID,
TaskID: r.TaskID,
+ Width: r.Width,
+ Height: r.Height,
}
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 883dd94221..c013de83fd 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -205,6 +205,8 @@ type Attachment struct {
ChatMessageID pgtype.UUID `json:"chat_message_id"`
TaskID pgtype.UUID `json:"task_id"`
SourceContextID pgtype.UUID `json:"source_context_id"`
+ Width pgtype.Int4 `json:"width"`
+ Height pgtype.Int4 `json:"height"`
}
type Autopilot struct {
diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sql
index 6dc6492794..b01483d297 100644
--- a/server/pkg/db/queries/attachment.sql
+++ b/server/pkg/db/queries/attachment.sql
@@ -2,11 +2,13 @@
WITH inserted AS (
INSERT INTO attachment (
id, workspace_id, issue_id, comment_id, chat_session_id, task_id, source_context_id,
- uploader_type, uploader_id, filename, url, content_type, size_bytes
+ uploader_type, uploader_id, filename, url, content_type, size_bytes,
+ width, height
)
VALUES (
$1, $2, sqlc.narg(issue_id), sqlc.narg(comment_id), sqlc.narg(chat_session_id), sqlc.narg(task_id), sqlc.narg(source_context_id),
- $3, $4, $5, $6, $7, $8
+ $3, $4, $5, $6, $7, $8,
+ sqlc.narg(width), sqlc.narg(height)
)
RETURNING *
), bumped_issue AS (