Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(gifs): restore media and improve composer pickers (#9370)
dev-rb66bd29c2fa4c
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 36f9d970f9..bc94b5b2fa 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -483,7 +483,8 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to- Keep desktop headers on the shared `ListHeader` / `HeaderActionGroup` pattern: view `Tabs` as pills after the title, `sm`/`icon-sm` semantic islands (28px controls) with 8px gaps on the right, fully rounded frames, New then expandable Search; retain `md` sizing for Tabs, New, and Search. Drive and Tasks list-header filter, layout, sort, and grouping islands use `md`/`icon-md` (32px) to match New and Search. Preserve touch layouts. Compose ButtonGroup actions with explicit `ButtonGroup.Button` segments; use `variant="secondary" finish="raised"` on action frames. Standalone Buttons do not inherit group styling. Pick each control by role from the [design system rule](../../.agents/rules/web/design-system.md); see [UI conventions](../../docs/agent-guide/ui-conventions.md#top-bars). Never use recessed/inset backgrounds in headers.- Keep desktop model and effort controls separate: the model selector opens the catalog and the speedometer opens the runtime's advertised slider stops; retain the mobile effort sheet.- Passive PR mentions must not retry initial GitHub status failures on remount; preserve confirmed status through refetch errors and keep pending data reads out of their parent Suspense boundary.-- PR description and comment images are remote URL images: rewrite GitHub blob/`raw` links to `raw.githubusercontent.com` and load them through the image proxy so COEP does not block github.com. Load Macro's own static-file URLs directly: a composer image reaches the server as Markdown and comes back as a URL image. The proxy authenticates by session cookie, so a proxied `<img>` uses `crossorigin="use-credentials"` and a fetch of it `credentials: 'include'` (`isImageProxyUrl`); `anonymous` drops the cookie cross-origin and the proxy answers 401.+- PR description and comment images are remote URL images: rewrite GitHub blob/`raw` links to `raw.githubusercontent.com` and load them through the image proxy so COEP does not block github.com. Load Macro's own static-file URLs and public Klipy GIFs directly with anonymous CORS, including in the image viewer. The proxy authenticates by session cookie, so a proxied `<img>` uses `crossorigin="use-credentials"` and a fetch of it `credentials: 'include'` (`isImageProxyUrl`); `anonymous` drops the cookie cross-origin and the proxy answers 401.+- Download selected GIFs without re-encoding through the shared abortable static-file uploader, and insert an `sfs` image only after success; preserve the caret, discard failed or unaccepted uploads, reject stale completions, and keep failure retry in the picker. Give explicit GIF picker opens precedence over formatting and link menus, and anchor to the editor when the browser selection is missing or has no rendered geometry.- Keep native booking exit navigation in the route shell, outside page loading boundaries, and use the router so the native hash route stays intact.- Diagnose native full reloads with `native_webview_started`, `native_diagnostic_recovered`, and the shared `frontend_instance_id`; use `reloadApp(reason)` for frontend reloads and keep breadcrumbs content-free. Treat `previous_document_*` checkpoints as last-observed lifecycle evidence, never a crash verdict; clear them on logout. `previous_document_last_*` comes from the native navigation breadcrumb (route and entity type, never ids). See [frontend checkpoints](docs/native-reload-diagnostics.md) and `tauri/src-tauri/README.md`.- Pass `$APPLOCALDATA` (Application Support on Apple platforms) as the native HTTP cookie storage directory; the plugin owns the `.cookies` filename. Never use purgeable caches. The location change intentionally requires one new sign-in, without migration. See `tauri/src-tauri/README.md#native-authentication-cookies`.diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.test.tsxindex b277565f09..4124c147a0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.test.tsx@@ -55,6 +55,22 @@ describe('markdown media loading', () => {);});+ it('loads a selected GIF directly with CORS instead of proxy authentication', () => {+ const src = 'https://static.klipy.com/media/example/medium.gif';+ const view = render(() => (+ <MarkdownImage+ {...unsetMedia}+ key="selected-gif"+ url={src}+ alt="Selected GIF"+ width={320}+ height={240}+ />+ ));+ const image = view.container.querySelector('img')!;+ expect(image.getAttribute('src')).toBe(src);+ expect(image.crossOrigin).toBe('anonymous');+ });it('sends the session cookie to the image proxy', () => {const view = render(() => (<MarkdownImagediff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsxindex 23e5da1f19..e72edce5df 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx@@ -106,9 +106,8 @@ export function MarkdownImage(props: ImageDecoratorProps) {return;}if (props.srcType === 'url') {- // External hosts (GitHub blob screenshots, GIFs) need the image proxy- // under COEP; GitHub blob/`raw` links are rewritten to the raw file host- // first so the proxy fetches bytes, not an HTML redirect page.+ // Public CORS-enabled media loads directly; other external hosts use+ // the proxy after GitHub blob links are rewritten to the raw file host.setImageUrl(displayImageUrl(props.url));return;}@@ -416,7 +415,14 @@ export function MarkdownImage(props: ImageDecoratorProps) {<Dialog.Portal><Dialog.Overlay class="fixed inset-0 z-modal scrim-glass" />- <Lightbox src={imageUrl} imageId={() => props.id} navigationHidden />+ <Lightbox+ src={imageUrl}+ crossOrigin={+ isImageProxyUrl(imageUrl()) ? 'use-credentials' : 'anonymous'+ }+ imageId={() => props.id}+ navigationHidden+ /></Dialog.Portal></Dialog>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsxindex 146ba47d65..f8c8a25bd8 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/ActionsMenu.tsx@@ -335,7 +335,7 @@ export function ActionMenu(props: {<ScopedPortal scope={props.portalScope}><divdata-holds-prompts- class="w-60 cursor-default select-none z-modal-content menu-open-animation"+ class="w-60 mobile:w-[calc(100cqw-1rem-2px)] max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content menu-open-animation"use:floatWithElement={floatWithElementProps()}use:floatWithSelection={floatWithSelectionProps()}use:clickOutside={clickOutsideHandler}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.test.tsxindex 059eaae009..ef52cce214 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.test.tsx@@ -1,16 +1,53 @@/** @vitest-environment jsdom */-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { $createParagraphNode, $getRoot } from 'lexical';-import { createSignal, onCleanup } from 'solid-js';-import { afterEach, expect, it, vi } from 'vitest';+import { setVirtualKeyboardHeight } from '@core/mobile/virtualKeyboard';+import { computePosition } from '@floating-ui/dom';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ $setSelection,+} from 'lexical';+import { err, ok, type Result } from 'neverthrow';+import { createSignal, onCleanup, onMount } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import {+ createMenuOpenSignal,+ FloatingMenuGroup,+ MenuPriority,+} from '../../context/FloatingMenuContext';import {createLexicalWrapper,LexicalWrapperContext,} from '../../context/LexicalWrapperContext';import { TRY_INSERT_GIF_COMMAND } from '../../plugins/gif';+import { FocusClickTarget } from '../core/FocusClickTarget';import { FloatingGifMenu } from './FloatingGifMenu';const insertGif = vi.hoisted(() => vi.fn());+const uploadGif = vi.hoisted(() => vi.fn());+const discardUpload = vi.hoisted(() => vi.fn(async () => {}));+vi.mock('../../plugins/gif/uploadGif', () => ({ uploadGif }));+vi.mock('@core/util/uploadFile', async (original) => ({+ ...(await original<typeof import('@core/util/uploadFile')>()),+ discardStaticUpload: discardUpload,+}));+const touchDevice = vi.hoisted(() => vi.fn(() => false));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: touchDevice,+}));+const nativeMobile = vi.hoisted(() => vi.fn(() => false));+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({+ isNativeMobilePlatform: nativeMobile,+}));vi.mock('../../plugins/gif', async (original) => ({...(await original<typeof import('../../plugins/gif')>()),$insertGifNode: insertGif,@@ -23,10 +60,41 @@ vi.mock('../../plugins/gif', async (original) => ({width: 100,height: 100,},+ {+ id: 'second-gif',+ title: 'Second GIF',+ previewUrl: 'https://example.com/second-preview.gif',+ url: 'https://example.com/second.gif',+ width: 100,+ height: 100,+ },+ {+ id: 'third-gif',+ title: 'Third GIF',+ previewUrl: 'https://example.com/third-preview.gif',+ url: 'https://example.com/third.gif',+ width: 100,+ height: 100,+ },+ {+ id: 'fourth-gif',+ title: 'Fourth GIF',+ previewUrl: 'https://example.com/fourth-preview.gif',+ url: 'https://example.com/fourth.gif',+ width: 100,+ height: 100,+ },],}));-vi.mock('../../directive/floatWithSelection', () => ({- floatWithSelection: vi.fn(),+vi.mock('@floating-ui/dom', async (original) => ({+ ...(await original<typeof import('@floating-ui/dom')>()),+ computePosition: vi.fn(async () => ({+ x: 100,+ y: 200,+ placement: 'top-start',+ strategy: 'fixed',+ middlewareData: {},+ })),}));vi.mock('@service-connection/websocket', () => ({ws: { send() {}, addEventListener() {}, removeEventListener() {} },@@ -40,16 +108,53 @@ vi.mock('@service-storage/websocket', () => ({createWebSocketJob() {},}));+beforeEach(() => {+ uploadGif.mockResolvedValue(ok('static-gif-id'));+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ vi.stubGlobal(+ 'MutationObserver',+ class {+ observe() {}+ disconnect() {}+ }+ );+});+afterEach(() => {cleanup();insertGif.mockClear();+ uploadGif.mockReset();+ discardUpload.mockClear();+ vi.mocked(computePosition).mockClear();+ vi.unstubAllGlobals();+ touchDevice.mockReturnValue(false);+ nativeMobile.mockReturnValue(false);+ setVirtualKeyboardHeight(0);vi.useRealTimers();+ vi.restoreAllMocks();});-function mountPicker() {+function mountPicker(companionPriority?: number) {const [canEdit, setCanEdit] = createSignal(true);+ const leaveComposer = vi.fn();let wrapper: ReturnType<typeof createLexicalWrapper>;- render(() => {+ let companionOpen = () => false;+ function CompanionMenu() {+ [companionOpen] = createMenuOpenSignal(+ 'companion-menu',+ companionPriority ?? MenuPriority.Normal,+ companionPriority !== undefined+ );+ return null;+ }+ const view = render(() => {wrapper = createLexicalWrapper({type: 'markdown',namespace: 'gif-lock-test',@@ -58,12 +163,32 @@ function mountPicker() {onCleanup(wrapper.cleanup);return (<LexicalWrapperContext.Provider value={wrapper}>- <FloatingGifMenu canEdit={canEdit} />+ <FloatingMenuGroup>+ <CompanionMenu />+ <FocusClickTarget+ editor={wrapper.editor}+ onFocusOut={(event) => {+ const next = event.relatedTarget;+ if (next instanceof Node && event.currentTarget.contains(next))+ return;+ leaveComposer();+ }}+ >+ <div+ ref={(element) =>+ onMount(() => wrapper.editor.setRootElement(element))+ }+ contentEditable+ />+ <FloatingGifMenu canEdit={canEdit} />+ </FocusClickTarget>+ </FloatingMenuGroup></LexicalWrapperContext.Provider>);});const editor = wrapper!.editor;const open = () => {+ editor.getRootElement()?.focus();editor.update(() => {$getRoot().append($createParagraphNode());@@ -73,18 +198,321 @@ function mountPicker() {{ discrete: true });};- return { editor, open, setCanEdit };+ return {+ editor,+ open,+ setCanEdit,+ leaveComposer,+ companionOpen,+ unmount: view.unmount,+ };}-it('opens the picker when the editor has no selection', async () => {+it('positions the picker at the editor when there is no selection', async () => {const { editor } = mountPicker();+ window.getSelection()?.removeAllRanges();editor.update(() => {editor.dispatchCommand(TRY_INSERT_GIF_COMMAND, undefined);},{ discrete: true });- expect(await screen.findByRole('searchbox')).toBeTruthy();+ const input = await screen.findByRole('searchbox');+ const panel = input.closest('[data-holds-prompts]')!;+ await waitFor(() => expect(panel).toHaveProperty('style.top', '200px'));+ expect(panel).toHaveProperty('style.visibility', 'visible');+ expect(vi.mocked(computePosition).mock.lastCall?.[0]).toBe(+ editor.getRootElement()+ );+});+it.each([MenuPriority.Normal, MenuPriority.High])(+ 'opens the GIF picker over an existing menu with priority %s',+ async (priority) => {+ const { open, companionOpen } = mountPicker(priority);+ expect(companionOpen()).toBe(true);+ open();+ expect(await screen.findByRole('searchbox')).toBe(document.activeElement);+ expect(companionOpen()).toBe(false);+ }+);++it.each(['element', 'text'])(+ 'keeps the editor %s anchor when search takes focus',+ async (anchorType) => {+ const { editor } = mountPicker();+ editor.update(+ () => {+ const paragraph = $createParagraphNode().append(+ $createTextNode('hello')+ );+ $getRoot().append(paragraph);+ paragraph.selectEnd();+ },+ { discrete: true }+ );+ const root = editor.getRootElement()!;+ root.focus();+ const anchor =+ anchorType === 'text'+ ? document.createTreeWalker(root, NodeFilter.SHOW_TEXT).nextNode()!+ : root;+ const range = document.createRange();+ range.selectNodeContents(anchor);+ range.collapse(false);+ const cloneRange = range.cloneRange.bind(range);+ vi.spyOn(range, 'cloneRange').mockImplementation(() => {+ const snapshot = cloneRange();+ snapshot.getBoundingClientRect = () => new DOMRect(100, 200, 0, 20);+ return snapshot;+ });+ const selection = window.getSelection()!;+ selection.removeAllRanges();+ selection.addRange(range);+ const nativeFocus = HTMLElement.prototype.focus;+ vi.spyOn(HTMLElement.prototype, 'focus').mockImplementation(function (+ this: HTMLElement+ ) {+ nativeFocus.call(this);+ if (this instanceof HTMLInputElement) selection.removeAllRanges();+ });+ editor.dispatchCommand(TRY_INSERT_GIF_COMMAND, undefined);+ const input = screen.getByRole('searchbox');+ expect(document.activeElement).toBe(input);+ const panel = input.closest('[data-holds-prompts]')!;+ await waitFor(() => expect(panel).toHaveProperty('style.top', '200px'));+ expect(panel).toHaveProperty('style.visibility', 'visible');+ const reference = vi.mocked(computePosition).mock.lastCall?.[0];+ if (anchorType === 'text') {+ expect(reference).toBeInstanceOf(Range);+ expect(reference).toMatchObject({+ startContainer: anchor,+ endContainer: anchor,+ startOffset: 5,+ endOffset: 5,+ collapsed: true,+ });+ } else {+ expect(reference).toBe(root);+ }+ }+);++it.each([+ 'empty text',+ 'empty element',+ 'clipped element',+ 'scrolled document',+ 'resized viewport',+ 'native keyboard',+])(+ 'keeps the picker correctly anchored within the viewport for a %s caret',+ async (anchorType) => {+ const floating =+ await vi.importActual<typeof import('@floating-ui/dom')>(+ '@floating-ui/dom'+ );+ const defaultPosition = vi.mocked(computePosition).getMockImplementation();+ vi.mocked(computePosition).mockImplementation(floating.computePosition);+ try {+ const changesViewport =+ anchorType === 'resized viewport' || anchorType === 'native keyboard';+ const editorTop = changesViewport ? 300 : 600;+ let viewportHeight = 768;+ nativeMobile.mockReturnValue(anchorType === 'native keyboard');+ const scrollY = anchorType === 'scrolled document' ? 900 : 0;+ vi.spyOn(window, 'scrollY', 'get').mockReturnValue(scrollY);+ vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(+ 1024+ );+ vi.spyOn(+ document.documentElement,+ 'clientHeight',+ 'get'+ ).mockImplementation(() => viewportHeight);+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(+ function (this: HTMLElement) {+ return this.getBoundingClientRect().width;+ }+ );+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(+ function (this: HTMLElement) {+ return this.getBoundingClientRect().height;+ }+ );+ vi.spyOn(+ HTMLElement.prototype,+ 'getBoundingClientRect'+ ).mockImplementation(function (this: HTMLElement) {+ if (this === document.documentElement)+ return new DOMRect(0, -scrollY, 1024, viewportHeight + scrollY);+ if (this.hasAttribute('contenteditable'))+ return new DOMRect(100, editorTop, 400, 40);+ if (this.hasAttribute('data-holds-prompts'))+ return new DOMRect(+ 0,+ 0,+ 448,+ Math.min(460, Number.parseFloat(this.style.maxHeight || '460'))+ );+ if (this.hasAttribute('data-lexical-text')) {+ if (anchorType === 'clipped element')+ return new DOMRect(100, -50, 100, 20);+ return new DOMRect();+ }+ return new DOMRect(0, 0, 1024, 768);+ });+ const { editor } = mountPicker();+ editor.update(+ () => {+ $getRoot().append(+ $createParagraphNode().append($createTextNode('hello'))+ );+ },+ { discrete: true }+ );+ const text = document+ .createTreeWalker(editor.getRootElement()!, NodeFilter.SHOW_TEXT)+ .nextNode()!;+ const range = document.createRange();+ if (anchorType === 'empty text') range.setStart(text, 5);+ else range.setStart(text.parentElement!, 0);+ range.collapse(true);+ const selection = window.getSelection()!;+ selection.removeAllRanges();+ selection.addRange(range);+ const nativeClone = Range.prototype.cloneRange;+ vi.spyOn(Range.prototype, 'cloneRange').mockImplementation(function (+ this: Range+ ) {+ const snapshot = nativeClone.call(this);+ snapshot.getBoundingClientRect = () => new DOMRect();+ return snapshot;+ });++ editor.dispatchCommand(TRY_INSERT_GIF_COMMAND, undefined);+ const input = await screen.findByRole('searchbox', { hidden: true });+ const panel = input.closest<HTMLElement>('[data-holds-prompts]')!;+ if (anchorType === 'clipped element') {+ await waitFor(() =>+ expect(panel).toHaveProperty('style.visibility', 'hidden')+ );+ return;+ }+ await waitFor(() =>+ expect(panel).toHaveProperty('style.visibility', 'visible')+ );+ if (changesViewport) {+ expect(Number.parseFloat(panel.style.top)).toBeGreaterThan(editorTop);+ if (anchorType === 'native keyboard') setVirtualKeyboardHeight(350);+ else {+ viewportHeight = 400;+ window.dispatchEvent(new Event('resize'));+ }+ await waitFor(() =>+ expect(Number.parseFloat(panel.style.top)).toBeLessThan(editorTop)+ );+ expect(Number.parseFloat(panel.style.maxHeight)).toBeGreaterThan(0);+ expect(Number.parseFloat(panel.style.maxHeight)).toBeLessThan(+ editorTop+ );+ }+ expect(Number.parseFloat(panel.style.top)).toBeGreaterThan(0);+ expect(Number.parseFloat(panel.style.top)).toBeLessThan(600);+ } finally {+ vi.mocked(computePosition).mockImplementation(defaultPosition!);+ }+ }+);++it('ignores an older placement after the keyboard changes again', async () => {+ vi.useFakeTimers();+ const { open } = mountPicker();+ open();+ await vi.runAllTimersAsync();+ const panel = screen+ .getByRole('searchbox')+ .closest<HTMLElement>('[data-holds-prompts]')!;+ const position = vi.mocked(computePosition);+ const original = position.getMockImplementation()!;+ const older =+ Promise.withResolvers<Awaited<ReturnType<typeof computePosition>>>();+ try {+ position.mockImplementationOnce(() => older.promise);+ setVirtualKeyboardHeight(350);+ setVirtualKeyboardHeight(0);+ await vi.runAllTimersAsync();+ expect(panel.style.left).toBe('100px');++ const stalePosition = {+ x: 900,+ y: 900,+ placement: 'bottom-start' as const,+ strategy: 'fixed' as const,+ middlewareData: {},+ };+ position.mockResolvedValue(stalePosition);+ older.resolve(stalePosition);+ await vi.runAllTimersAsync();+ expect(panel.style.left).toBe('100px');+ } finally {+ position.mockImplementation(original);+ }+});+it.each([false, true])(+ 'focuses search during opening and keeps composer clicks out on touch=%s',+ async (touch) => {+ touchDevice.mockReturnValue(touch);+ const { open, leaveComposer } = mountPicker();+ const focus = vi.spyOn(HTMLElement.prototype, 'focus');+ open();+ const input = screen.getByRole('searchbox');+ expect(document.activeElement).toBe(input);+ expect(focus).toHaveBeenLastCalledWith({ preventScroll: true });+ expect(leaveComposer).not.toHaveBeenCalled();++ expect(fireEvent.pointerDown(input)).toBe(true);+ expect(fireEvent.mouseDown(input)).toBe(true);+ expect(fireEvent.click(input)).toBe(true);+ expect(document.activeElement).toBe(input);++ input.blur();+ fireEvent.click(screen.getByRole('group'));+ expect(document.activeElement).toBe(input);+ expect(focus).toHaveBeenLastCalledWith({ preventScroll: true });+ fireEvent.input(input, { target: { value: 'hello' } });+ expect(input).toHaveProperty('value', 'hello');++ fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));+ await waitFor(() => expect(insertGif).toHaveBeenCalledOnce());+ expect(screen.queryByRole('searchbox')).toBeNull();+ }+);++it('preserves native blur and outside focus while search owns composer focus', () => {+ const { editor, open, leaveComposer } = mountPicker();+ const nativeBlur = vi.fn();+ editor.getRootElement()!.addEventListener('blur', nativeBlur);+ render(() => <input aria-label="Outside composer" />);+ open();+ expect(nativeBlur).toHaveBeenCalledOnce();+ expect(leaveComposer).not.toHaveBeenCalled();++ screen.getByRole('textbox', { name: 'Outside composer' }).focus();+ expect(leaveComposer).toHaveBeenCalledOnce();++ editor.getRootElement()!.focus();+ screen.getByRole('textbox', { name: 'Outside composer' }).focus();+ expect(leaveComposer).toHaveBeenCalledTimes(2);+});++it('removes the composer focus guard when the picker closes', () => {+ const { editor, open, leaveComposer } = mountPicker();+ open();+ const input = screen.getByRole('searchbox');+ fireEvent.pointerDown(document.body);+ expect(screen.queryByRole('searchbox')).toBeNull();+ fireEvent.focusOut(editor.getRootElement()!, { relatedTarget: input });+ expect(leaveComposer).toHaveBeenCalledOnce();});it('inserts a GIF when the editor has no saved caret', async () => {@@ -97,16 +525,78 @@ it('inserts a GIF when the editor has no saved caret', async () => {{ discrete: true });fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));- expect(insertGif).toHaveBeenCalledOnce();+ await waitFor(() => expect(insertGif).toHaveBeenCalledOnce());});it('inserts a selected GIF while editing remains allowed', async () => {const { open } = mountPicker();open();fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));- expect(insertGif).toHaveBeenCalledOnce();+ await waitFor(() => expect(insertGif).toHaveBeenCalledOnce());expect(screen.queryByRole('searchbox')).toBeNull();});+it('restores the insertion caret after searching outside the editor', async () => {+ const { editor } = mountPicker();+ editor.update(+ () => {+ const text = $createTextNode('hello');+ $getRoot().append($createParagraphNode().append(text));+ text.select(2, 2);+ editor.dispatchCommand(TRY_INSERT_GIF_COMMAND, undefined);+ },+ { discrete: true }+ );+ const input = screen.getByRole('searchbox');+ fireEvent.click(input);+ fireEvent.input(input, { target: { value: 'hello' } });+ let offset: number | undefined;+ insertGif.mockImplementationOnce(() => {+ const selection = $getSelection();+ if ($isRangeSelection(selection)) offset = selection.anchor.offset;+ });+ fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));+ editor.update(() => $setSelection(null), { discrete: true });+ await waitFor(() => expect(insertGif).toHaveBeenCalledOnce());+ expect(offset).toBe(2);+});++it('steps through grid rows, scrolls only on keyboard movement, and inserts the selected GIF', async () => {+ const { open } = mountPicker();+ open();+ const input = await screen.findByRole('searchbox');+ const first = await screen.findByRole('button', { name: 'Audit GIF' });+ const second = screen.getByRole('button', { name: 'Second GIF' });+ const third = screen.getByRole('button', { name: 'Third GIF' });+ const fourth = screen.getByRole('button', { name: 'Fourth GIF' });+ first.scrollIntoView = vi.fn();+ second.scrollIntoView = vi.fn();+ third.scrollIntoView = vi.fn();+ fourth.scrollIntoView = vi.fn();++ fireEvent.pointerEnter(second);+ expect(second.scrollIntoView).not.toHaveBeenCalled();++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(fourth.scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });++ fireEvent.keyDown(input, { key: 'ArrowUp' });+ expect(second.scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });++ fireEvent.keyDown(input, { key: 'ArrowLeft' });+ expect(first.scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });++ fireEvent.keyDown(input, { key: 'ArrowDown' });+ expect(third.scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });+ // Scrolling can move another result under the pointer during a key press.+ fireEvent.pointerEnter(first);+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() =>+ expect(insertGif).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'third-gif' }),+ 'static-gif-id'+ )+ );+});it('rejects a GIF selection after the editor becomes readonly', async () => {const { editor, open } = mountPicker();@@ -127,7 +617,7 @@ it('closes an open picker when send locking removes edit permission', async () =expect(insertGif).not.toHaveBeenCalled();});-it('does not open a deferred picker after send locking', () => {+it('closes the picker when send locking removes edit permission immediately after opening', () => {vi.useFakeTimers();const { open, setCanEdit } = mountPicker();open();@@ -135,3 +625,102 @@ it('does not open a deferred picker after send locking', () => {vi.runOnlyPendingTimers();expect(screen.queryByRole('searchbox')).toBeNull();});++it('uploads once before inserting, even when Enter repeats during the upload', async () => {+ let resolveUpload!: (id: string) => void;+ const pending = new Promise<Result<string, never>>((resolve) => {+ resolveUpload = (id) => resolve(ok(id));+ });+ uploadGif.mockReturnValueOnce(pending);+ const { open } = mountPicker();+ open();+ const button = await screen.findByRole('button', { name: 'Audit GIF' });+ fireEvent.click(button);+ fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Enter' });+ fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Enter' });+ expect(uploadGif).toHaveBeenCalledOnce();+ expect(button).toHaveProperty('disabled', true);+ expect(insertGif).not.toHaveBeenCalled();+ resolveUpload('uploaded-gif');+ await waitFor(() =>+ expect(insertGif).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'audit-gif' }),+ 'uploaded-gif'+ )+ );+ expect(discardUpload).not.toHaveBeenCalled();+});++it('keeps the picker and caret for retry after upload failure', async () => {+ uploadGif.mockResolvedValueOnce(err({ kind: 'failed' }));+ const { open } = mountPicker();+ open();+ fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));+ await screen.findByRole('alert');+ expect(insertGif).not.toHaveBeenCalled();+ expect(screen.getByRole('searchbox')).toBeTruthy();+ const button = screen.getByRole('button', { name: 'Audit GIF' });+ expect(button).toHaveProperty('disabled', false);+ fireEvent.click(button);+ await waitFor(() => expect(insertGif).toHaveBeenCalledOnce());+ expect(uploadGif).toHaveBeenCalledTimes(2);+});++it.each([+ 'dismissed',+ 'readonly',+ 'permission lost',+ 'disposed',+ 'draft changed',+])(+ 'does not insert a completed upload after the picker is %s',+ async (reason) => {+ let resolveUpload!: (id: string) => void;+ const pending = new Promise<Result<string, never>>((resolve) => {+ resolveUpload = (id) => resolve(ok(id));+ });+ uploadGif.mockReturnValueOnce(pending);+ const { editor, open, setCanEdit, unmount } = mountPicker();+ open();+ fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));+ if (reason === 'dismissed') {+ fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Escape' });+ } else if (reason === 'readonly') {+ editor.setEditable(false);+ } else if (reason === 'permission lost') {+ setCanEdit(false);+ } else if (reason === 'disposed') {+ unmount();+ } else {+ editor.update(() => $getRoot().clear(), { discrete: true });+ }+ resolveUpload('uploaded-gif');+ await pending;+ expect(insertGif).not.toHaveBeenCalled();+ expect(discardUpload).toHaveBeenCalledWith('uploaded-gif');+ }+);++it('ignores a dismissed upload after the picker reopens', async () => {+ let resolveUpload!: (id: string) => void;+ const pending = new Promise<Result<string, never>>((resolve) => {+ resolveUpload = (id) => resolve(ok(id));+ });+ uploadGif.mockReturnValueOnce(pending);+ const { open } = mountPicker();+ open();+ fireEvent.click(await screen.findByRole('button', { name: 'Audit GIF' }));+ fireEvent.keyDown(screen.getByRole('searchbox'), { key: 'Escape' });+ open();+ fireEvent.click(await screen.findByRole('button', { name: 'Second GIF' }));+ await waitFor(() =>+ expect(insertGif).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'second-gif' }),+ 'static-gif-id'+ )+ );+ resolveUpload('old-upload');+ await pending;+ expect(insertGif).toHaveBeenCalledOnce();+ expect(discardUpload).toHaveBeenCalledWith('old-upload');+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.tsxindex de08f9c089..15731cb1a6 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingGifMenu.tsx@@ -1,16 +1,22 @@import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';import clickOutside from '@core/directive/clickOutside';-import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useCanEdit } from '@core/signal/permissions';+import { fireAndForget } from '@core/util/fireAndForget';+import { discardStaticUpload } from '@core/util/uploadFile';+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';import MagnifyingGlassIcon from '@icon/system/regular/magnifying-glass.svg';import { createCallback } from '@solid-primitives/rootless';import { debounce } from '@solid-primitives/scheduled';import { cn, InputGroup, Surface } from '@ui';import {+ $addUpdateTag,+ $getNodeByKey,$getRoot,$getSelection,+ $isRangeSelection,$setSelection,type BaseSelection,+ SKIP_DOM_SELECTION_TAG,} from 'lexical';import {type Accessor,@@ -19,6 +25,8 @@ import {createSignal,For,Match,+ onCleanup,+ onMount,Show,Switch,untrack,@@ -37,6 +45,8 @@ import {searchGifs,} from '../../plugins/gif';import PoweredByKlipy from '../../plugins/gif/powered-by-klipy.svg';+import { uploadGif } from '../../plugins/gif/uploadGif';+import { registerRootEventListener } from '../../plugins/shared/utils';import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';false && floatWithSelection;@@ -45,15 +55,15 @@ false && clickOutside;const COLUMNS = 2;const RESULT_LIMIT = 30;// Search field, padding, and "Powered by" row around the grid.-const PANEL_CHROME_HEIGHT = 76;-const MAX_GRID_HEIGHT = 280;+const PANEL_CHROME_HEIGHT = 100;+const MAX_GRID_HEIGHT = 360;/*** GIF search, opened via TRY_INSERT_GIF_COMMAND (`/gif` or a composer's +).- * Desktop focuses the search field; touch leaves the composer focused so the- * picker does not vanish. Arrows move through the grid, Enter inserts,- * Escape closes. Portalled like the slash menu so the editor shell's click- * and keydown handlers don't swallow the picker's events.+ * Focuses search on open while keeping the insertion caret in the editor.+ * Arrows move through the grid, Enter inserts, Escape closes. Portalled like+ * the slash menu, with an event boundary so composer handlers cannot steal+ * focus from search.*/export function FloatingGifMenu(props: { canEdit?: Accessor<boolean>; portalScope?: PortalScope } = {}@@ -65,13 +75,16 @@ export function FloatingGifMenu(const [menuOpen, setMenuOpen] = createMenuOpenSignal('gif-picker-menu',- MenuPriority.Low,+ MenuPriority.High,false);const [searchTerm, setSearchTerm] = createSignal('');const [debouncedSearchTerm, setDebouncedSearchTerm] = createSignal('');const [selectedIndex, setSelectedIndex] = createSignal(0);+ const [uploading, setUploading] = createSignal(false);+ const [uploadError, setUploadError] = createSignal(false);+ let uploadController: AbortController | undefined;const [menuAvailableHeight, setMenuAvailableHeight] = createSignal<number | undefined>(undefined);@@ -87,6 +100,7 @@ export function FloatingGifMenu(// The search field takes focus, so the editor's caret is kept to insert at.let insertAt: BaseSelection | null = null;let inputRef: HTMLInputElement | undefined;+ let gridRef: HTMLDivElement | undefined;const debouncedSetSearch = debounce(setDebouncedSearchTerm, 300);const updateSearch = (term: string) => {@@ -101,7 +115,15 @@ export function FloatingGifMenu();const gifList = () => (gifs.state === 'ready' ? gifs() : []);+ const cancelUpload = () => {+ uploadController?.abort();+ uploadController = undefined;+ setUploading(false);+ };+const resetMenu = () => {+ cancelUpload();+ setUploadError(false);setMenuOpen(false);debouncedSetSearch.clear();setSearchTerm('');@@ -122,30 +144,78 @@ export function FloatingGifMenu(return;}insertAt = $getSelection()?.clone() ?? null;- // Defer past the keystroke that ran the command, as FloatingTableMenu does.- setTimeout(() => {- if (!canEdit() || !editor()?.isEditable()) return;- setMenuOpen(true);- // Autofocusing search on touch moves focus out of the composer and- // lets iOS hide the caret — the picker then vanishes. Tap to search.- if (!isTouchDevice()) inputRef?.focus();- }, 0);+ // Keep Lexical's commit from reclaiming focus after the command returns.+ $addUpdateTag(SKIP_DOM_SELECTION_TAG);+ setMenuOpen(true);});- const insertGif = (gif: Gif) => {+ const insertGif = async (gif: Gif) => {+ if (uploading()) return;const currentEditor = editor();if (!canEdit() || !currentEditor?.isEditable()) {resetMenu();return;}- const selection = insertAt;- currentEditor.update(() => {- if (!canEdit() || !currentEditor.isEditable()) return;- if (selection) $setSelection(selection.clone());- else if (!$getSelection()) $getRoot().selectEnd();- $insertGifNode(gif);- });- closeToEditor();+ const selection = insertAt?.clone();+ const root = currentEditor.getRootElement();+ const request = new AbortController();+ uploadController = request;+ setUploading(true);+ let uploadedId: string | undefined;+ let inserted = false;+ setUploadError(false);+ const unregisterUpdate = currentEditor.registerUpdateListener(+ ({ dirtyElements, dirtyLeaves }) => {+ if (dirtyElements.size || dirtyLeaves.size) resetMenu();+ }+ );+ request.signal.addEventListener('abort', unregisterUpdate, { once: true });+ try {+ const result = await uploadGif(gif, request.signal);+ if (result.isErr()) {+ if (!request.signal.aborted && result.error.kind === 'failed') {+ setUploadError(true);+ }+ return;+ }+ uploadedId = result.value;+ if (+ request.signal.aborted ||+ !menuOpen() ||+ !canEdit() ||+ !currentEditor.isEditable() ||+ currentEditor !== editor() ||+ root !== currentEditor.getRootElement()+ )+ return;++ currentEditor.update(+ () => {+ // A cleared draft must not receive the old request's image.+ if (+ selection &&+ $isRangeSelection(selection) &&+ (!$getNodeByKey(selection.anchor.key)?.isAttached() ||+ !$getNodeByKey(selection.focus.key)?.isAttached())+ )+ return;+ if (selection) $setSelection(selection);+ else if (!$getSelection()) $getRoot().selectEnd();+ $insertGifNode(gif, result.value);+ inserted = true;+ },+ { discrete: true }+ );+ closeToEditor();+ } finally {+ request.signal.removeEventListener('abort', unregisterUpdate);+ unregisterUpdate();+ if (uploadController === request) {+ uploadController = undefined;+ setUploading(false);+ }+ if (uploadedId && !inserted) await discardStaticUpload(uploadedId);+ }};createEffect(() => {@@ -162,12 +232,17 @@ export function FloatingGifMenu(});});+ const { isKeypressActive } = useIsKeyPressActive();+ const selectFromPointer = (index: number) => {+ if (!isKeypressActive()) setSelectedIndex(index);+ };+const moveSelection = (delta: number) => {const lastIndex = gifList().length - 1;if (lastIndex < 0) return;- setSelectedIndex((index) =>- Math.min(lastIndex, Math.max(0, index + delta))- );+ const nextIndex = Math.min(lastIndex, Math.max(0, selectedIndex() + delta));+ setSelectedIndex(nextIndex);+ gridRef?.children[nextIndex]?.scrollIntoView({ block: 'nearest' });};useMenuKeyboardNavigation({@@ -178,7 +253,7 @@ export function FloatingGifMenu(onRight: () => moveSelection(1),onSelect: () => {const gif = gifList()[selectedIndex()];- if (gif) insertGif(gif);+ if (gif) fireAndForget(insertGif(gif), 'gif-picker');},onClose: closeToEditor,});@@ -187,10 +262,28 @@ export function FloatingGifMenu(<Show when={menuOpen()}><ScopedPortal scope={props.portalScope}><div+ ref={(panel) => {+ const currentEditor = editor();+ if (!currentEditor) return;+ onCleanup(cancelUpload);+ // Search belongs to this composer even though its DOM is portalled.+ onCleanup(+ registerRootEventListener(currentEditor, 'focusout', (event) => {+ if (+ event.relatedTarget instanceof Node &&+ panel.contains(event.relatedTarget)+ ) {+ event.stopPropagation();+ }+ })+ );+ }}data-holds-prompts- class="w-80 cursor-default select-none z-modal-content menu-open-animation"+ data-keep-keyboard+ class="w-[28rem] mobile:w-[calc(100cqw-1rem-2px)] max-w-[calc(100cqw-1rem-2px)] cursor-default select-none z-modal-content menu-open-animation"use:floatWithSelection={{selection: untrack(() => window.getSelection()),+ fallbackElement: editor()?.getRootElement(),reactiveOnContainer: editor()?.getRootElement(),onAvailableHeight: setMenuAvailableHeight,fullHeight: MAX_GRID_HEIGHT + PANEL_CHROME_HEIGHT,@@ -201,16 +294,33 @@ export function FloatingGifMenu(// pointerdown and mousedown; iOS still emits the latter.on:pointerdown={(event) => {if (event.target !== inputRef) event.preventDefault();+ event.stopPropagation();}}on:mousedown={(event) => {if (event.target !== inputRef) event.preventDefault();+ event.stopPropagation();}}+ onClick={(event) => event.stopPropagation()}>- <Surface depth={2} class="menu-surface flex flex-col gap-1.5 p-1.5">- <InputGroup size="sm">+ <Surface+ depth={2}+ hideBorder+ class="menu-surface rounded-xl flex flex-col gap-1.5 p-1.5"+ >+ <InputGroup+ size="xl"+ onClick={() => inputRef?.focus({ preventScroll: true })}+ ><InputGroup.Input- ref={inputRef}+ ref={(element) => {+ inputRef = element;+ onMount(() => {+ if (menuOpen() && canEdit())+ element.focus({ preventScroll: true });+ });+ }}type="search"+ readOnly={uploading()}value={searchTerm()}onInput={(event) => updateSearch(event.currentTarget.value)}placeholder="Search KLIPY"@@ -222,7 +332,7 @@ export function FloatingGifMenu(</InputGroup><div- class="overflow-y-auto overscroll-contain scrollbar-hidden"+ class="overflow-y-auto overscroll-contain scrollbar-hidden scroll-p-1"style={{ height: `${gridMaxHeight()}px` }}><Switch>@@ -249,20 +359,27 @@ export function FloatingGifMenu(</div></Match><Match when={true}>- <div class="grid grid-cols-2 auto-rows-24 gap-1.5 p-0.5">+ <div+ ref={gridRef}+ class="grid grid-cols-2 auto-rows-28 gap-1.5 p-1"+ ><For each={gifList()}>{(gif, index) => (<buttontype="button"+ disabled={uploading()}aria-label={gif.title}- onClick={() => insertGif(gif)}- onPointerEnter={() => setSelectedIndex(index())}+ onClick={() =>+ fireAndForget(insertGif(gif), 'gif-picker')+ }+ onPointerEnter={() => selectFromPointer(index())}class={cn(- 'size-full overflow-hidden rounded-lg bg-ink/5 outline-none',+ 'size-full overflow-hidden rounded-lg bg-ink/5 outline-none disabled:opacity-50',selectedIndex() === index() && 'ring-2 ring-accent')}><img+ crossorigin="anonymous"src={gif.previewUrl}alt=""loading="lazy"@@ -276,7 +393,13 @@ export function FloatingGifMenu(</Switch></div>- <div class="flex justify-end px-1">+ <div class="flex items-center justify-between gap-2 px-1">+ <div class="text-xs text-ink-muted" aria-live="polite">+ <Show when={uploading()}>Uploading GIF…</Show>+ <Show when={uploadError()}>+ <span role="alert">Couldn't insert GIF. Try again.</span>+ </Show>+ </div><PoweredByKlipyclass="h-2.5 w-auto text-ink-extra-muted"aria-label="Powered by KLIPY"diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts b/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.tsindex 92621ced3b..7c2710d2bc 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts@@ -1,4 +1,5 @@import { isInBlock } from '@core/block';+import { virtualKeyboardHeight } from '@core/mobile/virtualKeyboard';import { blockElementSignal } from '@core/signal/blockElement';import { getScrollParent } from '@core/util/scrollParent';import {@@ -17,7 +18,7 @@ import {} from '@floating-ui/dom';import { Telemetry } from '@macro-inc/observability';import type { Accessor, JSX } from 'solid-js';-import { createEffect, createSignal, onCleanup, onMount } from 'solid-js';+import { createEffect, createSignal, on, onCleanup, onMount } from 'solid-js';import { iosSafePadding, iosSizeMiddleware } from './iosFloatingMiddleware';const DEFAULT_SPACING = 8;@@ -36,6 +37,8 @@ function style(el: HTMLElement, styles: Partial<JSX.CSSProperties>) {type FloatWithSelectionOptions = {selection: Selection | undefined | null;+ /** Use this anchor when the browser selection is missing or has no geometry. */+ fallbackElement?: Element | null;reactiveOnContainer?: HTMLElement | null;useBlockBoundary?: boolean;spacing?: number;@@ -110,8 +113,15 @@ export function floatWithSelection(null);let decidedPlacement: Placement | null = null;+ let positionVersion = 0;function toReference(anchor: Range | Element): ReferenceElement {+ const fallback = accessor()?.fallbackElement;+ if (fallback) {+ const rect = anchor.getBoundingClientRect();+ // Removing an inline command can leave a caret with no geometry.+ if (rect.width === 0 && rect.height === 0) return fallback;+ }return accessor()?.clipToVisible && anchor instanceof Range? visibleRangeReference(anchor): anchor;@@ -124,6 +134,7 @@ export function floatWithSelection() {let room = 0;await computePosition(toReference(anchor), floatingEl, {+ strategy: 'fixed',placement,middleware: [offset(spacing),@@ -154,10 +165,9 @@ export function floatWithSelection(async function setInitialFloatingPosition(selection: Selection | null | undefined) {- if (!selection) return;- let anchor: Range | Element | null = null;+ let anchor: Range | Element | null = accessor()?.fallbackElement ?? null;- if (selection.rangeCount >= 1) {+ if (selection && selection.rangeCount >= 1) {// Snapshot the caret. getRangeAt() is live, so focusing a picker// search field would rewrite this anchor and hide() the menu.const range = selection.getRangeAt(0).cloneRange();@@ -168,7 +178,7 @@ export function floatWithSelection(} else {anchor = range;}- } else if (selection.anchorNode instanceof Element) {+ } else if (selection?.anchorNode instanceof Element) {anchor = selection.anchorNode;}@@ -177,7 +187,6 @@ export function floatWithSelection(const spacing = accessor()?.spacing ?? DEFAULT_SPACING;const fullHeight = accessor()?.fullHeight;if (fullHeight !== undefined) {- decidedPlacement = await sideWithRoomFor(anchor, fullHeight, spacing);await updatePosition();return;}@@ -204,6 +213,7 @@ export function floatWithSelection(hide(),],...floatingOptions,+ strategy: 'fixed',});@@ -214,15 +224,24 @@ export function floatWithSelection(async function updatePosition() {let current = currentAnchor();- if (!current || !decidedPlacement) return;+ if (!current) return;+ const version = ++positionVersion;const spacing = accessor()?.spacing ?? DEFAULT_SPACING;+ const fullHeight = accessor()?.fullHeight;+ if (fullHeight !== undefined) {+ const placement = await sideWithRoomFor(current, fullHeight, spacing);+ if (version !== positionVersion) return;+ decidedPlacement = placement;+ }+ if (!decidedPlacement) return;const onAvailableHeight = accessor()?.onAvailableHeight;const { x, y, middlewareData } = await computePosition(toReference(current),floatingEl,{placement: decidedPlacement,+ strategy: 'fixed',middleware: [offset(spacing),shift({ padding: iosSafePadding(spacing), boundary }),@@ -233,6 +252,7 @@ export function floatWithSelection(],});+ if (version !== positionVersion) return;style(floatingEl, {left: `${x}px`,@@ -298,6 +318,9 @@ export function floatWithSelection(}});+ createEffect(+ on(virtualKeyboardHeight, repositionInBackground, { defer: true })+ );createEffect(() => {cleanupAutoUpdate();const reference = currentAnchor();@@ -318,6 +341,7 @@ export function floatWithSelection(});onCleanup(() => {+ positionVersion++;document.removeEventListener('selectionchange', selectionChangeHandler);scrollParent?.removeEventListener('scroll', scrollHandler);resizeObserver.disconnect();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.test.tsnew file mode 100644index 0000000000..078b481051--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.test.ts@@ -0,0 +1,86 @@+import { staticFileIdEndpoint } from '@core/constant/servers';+import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';+import { ImageNode, SupportedNodeTypes } from '@macro-inc/lexical-core';+import { $createParagraphNode, $getRoot, createEditor } from 'lexical';+import { expect, it } from 'vitest';+import { $insertGifNode } from './gifPlugin';+import type { Gif } from './klipy';++it('preserves static-file GIFs through JSON and HTML copying', () => {+ const editor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ const gif: Gif = {+ id: 'gif-1',+ title: 'Animated GIF',+ previewUrl: 'https://media.example/preview.gif',+ url: 'https://media.example/animation.gif',+ width: 640,+ height: 480,+ };++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ $getRoot().append(paragraph);+ paragraph.select();+ $insertGifNode(gif, 'static-1');+ },+ { discrete: true }+ );++ const image = editor.read(() =>+ $getRoot()+ .getChildren()+ .find((node) => node instanceof ImageNode)+ );+ expect(image).toBeInstanceOf(ImageNode);+ const serialized = editor.getEditorState().toJSON().root.children;+ expect(serialized).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: 'image',+ srcType: 'sfs',+ id: 'static-1',+ url: staticFileIdEndpoint('static-1'),+ alt: gif.title,+ width: 640,+ height: 480,+ constrainedWidth: 400,+ constrainedHeight: 300,+ }),+ ])+ );++ const html = editor.read(() => $generateHtmlFromNodes(editor));+ const document = new DOMParser().parseFromString(html, 'text/html');+ expect(document.querySelector('img')?.getAttribute('src')).toBe(+ staticFileIdEndpoint('static-1')+ );+ const pastedEditor = createEditor({+ nodes: SupportedNodeTypes,+ onError(error) {+ throw error;+ },+ });+ pastedEditor.update(+ () => {+ $getRoot().append(...$generateNodesFromDOM(pastedEditor, document));+ },+ { discrete: true }+ );+ expect(pastedEditor.getEditorState().toJSON().root.children).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ type: 'image',+ srcType: 'sfs',+ id: 'static-1',+ url: staticFileIdEndpoint('static-1'),+ alt: gif.title,+ }),+ ])+ );+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.tsindex 2af099b657..5257f2cbe3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/gifPlugin.ts@@ -1,3 +1,4 @@+import { staticFileIdEndpoint } from '@core/constant/servers';import { $createImageNode, ImageNode } from '@macro-inc/lexical-core';import {COMMAND_PRIORITY_NORMAL,@@ -39,11 +40,12 @@ export function gifPickerPlugin(props: GifPickerPluginProps) {return (editor: LexicalEditor) => registerGifPickerPlugin(editor, props);}-export function $insertGifNode(gif: Gif) {+export function $insertGifNode(gif: Gif, staticFileId: string) {const width = Math.min(gif.width, MAX_GIF_WIDTH);const imageNode = $createImageNode({- srcType: 'url',- url: gif.url,+ srcType: 'sfs',+ id: staticFileId,+ url: staticFileIdEndpoint(staticFileId),alt: gif.title,width: gif.width,height: gif.height,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.test.tsnew file mode 100644index 0000000000..b44d227f40--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.test.ts@@ -0,0 +1,139 @@+import { Blob as BufferBlob, File as BufferFile } from 'node:buffer';+import { createStaticUploadFile } from '@core/util/uploadFile';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { Gif } from './klipy';+import { uploadGif } from './uploadGif';++vi.mock('@core/util/uploadFile', () => ({+ createStaticUploadFile: vi.fn(),+ createUploadFile: (file: File) => ({ file }),+}));+vi.mock('@macro-inc/observability', () => ({+ Telemetry: {+ span: (_name: string, operation: (span: unknown) => unknown) =>+ operation({+ setAttr: vi.fn(),+ error: vi.fn(),+ span: (_childName: string, child: () => unknown) => child(),+ }),+ },+}));++const gif: Gif = {+ id: 'gif-1',+ title: 'Animated GIF',+ previewUrl: 'https://media.example/preview.gif',+ url: 'https://media.example/animation.gif',+ width: 640,+ height: 480,+};++beforeEach(() => {+ vi.stubGlobal('File', BufferFile);+ vi.mocked(createStaticUploadFile).mockReset();+});++afterEach(() => {+ vi.unstubAllGlobals();+});++it.each(['GIF87a', 'GIF89a'])(+ 'uploads original %s bytes to static storage',+ async (signature) => {+ // Two image descriptors keep this fixture animated rather than a static GIF.+ const bytes = new Uint8Array(+ Buffer.concat([+ Buffer.from(signature),+ Buffer.from(+ '01000100800000000000ffffff2c00000000010001000002024401002c00000000010001000002024401003b',+ 'hex'+ ),+ ])+ );+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: true,+ blob: () =>+ Promise.resolve(new BufferBlob([bytes], { type: 'image/gif' })),+ })+ );+ vi.mocked(createStaticUploadFile).mockResolvedValue('static-1');+ const controller = new AbortController();++ const result = await uploadGif(gif, controller.signal);+ expect(result._unsafeUnwrap()).toBe('static-1');++ expect(fetch).toHaveBeenCalledWith(gif.url, {+ signal: controller.signal,+ credentials: 'omit',+ });+ expect(createStaticUploadFile).toHaveBeenCalledOnce();+ const [source, signal] = vi.mocked(createStaticUploadFile).mock.calls[0];+ const file = source.file;+ expect(signal).toBe(controller.signal);+ expect(file.name).toBe('animation.gif');+ expect(file.type).toBe('image/gif');+ expect(new Uint8Array(await file.arrayBuffer())).toEqual(bytes);+ }+);++it('does not upload when the download returns an HTTP error', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 403 }));++ const result = await uploadGif(gif, new AbortController().signal);+ expect(result._unsafeUnwrapErr()).toEqual({ kind: 'failed' });+ expect(createStaticUploadFile).not.toHaveBeenCalled();+});++it('does not upload media without a GIF signature', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: true,+ blob: () =>+ Promise.resolve(+ new BufferBlob(['<html>not a gif</html>'], { type: 'image/gif' })+ ),+ })+ );++ const result = await uploadGif(gif, new AbortController().signal);+ expect(result._unsafeUnwrapErr()).toEqual({ kind: 'failed' });+ expect(createStaticUploadFile).not.toHaveBeenCalled();+});++it('propagates upload failure without returning a static file ID', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: true,+ blob: () => Promise.resolve(new BufferBlob(['GIF89a', '\0'])),+ })+ );+ const error = new Error('Static upload failed');+ vi.mocked(createStaticUploadFile).mockRejectedValue(error);++ const result = await uploadGif(gif, new AbortController().signal);+ expect(result._unsafeUnwrapErr()).toEqual({ kind: 'failed' });+ expect(createStaticUploadFile).toHaveBeenCalledOnce();+});++it('does not upload when cancelled during the download', async () => {+ const download = Promise.withResolvers<BufferBlob>();+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue({+ ok: true,+ blob: () => download.promise,+ })+ );+ const controller = new AbortController();+ const result = uploadGif(gif, controller.signal);++ controller.abort();+ download.resolve(new BufferBlob(['GIF89a', '\0']));++ expect((await result)._unsafeUnwrapErr()).toEqual({ kind: 'cancelled' });+ expect(createStaticUploadFile).not.toHaveBeenCalled();+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.tsnew file mode 100644index 0000000000..a7973347c3--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/gif/uploadGif.ts@@ -0,0 +1,48 @@+import {+ createStaticUploadFile,+ createUploadFile,+} from '@core/util/uploadFile';+import { Telemetry } from '@macro-inc/observability';+import { ResultAsync } from 'neverthrow';+import type { Gif } from './klipy';++type GifUploadError = { kind: 'cancelled' } | { kind: 'failed' };+/** Keep the original animated bytes; never decode through an image or canvas. */+export function uploadGif(+ gif: Gif,+ signal: AbortSignal+): ResultAsync<string, GifUploadError> {+ return ResultAsync.fromPromise(+ Telemetry.span('gif.upload', async (span) => {+ span.setAttr('gif.id', gif.id);+ try {+ const file = await span.span('gif.download', async () => {+ const response = await fetch(gif.url, {+ signal,+ credentials: 'omit',+ });+ if (!response.ok)+ throw new Error(`GIF download failed: ${response.status}`);+ const blob = await response.blob();+ const signature = await blob.slice(0, 6).text();+ if (signature !== 'GIF87a' && signature !== 'GIF89a') {+ throw new Error('The download is not a GIF');+ }+ span.setAttr('file.size', blob.size);+ return new File([blob], 'animation.gif', { type: 'image/gif' });+ });+ signal.throwIfAborted();+ const id = await span.span('gif.static_upload', () =>+ createStaticUploadFile(createUploadFile(file), signal)+ );+ span.setAttr('file.id', id);+ return id;+ } catch (error) {+ if (signal.aborted) span.setAttr('gif.cancelled', true);+ else span.error(error);+ throw error;+ }+ }),+ () => ({ kind: signal.aborted ? 'cancelled' : 'failed' })+ );+}diff --git a/apps/web/src/lib/core/component/Lightbox/Lightbox.tsx b/apps/web/src/lib/core/component/Lightbox/Lightbox.tsxindex a6ec002b3b..78414e7ec3 100644--- a/apps/web/src/lib/core/component/Lightbox/Lightbox.tsx+++ b/apps/web/src/lib/core/component/Lightbox/Lightbox.tsx@@ -34,6 +34,8 @@ const SpinnerIcon: Component<JSX.SvgSVGAttributes<SVGSVGElement>> = (p) => (type LightboxProps = {// Current image to displaysrc: Accessor<string | undefined>;+ // Match the source image's CORS mode when the host does not supply CORP.+ crossOrigin?: JSX.ImgHTMLAttributes<HTMLImageElement>['crossorigin'];// Used for the download filenameimageId: Accessor<string>;// Optional pre-fetched blob override (e.g. DSS images). Falls back to fetching `src`.@@ -182,6 +184,7 @@ export function Lightbox(props: LightboxProps) {}><img+ crossorigin={props.crossOrigin}class="size-full sm:min-w-50 sm:max-h-[80vh] object-contain select-none"style={{ '-webkit-touch-callout': 'none' }}src={props.src()}diff --git a/apps/web/src/lib/core/util/imageProxy.test.ts b/apps/web/src/lib/core/util/imageProxy.test.tsindex 85a0ba1236..7fa19f796b 100644--- a/apps/web/src/lib/core/util/imageProxy.test.ts+++ b/apps/web/src/lib/core/util/imageProxy.test.ts@@ -54,6 +54,18 @@ describe('displayImageUrl', () => {expect(displayImageUrl(src)).toBe(src);});+ it('loads public Klipy GIFs directly without proxy authentication', () => {+ const src = 'https://static.klipy.com/media/example/medium.gif';+ expect(displayImageUrl(src)).toBe(src);+ });++ it('does not bypass the proxy for a host impersonating Klipy', () => {+ const src = 'https://static.klipy.com.example.com/medium.gif';+ expect(displayImageUrl(src)).toBe(+ `${SERVER_HOSTS['image-proxy-service']}/proxy?url=${encodeURIComponent(src)}`+ );+ });+it('proxies a host that only begins like the static file host', () => {const src = `${SERVER_HOSTS['static-file']}.example.com/shot.png`;expect(displayImageUrl(src)).toBe(diff --git a/apps/web/src/lib/core/util/imageProxy.ts b/apps/web/src/lib/core/util/imageProxy.tsindex b2d3e56935..bb135bba69 100644--- a/apps/web/src/lib/core/util/imageProxy.ts+++ b/apps/web/src/lib/core/util/imageProxy.ts@@ -48,9 +48,14 @@ export function proxyImageUrl(src: string): string {/** URL to put on an `<img>` for a remote markdown image. */export function displayImageUrl(src: string): string {- // Markdown import turns a pasted image into a plain URL. Static files are- // public and send their own CORS headers, so they skip the proxy.- if (src.startsWith(`${SERVER_HOSTS['static-file']}/`)) return src;+ // Static files and Klipy's GIF CDN are public and send their own CORS+ // headers, so they do not need the authenticated proxy.+ if (+ src.startsWith(`${SERVER_HOSTS['static-file']}/`) ||+ src.startsWith('https://static.klipy.com/')+ ) {+ return src;+ }return proxyImageUrl(githubRawImageUrl(src));}diff --git a/apps/web/src/lib/core/util/uploadFile.test.ts b/apps/web/src/lib/core/util/uploadFile.test.tsnew file mode 100644index 0000000000..9d07ea6685--- /dev/null+++ b/apps/web/src/lib/core/util/uploadFile.test.ts@@ -0,0 +1,166 @@+import { fetchWithToken } from '@core/util/fetchWithToken';+import { platformFetch } from '@core/util/platformFetch';+import { ok } from 'neverthrow';+import { beforeEach, expect, it, vi } from 'vitest';+import { createStaticUploadFile, createUploadFile } from './uploadFile';++vi.mock('@core/mobile/nativeStagedUpload', () => ({+ getNativeStagedUpload: () => undefined,+ uploadNativeStagedFileToPresignedUrl: vi.fn(),+}));+vi.mock('@queries/auth', () => ({ invalidateUserQuota: async () => {} }));+vi.mock('@core/util/fetchWithToken', () => ({ fetchWithToken: vi.fn() }));+vi.mock('@core/util/platformFetch', () => ({ platformFetch: vi.fn() }));++beforeEach(() => {+ vi.mocked(fetchWithToken).mockReset();+ vi.mocked(platformFetch).mockReset();+ vi.mocked(fetchWithToken).mockResolvedValue(+ ok({+ id: 'static-gif',+ upload_url: 'https://storage.example/put',+ })+ );+});++it('keeps the reservation readable and forwards cancellation to the PUT', async () => {+ vi.mocked(platformFetch).mockResolvedValue(+ new Response(null, { status: 200 })+ );+ const controller = new AbortController();+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );++ await expect(createStaticUploadFile(file, controller.signal)).resolves.toBe(+ 'static-gif'+ );++ expect(fetchWithToken).toHaveBeenCalledOnce();+ expect(fetchWithToken).toHaveBeenCalledWith(+ expect.stringContaining('/api/file'),+ {+ method: 'PUT',+ body: JSON.stringify({+ file_name: 'animation.gif',+ content_type: 'image/gif',+ }),+ }+ );+ expect(platformFetch).toHaveBeenCalledWith('https://storage.example/put', {+ method: 'PUT',+ body: file.file,+ headers: { 'Content-Type': 'image/gif' },+ signal: controller.signal,+ });+});++it.each(['response', 'network'])(+ 'deletes the reserved static file when a PUT fails with a %s error',+ async (failure) => {+ if (failure === 'response') {+ vi.mocked(platformFetch).mockResolvedValue(+ new Response(null, { status: 500 })+ );+ } else {+ vi.mocked(platformFetch).mockRejectedValue(+ new Error('Network unavailable')+ );+ }+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );++ await expect(createStaticUploadFile(file)).rejects.toThrow(+ failure === 'response' ? 'Failed to upload file' : 'Network unavailable'+ );+ expect(fetchWithToken).toHaveBeenLastCalledWith(+ expect.stringContaining('/api/file/static-gif'),+ { method: 'DELETE' }+ );+ }+);++it('aborts an in-flight PUT and deletes its reserved static file', async () => {+ const started = Promise.withResolvers<void>();+ vi.mocked(platformFetch).mockImplementation(+ (_url, options) =>+ new Promise((_resolve, reject) => {+ options?.signal?.addEventListener(+ 'abort',+ () => reject(new DOMException('Cancelled', 'AbortError')),+ { once: true }+ );+ started.resolve();+ })+ );+ const controller = new AbortController();+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );+ const upload = createStaticUploadFile(file, controller.signal);+ await started.promise;+ controller.abort();++ await expect(upload).rejects.toMatchObject({ name: 'AbortError' });+ expect(fetchWithToken).toHaveBeenCalledTimes(2);+ expect(fetchWithToken).toHaveBeenLastCalledWith(+ expect.stringContaining('/api/file/static-gif'),+ { method: 'DELETE' }+ );+});++it('cleans up when cancellation races a successful PUT response', async () => {+ const controller = new AbortController();+ vi.mocked(platformFetch).mockImplementation(async () => {+ controller.abort();+ return new Response(null, { status: 200 });+ });+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );++ await expect(+ createStaticUploadFile(file, controller.signal)+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(fetchWithToken).toHaveBeenLastCalledWith(+ expect.stringContaining('/api/file/static-gif'),+ { method: 'DELETE' }+ );+});++it('does not reserve storage for an already cancelled upload', async () => {+ const controller = new AbortController();+ controller.abort();+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );++ await expect(+ createStaticUploadFile(file, controller.signal)+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(fetchWithToken).not.toHaveBeenCalled();+ expect(platformFetch).not.toHaveBeenCalled();+});++it('waits for a cancelled reservation and deletes it without uploading', async () => {+ const reservation =+ Promise.withResolvers<Awaited<ReturnType<typeof fetchWithToken>>>();+ vi.mocked(fetchWithToken).mockReturnValueOnce(reservation.promise);+ const controller = new AbortController();+ const file = createUploadFile(+ new File(['GIF89a'], 'animation.gif', { type: 'image/gif' })+ );+ const upload = createStaticUploadFile(file, controller.signal);+ controller.abort();+ reservation.resolve(+ ok({ id: 'static-gif', upload_url: 'https://storage.example/put' })+ );++ await expect(upload).rejects.toMatchObject({ name: 'AbortError' });+ expect(platformFetch).not.toHaveBeenCalled();+ expect(fetchWithToken).toHaveBeenLastCalledWith(+ expect.stringContaining('/api/file/static-gif'),+ { method: 'DELETE' }+ );+});diff --git a/apps/web/src/lib/core/util/uploadFile.ts b/apps/web/src/lib/core/util/uploadFile.tsindex 451613578e..ecef31a59c 100644--- a/apps/web/src/lib/core/util/uploadFile.ts+++ b/apps/web/src/lib/core/util/uploadFile.ts@@ -4,6 +4,7 @@ import {uploadNativeStagedFileToPresignedUrl,} from '@core/mobile/nativeStagedUpload';import { fireAndForget } from '@core/util/fireAndForget';+import { Telemetry } from '@macro-inc/observability';import { invalidateUserQuota } from '@queries/auth';import { staticFileClient } from '@service-static-files/client';import { contentHash } from './hash';@@ -64,10 +65,25 @@ export function isNativeStagedUpload(return file.kind === 'native-staged';}+/** Remove a failed or unaccepted static upload. */+export async function discardStaticUpload(id: string): Promise<void> {+ const removed = await staticFileClient.deleteFile({ file_id: id });+ if (removed.isErr()) {+ Telemetry.error('Could not remove unused static upload', {+ 'file.id': id,+ });+ } else {+ fireAndForget(invalidateUserQuota(), 'file-upload');+ }+}+export async function createStaticUploadFile(- file: UploadFile+ file: UploadFile,+ signal?: AbortSignal): Promise<string> {const contentType = resolveUploadContentType(file);+ signal?.throwIfAborted();+ // Let reservation finish so cancellation can delete the returned ID.const result = await staticFileClient.makePresignedUrl({file_name: file.name,content_type: contentType,@@ -76,20 +92,25 @@ export async function createStaticUploadFile(if (result.isErr()) throw new Error('Failed to upload file');const { upload_url, id } = result.value;- if (isNativeStagedUpload(file)) {- await uploadNativeStagedFileToPresignedUrl(file, upload_url);+ try {+ signal?.throwIfAborted();+ if (isNativeStagedUpload(file)) {+ await uploadNativeStagedFileToPresignedUrl(file, upload_url);+ } else {+ const uploadResult = await staticFileClient.uploadToPresignedUrl({+ url: upload_url,+ blob: file.file,+ contentType,+ signal,+ });+ if (!uploadResult.success) throw new Error('Failed to upload file');+ }+ signal?.throwIfAborted();return id;+ } catch (error) {+ await discardStaticUpload(id);+ throw error;}-- const uploadResult = await staticFileClient.uploadToPresignedUrl({- url: upload_url,- blob: file.file,- contentType,- });- if (!uploadResult.success) {- throw new Error('Failed to upload file');- }- return id;}/**diff --git a/apps/web/src/lib/service-clients/service-static-files/client.ts b/apps/web/src/lib/service-clients/service-static-files/client.tsindex 7033fda258..7d714c003e 100644--- a/apps/web/src/lib/service-clients/service-static-files/client.ts+++ b/apps/web/src/lib/service-clients/service-static-files/client.ts@@ -80,11 +80,13 @@ export const staticFileClient = {url: string;blob: Blob | File;contentType?: string;+ signal?: AbortSignal;}) {const result = await platformFetch(args.url, {method: 'PUT',body: args.blob,headers: args.contentType ? { 'Content-Type': args.contentType } : {},+ signal: args.signal,});return { success: result.ok };},diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 76cd0d9ef4..3bc19bea43 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -432,10 +432,32 @@ An `@` inside a word stays literal text. Check hardware-keyboard input too;it should open only one menu.The same software-keyboard check applies to `:` for emoji and `/` for formattingcommands: type a search and tap a result without sending the draft.-Type `/gif` or choose **GIF** from `+`. The picker opens above the composer on-phones and stays visible after you choose the action, including with the iOS-keyboard open. Trending GIFs show first; tap search to filter, then tap a GIF-to insert it without sending the draft.+Type `/gif` or choose **GIF** from `+`. The rounded picker replaces any active+formatting or link menu, opens above the composer on phones, and stays visible+after you choose the action, including with the iOS keyboard open. Both the `/`+formatting menu and the GIF picker span the available chat width on phones,+using the mentions menu's side gutters.+If the browser has no caret selection or its range has no rendered geometry,+the GIF picker anchors to its editor rather than staying hidden.+The larger desktop GIF picker stays within the viewport on narrow screens.+Repeat after scrolling the page: the picker must stay beside the composer,+without adding the page's scroll offset to its fixed position.+Open and dismiss the keyboard while the picker is open: it must recalculate+its placement and available height. Focusing search must not scroll the page+away from the composer.+Trending GIFs show first, with the large search field focused on both desktop+and phones. Search keeps the composer expanded, and tapping anywhere in the+search field keeps focus there. Tap a GIF to download its original animated bytes+and upload them to Macro's static-file service before insertion, without sending+the draft. The picker shows upload progress and prevents duplicate selections;+a failure removes the unused upload and leaves the picker open for retry. Closing+the picker, changing the draft, or losing edit permission prevents a late insertion.+Cancellation aborts the transfer and discards any completed upload that was not inserted.+On desktop, arrow keys move through the two-column grid and scroll the full+selection outline into view; Enter inserts it and Escape closes the picker.+Check that GIFs animate in the picker, in the draft, after sending, after copying+and pasting, and in the enlarged image viewer. Newly inserted GIFs use static-file references; picker+previews and existing Klipy URL images still load directly with anonymous CORS.Closed mention menus do not gather, rank, or paginate candidates. When checkingchannel-switch performance, include touch navigation back to the list and reopening