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

Keep each chat's activity timer when switching chats

Pranitad74ee1d140d
diff --git a/components/chat-app.tsx b/components/chat-app.tsx
index 38096f8..2cdfaa5 100644
--- a/components/chat-app.tsx
+++ b/components/chat-app.tsx
@@ -46,12 +46,16 @@ import SourceLink from './source-link'
import {
DEFAULT_VIEW,
applyStreamItem,
+ endActivity,
isPreviewOpenFromSearch,
joinedMessageId,
mergeSessionView,
projectSessionView,
+ renameActivity,
replayEvents,
+ startActivity,
upsertSession,
+ type ActivityStarts,
} from './chat-state'
import type { ChatEntry } from './thread'
import Transcript from './transcript'
@@ -281,8 +285,9 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
const [activeTurnId, setActiveTurnId] = useState<number | null>(initialState.activeTurnId)
const [turnStartedAt, setTurnStartedAt] = useState<number | null>(initialState.activeTurnStartedAt)
// The wait the user feels starts at send, not at the server's turn_start, so the
- // counter runs through "sending" and "thinking" instead of sitting at 0s.
- const [sentAt, setSentAt] = useState<number | null>(null)
+ // counter runs through "sending" and "thinking" instead of sitting at 0s. Kept
+ // per chat, so switching to another chat and back doesn't restart it.
+ const [activityStarts, setActivityStarts] = useState<ActivityStarts>(() => new Map())
const [awaiting, setAwaiting] = useState(false)
const [authStatus, setAuthStatus] = useState<401 | 403 | null>(null)
const [signOutStatus, setSignOutStatus] = useState<'pending' | 'failed' | null>(null)
@@ -1215,7 +1220,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
const designPick = targetSession === 'draft' ? composerRef.current?.getDesignMd() ?? null : null
// The bubble shows at once, before a draft's chat is reserved on the server.
setAwaiting(true)
- setSentAt((current) => current ?? Date.now())
+ setActivityStarts((starts) => startActivity(starts, targetSession, Date.now()))
setInteractionNotice(null)
setEntries((prev) => [
...prev,
@@ -1348,6 +1353,7 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
if (admittedTrialChat) createdSummary.trialChat = true
// Promote the draft in place, unless the user already moved elsewhere.
cacheSession(created, { transcript: compactTranscript([], DEFAULT_VIEW), summary: createdSummary })
+ setActivityStarts((starts) => renameActivity(starts, targetSession, created))
if (activeSession.current === targetSession) {
activeSession.current = created
setSessionId(created)
@@ -1653,9 +1659,11 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
?.text?.trim()
const announcement = interactionNotice?.text ?? activityText
+ // Only the chat on screen can end its activity: leaving one mid-turn keeps its start.
useEffect(() => {
- if (!activityText) setSentAt(null)
- }, [activityText])
+ if (!activityText) setActivityStarts((starts) => endActivity(starts, sessionId))
+ }, [activityText, sessionId])
+ const activityStartedAt = activityStarts.get(sessionId) ?? turnStartedAt
const visibleErrorNotice =
interactionNotice?.tone === 'error' ? interactionNotice : null
@@ -1974,13 +1982,13 @@ export default function ChatApp({ account, sidebar, boot, preference, defaultMod
onOpenRevision={canAccessSession ? openRevision : undefined} onSend={sendFromTranscript} />
))}
- {activityText && <ActivityLine label={activityText} startedAt={sentAt ?? turnStartedAt} />}
+ {activityText && <ActivityLine label={activityText} startedAt={activityStartedAt} />}
</div>
</div>
{previewOpen && activityText && (
<div className="order-2 shrink-0 border-b border-border px-4 py-2 lg:hidden">
- <ActivityLine label={activityText} startedAt={sentAt ?? turnStartedAt} />
+ <ActivityLine label={activityText} startedAt={activityStartedAt} />
{latestAssistantText && (
<p className="line-clamp-2 font-mono text-[11px] leading-4 text-foreground-tertiary">
{latestAssistantText}
diff --git a/components/chat-state.ts b/components/chat-state.ts
index fdc5bb6..419e59c 100644
--- a/components/chat-state.ts
+++ b/components/chat-state.ts
@@ -350,6 +350,31 @@ export function waitingLabel(
// The message a status item says joined another message's running turn, which
// no longer waits.
+// When each chat's current activity began on this device, so its counter keeps
+// counting after switching to another chat and back. A send while the chat is
+// busy keeps the first start; a chat drops its start once its activity ends.
+export type ActivityStarts = ReadonlyMap<string, number>
+
+export function startActivity(starts: ActivityStarts, chatId: string, now: number): ActivityStarts {
+ return starts.has(chatId) ? starts : new Map(starts).set(chatId, now)
+}
+
+// A draft's chat gets its ID once the server accepts its first prompt.
+export function renameActivity(starts: ActivityStarts, from: string, to: string): ActivityStarts {
+ const at = starts.get(from)
+ if (at === undefined) return starts
+ const next = new Map(starts)
+ next.delete(from)
+ return next.set(to, at)
+}
+
+export function endActivity(starts: ActivityStarts, chatId: string): ActivityStarts {
+ if (!starts.has(chatId)) return starts
+ const next = new Map(starts)
+ next.delete(chatId)
+ return next
+}
+
export function joinedMessageId(item: StreamItem): number | null {
return item.type === 'status' && item.id != null && item.turnId != null && item.id !== item.turnId ? item.id : null
}
diff --git a/tests/core.test.mjs b/tests/core.test.mjs
index d0f6df5..39aa737 100644
--- a/tests/core.test.mjs
+++ b/tests/core.test.mjs
@@ -10,12 +10,15 @@ import {
} from '../lib/design-artifact.ts'
import {
applyStreamItem,
+ endActivity,
groupThreadEntries,
isPreviewOpenFromSearch,
mergeSessionView,
projectSessionView,
+ renameActivity,
replayEvents,
shouldAcceptSessionEvent,
+ startActivity,
upsertSession,
waitingLabel,
} from '../components/chat-state.ts'
@@ -460,6 +463,36 @@ test('out-of-order view responses and events cannot roll back the client view',
assert.equal(projectSessionView(view, { type: 'artifact', artifactRevision: 4 }), view)
})
+test('a chat keeps its activity start after switching to another chat and back', () => {
+ // What chat-app's effect does on each render: only the chat on screen, showing
+ // no activity, ends its start.
+ const shown = (starts, chatId, active) => (active ? starts : endActivity(starts, chatId))
+ let starts = new Map()
+ starts = startActivity(starts, 'draft', 1_000) // the first prompt of a new chat
+ starts = renameActivity(starts, 'draft', 'chat-a') // the server names the chat
+ starts = shown(starts, 'chat-a', true)
+ starts = shown(starts, 'draft', false) // 30s in: open a new chat
+ starts = shown(starts, 'chat-b', false) // and an idle one
+ starts = shown(starts, 'chat-a', true) // back while it still generates
+ assert.equal(starts.get('chat-a'), 1_000)
+ // A message sent while it is busy keeps the first start.
+ assert.equal(startActivity(starts, 'chat-a', 40_000).get('chat-a'), 1_000)
+
+ // The turn ends on screen: the next send starts its own count.
+ starts = shown(starts, 'chat-a', false)
+ assert.equal(starts.has('chat-a'), false)
+ starts = startActivity(starts, 'chat-a', 60_000)
+ // It ends while another chat is open: coming back to the idle chat drops it.
+ starts = shown(starts, 'draft', false)
+ assert.equal(starts.get('chat-a'), 60_000)
+ starts = shown(starts, 'chat-a', false)
+ assert.equal(startActivity(starts, 'chat-a', 90_000).get('chat-a'), 90_000)
+
+ // No change returns the same map, so React skips the update.
+ assert.equal(endActivity(starts, 'chat-b'), starts)
+ assert.equal(renameActivity(starts, 'draft', 'chat-c'), starts)
+})
+
test('previous-session events are rejected before sequence dedupe mutates', () => {
const seen = new Set([1])
assert.equal(shouldAcceptSessionEvent('active', 'previous', { type: 'error', seq: 2 }, seen), false)