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

Commit the first text without the batch wait and load Blob on first use

Esteban Suarez73420fd12017
diff --git a/lib/design-assets.ts b/lib/design-assets.ts
index decc4bb..1e2a37c 100644
--- a/lib/design-assets.ts
+++ b/lib/design-assets.ts
@@ -1,5 +1,5 @@
import { randomBytes } from 'node:crypto'
-import { del, get, list, put } from '@vercel/blob'
+import type { del, get, list, put } from '@vercel/blob'
import {
MAX_CHAT_ASSETS, MAX_DAILY_ASSETS, finishDesignAssetCleanup, pendingDesignAssetCleanups,
queueDesignAssetCleanup, readDesignAssets, recordDesignAssets, reserveDesignAssets,
@@ -18,7 +18,16 @@ export interface DesignAssetStore {
list: typeof list
}
-const BLOB: DesignAssetStore = { put, get, del, list }
+// @vercel/blob carries its own undici, jose and the Vercel OIDC client (~0.6 MB), so it
+// loads on the first Blob call: routes that import this module cold-start without it.
+let blob: Promise<typeof import('@vercel/blob')> | undefined
+const loadBlob = () => blob ??= import('@vercel/blob')
+const BLOB: DesignAssetStore = {
+ put: async (...args) => (await loadBlob()).put(...args),
+ get: async (...args) => (await loadBlob()).get(...args),
+ del: async (...args) => (await loadBlob()).del(...args),
+ list: async (...args) => (await loadBlob()).list(...args),
+}
/** A message that would pass the per-chat or per-day image cap. Nothing was stored. */
export class DesignAssetLimitError extends Error {
diff --git a/lib/projector.ts b/lib/projector.ts
index 4122111..abdbd16 100644
--- a/lib/projector.ts
+++ b/lib/projector.ts
@@ -270,11 +270,16 @@ export async function project(agent: FxAgent, host: SessionState, libfxSessionId
return true
}
+ // Commits start at most once per BATCH_MS. A line after a quiet spell, such as a
+ // turn's first text, commits on the next tick with whatever its read brought;
+ // lines that follow inside the window wait for it and go together.
let flushTimer: ReturnType<typeof setTimeout> | null = null
let committing: Promise<boolean> = Promise.resolve(true)
+ let lastCommitAt = -Infinity
const scheduleCommit = () => {
flushTimer ??= setTimeout(() => {
flushTimer = null
+ lastCommitAt = performance.now()
committing = committing.then((ok) => (ok ? commit() : false)).catch((error) => {
// Nothing committed: the next follower projects these lines again.
log(host.id, 'projector:error', { error: errorText(error) })
@@ -283,7 +288,7 @@ export async function project(agent: FxAgent, host: SessionState, libfxSessionId
if (!ok) stop()
return ok
})
- }, BATCH_MS)
+ }, Math.max(0, lastCommitAt + BATCH_MS - performance.now()))
}
try {
diff --git a/tests/design-assets.test.mjs b/tests/design-assets.test.mjs
index 3e32d71..1e3703d 100644
--- a/tests/design-assets.test.mjs
+++ b/tests/design-assets.test.mjs
@@ -43,12 +43,24 @@ registerHooks({
}
`)}`, shortCircuit: true }
}
+ if (specifier === '@vercel/blob' && context.parentURL?.endsWith('/lib/design-assets.ts')) {
+ return { url: `data:text/javascript,${encodeURIComponent(`
+ const j = globalThis.__assetJournal
+ j.blobLoaded = true
+ export async function put(...args) { j.blobCalls.push(['put', ...args]); return { pathname: args[0] } }
+ export async function get() { return null }
+ export async function del(...args) { j.blobCalls.push(['del', ...args]) }
+ export async function list() { return { blobs: [], hasMore: false } }
+ `)}`, shortCircuit: true }
+ }
return next(specifier, context)
},
})
process.env.SESSION_SECRET ??= 'deterministic-design-assets-test-secret-32+'
const { storeDesignAssets, readDesignAsset, deleteDesignAssets, retryDesignAssetCleanup, DesignAssetLimitError } = await import('../lib/design-assets.ts')
+journal.blobCalls = []
+const blobLoadedOnImport = journal.blobLoaded === true
const { validateDesignArtifactHtml, rewriteRemoteImages, BLANK_IMAGE } = await import('../lib/design-artifact.ts')
const { markRemoteImages } = await import('../lib/remote-image.ts')
const { artifactImageSrc, verifyArtifactImage } = await import('../lib/artifact-image.ts')
@@ -122,6 +134,18 @@ test('the chat and daily caps are taken before anything is stored, and given bac
assert.equal(calls[0][4], calls[1][4], 'the refund uses the reservation day')
})
+test('the default Blob store loads @vercel/blob on first use, not on import', async () => {
+ assert.equal(blobLoadedOnImport, false)
+ await retryDesignAssetCleanup()
+ assert.equal(journal.blobLoaded, undefined, 'no pending cleanup, no Blob client')
+ const image = { type: 'image', data: PNG, mimeType: 'image/png' }
+ const [handle] = await storeDesignAssets(CHAT, USER, [image])
+ assert.equal(journal.blobLoaded, true)
+ const [[name, pathname, body, options]] = journal.blobCalls
+ assert.deepEqual([name, pathname, Buffer.from(body).toString('base64'), options],
+ ['put', `chats/${CHAT}/${handle}`, PNG, { access: 'private', contentType: 'image/png', addRandomSuffix: false }])
+})
+
test('an image is read only for the chat that received it', async () => {
manifests.clear()
const store = fakeStore()
diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs
index 6c1f0ac..a85a894 100644
--- a/tests/runtime.test.mjs
+++ b/tests/runtime.test.mjs
@@ -668,6 +668,26 @@ test('the projector copies a turn once however many follow it, then records its
assert.deepEqual(f.calls.filter((call) => call[0] === 'generation').map((call) => call.slice(1, 4)), [['project-chat', 3, 4]])
})
+test('the projector commits a line after a quiet spell at once and batches the lines right behind it', async (t) => {
+ const f = fixture(t, { libfxSessionId: 'wrun_quick', preferredModel: null, preferredEffort: null, preferredFast: null })
+ const host = boundHost('quick-chat')
+ const log = f.logOf('wrun_quick')
+ const following = projector.project(runtime.agent(), host, 'wrun_quick', { idleMs: 200 })
+ log.push({ type: 'turn_start', messageId: 'm1', sessionId: 'wrun_quick', input: '[Ada] Hi' })
+ await until(() => f.events.some((item) => item.type === 'turn_start'), 'turn start')
+ await new Promise((resolve) => setTimeout(resolve, 60))
+ const pushed = performance.now()
+ log.push({ type: 'text_delta', messageId: 'm1', delta: 'Hel' })
+ await until(() => f.events.some((item) => item.type === 'text'), 'first text')
+ assert.ok(performance.now() - pushed < 30, 'the first text does not wait out a batch window')
+ log.push({ type: 'text_delta', messageId: 'm1', delta: 'lo' })
+ log.push({ type: 'text_delta', messageId: 'm1', delta: ' there' })
+ log.push({ type: 'turn_end', messageId: 'm1', stopReason: 'end_turn' })
+ await following
+ assert.deepEqual(f.events.filter((item) => item.type === 'text').map((item) => item.delta), ['Hel', 'lo there'])
+ assert.deepEqual(f.events.map((item) => item.seq), f.events.map((_, index) => index + 1), 'each item lands once, in order')
+})
+
test('a turn\'s history waits when the database fails, and a later follower writes it once', async (t) => {
const f = fixture(t, { libfxSessionId: 'wrun_retry', preferredModel: null, preferredEffort: null, preferredFast: null })
const host = boundHost('retry-chat')