Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Start fetching a design's remote images while the model writes it

Esteban Suarez8c5f1268c613
diff --git a/app/api/artifact-frame/route.ts b/app/api/artifact-frame/route.ts
index 835cc48..c6e9433 100644
--- a/app/api/artifact-frame/route.ts
+++ b/app/api/artifact-frame/route.ts
@@ -27,9 +27,11 @@ export const GET = withSessionRoute(async (request, { id: sessionId, user }) =>
const readyToken = crypto.randomUUID()
// Remote images are fetched here and embedded as data: URLs, so the design has no
// network while it runs (lib/remote-image.ts). A copy missing an image is not kept.
+ const embedStarted = performance.now()
const embedded = artifact != null && remoteImagesEnabled()
? await embedRemoteImages(artifact, cachedRemoteImage)
- : { html: artifact, complete: true }
+ : { html: artifact, complete: true, images: 0 }
+ const embedMs = Math.round(performance.now() - embedStarted)
const keep = etag != null && embedded.complete
const prepared = embedded.html == null ? null : prepareDesignArtifactHtml(embedded.html, DESIGN_ARTIFACT_EMBEDDED_CSP, readyToken)
// Every stored design passed validation, so this only guards against one that
@@ -95,7 +97,9 @@ document.querySelector('#frame-root').append(frame);
</body>
</html>`
// Streamed: embedded images can take it past the buffered response limit.
- const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode(html)); controller.close() } })
+ const bytes = new TextEncoder().encode(html)
+ if (embedded.images) log(sessionId, 'artifact:images', { images: embedded.images, complete: embedded.complete, embedMs, bytes: bytes.length })
+ const body = new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close() } })
return new Response(body, {
status: artifact == null ? 404 : 200,
headers: {
diff --git a/lib/agent.ts b/lib/agent.ts
index 3367443..ec4eb6b 100644
--- a/lib/agent.ts
+++ b/lib/agent.ts
@@ -2,6 +2,7 @@ import type { FxAgent } from 'libfx'
import { createTools, type AskQuestion, type ToolHost } from './tools'
import { assertGenerationCredential } from './gateway-session'
import { remoteImagesEnabled } from './design-artifact'
+import { prefetchRemoteImages } from './remote-image-cache'
import { chatSession, durableAgent, runSubagent, type ChatRuntime } from './libfx-agent'
import { project } from './projector'
import {
@@ -73,6 +74,7 @@ const runtime: ChatRuntime = {
await hydrateSession(host)
return buildToolHost(host, turnId)
},
+ watchDraft: prefetchRemoteImages,
}
// The process's durable agent. libfx runs each chat's turns through it, on
diff --git a/lib/libfx-agent.ts b/lib/libfx-agent.ts
index 23a00d3..0575ced 100644
--- a/lib/libfx-agent.ts
+++ b/lib/libfx-agent.ts
@@ -36,6 +36,8 @@ export const SIGN_IN_AGAIN = 'Sign in again to continue this chat, then resend.'
// they live there because they read and write the chat's journal state.
export interface ChatRuntime {
toolHost(chatId: string, turnId: number, signal: AbortSignal): Promise<ToolHost>
+ // Also sees each design as the model writes it (agent.ts prefetches its images).
+ watchDraft?(observer: DesignDraftObserver | undefined): DesignDraftObserver | undefined
}
// Which model request of a turn this is: who sent it, and the conversation it
@@ -99,6 +101,7 @@ function chatFetch(
chatId: () => Promise<string | null>,
executionTurn: () => number | undefined,
sender = 'parent',
+ watchDraft?: ChatRuntime['watchDraft'],
): typeof fetch {
return async (input, init) => {
const turn = executionTurn()
@@ -131,7 +134,7 @@ function chatFetch(
if (!funding.ok && modelRequest) log(id, 'funding:refused', { turn: turn ?? null, reason: funding.refused })
const credential = funding.ok ? funding.credential : null
gateway.gatewaySession = !credential ? null : 'kind' in credential ? credential : { ...credential, email: '', loginAt: 0, isLoggedIn: true }
- observer = draft
+ observer = modelRequest && watchDraft ? watchDraft(draft) : draft
}
try {
return await gatewayFetch(gateway, fetch, observer)(input, init)
@@ -212,7 +215,7 @@ export function durableAgent(runtime: ChatRuntime, instructions: string): FxAgen
apiKey: 'session-authenticated',
fetch: (input, init) => {
const id = requestHeader(input, init, 'x-session-id')
- return chatFetch(() => chatOfRequest(id), () => drafts.turn(id))(input, init)
+ return chatFetch(() => chatOfRequest(id), () => drafts.turn(id), 'parent', runtime.watchDraft)(input, init)
},
onEvent: event => drafts.observe(event),
// Hooks run synchronously before a restored engine starts its next request.
@@ -270,7 +273,7 @@ export async function runSubagent(
const pinned = active?.id === turnId ? active.settings : undefined
const engine = await createFxEngine({
apiKey: 'session-authenticated',
- fetch: chatFetch(async () => chatId, () => turnId, `subagent:${crypto.randomUUID()}`),
+ fetch: chatFetch(async () => chatId, () => turnId, `subagent:${crypto.randomUUID()}`, runtime.watchDraft),
model: pinned
? { id: pinned.model, effort: pinned.effort as FxEffort, fast: pinned.fast }
: chatModel(host, funding.ok && 'kind' in funding.credential),
diff --git a/lib/remote-image-cache.ts b/lib/remote-image-cache.ts
index 1043516..eaa25a0 100644
--- a/lib/remote-image-cache.ts
+++ b/lib/remote-image-cache.ts
@@ -1,5 +1,7 @@
import { cacheLife } from 'next/cache.js'
-import { loadRemoteImage } from './remote-image'
+import { BLANK_IMAGE, MAX_DESIGN_ARTIFACT_BYTES, remoteImagesEnabled, rewriteRemoteImages } from './design-artifact'
+import type { DesignDraftObserver } from './gateway-session'
+import { loadRemoteImage, MAX_REMOTE_IMAGES } from './remote-image'
// Shared by every instance in the region (Runtime Cache), so a design's images are
// fetched once, not on every preview. A failed fetch throws and is never cached.
@@ -8,3 +10,45 @@ export async function cachedRemoteImage(url: string): Promise<string> {
cacheLife({ revalidate: 86400, expire: 7 * 86400 })
return loadRemoteImage(url)
}
+
+const SCAN_MS = 250
+
+// Starts fetching a design's remote images into the cache while the model is still
+// writing it, so the published preview need not wait for them. Only tags the model
+// has finished are read, and only the model's markup decides what is fetched.
+export function prefetchRemoteImages(observer: DesignDraftObserver | undefined, load = cachedRemoteImage): DesignDraftObserver | undefined {
+ if (!remoteImagesEnabled()) return observer
+ const drafts = new Map<string, { html: string; scannedAt: number }>()
+ const started = new Set<string>()
+ const scan = (html: string) => {
+ rewriteRemoteImages(html, (url: string) => {
+ if (!started.has(url) && started.size < MAX_REMOTE_IMAGES) {
+ started.add(url)
+ void load(url).catch(() => {})
+ }
+ return BLANK_IMAGE
+ })
+ }
+ return {
+ delta(callId, chunk) {
+ observer?.delta(callId, chunk)
+ const draft = drafts.get(callId) ?? { html: '', scannedAt: 0 }
+ if (draft.html.length + chunk.length > MAX_DESIGN_ARTIFACT_BYTES) return
+ draft.html += chunk
+ drafts.set(callId, draft)
+ if (Date.now() - draft.scannedAt < SCAN_MS) return
+ draft.scannedAt = Date.now()
+ scan(draft.html)
+ },
+ end(callId) {
+ const draft = drafts.get(callId)
+ drafts.delete(callId)
+ if (draft) scan(draft.html)
+ return observer?.end?.(callId)
+ },
+ abort() {
+ drafts.clear()
+ return observer?.abort?.()
+ },
+ }
+}
diff --git a/lib/remote-image.ts b/lib/remote-image.ts
index 160e650..c83fa37 100644
--- a/lib/remote-image.ts
+++ b/lib/remote-image.ts
@@ -30,13 +30,13 @@ export async function loadRemoteImage(url: string): Promise<string> {
* the preview past it. `complete` is false when an image failed to load, so the
* caller does not let a browser keep that copy.
*/
-export async function embedRemoteImages(html: string, load: (url: string) => Promise<string>): Promise<{ html: string; complete: boolean }> {
+export async function embedRemoteImages(html: string, load: (url: string) => Promise<string>): Promise<{ html: string; complete: boolean; images: number }> {
const urls: string[] = []
rewriteRemoteImages(html, (url: string) => {
if (!urls.includes(url)) urls.push(url)
return BLANK_IMAGE
})
- if (!urls.length) return { html, complete: true }
+ if (!urls.length) return { html, complete: true, images: 0 }
const wanted = urls.slice(0, MAX_REMOTE_IMAGES)
const loaded = await Promise.all(wanted.map((url) => load(url).catch(() => null)))
const embedded = new Map<string, string>()
@@ -50,7 +50,7 @@ export async function embedRemoteImages(html: string, load: (url: string) => Pro
total += imageBytes(image)
return image
})
- return { html: rewritten, complete: loaded.every(Boolean) }
+ return { html: rewritten, complete: loaded.every(Boolean), images: wanted.length }
}
function imageBytes(image: string): number {
diff --git a/tests/remote-image.test.mjs b/tests/remote-image.test.mjs
index 80fc3e7..a2b7b7a 100644
--- a/tests/remote-image.test.mjs
+++ b/tests/remote-image.test.mjs
@@ -4,6 +4,15 @@ import https from 'node:https'
import dns from 'node:dns/promises'
import { Readable } from 'node:stream'
import { EventEmitter } from 'node:events'
+import { registerHooks } from 'node:module'
+
+// lib/remote-image-cache.ts imports without extensions, as Next resolves them.
+registerHooks({
+ resolve(specifier, context, next) {
+ if (specifier.startsWith('.') && !/\.[a-z]+$/.test(specifier) && !context.parentURL?.includes('/node_modules/')) return next(`${specifier}.ts`, context)
+ return next(specifier, context)
+ },
+})
import { BLANK_IMAGE, DESIGN_ARTIFACT_EMBEDDED_CSP, MAX_DESIGN_ARTIFACT_BYTES, remoteImageUrl, rewriteRemoteImages, validateDesignArtifactHtml } from '../lib/design-artifact.ts'
import { embedRemoteImages, loadRemoteImage, MAX_REMOTE_IMAGES, MAX_REMOTE_IMAGES_TOTAL_BYTES } from '../lib/remote-image.ts'
import { sniffImageType } from '../lib/image-sniff.ts'
@@ -130,7 +139,7 @@ test('a failed image is blank and the copy is marked incomplete; a design withou
assert.equal(result.complete, false)
assert.ok(result.html.includes(`<img src="${PNG_URL}"><img src="${BLANK_IMAGE}">`))
const plain = doc('<p>no images</p>')
- assert.deepEqual(await embedRemoteImages(plain, async () => { throw new Error('never called') }), { html: plain, complete: true })
+ assert.deepEqual(await embedRemoteImages(plain, async () => { throw new Error('never called') }), { html: plain, complete: true, images: 0 })
})
test('embedded designs need no network: the CSP stays data-only', () => {
@@ -193,3 +202,42 @@ test('with remote images off, a remote image is refused at publish', (t) => {
t.after(() => { delete process.env.FX0_REMOTE_IMAGES })
assert.equal(validateDesignArtifactHtml(doc('<img src="https://example.com/a.png">')).ok, false)
})
+
+test('images are prefetched from finished tags while the model writes, once each, without touching the preview', async () => {
+ const { prefetchRemoteImages } = await import('../lib/remote-image-cache.ts')
+ const forwarded = []
+ const inner = { delta: (id, chunk) => forwarded.push(chunk), end: (id) => forwarded.push(`end:${id}`), abort: () => forwarded.push('abort') }
+ const loads = []
+ const observer = prefetchRemoteImages(inner, async (url) => { loads.push(url); return PNG_URL })
+ const chunks = ['<!doctype html><html><head><style>.h{background:url(https://example.com/bg', '.png)}</style></head><body><img src="https://example.com/he',
+ 'ro.png" alt=""><img src="https://example.com/hero.png">',
+ ...Array.from({ length: 14 }, (_, index) => `<img src="https://example.com/${index}.png">`), '</body></html>']
+ observer.delta('call', chunks[0])
+ assert.deepEqual(loads, [], 'an unfinished url( is never fetched')
+ observer.delta('call', chunks[1])
+ assert.deepEqual(loads, [], 'scans are spaced out while chunks arrive')
+ for (const chunk of chunks.slice(2)) observer.delta('call', chunk)
+ await observer.end('call')
+ assert.equal(loads.length, MAX_REMOTE_IMAGES)
+ assert.deepEqual(loads.slice(0, 3), ['https://example.com/bg.png', 'https://example.com/hero.png', 'https://example.com/0.png'])
+ assert.ok(!loads.some((url) => url.endsWith('/he') || url.endsWith('/bg')), 'no URL cut mid-chunk')
+ assert.deepEqual(forwarded, [...chunks, 'end:call'], 'the preview observer still sees every chunk')
+ await observer.abort()
+ assert.equal(forwarded.at(-1), 'abort')
+})
+
+test('prefetching scans again once the spacing has passed, and does nothing with remote images off', async (t) => {
+ const { prefetchRemoteImages } = await import('../lib/remote-image-cache.ts')
+ const loads = []
+ const observer = prefetchRemoteImages(undefined, async (url) => { loads.push(url); return PNG_URL })
+ observer.delta('call', '<img src="https://example.com/early.png">')
+ assert.deepEqual(loads, ['https://example.com/early.png'], 'the first finished tag starts at once')
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ observer.delta('call', '<img src="https://example.com/later.png">')
+ assert.deepEqual(loads, ['https://example.com/early.png', 'https://example.com/later.png'])
+
+ process.env.FX0_REMOTE_IMAGES = '0'
+ t.after(() => { delete process.env.FX0_REMOTE_IMAGES })
+ const inner = { delta() {} }
+ assert.equal(prefetchRemoteImages(inner), inner)
+})
diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs
index 20826f8..5fae654 100644
--- a/tests/runtime.test.mjs
+++ b/tests/runtime.test.mjs
@@ -27,7 +27,7 @@ export const assertGenerationCredential = (host) => {
}
export const gatewayFetch = () => async () => Response.json({})`)
registerHooks({ resolve(specifier, context, next) {
- if (context.parentURL?.includes('/lib/')) {
+ if (context.parentURL?.includes('/lib/') && !context.parentURL.includes('/node_modules/')) {
const fake = { libfx: libfxUrl, './journal': journalUrl, './turn-credential': credentialUrl, './history': historyUrl, './gateway-session': gatewayUrl }[specifier]
if (fake) return { url: fake, shortCircuit: true }
if (specifier.startsWith('./') && !/\.[cm]?[jt]s$/.test(specifier)) return next(`${specifier}.ts`, context)