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

Show a new chat when Back returns to the new-chat page

Pranitda96024b0b6b
diff --git a/components/chat-app.tsx b/components/chat-app.tsx
index 036a2b9..e599259 100644
--- a/components/chat-app.tsx
+++ b/components/chat-app.tsx
@@ -61,7 +61,7 @@ import type { ChatEntry } from './thread'
import Transcript from './transcript'
import { compactTranscript, transcriptState, type SessionSnapshot } from '../lib/transcript'
import type { SessionInfo, SessionPage, SessionView, StreamItem } from '../lib/events'
-import { sanitizeSessionId } from '../lib/session-id'
+import { urlChat } from '../lib/session-id'
import { TRIAL_MODEL } from '../lib/trial-policy'
function newClientId(): string {
@@ -431,6 +431,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
const lastDraftId = useRef<string | null>(null)
const draftState = useRef<DraftState>(EMPTY_DRAFT)
const switchSessionRef = useRef<(id: string, pushHistory?: boolean) => Promise<void>>(async () => {})
+ const returnToDraftRef = useRef<(missing: boolean) => void>(() => {})
activeSession.current = sessionId
const applyCurrentView = useCallback((view: SessionView) => {
currentView.current = view
@@ -546,11 +547,13 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
useEffect(() => {
const onPopState = () => {
- const params = new URLSearchParams(window.location.search)
- const nextSession = sanitizeSessionId(params.get('s'))
- const nextPreviewOpen = isPreviewOpenFromSearch(window.location.search)
- setPreviewChosen(nextPreviewOpen)
- if (nextSession !== activeSession.current) void switchSessionRef.current(nextSession, false)
+ const next = urlChat(window.location.search)
+ setPreviewChosen(isPreviewOpenFromSearch(window.location.search))
+ if (next.kind === 'chat') {
+ if (next.id !== activeSession.current) void switchSessionRef.current(next.id, false)
+ } else if (next.kind === 'invalid' || activeSession.current !== 'draft') {
+ returnToDraftRef.current(next.kind === 'invalid')
+ }
}
window.addEventListener('popstate', onPopState)
return () => window.removeEventListener('popstate', onPopState)
@@ -994,6 +997,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
}
switchSessionRef.current = switchSession
+ returnToDraftRef.current = returnToDraft
// A send before the account is known waits for it instead of gating sign-in; the
// composer keeps the text meanwhile, so later edits go with it.
@@ -1070,9 +1074,11 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
if (!sendRef.current(text, draft.images)) composerRef.current?.restoreDraft(draft)
}, [booting])
- function resetLocalDraft(pushHistory = false) {
- composerRef.current?.clearDraft()
- try { clearGuestDraft(window.sessionStorage) } catch { /* Storage is optional. */ }
+ function resetLocalDraft(pushHistory = false, { keepTyping = false } = {}) {
+ if (!keepTyping) {
+ composerRef.current?.clearDraft()
+ try { clearGuestDraft(window.sessionStorage) } catch { /* Storage is optional. */ }
+ }
setEntries([])
setArtifactRevision(0)
setActiveTurnId(null)
@@ -1141,6 +1147,20 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
resetLocalDraft(hasIdentity && activeSession.current !== 'draft')
}
+ // Back or Forward to a URL that opens no chat: show a new chat as New chat does,
+ // but keep what's typed, as switching chats does. The URL is already in history,
+ // so this adds no entry; an `s` that cannot name a chat is dropped with the
+ // notice the first paint shows.
+ function returnToDraft(missing: boolean) {
+ document.documentElement.classList.remove('chat-url')
+ focusPrompt()
+ bootAbandoned.current = true
+ pendingSend.current = false
+ setChatReady(true)
+ resetLocalDraft(false, { keepTyping: true })
+ if (missing) setInteractionNotice({ tone: 'error', text: 'That chat does not exist or is not yours.' })
+ }
+
async function removeSession(id: string) {
// Gated on the account, not the open chat: the sidebar deletes other chats.
if (!hasIdentity || authBlocked || id === 'draft') return
@@ -1152,7 +1172,8 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
setSessions(remaining)
// While the page boots, the open chat is the one its URL is still loading;
// leaving it abandons that load so it cannot reopen the deleted chat.
- const openId = chatReady ? activeSession.current : sanitizeSessionId(new URLSearchParams(window.location.search).get('s'))
+ const fromUrl = urlChat(window.location.search)
+ const openId = chatReady ? activeSession.current : fromUrl.kind === 'chat' ? fromUrl.id : 'draft'
let leaving: Promise<void> | undefined
if (id === openId) {
const next = remaining[0]
diff --git a/lib/accounts.ts b/lib/accounts.ts
index 0d88161..9c5bd63 100644
--- a/lib/accounts.ts
+++ b/lib/accounts.ts
@@ -1,4 +1,9 @@
// Server-only account metadata and authoritative chat ownership; no OAuth tokens.
+// @ts-expect-error Node strip-types tests require the source extension.
+import { validSessionId } from './session-id.ts'
+
+export { validSessionId }
+
export interface AccountUser {
id: string
name: string
@@ -42,10 +47,6 @@ export async function withAccountDatabase<T>(work: (query: AccountQuery) => Prom
timeoutMs ? { fetchOptions: { signal: AbortSignal.timeout(timeoutMs) } } : undefined) as Record<string, unknown>[])
}
-export function validSessionId(id: unknown): id is string {
- return typeof id === 'string' && /^[a-z0-9-]{1,40}$/.test(id)
-}
-
export function isNewSessionId(id: unknown): id is string {
return typeof id === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)
}
diff --git a/lib/session-id.ts b/lib/session-id.ts
index 0d0f57b..952faf1 100644
--- a/lib/session-id.ts
+++ b/lib/session-id.ts
@@ -1,3 +1,18 @@
+// A chat ID as fx0 stores and checks it. Pure, so the browser uses the same rule.
+export function validSessionId(id: unknown): id is string {
+ return typeof id === 'string' && /^[a-z0-9-]{1,40}$/.test(id)
+}
+
+// What a page URL opens, by the rule the server's first paint uses: no `s` is a
+// new chat, and an `s` that cannot name a chat is a new chat with a notice.
+export type UrlChat = { kind: 'new' } | { kind: 'chat'; id: string } | { kind: 'invalid' }
+
+export function urlChat(search: string): UrlChat {
+ const requested = new URLSearchParams(search).get('s')
+ if (requested === null) return { kind: 'new' }
+ return validSessionId(requested) ? { kind: 'chat', id: requested } : { kind: 'invalid' }
+}
+
export function sanitizeSessionId(raw: string | null | undefined): string {
const id = String(raw ?? '')
.toLowerCase()
diff --git a/tests/core.test.mjs b/tests/core.test.mjs
index fedb8bb..7fb8668 100644
--- a/tests/core.test.mjs
+++ b/tests/core.test.mjs
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict'
import test from 'node:test'
+import { urlChat } from '../lib/session-id.ts'
import './runtime.test.mjs'
import {
DESIGN_ARTIFACT_EMBEDDED_CSP,
@@ -721,3 +722,13 @@ test('the first user bubble shows the design.md only when the server applied it'
])
assert.equal(replayed.entries[0].designMd, 'Stripe')
})
+
+test('a page URL opens a chat only when its s names one, by the first paint\'s rule', () => {
+ assert.deepEqual(urlChat(''), { kind: 'new' })
+ assert.deepEqual(urlChat('?preview=1'), { kind: 'new' })
+ assert.deepEqual(urlChat('?s=0f8e2a3c-1b2d-4c5e-8f90-123456789abc&preview=1'), { kind: 'chat', id: '0f8e2a3c-1b2d-4c5e-8f90-123456789abc' })
+ // An s that cannot name a chat is never cleaned up into one, and never `lobby`.
+ for (const search of ['?s=', '?s=Chat-A', '?s=..%2Fchat', `?s=${'a'.repeat(41)}`]) {
+ assert.deepEqual(urlChat(search), { kind: 'invalid' }, search)
+ }
+})
diff --git a/tests/guest-ui.test.mjs b/tests/guest-ui.test.mjs
index a918476..60db745 100644
--- a/tests/guest-ui.test.mjs
+++ b/tests/guest-ui.test.mjs
@@ -351,6 +351,57 @@ test('the first prompt response retains trial eligibility when a signed-in draft
assert.equal(ui.requests.some(({ url }) => url === '/api/session?session=admitted-trial'), false)
})
+// The browser pressing Back or Forward to `search`.
+function navigate(search) {
+ window.location.href = `http://localhost/${search}`
+ window.location.search = search
+ window.dispatchEvent(new Event('popstate'))
+}
+
+test('Back from a chat to the new-chat page shows a new chat, keeps what was typed, and its next prompt starts a new chat', async (t) => {
+ t.mock.method(console, 'info', () => {})
+ const ui = browser(t, {
+ '/api/events?session=chat-a&after=1': () => new Response(''),
+ '/api/prompt?session=new': () => new Response('', { headers: { 'content-type': 'text/event-stream', 'x-fx0-session': 'chat-b' } }),
+ '/api/events?session=chat-b&after=0': () => new Response(''),
+ })
+ const app = mount(t, ui, {
+ ...guestBoot, user: { id: 'user-1', name: 'User', email: null, picture: null }, sessionId: 'chat-a',
+ sessions: [{ id: 'chat-a', title: 'chat-a', createdAt: 1, lastActivity: 1, busy: false }],
+ events: [{ type: 'user', seq: 1, id: 1, text: 'Earlier design' }],
+ })
+ await tick()
+ app.render()
+ app.handle().restoreDraft(draft)
+ navigate('')
+ await tick()
+ app.render()
+ assert.equal(find(app.tree(), (node) => node.type === Transcript).props.sessionId, 'draft')
+ assert.deepEqual(app.handle().getDraft(), { ...draft, designMd: null }, 'Back keeps what was typed')
+ app.send()
+ await tick()
+ app.render()
+ assert.deepEqual(ui.requests.filter(({ url }) => url.startsWith('/api/prompt')).map(({ url }) => url), ['/api/prompt?session=new'])
+ assert.equal(ui.requests.some(({ url }) => url.startsWith('/api/session?')), false, 'Back loads no chat')
+})
+
+test('Back to a link whose chat ID is invalid shows a new chat with the first paint\'s notice', async (t) => {
+ t.mock.method(console, 'info', () => {})
+ const ui = browser(t, { '/api/events?session=chat-a&after=1': () => new Response('') })
+ const app = mount(t, ui, {
+ ...guestBoot, user: { id: 'user-1', name: 'User', email: null, picture: null }, sessionId: 'chat-a',
+ events: [{ type: 'user', seq: 1, id: 1, text: 'Earlier design' }],
+ })
+ await tick()
+ app.render()
+ navigate('?s=Not-A-Chat')
+ await tick()
+ app.render()
+ assert.equal(find(app.tree(), (node) => node.type === Transcript).props.sessionId, 'draft')
+ assert.equal(find(app.tree(), (node) => node.props?.role === 'status' && node.props['aria-live'] === 'polite').props.children, 'That chat does not exist or is not yours.')
+ assert.equal(ui.requests.some(({ url }) => url.startsWith('/api/session?')), false)
+})
+
test('account bootstrap clears a stale signed-in hint after the account is known', (t) => {
const ui = browser(t)
document.cookie = 'fx0-signed-in=1'