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

Open a history chat at once and start its preview with it

Esteban Suarez6c1d97afdce7
diff --git a/components/chat-app.tsx b/components/chat-app.tsx
index caee365..65a39cc 100644
--- a/components/chat-app.tsx
+++ b/components/chat-app.tsx
@@ -405,6 +405,9 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
const [startedTurns, setStartedTurns] = useState<Set<number>>(initialState.startedTurns)
const [streamStartSeq, setStreamStartSeq] = useState(initialState.lastSeq)
const [switchingTo, setSwitchingTo] = useState<string | null>(null)
+ // While an uncached chat opens: its latest design revision from the history list, so
+ // the preview starts loading alongside the transcript instead of after it.
+ const [switchPreview, setSwitchPreview] = useState<{ sessionId: string; revision: number } | null>(null)
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
// The session rail drags through SidebarGestures; this tracks the conversation pane.
const [agentResizing, setAgentResizing] = useState(false)
@@ -953,32 +956,52 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
if (hasIdentity && !authBlocked && id !== 'draft' && id !== sessionId) void loadSession(id).catch(() => {})
}
+ // The chat the latest switch is moving to; a later click replaces it, and an earlier
+ // load that finishes afterwards is dropped.
+ const switchTarget = useRef<string | null>(null)
async function switchSession(id: string, pushHistory = true) {
focusPrompt()
- if (!hasIdentity || authBlocked || id === 'draft' || id === activeSession.current || switchingTo) return
+ if (!hasIdentity || authBlocked || id === 'draft' || id === activeSession.current || id === switchTarget.current) return
if (!chatReady) bootAbandoned.current = true
pendingSend.current = false
- const cached = eventCache.current.get(id)
- if (!cached) setSwitchingTo(id)
setInteractionNotice(null)
+ // Move to the chat at once: its URL now, and, until its snapshot arrives, the empty
+ // chat a chat URL shows while loading (html.chat-url skeletons).
+ if (pushHistory) {
+ const url = new URL(window.location.href)
+ url.searchParams.set('s', id)
+ window.history.pushState(null, '', url)
+ }
+ const cached = eventCache.current.get(id)
+ switchTarget.current = id
+ const listedRevision = sessions.find((session) => session.id === id)?.artifactRevision
+ setSwitchPreview(!cached && listedRevision ? { sessionId: id, revision: listedRevision } : null)
+ if (!cached) {
+ document.documentElement.classList.add('chat-url')
+ clearChatView()
+ setSwitchingTo(id)
+ }
try {
const snapshot = cached ?? (await loadSession(id))
- if (signedOut.current) return
+ if (signedOut.current || switchTarget.current !== id) return
showSession(id, snapshot)
setChatReady(true)
- if (pushHistory) {
- const url = new URL(window.location.href)
- url.searchParams.set('s', id)
- window.history.pushState(null, '', url)
- }
setInteractionNotice({ tone: 'status', text: 'Session loaded.' })
} catch (error) {
+ if (switchTarget.current !== id) return
+ document.documentElement.classList.remove('chat-url')
if (error instanceof AuthRouteError) return
console.error('[fx0] session load failed', { sessionId: id, error })
+ // The URL already names the chat; back to a new chat, keeping what was typed.
+ resetLocalDraft(false, { keepTyping: true })
setInteractionNotice({ tone: 'error', text: 'Unable to load that session. Try again.' })
if (!chatReady) setChatReady(true)
} finally {
- setSwitchingTo(null)
+ if (switchTarget.current === id) {
+ switchTarget.current = null
+ setSwitchingTo(null)
+ setSwitchPreview(null)
+ }
}
}
@@ -1096,6 +1119,16 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
composerRef.current?.clearDraft()
try { clearGuestDraft(window.sessionStorage) } catch { /* Storage is optional. */ }
}
+ clearChatView()
+ const url = new URL(window.location.href)
+ url.searchParams.delete('s')
+ if (pushHistory) window.history.pushState(null, '', url)
+ else window.history.replaceState(null, '', url)
+ }
+
+ // An empty chat: no entries, turn, design or stream state. The composer and the URL
+ // are the caller's.
+ function clearChatView() {
setEntries([])
setArtifactRevision(0)
setActiveTurnId(null)
@@ -1119,10 +1152,6 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
setStartedTurns(new Set())
setStreamStartSeq(0)
setInteractionNotice(null)
- const url = new URL(window.location.href)
- url.searchParams.delete('s')
- if (pushHistory) window.history.pushState(null, '', url)
- else window.history.replaceState(null, '', url)
}
// Typing in a draft is a strong signal a prompt follows, so its chat is reserved
@@ -1149,7 +1178,9 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
function onComposerInput(text: string) {
if (!text.trim() || !isAuthenticated || !authAllowed.current) return
- if (activeSession.current === 'draft') reserveDraftChat()
+ // While a chat is opening, typing belongs to that chat, not to a new draft.
+ if (switchTarget.current) warmChat(switchTarget.current)
+ else if (activeSession.current === 'draft') reserveDraftChat()
else warmChat(activeSession.current)
}
@@ -1733,7 +1764,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
<Sidebar
sessions={view.sessions}
loading={loading}
- activeId={sessionId}
+ activeId={switchingTo ?? sessionId}
loadingId={switchingTo}
now={view.now ?? clock}
onPrefetch={prefetchSession}
@@ -2102,7 +2133,11 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
</div>
{region((view) => (
<PreviewPane
- source={{ kind: 'design', sessionId: view.sessionId, revision: view.snapshot.transcript.view.artifactRevision }}
+ source={switchPreview && view.sessionId === 'draft'
+ // The opening chat's listed revision; its snapshot later names the same
+ // source, so the frame keeps loading instead of starting over.
+ ? { kind: 'design', ...switchPreview }
+ : { kind: 'design', sessionId: view.sessionId, revision: view.snapshot.transcript.view.artifactRevision }}
viewing={viewing}
draft={designDraft?.html ?? null}
accessAllowed={!authBlocked && signOutStatus == null}
diff --git a/lib/events.ts b/lib/events.ts
index 070652e..961b2a4 100644
--- a/lib/events.ts
+++ b/lib/events.ts
@@ -85,6 +85,9 @@ export interface SessionInfo {
busy: boolean
// The chat's stored picker settings, so switching to it needs no settings request.
generation?: { model: string; effort: string; fast: boolean }
+ // The latest published design revision, when there is one, so opening the chat can
+ // start loading its preview while the transcript is still on its way.
+ artifactRevision?: number
}
export interface SessionPage {
diff --git a/lib/journal.ts b/lib/journal.ts
index 4005b9c..72cbc75 100644
--- a/lib/journal.ts
+++ b/lib/journal.ts
@@ -341,11 +341,13 @@ export const readTranscript = createTranscriptReader({
const values: Record<string, string> = {}
for (let i = 0; i < fields.length; i += 2) values[fields[i]] = fields[i + 1]
const stored = parseStoredSession(id, values)
+ const view = sessionView(values)
return {
previous: previous ? parseJson<TranscriptSnapshot>(previous) : null,
events: tail.map((item) => parseJson<StreamItem>(item)),
- view: sessionView(values),
- summary: stored ? { id, title: stored.title, createdAt: stored.createdAt, lastActivity: stored.lastActivity, busy: busy > 0, ...(stored.trialChat ? { trialChat: true as const } : {}) } : null,
+ view,
+ summary: stored ? { id, title: stored.title, createdAt: stored.createdAt, lastActivity: stored.lastActivity, busy: busy > 0, ...(stored.trialChat ? { trialChat: true as const } : {}),
+ ...(view.artifactRevision > 0 ? { artifactRevision: view.artifactRevision } : {}) } : null,
}
},
publish: publishTranscriptSnapshot,
@@ -528,19 +530,22 @@ export async function readSessionSummaries(ids: string[]): Promise<SessionInfo[]
const batch = ids.slice(offset, offset + 200)
const pipeline = redis().pipeline()
for (const id of batch) {
- pipeline.hmget(key(id, 'state'), 'id', 'createdAt', 'lastActivity', 'title', 'trialChat', 'preferredModel', 'preferredEffort', 'preferredFast')
+ pipeline.hmget(key(id, 'state'), 'id', 'createdAt', 'lastActivity', 'title', 'trialChat', 'preferredModel', 'preferredEffort', 'preferredFast', 'artifactRevision')
pipeline.exists(key(id, 'active'))
pipeline.get(key(id, 'message-seq'))
}
const values = await pipeline.exec()
for (let index = 0; index < batch.length; index++) {
if (Number(values[index * 3 + 2] ?? 0) < 1) continue
- const state = parseStoredSession(batch[index], values[index * 3] as Record<string, unknown> | null)
+ const fields = values[index * 3] as Record<string, unknown> | null
+ const state = parseStoredSession(batch[index], fields)
if (!state) continue
+ const { artifactRevision } = sessionView(fields)
sessions.push({ id: state.id, title: state.title, createdAt: state.createdAt,
lastActivity: state.lastActivity, busy: Number(values[index * 3 + 1] ?? 0) > 0,
...(state.trialChat ? { trialChat: true as const } : {}),
- generation: { model: state.preferredModel ?? '', effort: state.preferredEffort ?? '', fast: state.preferredFast ?? false } })
+ generation: { model: state.preferredModel ?? '', effort: state.preferredEffort ?? '', fast: state.preferredFast ?? false },
+ ...(Number.isSafeInteger(artifactRevision) && artifactRevision > 0 ? { artifactRevision } : {}) })
}
}
return sessions.sort((a, b) => b.lastActivity - a.lastActivity).slice(0, 100)
diff --git a/package.json b/package.json
index 293b6f7..0d3cd99 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
"build": "next build",
"typecheck": "next typegen && tsc --noEmit --incremental false",
"start": "next start",
- "test:core": "node --experimental-strip-types --test tests/core.test.mjs tests/function-grouping.test.mjs tests/transcript.test.mjs tests/design-draft.test.mjs tests/design-publish.test.mjs tests/event-delivery.test.mjs tests/event-stream.test.mjs tests/public-fetch.test.mjs tests/remote-image.test.mjs tests/prompt-images.test.mjs tests/design-assets.test.mjs tests/capture-protocol.test.mjs tests/runtime.test.mjs",
+ "test:core": "node --experimental-strip-types --test tests/core.test.mjs tests/session-summary.test.mjs tests/function-grouping.test.mjs tests/transcript.test.mjs tests/design-draft.test.mjs tests/design-publish.test.mjs tests/event-delivery.test.mjs tests/event-stream.test.mjs tests/public-fetch.test.mjs tests/remote-image.test.mjs tests/prompt-images.test.mjs tests/design-assets.test.mjs tests/capture-protocol.test.mjs tests/runtime.test.mjs",
"test:auth": "node --experimental-strip-types --test tests/auth.test.mjs tests/auth-callback.test.mjs tests/signout.test.mjs tests/ownership.test.mjs tests/history.test.mjs tests/route-security.test.mjs tests/gateway-session.test.mjs tests/libfx-transport.test.mjs tests/libfx-agent.test.mjs tests/auth-ui.test.mjs tests/html-ui.test.mjs tests/guest-ui.test.mjs tests/guest-draft.test.mjs tests/trial.test.mjs tests/turn-funding.test.mjs",
"test:journal:integration": "node --env-file-if-exists=.env.local --experimental-strip-types --test tests/journal.integration.mjs",
"test:smoke": "node tests/local-auth-smoke.mjs",
diff --git a/tests/guest-ui.test.mjs b/tests/guest-ui.test.mjs
index 8ec1684..b563285 100644
--- a/tests/guest-ui.test.mjs
+++ b/tests/guest-ui.test.mjs
@@ -325,6 +325,78 @@ test('an existing paid chat cannot claim free prompts; switching chats and new d
assert.equal(ui.requests.filter(({ url }) => url === '/api/session?session=trial-chat').length, 1)
})
+test('opening an uncached chat moves to its URL and an empty chat at once; a later click wins; a failed load returns to a new chat', async (t) => {
+ const summary = (id) => ({ id, title: id, createdAt: 1, lastActivity: 1, busy: false })
+ const snapshot = (id) => Response.json({ transcript: compactTranscript([{ type: 'user', seq: 1, id: 1, text: `Design ${id}` }], guestBoot.view), summary: summary(id) })
+ let releaseSlow
+ const slow = new Promise((resolve) => { releaseSlow = resolve })
+ const ui = browser(t, {
+ '/api/events?session=one&after=1': () => new Response(''),
+ '/api/events?session=fast&after=1': () => new Response(''),
+ '/api/model?session=one': () => Response.json({ model: '', effort: '', fast: false }),
+ '/api/model?session=fast': () => Response.json({ model: '', effort: '', fast: false }),
+ '/api/session?session=slow': () => slow.then(() => snapshot('slow')),
+ '/api/session?session=fast': () => snapshot('fast'),
+ '/api/session?session=broken': () => new Response('unavailable', { status: 503 }),
+ })
+ const pushes = []
+ const replaces = []
+ window.history.pushState = (_state, _title, url) => { pushes.push(String(url)); window.location.search = new URL(String(url)).search }
+ window.history.replaceState = (_state, _title, url) => { replaces.push(String(url)); window.location.search = new URL(String(url)).search }
+ const classes = new Set()
+ document.documentElement.classList = { add: (name) => classes.add(name), remove: (name) => classes.delete(name), toggle() {}, contains: (name) => classes.has(name) }
+ t.mock.method(console, 'error', () => {})
+ const app = mount(t, ui, {
+ ...guestBoot, user: { id: 'user-1', name: 'User', email: null, picture: null },
+ sessionId: 'one', sessions: [summary('one'), { ...summary('slow'), artifactRevision: 3 }, summary('fast'), summary('broken')],
+ events: [{ type: 'user', seq: 1, id: 1, text: 'Design one' }],
+ })
+ await tick()
+ app.render()
+ const rail = () => find(app.tree(), (node) => node.type === Sidebar).props
+ const entries = () => find(app.tree(), (node) => node.type === Transcript).props.entries
+
+ // The click moves at once: URL, highlighted item and the empty chat, before any response.
+ rail().onSelect('slow')
+ assert.match(pushes.at(-1), /[?&]s=slow\b/, 'the URL names the chat in the click itself')
+ assert.ok(classes.has('chat-url'), 'the empty chat shows its loading skeleton')
+ app.render()
+ assert.equal(rail().activeId, 'slow', 'the clicked chat is highlighted at once')
+ assert.deepEqual(entries(), [], 'the previous chat is no longer shown')
+ const preview = () => find(app.tree(), (node) => node.type === PreviewPane)?.props
+ assert.deepEqual(preview()?.source, { kind: 'design', sessionId: 'slow', revision: 3 },
+ 'the preview starts loading the listed design before the transcript arrives')
+
+ // Typing while it opens does not reserve a new draft chat.
+ find(app.tree(), (node) => node.type === Composer).props.onDraftInput('typed while loading')
+ await tick()
+ assert.equal(ui.requests.filter(({ url }) => url === '/api/sessions').length, 0, 'no draft reservation while a chat opens')
+
+ // A later click wins; the slow response that lands afterwards is dropped.
+ rail().onSelect('fast')
+ await tick()
+ app.render()
+ assert.equal(entries()[0]?.text, 'Design fast')
+ releaseSlow()
+ await tick()
+ await tick()
+ app.render()
+ assert.equal(entries()[0]?.text, 'Design fast', 'the earlier load does not replace the chat clicked later')
+ assert.equal(rail().activeId, 'fast')
+ assert.equal(preview()?.source.sessionId, 'fast', 'the dropped chat\'s early preview is gone')
+ assert.ok(!classes.has('chat-url'))
+
+ // A failed load returns to a new chat with the usual notice, not an endless skeleton.
+ rail().onSelect('broken')
+ await tick()
+ await tick()
+ app.render()
+ assert.ok(!classes.has('chat-url'), 'no skeleton is left behind')
+ assert.doesNotMatch(replaces.at(-1), /[?&]s=/, 'the URL no longer names the chat that failed')
+ assert.equal(rail().activeId, 'draft')
+ assert.ok(find(app.tree(), (node) => node.props?.role === 'alert' && node.props.children === 'Unable to load that session. Try again.'))
+})
+
test('the first prompt response retains trial eligibility when a signed-in draft becomes a cached chat', async (t) => {
t.mock.method(console, 'info', () => {})
const ui = browser(t, {
diff --git a/tests/session-summary.test.mjs b/tests/session-summary.test.mjs
new file mode 100644
index 0000000..8598e1d
--- /dev/null
+++ b/tests/session-summary.test.mjs
@@ -0,0 +1,43 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { registerHooks } from 'node:module'
+
+// readSessionSummaries reads each chat's state hash, activity flag and message count in
+// one pipeline. The fake answers HMGET like Upstash: an object of the requested fields.
+globalThis.__summaryState = new Map()
+registerHooks({
+ resolve(specifier, context, next) {
+ if (specifier === '@upstash/redis' && context.parentURL?.endsWith('/lib/journal.ts')) {
+ const fake = `export class Redis {
+ pipeline() {
+ const queued = []
+ const pipeline = {
+ hmget: (key, ...fields) => { const hash = globalThis.__summaryState.get(key) ?? {}; queued.push(Object.fromEntries(fields.map((field) => [field, hash[field] ?? null]))); return pipeline },
+ exists: () => { queued.push(0); return pipeline },
+ get: () => { queued.push('2'); return pipeline },
+ exec: async () => queued,
+ }
+ return pipeline
+ }
+ }`
+ return { url: `data:text/javascript,${encodeURIComponent(fake)}`, shortCircuit: true }
+ }
+ return next(specifier, context)
+ },
+})
+process.env.KV_REST_API_URL ??= 'https://redis.invalid'
+process.env.KV_REST_API_TOKEN ??= 'test-token'
+process.env.FX0_REDIS_PREFIX = 'summary-test'
+const { readSessionSummaries } = await import('../lib/journal.ts')
+
+test('history summaries carry the latest design revision only when a design exists', async () => {
+ const state = (id, extra) => globalThis.__summaryState.set(`summary-test:session:${id}:state`, { id, createdAt: '1', lastActivity: '2', title: id, ...extra })
+ state('designed', { artifactRevision: '3' })
+ state('empty', { artifactRevision: '0' })
+ state('broken', { artifactRevision: 'x' })
+ state('unset', {})
+ const summaries = Object.fromEntries((await readSessionSummaries(['designed', 'empty', 'broken', 'unset'])).map((summary) => [summary.id, summary]))
+ assert.equal(summaries.designed.artifactRevision, 3)
+ for (const id of ['empty', 'broken', 'unset']) assert.equal('artifactRevision' in summaries[id], false, `${id} has no revision`)
+ assert.deepEqual(summaries.designed.generation, { model: '', effort: '', fast: false }, 'other fields are unchanged')
+})