Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

perf(agents): preload transcript folding on composer focus (#7582)

Wolf Mermelsteinf963780c76bb
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
index 76a2efd38b..b7046dfc5a 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.test.tsx
@@ -1,5 +1,6 @@
import { createSessionComposerDraft } from '@app/features/block-agent/primitives/session-composer-draft';
import type { InputAttachmentData } from '@channel/Input/types';
+import { preloadAgentFold } from '@core/agent-fold/client';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { $createQuoteNode, QuoteNode } from '@lexical/rich-text';
import { fireEvent, render, screen } from '@solidjs/testing-library';
@@ -15,6 +16,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { RepositoryPicker } from '../views/RepositoryPicker';
import { ChatComposer, ChatSessionInput } from './ChatComposer';
+vi.mock('@core/agent-fold/client', () => ({
+ preloadAgentFold: vi.fn(async () => {}),
+}));
+
vi.mock('@core/mobile/isTouchDevice', () => ({
isTouchDevice: vi.fn(() => false),
}));
@@ -140,6 +145,25 @@ function type(text: string) {
}
describe('Chat session input', () => {
+ it('preloads the fold only when focused without sending or changing the draft', () => {
+ const send = vi.fn();
+ const change = vi.fn();
+ render(() => (
+ <ChatComposer
+ draft="Keep this draft"
+ onDraftChange={change}
+ onSend={send}
+ selector={null}
+ />
+ ));
+ expect(preloadAgentFold).not.toHaveBeenCalled();
+ fireEvent.focusIn(screen.getByTestId('editor'));
+ expect(preloadAgentFold).toHaveBeenCalledOnce();
+ expect(send).not.toHaveBeenCalled();
+ expect(change).not.toHaveBeenCalled();
+ expect(editor.clear).not.toHaveBeenCalled();
+ });
+
it('seeds the supplied context without sending it', () => {
const send = vi.fn();
render(() => (
diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsx
index e7fc090031..c3e63b2729 100644
--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx
+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx
@@ -9,6 +9,7 @@ import { InputProvider } from '@channel/Input/context';
import { Input } from '@channel/Input/Input';
import type { InputAttachmentData, InputCommands } from '@channel/Input/types';
import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
+import { preloadAgentFold } from '@core/agent-fold/client';
import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import { createComposerLayout } from '@core/component/LexicalMarkdown/utils/create-composer-layout';
@@ -223,7 +224,10 @@ export function ChatComposer(props: {
ref={container}
data-keep-keyboard
class="min-w-0"
- onFocusIn={() => setFocused(true)}
+ onFocusIn={() => {
+ setFocused(true);
+ void preloadAgentFold();
+ }}
onFocusOut={(event) => {
// iOS control taps can blur with no relatedTarget before click.
// Collapse only for a known outside focus or pointer interaction.
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
index b6e9c6aa8e..df2fb4f0da 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx
@@ -6,15 +6,21 @@ import {
createEditor,
type LexicalEditor,
} from 'lexical';
+
/**
* @vitest-environment jsdom
*/
+import { preloadAgentFold } from '@core/agent-fold/client';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AGENT_INPUT_TEXT_AREA_ID, AgentInput } from './AgentInput';
+vi.mock('@core/agent-fold/client', () => ({
+ preloadAgentFold: vi.fn(async () => {}),
+}));
+
vi.mock('@core/mobile/isTouchDevice', () => ({
isTouchDevice: vi.fn(() => false),
}));
@@ -107,6 +113,7 @@ vi.mock('@phosphor/spinner-gap.svg', () => ({
}));
beforeEach(() => {
+ vi.mocked(preloadAgentFold).mockClear();
vi.stubGlobal(
'ResizeObserver',
class {
@@ -123,6 +130,16 @@ beforeEach(() => {
vi.mocked(isTouchDevice).mockReturnValue(false);
});
+it('preloads on document-chat composer focus without submitting its context', () => {
+ const send = vi.fn();
+ render(() => <AgentInput initialInput="Document context" onSend={send} />);
+ expect(preloadAgentFold).not.toHaveBeenCalled();
+ fireEvent.focusIn(screen.getByTestId('agent-input-editor'));
+ expect(preloadAgentFold).toHaveBeenCalledOnce();
+ expect(send).not.toHaveBeenCalled();
+ expect(editor.clear).not.toHaveBeenCalled();
+});
+
it('seeds context without sending it and submits it only on Send', () => {
const onSend = vi.fn();
render(() => <AgentInput initialInput="Document context" onSend={onSend} />);
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index b79ce6db48..187925f14b 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -20,6 +20,7 @@ import { InputProvider } from '@channel/Input/context';
import { Input } from '@channel/Input/Input';
import type { InputAttachmentData, InputCommands } from '@channel/Input/types';
import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';
+import { preloadAgentFold } from '@core/agent-fold/client';
import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
import { ComposerEditor } from '@core/component/LexicalMarkdown/component/ComposerEditor';
import type { AgentCommandItem } from '@core/component/LexicalMarkdown/plugins';
@@ -324,6 +325,7 @@ export function AgentInput(props: AgentInputProps) {
<div
ref={containerRef}
data-keep-keyboard
+ onFocusIn={() => void preloadAgentFold()}
class="flex flex-col gap-1.5"
classList={{ 'opacity-50': props.readOnly }}
>
diff --git a/apps/web/src/lib/core/agent-fold/client.test.ts b/apps/web/src/lib/core/agent-fold/client.test.ts
new file mode 100644
index 0000000000..6c07ea4854
--- /dev/null
+++ b/apps/web/src/lib/core/agent-fold/client.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { FoldRequest, FoldResponse } from './protocol';
+
+const workers: FakeWorker[] = [];
+
+class FakeWorker extends EventTarget {
+ readonly requests: FoldRequest[] = [];
+
+ constructor() {
+ super();
+ workers.push(this);
+ }
+
+ postMessage(request: FoldRequest): void {
+ this.requests.push(request);
+ }
+
+ reply(response: FoldResponse): void {
+ this.dispatchEvent(new MessageEvent('message', { data: response }));
+ }
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.stubGlobal('Worker', FakeWorker);
+ vi.stubGlobal('fetch', vi.fn());
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ workers.length = 0;
+});
+
+describe('agent fold preloading', () => {
+ it('stays lazy until focus and initializes without creating a session or making an API call', async () => {
+ const { preloadAgentFold } = await import('./client');
+ expect(workers).toHaveLength(0);
+
+ const ready = preloadAgentFold();
+ const worker = workers[0]!;
+ expect(worker.requests).toEqual([{ id: 0, kind: 'preload' }]);
+ expect(fetch).not.toHaveBeenCalled();
+ worker.reply({ id: 0, kind: 'preload', ok: true });
+ await ready;
+
+ await preloadAgentFold();
+ expect(workers).toHaveLength(1);
+ expect(worker.requests).toHaveLength(1);
+ });
+
+ it('uses the same worker for repeated focus and a prompt that arrives during initialization', async () => {
+ const { preloadAgentFold, pushSession } = await import('./client');
+ const ready = preloadAgentFold();
+ await preloadAgentFold();
+ const pushed = pushSession('session', [{ kind: 'snapshot', rows: [] }]);
+ const worker = workers[0]!;
+ expect(workers).toHaveLength(1);
+ expect(worker.requests.map((request) => request.kind)).toEqual([
+ 'preload',
+ 'push',
+ ]);
+ worker.reply({ id: 0, kind: 'preload', ok: true });
+ worker.reply({ id: 1, kind: 'push', ok: true, changes: [] });
+ await ready;
+ await expect(pushed).resolves.toEqual([]);
+ });
+
+ it('does no extra work when a real session has already started the worker', async () => {
+ const { preloadAgentFold, pushSession } = await import('./client');
+ const pushed = pushSession('session', [{ kind: 'snapshot', rows: [] }]);
+ await preloadAgentFold();
+ const worker = workers[0]!;
+ expect(workers).toHaveLength(1);
+ expect(worker.requests.map((request) => request.kind)).toEqual(['push']);
+ worker.reply({ id: 0, kind: 'push', ok: true, changes: [] });
+ await pushed;
+ });
+
+ it('contains worker startup errors and lets a later session start a fresh worker', async () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const { preloadAgentFold, pushSession } = await import('./client');
+ const ready = preloadAgentFold();
+ workers[0]!.dispatchEvent(
+ new ErrorEvent('error', { message: 'module could not load' })
+ );
+ await ready;
+ expect(warning).toHaveBeenCalledOnce();
+
+ const pushed = pushSession('session', [{ kind: 'snapshot', rows: [] }]);
+ expect(workers).toHaveLength(2);
+ workers[1]!.reply({ id: 1, kind: 'push', ok: true, changes: [] });
+ await expect(pushed).resolves.toEqual([]);
+ });
+
+ it('contains constructor failures without preventing a later real load', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.stubGlobal(
+ 'Worker',
+ class {
+ constructor() {
+ throw new Error('worker unavailable');
+ }
+ }
+ );
+ const { preloadAgentFold, pushSession } = await import('./client');
+ await expect(preloadAgentFold()).resolves.toBeUndefined();
+
+ vi.stubGlobal('Worker', FakeWorker);
+ const pushed = pushSession('session', [{ kind: 'snapshot', rows: [] }]);
+ workers[0]!.reply({ id: 1, kind: 'push', ok: true, changes: [] });
+ await expect(pushed).resolves.toEqual([]);
+ });
+});
diff --git a/apps/web/src/lib/core/agent-fold/client.ts b/apps/web/src/lib/core/agent-fold/client.ts
index 686c27f344..b06402995d 100644
--- a/apps/web/src/lib/core/agent-fold/client.ts
+++ b/apps/web/src/lib/core/agent-fold/client.ts
@@ -75,11 +75,31 @@ function request(
const message = build(id);
return new Promise((resolve, reject) => {
- pending.set(id, { resolve, reject });
- ensureWorker().postMessage(message);
+ try {
+ const target = ensureWorker();
+ pending.set(id, { resolve, reject });
+ target.postMessage(message);
+ } catch (error) {
+ pending.delete(id);
+ reject(error);
+ }
});
}
+/**
+ * Start the shared fold on composer focus, while the user is still typing.
+ * A real request already starts the same worker, so repeat focus is free.
+ * No session is opened and a preload failure must not interrupt the input.
+ */
+export async function preloadAgentFold(): Promise<void> {
+ if (worker) return;
+ try {
+ await request((id) => ({ id, kind: 'preload' }));
+ } catch (error) {
+ console.warn('[agent-fold] fold could not be preloaded', error);
+ }
+}
+
/**
* Fold inputs into a session's machine, in order, and hear what changed.
*
diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.test.ts b/apps/web/src/lib/core/agent-fold/fold.worker.test.ts
new file mode 100644
index 0000000000..a06cf3c9e0
--- /dev/null
+++ b/apps/web/src/lib/core/agent-fold/fold.worker.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { FoldRequest, FoldResponse } from './protocol';
+
+const fold = vi.hoisted(() => ({
+ initialize: vi.fn(),
+ open: vi.fn(),
+ push: vi.fn(() => []),
+}));
+
+vi.mock('./wasm-module', () => ({
+ loadAgentFoldWasm: fold.initialize,
+}));
+
+class WorkerScope extends EventTarget {
+ postMessage = vi.fn<(response: FoldResponse) => void>();
+
+ send(request: FoldRequest): void {
+ this.dispatchEvent(new MessageEvent('message', { data: request }));
+ }
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.clearAllMocks();
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+it('initializes on preload without opening a fold, then processes a session after initialization', async () => {
+ const scope = new WorkerScope();
+ vi.stubGlobal('self', scope);
+ let initialize!: () => void;
+ const initialized = new Promise<void>((resolve) => {
+ initialize = resolve;
+ });
+ fold.initialize.mockImplementation(async () => {
+ await initialized;
+ return {
+ FoldStream: class {
+ push = fold.push;
+
+ constructor(id: string) {
+ fold.open(id);
+ }
+ },
+ };
+ });
+ await import('./fold.worker');
+ expect(fold.initialize).not.toHaveBeenCalled();
+
+ scope.send({ id: 1, kind: 'preload' });
+ await vi.waitFor(() => expect(fold.initialize).toHaveBeenCalledOnce());
+ expect(fold.open).not.toHaveBeenCalled();
+ expect(scope.postMessage).not.toHaveBeenCalled();
+
+ scope.send({
+ id: 2,
+ kind: 'push',
+ sessionId: 'session',
+ inputs: [{ kind: 'snapshot', rows: [] }],
+ });
+ initialize();
+ await vi.waitFor(() => expect(scope.postMessage).toHaveBeenCalledTimes(2));
+ expect(
+ scope.postMessage.mock.calls.map(([response]) =>
+ response.ok ? response.kind : response.error
+ )
+ ).toEqual(['preload', 'push']);
+ expect(fold.open).toHaveBeenCalledExactlyOnceWith('session');
+ expect(fold.push).toHaveBeenCalledExactlyOnceWith([
+ { kind: 'snapshot', rows: [] },
+ ]);
+});
diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.ts b/apps/web/src/lib/core/agent-fold/fold.worker.ts
index 6f063b4123..bb32f91731 100644
--- a/apps/web/src/lib/core/agent-fold/fold.worker.ts
+++ b/apps/web/src/lib/core/agent-fold/fold.worker.ts
@@ -39,6 +39,11 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {
const wasm = await loadAgentFoldWasm();
return match(request)
+ .with({ kind: 'preload' }, ({ id, kind }) => ({
+ id,
+ kind,
+ ok: true as const,
+ }))
.with({ kind: 'push' }, ({ id, kind, sessionId, inputs }) => {
// Created on first use. The machine itself refuses anything before a
// snapshot, so a caller that lost its machine (a worker restart) hears
@@ -79,9 +84,8 @@ scope.addEventListener('message', (event: MessageEvent<FoldRequest>) => {
try {
response = await serve(request);
} catch (error) {
- // Includes the wasm module failing to load at all, which is why the
- // caller treats a failure as "this session folds to nothing" rather
- // than retrying: a missing module will not appear on a second try.
+ // A failed WASM preload reports an error without creating a session.
+ // The loader permits a later request to retry initialization.
response = {
id: request.id,
ok: false,
diff --git a/apps/web/src/lib/core/agent-fold/protocol.ts b/apps/web/src/lib/core/agent-fold/protocol.ts
index db68c71eb9..cc0433ba2c 100644
--- a/apps/web/src/lib/core/agent-fold/protocol.ts
+++ b/apps/web/src/lib/core/agent-fold/protocol.ts
@@ -76,7 +76,17 @@ export interface FoldCloseRequest {
sessionId: string;
}
-export type FoldRequest = FoldPushRequest | FoldReadRequest | FoldCloseRequest;
+/** Initialize the worker and WASM without opening a session. */
+export interface FoldPreloadRequest {
+ id: number;
+ kind: 'preload';
+}
+
+export type FoldRequest =
+ | FoldPushRequest
+ | FoldReadRequest
+ | FoldCloseRequest
+ | FoldPreloadRequest;
/** What the worker sends back, one per request. */
export type FoldResponse =
@@ -89,4 +99,5 @@ export type FoldResponse =
metadata: SessionMetadata;
}
| { id: number; ok: true; kind: 'close' }
+ | { id: number; ok: true; kind: 'preload' }
| { id: number; ok: false; error: string };
diff --git a/apps/web/src/lib/core/agent-fold/wasm-module.test.ts b/apps/web/src/lib/core/agent-fold/wasm-module.test.ts
new file mode 100644
index 0000000000..e500d7ed70
--- /dev/null
+++ b/apps/web/src/lib/core/agent-fold/wasm-module.test.ts
@@ -0,0 +1,28 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+const moduleUrl = new URL('./wasm/agent_fold.js', import.meta.url).href;
+
+afterEach(() => {
+ vi.doUnmock(moduleUrl);
+ vi.resetModules();
+});
+
+it('shares initialization and retries after a failed speculative preload', async () => {
+ const initialize = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue(undefined);
+ vi.doMock(moduleUrl, () => ({ default: initialize }));
+ const { loadAgentFoldWasm } = await import('./wasm-module');
+
+ const first = loadAgentFoldWasm();
+ expect(loadAgentFoldWasm()).toBe(first);
+ await expect(first).rejects.toThrow('offline');
+
+ const retried = loadAgentFoldWasm();
+ expect(retried).not.toBe(first);
+ expect(loadAgentFoldWasm()).toBe(retried);
+ await retried;
+ expect(initialize).toHaveBeenCalledTimes(2);
+ expect(loadAgentFoldWasm()).toBe(retried);
+});
diff --git a/apps/web/src/lib/core/agent-fold/wasm-module.ts b/apps/web/src/lib/core/agent-fold/wasm-module.ts
index f802b27bca..61434ac2b8 100644
--- a/apps/web/src/lib/core/agent-fold/wasm-module.ts
+++ b/apps/web/src/lib/core/agent-fold/wasm-module.ts
@@ -52,19 +52,28 @@ interface AgentFoldWasmModule {
let modulePromise: Promise<AgentFoldWasmModule> | undefined;
-/** Loads and initializes the wasm module exactly once per worker context. */
+/** Shares WASM initialization per worker, allowing failed attempts to retry. */
export function loadAgentFoldWasm(): Promise<AgentFoldWasmModule> {
if (!modulePromise) {
modulePromise = (async () => {
- const url = new URL('./wasm/agent_fold.js', import.meta.url).href;
- const mod = (await import(/* @vite-ignore */ url)) as AgentFoldWasmModule;
- // Resolve the wasm binary explicitly: vite copies the generated JS as an
- // opaque asset, so its internal relative `agent_fold_bg.wasm` URL would
- // 404 in production. This `new URL` pattern is statically analyzable, so
- // vite emits the binary as an asset and rewrites it.
- const wasmUrl = new URL('./wasm/agent_fold_bg.wasm', import.meta.url);
- await mod.default({ module_or_path: wasmUrl });
- return mod;
+ try {
+ const url = new URL('./wasm/agent_fold.js', import.meta.url).href;
+ const mod = (await import(
+ /* @vite-ignore */ url
+ )) as AgentFoldWasmModule;
+ // Resolve the wasm binary explicitly: vite copies the generated JS as an
+ // opaque asset, so its internal relative `agent_fold_bg.wasm` URL would
+ // 404 in production. This `new URL` pattern is statically analyzable, so
+ // vite emits the binary as an asset and rewrites it.
+ const wasmUrl = new URL('./wasm/agent_fold_bg.wasm', import.meta.url);
+ await mod.default({ module_or_path: wasmUrl });
+ return mod;
+ } catch (error) {
+ // An optional preload can fail while offline. Let the next real load
+ // retry instead of retaining that rejected promise for the whole tab.
+ modulePromise = undefined;
+ throw error;
+ }
})();
}
return modulePromise;
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 4682eab7c7..490a77a4bc 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -15,6 +15,12 @@ first prose. Verify a second prompt and a reload preserve the complete answer.
Selected model and effort must be confirmed before the first prompt; settings
already confirmed by the runtime do not need another control request.
+Repeat from a fresh tab using Home, Agents, and a document's Chat action.
+Focusing an agent composer prepares its transcript renderer locally; focus alone
+must not send a prompt. Record navigation and focus time separately from typing
+and Enter-to-first-answer time. Check the first readable agent words in the DOM,
+not a loading indicator or a bare Markdown delimiter.
+
Repeat from Home, Agents, and the create menu with an already-ready session.
The first prompt can be accepted before its destination mounts; navigating into
the session must keep the same streamed turn without restarting its load. Also