Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import {
type TaskKey,
type TaskState,
makeTaskKey,
parseTaskKey,
useAgentTaskTracker,
} from '@contexts/AgentTaskTrackerContext'
import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'
import {
COMPOSER_MAX_ATTACHMENTS,
COMPOSER_MAX_NON_IMAGE_BODY_BYTES,
COMPOSER_MAX_REQUEST_BODY_BYTES,
COMPOSER_MAX_TOTAL_FILE_BASE64_BYTES,
} from '@constants/attachments'
import {
buildChatMessageAttachments,
buildResponseFileAttachments,
} from '@lib/chatMessageAttachments'
import { runChatSwitchRequest } from '@lib/chatSwitchRequest'
import type { PendingChatSwitchRequest, ProvisionalSelection } from '@lib/chatSwitchRequest.types'
import { truncateTitle } from '@lib/chatTitle'
import {
clearAllComposerDrafts,
clearComposerDraft,
getComposerDraft,
getComposerDraftRevision,
setComposerDraft,
} from '@lib/composerDraftStore'
import {
composerFileBase64Bytes,
composerNonImageShareBytes,
composerRequestBodyBytes,
formatFileSize,
} from '@lib/composerFileAdmission'
import { buildComposerFileReferences } from '@lib/composerFileReferences'
import {
composerRequestBaseContent,
mapComposerAttachmentsToHostRequest,
} from '@lib/composerHostRequest'
import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'
import {
confirmHostModelSelectionFromSend,
dropIgnoredHostModelIntent,
loadHostModels,
noteHostModelSelectionConflict,
readHostModelSelection,
} from '@lib/hostModelSelectionStore'
import { createRetainedSendStore } from '@lib/retainedSendStore'
import {
mergeAuthoritativeServerMessages,
messageServerTurnNumber,
} from '../../../../src/chatMessageMerge'
import type {
ChatMessageAttachment,
HostActivityEvent,
HostActivityStreamEvent,
MessageToolStep,
SessionMessagesQuery,
} from '../../../../src/types'
import type { SessionMessagesResult } from '../../../../src/types'
import { DESKTOP_ROUTES } from '../../constants/navigation'
import {
classifyErrorKind,
errorRecoveryHint,
extractAssistantReply,
isAuthorizationError,
isConfirmedHostAccessRevoked,
isHttp403,
isHttp404,
isNetworkError,
} from '../../lib/format'
import type {
AgentApprovalNotificationTarget,
AgentChatMessage,
AgentConversationNotificationTarget,
AgentMessageActivity,
ComposerImageAttachment,
ComposerReferenceAttachment,
DesktopNotificationPayload,
DesktopNotificationPermission,
FailedAgentSend,
NavItem,
ProgressStep,
ReadyComposerFileAttachment,
TaskProgress,
Tone,
} from '../../uiTypes'
import { turnsToChatMessages } from '../sessionAdapter'
import { useChatStore } from '../useChatStore'
import {
type ReconcileChat,
type ReconcileChatArgs,
type ReconcileChatDeps,
createReconcileChat,
} from './reconcileChat'
import {
type SessionFsmEffect,
type SessionFsmEvent,
type SessionFsmStore,
type SessionStateProjection,
createSessionFsmStore,
projectSessionState,
} from './sessionFsm'
import { mapTrackerStatusToProgress, readApprovalInputPreview } from './trackerToProgress'
import { type TranscriptMemoEntry, createTranscriptMemo, transcriptMemoKey } from './transcriptMemo'
import type { PushNotificationInput } from './types'
import {
type ChatListControllerHost,
type LatestSidebarChatEntry,
type PendingChatSelection,
type SidebarChatEntry,
useChatListController,
} from './useChatListController'
import { type ActiveChatVisibility, useChatNotifications } from './useChatNotifications'
import { useChatScroll } from './useChatScroll'
import { useComposerAttachments } from './useComposerAttachments'
import type { PushToastOptions } from './useToastController'
// Re-exported from `useChatListController` (§4.4) so external importers
// (useWorkspaceController, useActivityController) keep their import site.
export type { SidebarChatEntry, LatestSidebarChatEntry }
/**
* Per-chat session lifecycle snapshot, keyed by `makeTaskKey(agentRef, chatId)`.
* Populated from the server (D.1 fields via listSessions / loadSessionMessages)
* and consumed by the UI (D.5 badges/syncing/offline indicators). `syncing` is
* true while a Phase-2 reconcile is in flight for that chat.
*
* Single source of truth: this is a re-exported alias of the FSM's
* `SessionStateProjection` (sessionFsm.ts) — `projectSessionState` produces it and
* the many existing importers keep this name.
*/
export type SessionStateLite = SessionStateProjection
const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100
/**
* B14 cap: max number of per-message activity/progress entries retained per agent.
* On a task terminal (§4.1 cleanup transition) the oldest entries beyond this cap
* are pruned so the two maps can't grow unbounded across a long-lived session. The
* most-recent N (insertion order) are kept — any still-in-flight message is among
* them — and an evicted completed message's stepper still reloads from its
* persisted `toolSteps` (#582 fallback in ChatThread).
*/
const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50
const LOCAL_MESSAGE_PAGE_SIZE = 80
const SERVER_TURN_PAGE_SIZE = 40
// #1091 A9: transcripts kept for instant reopen. The A/B harness reopens at most
// this many chats per Host, newest first, so the LRU never thrashes there.
const TRANSCRIPT_MEMO_LIMITS = {
maxChats: 8,
maxMessages: 3 * LOCAL_MESSAGE_PAGE_SIZE,
maxAttachmentBase64Chars: 8 * 1024 * 1024,
}
const MAX_RECONCILE_DELTA_PAGES = 5
const FILE_REFERENCES_NOT_RECEIVED_MESSAGE =
'The Host did not receive the selected Global Files; the message was sent without them.'
// #678 D13 — a Host that predates `kind:'file'` either rejects the attachment
// with LLM_INVALID_ATTACHMENT or drops it and still accepts the message.
const HOST_FILE_ATTACHMENTS_UNSUPPORTED_MESSAGE =
'The Host does not accept file attachments yet; the message was not delivered with them. Your files are kept so you can retry once the Host is updated.'
const HOST_FILE_ATTACHMENTS_DROPPED_MESSAGE =
'The Host does not accept file attachments yet; the message was sent without them. Recover the files to attach them again once the Host is updated.'
const HOST_INVALID_ATTACHMENT_CODE = 'LLM_INVALID_ATTACHMENT'
const LATEST_PAGE_FALLBACK_WINDOW = Symbol('latest-page-fallback-window')
const DELTA_RECONCILIATION_WINDOW = Symbol('delta-reconciliation-window')
type ReconciliationMessagesResult = SessionMessagesResult & {
[LATEST_PAGE_FALLBACK_WINDOW]?: true
[DELTA_RECONCILIATION_WINDOW]?: true
}
function serverTurnNumber(message: AgentChatMessage): number | undefined {
return messageServerTurnNumber(message)
}
function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {
return messages.reduce<number | undefined>((oldest, message) => {
const current = serverTurnNumber(message)
return current === undefined ? oldest : Math.min(oldest ?? current, current)
}, undefined)
}
function latestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {
return messages.reduce<number | undefined>((latest, message) => {
const current = serverTurnNumber(message)
return current === undefined ? latest : Math.max(latest ?? current, current)
}, undefined)
}
function sortedUniqueServerTurnNumbers(messages: AgentChatMessage[]): number[] {
return Array.from(
new Set(messages.map(serverTurnNumber).filter((turn): turn is number => turn !== undefined))
).sort((left, right) => left - right)
}
function mergeUniqueSessionTurns(
...turnPages: Array<SessionMessagesResult['turns']>
): SessionMessagesResult['turns'] {
const byNumber = new Map<number, SessionMessagesResult['turns'][number]>()
for (const turns of turnPages) {
for (const turn of turns) {
byNumber.set(turn.number, turn)
}
}
return Array.from(byNumber.values()).sort((left, right) => left.number - right.number)
}
function firstServerTurnGapUpperBound(
messages: AgentChatMessage[],
ignoredGapUpperBounds?: ReadonlySet<number>
): number | undefined {
const turns = sortedUniqueServerTurnNumbers(messages)
for (let index = 1; index < turns.length; index += 1) {
const previous = turns[index - 1]!
const current = turns[index]!
if (current > previous + 1 && !ignoredGapUpperBounds?.has(current)) return current
}
return undefined
}
function nextServerBackfillBeforeTurn(
messages: AgentChatMessage[],
ignoredGapUpperBounds?: ReadonlySet<number>
): number | undefined {
const gapUpperBound = firstServerTurnGapUpperBound(messages, ignoredGapUpperBounds)
if (gapUpperBound !== undefined) return gapUpperBound
const oldestTurn = oldestServerTurnNumber(messages)
return oldestTurn !== undefined && oldestTurn > 1 ? oldestTurn : undefined
}
type ChatStoreClient = ReturnType<typeof useChatStore>
async function hasLocalMessagesBeyond(
chatStore: ChatStoreClient,
agentRef: string,
chatId: string,
offset: number
): Promise<boolean> {
return chatStore
.loadMessages(agentRef, chatId, 1, offset)
.then(messages => messages.length > 0)
.catch(() => false)
}
function mergeUniqueMessages(
existing: AgentChatMessage[],
incoming: AgentChatMessage[],
position: 'before' | 'after' = 'after'
): AgentChatMessage[] {
const source = position === 'before' ? [...incoming, ...existing] : [...existing, ...incoming]
const seen = new Set<string>()
return source.filter(message => {
if (seen.has(message.id)) return false
seen.add(message.id)
return true
})
}
function mergeServerMessages(
existing: AgentChatMessage[],
incoming: AgentChatMessage[],
activeTaskIds?: ReadonlySet<string>,
replaceLegacyTurnlessWindow = false
): AgentChatMessage[] {
return mergeAuthoritativeServerMessages(existing, incoming, {
activeTaskIds,
replaceLegacyTurnlessWindow,
})
}
function sameMessageSequence(a: AgentChatMessage[], b: AgentChatMessage[]): boolean {
return (
a.length === b.length &&
a.every((message, index) => {
const other = b[index]
if (!other) return false
const { timestamp: _timestamp, serverTurnNumber: _serverTurnNumber, ...comparable } = message
const {
timestamp: _otherTimestamp,
serverTurnNumber: _otherServerTurnNumber,
...otherComparable
} = other
return stableJson(comparable) === stableJson(otherComparable)
})
)
}
function stableJson(value: unknown): string {
return JSON.stringify(value, (_key, nested: unknown) => {
if (nested === null || typeof nested !== 'object' || Array.isArray(nested)) return nested
return Object.fromEntries(
Object.entries(nested as Record<string, unknown>).sort(([left], [right]) =>
left.localeCompare(right)
)
)
})
}
/** Keep only the last `n` insertion-ordered keys of a per-message map. Returns the
* same reference when already within the cap (so React state stays identity-stable). */
function pruneToLastN<T>(map: Record<string, T>, n: number): Record<string, T> {
const keys = Object.keys(map)
if (keys.length <= n) return map
const next: Record<string, T> = {}
for (const key of keys.slice(keys.length - n)) next[key] = map[key]!
return next
}
/**
* Downsample the tracker's live `ProgressStep[]` to the minimal, serializable
* `MessageToolStep[]` persisted on the assistant message (#582), so the progress
* stepper's "N tools" view survives a reload. Mirrors the server projection in
* `/messages`. Drops in-flight steps and raw previews/args.
*/
function toMessageToolSteps(steps: ProgressStep[]): MessageToolStep[] | undefined {
const done = steps
.filter(s => s.state === 'completed' || s.state === 'error')
.map(s => ({
toolName: s.toolName,
displayName: s.displayName,
state: s.state as 'completed' | 'error',
...(s.durationMs != null ? { durationMs: s.durationMs } : {}),
...(s.errorSummary ? { errorSummary: s.errorSummary } : {}),
}))
return done.length ? done : undefined
}
function withResponseFileAttachments(
messages: AgentChatMessage[],
attachments: ChatMessageAttachment[]
): AgentChatMessage[] {
if (!attachments.length) return messages
let assistantIndex = -1
for (let index = messages.length - 1; index >= 0; index -= 1) {
if (messages[index]?.role === 'assistant') {
assistantIndex = index
break
}
}
if (assistantIndex < 0) return messages
const existingAttachments = messages[assistantIndex]?.attachments ?? []
const existingIds = new Set(existingAttachments.map(attachment => attachment.id))
const newAttachments = attachments.filter(attachment => !existingIds.has(attachment.id))
if (!newAttachments.length) return messages
return messages.map((message, index) =>
index === assistantIndex
? { ...message, attachments: [...existingAttachments, ...newAttachments] }
: message
)
}
async function loadTaskResultResponseFileAttachments(
agentRef: string,
taskId: string
): Promise<ChatMessageAttachment[]> {
try {
const result = await window.clerum.rpc.getTaskResult(agentRef, taskId, [agentRef])
return buildResponseFileAttachments(result)
} catch (error) {
if (isAuthorizationError(error)) throw error
return []
}
}
// Shared empty maps so the selected-agent activity/progress slices keep a STABLE
// identity when the agent has no entries yet (R-F3): returning a fresh `{}` each
// render made every consumer re-render on unrelated updates (a B4 amplifier).
const EMPTY_ACTIVITY_MAP: Record<string, AgentMessageActivity> = Object.freeze({})
const EMPTY_PROGRESS_MAP: Record<string, TaskProgress> = Object.freeze({})
interface UseAgentChatControllerParams {
selectedAgent: string | null
agentNames: string[]
currentUserId?: string
currentTeamId: string
currentEnvironmentKey: string
currentTeamName: string
isAuthenticated: boolean
loadMenuData: boolean
navItem: NavItem
pushToast: (msg: string, tone: Tone, options?: PushToastOptions) => void
pushNotification: (n: PushNotificationInput) => void
/**
* Human-visible name for an agent identifier (catalog `spec.host` display
* name, identifier fallback). Used for desktop toast titles only — supplied
* by the host (useAppController) so this controller keeps zero TanStack
* Query coupling.
*/
agentDisplayName: (agentName: string) => string
canDeliverChatResponseNotification: (
channel: 'inApp' | 'desktop',
context: { activeChatVisible: boolean }
) => boolean
showDesktopNotification: (
payload: DesktopNotificationPayload
) => Promise<DesktopNotificationPermission>
openAgentConversationFromNotification: (
target: AgentConversationNotificationTarget
) => Promise<void>
decideApprovalFromNotification: (target: AgentApprovalNotificationTarget) => Promise<void>
onHostAccessRevoked: (agentRef: string) => void
onHostAuthorityUncertain: (agentRef: string) => void
isHostAccessBlocked: (agentRef: string) => boolean
getHostAuthorityEpoch: (agentRef: string) => number
/** Changes whenever a Host is held, released, or the authority scope resets. */
hostAuthorityRevision: number
/**
* The authenticated principal's own team (`me.teamId`), with no directory
* fallback. The chat delete fence and its tombstones are scoped to it, the
* same value AppService's `getChatDeletionFenceAuthority` uses.
*/
chatAuthorityTeamId: string
}
export function useAgentChatController({
selectedAgent,
agentNames,
currentUserId,
currentTeamId,
currentEnvironmentKey,
currentTeamName,
isAuthenticated,
loadMenuData,
navItem,
pushToast,
pushNotification,
agentDisplayName,
canDeliverChatResponseNotification,
showDesktopNotification,
openAgentConversationFromNotification,
decideApprovalFromNotification,
onHostAccessRevoked,
onHostAuthorityUncertain,
isHostAccessBlocked,
getHostAuthorityEpoch,
hostAuthorityRevision,
chatAuthorityTeamId,
}: UseAgentChatControllerParams) {
const chatStore = useChatStore()
const userScopeKey = currentUserId ?? 'unknown-user'
const normalizedTeamId = String(currentTeamId || '').trim() || null
const fenceTeamId = chatAuthorityTeamId.trim() || null
const authorityScope = useMemo(
() => ({
environmentKey: currentEnvironmentKey,
userId: userScopeKey,
teamId: fenceTeamId,
}),
[currentEnvironmentKey, fenceTeamId, userScopeKey]
)
const authenticatedScope = `${currentEnvironmentKey}:${userScopeKey}:${normalizedTeamId ?? ''}`
useEffect(() => {
chatStore.setRemoteCacheScope(
isAuthenticated ? `authenticated:${authenticatedScope}` : 'signed-out'
)
}, [authenticatedScope, chatStore.setRemoteCacheScope, isAuthenticated])
const tracker = useAgentTaskTracker()
const [activeChatId, setActiveChatId] = useState<string | null>(null)
const selectionIntentRevisionRef = useRef(0)
// Effects can share an in-flight execution or its successful same-intent
// result. A previously rejected execution instead permits an independent retry.
const pendingChatSwitchRequestRef = useRef<PendingChatSwitchRequest | null>(null)
const activeChatSwitchRequestRef = useRef<symbol | null>(null)
const activeChatSwitchKeyRef = useRef<string | null>(null)
// Fase 2b (§4.1): the SessionFSM is now the SINGLE writer of the per-chat
// session projection. `sessionStateByChatKey` (the public contract) is derived
// from the reducer's map via `useSyncExternalStore` + `projectSessionState`.
// The store instance is stable for the hook's lifetime (per-mount, so test
// renders stay isolated).
const fsmStore = useRef<SessionFsmStore | null>(null)
if (!fsmStore.current) fsmStore.current = createSessionFsmStore()
const fsm = fsmStore.current
const fsmMap = useSyncExternalStore(fsm.subscribe, fsm.getSnapshot)
// §4.4 / §5d: the whole sidebar chat-list subsystem — the per-agent `chatList`
// (+loading) and its loader, the cross-agent "Latest sessions" list, the
// pending-selection ref, chat CRUD, and the narrow mutation API the flows below
// call — lives in useChatListController. The active-chat concerns CRUD needs
// (switchToChat/scrollChatToBottom/dispatchSession/clearComposerDraft/the live
// activeChatId) are injected through `chatListHostRef`, filled each render once
// those parent callbacks are defined (created here so the hook can receive it).
const chatListHostRef = useRef<ChatListControllerHost | null>(null)
const hideHostAccessRef = useRef<
((agentRef: string, kind: 'revoked' | 'uncertain') => void) | null
>(null)
const onCatalogHostAccessRevoked = useCallback(
(agentRef: string) => hideHostAccessRef.current!(agentRef, 'revoked'),
[]
)
const onCatalogHostAuthorityUncertain = useCallback(
(agentRef: string) => hideHostAccessRef.current!(agentRef, 'uncertain'),
[]
)
const autoSelectedChatIdRef = useRef<string | null>(null)
const chatListCtl = useChatListController({
selectedAgent,
agentNames,
isAuthenticated,
scopeKey: authenticatedScope,
// User portion of the scope only (NOT the combined user:team scopeKey): the
// pending-rename queue is per-user and must survive a team-switch (R1-H1).
authUserKey: currentUserId ?? 'unknown-user',
authorityScope,
loadMenuData,
chatStore,
fsm,
host: chatListHostRef,
isHostAccessBlocked,
getHostAuthorityEpoch,
hostAuthorityRevision,
onHostAccessRevoked: onCatalogHostAccessRevoked,
onHostAuthorityUncertain: onCatalogHostAuthorityUncertain,
})
const {
chatList,
chatListLoading,
chatListMoreLoading,
chatListHasMoreRemoteSessions,
latestChatSessions,
latestChatSessionsLoading,
hideAgent,
loadChatList,
loadMoreChatSessions,
setChatListLoading,
clearList,
markUnreadInList,
clearUnreadInList,
upsertProvisionalEntry,
applyEntryTitle,
applyLatestTitle,
upsertHydratedEntry,
removeFromList,
bumpActivity,
appendNewEntry,
readPendingSelection,
writePendingSelection,
clearPendingSelection,
isChatDeleted,
} = chatListCtl
const [chatMessages, setChatMessages] = useState<AgentChatMessage[]>([])
const [chatMessagesLoading, setChatMessagesLoadingState] = useState(false)
const chatMessagesLoadingRef = useRef(false)
const setChatMessagesLoading = useCallback((loading: boolean) => {
chatMessagesLoadingRef.current = loading
setChatMessagesLoadingState(loading)
}, [])
const [hasOlderMessages, setHasOlderMessages] = useState(false)
const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)
const chatMessagesRef = useRef<AgentChatMessage[]>([])
const loadedLocalMessageCountRef = useRef(0)
const olderMessagesRequestRef = useRef<symbol | null>(null)
const unfillableServerGapUpperBoundsRef = useRef<Map<string, Set<number>>>(new Map())
const cancelOlderMessagesLoad = useCallback(() => {
olderMessagesRequestRef.current = null
setOlderMessagesLoading(false)
}, [])
// #1091 A17: a chat shown from memory before its last-active write and first
// local page settled. Without the memo this state was the blank view with the
// spinner, and every path below relied on that. `revision` is the selection
// intent that owns it. Invariant: the mark exists only at the current
// revision. `beginSelectionIntent` retires it on every advance, and a
// same-row click that finds it live passes it on to its own intent as a new
// object, so a superseded mark can never be revived by a later click.
const provisionalSelectionRef = useRef<ProvisionalSelection | null>(null)
const provisionalSelectionFor = useCallback((agentRef: string | null, chatId: string | null) => {
const selection = provisionalSelectionRef.current
return selection &&
selection.request === activeChatSwitchRequestRef.current &&
selection.agentRef === agentRef &&
selection.chatId === chatId
? selection
: null
}, [])
/** Withdraw an unconfirmed transcript: the view returns to what the base showed, blank. */
const withdrawProvisionalSelection = useCallback(() => {
if (!provisionalSelectionRef.current) return
provisionalSelectionRef.current = null
// Retire the request so a page an older click already started cannot publish.
activeChatSwitchRequestRef.current = null
activeChatSwitchKeyRef.current = null
activeChatLocalPageRequestRef.current = null
cancelOlderMessagesLoad()
// Invariant: the ref is cleared with the state, not by the passive sync
// effect. Merges read the ref, and a merge that runs before that effect
// would otherwise build on the withdrawn transcript. Under `act` the effect
// always runs first, so no unit test can observe this line.
chatMessagesRef.current = []
setChatMessages([])
setHasOlderMessages(false)
loadedLocalMessageCountRef.current = 0
}, [cancelOlderMessagesLoad])
const beginSelectionIntent = useCallback(
(startsHistoryLoad = false) => {
// A switch that follows keeps the view; it inherits a live mark itself.
if (startsHistoryLoad) provisionalSelectionRef.current = null
else withdrawProvisionalSelection()
selectionIntentRevisionRef.current += 1
if (!startsHistoryLoad) {
setChatMessagesLoading(false)
activeChatSwitchRequestRef.current = null
activeChatSwitchKeyRef.current = null
}
return selectionIntentRevisionRef.current
},
[setChatMessagesLoading, withdrawProvisionalSelection]
)
const settleChatMessagesLoading = useCallback(
(selectionIntentRevision: number) => {
if (selectionIntentRevisionRef.current !== selectionIntentRevision) return false
setChatMessagesLoading(false)
return true
},
[setChatMessagesLoading]
)
const ignoredServerGapUpperBounds = useCallback((agentRef: string, chatId: string) => {
return unfillableServerGapUpperBoundsRef.current.get(makeTaskKey(agentRef, chatId))
}, [])
const markServerGapUnfillable = useCallback(
(agentRef: string, chatId: string, beforeTurn: number) => {
const key = makeTaskKey(agentRef, chatId)
const gaps = unfillableServerGapUpperBoundsRef.current.get(key) ?? new Set<number>()
gaps.add(beforeTurn)
unfillableServerGapUpperBoundsRef.current.set(key, gaps)
},
[]
)
const [activityByAgentMessage, setActivityByAgentMessage] = useState<
Record<string, Record<string, AgentMessageActivity>>
>({})
const [progressByAgentMessage, setProgressByAgentMessage] = useState<
Record<string, Record<string, TaskProgress>>
>({})
useEffect(() => {
chatMessagesRef.current = chatMessages
}, [chatMessages])
const [agentSending, setAgentSending] = useState(false)
const [agentError, setAgentError] = useState<string | null>(null)
const [failedAgentSend, setFailedAgentSend] = useState<FailedAgentSend | null>(null)
const [retainedRevision, setRetainedRevision] = useState(0)
const [retainedSends] = useState(() =>
createRetainedSendStore(() => setRetainedRevision(value => value + 1))
)
const {
retainSendSnapshot,
attachTaskIdToRetainedSend,
releaseRetainedSend,
releaseRetainedSendsForTask,
releaseRetainedFailuresForChat,
releaseSucceededRetainedSend,
releaseSucceededRetainedSendsForTask,
getRetainedSendsForTask,
markRetainedSendReason,
failRetainedSend,
} = retainedSends
const sendScopeGeneration = useRef(0)
const currentAuthScopeRef = useRef(`${isAuthenticated}:${authenticatedScope}`)
currentAuthScopeRef.current = `${isAuthenticated}:${authenticatedScope}`
// #654 M5 — the userMessageId of the most recent send that retained its
// payload. A retry compares it before and after to learn whether it retained
// a snapshot of its own; `sendAgentMessage` has several early returns (image
// guard, running task, send in flight) that retain nothing.
const lastRetainedSendIdRef = useRef<string | null>(null)
const lastRetentionScope = useRef(`${isAuthenticated}:${authenticatedScope}`)
useEffect(() => {
const scope = `${isAuthenticated}:${authenticatedScope}`
if (lastRetentionScope.current === scope) return
lastRetentionScope.current = scope
clearAllComposerDrafts()
// The memo key already carries the scope; this frees the previous scope's entries.
transcriptMemoRef.current?.clear()
sendScopeGeneration.current += 1
agentSendSetupOwnerRef.current = null
agentSendInFlightRef.current = false
setAgentSending(false)
retainedSends.resetRetainedSendStore()
parkedRestorationsRef.current.clear()
setFailedAgentSend(null)
setAgentError(null)
}, [authenticatedScope, isAuthenticated, retainedSends])
const activityUnsubByAgentRef = useRef<Record<string, () => Promise<void>>>({})
const activityInFlightByAgentRef = useRef<Record<string, string[]>>({})
const activityTaskToMessageByAgentRef = useRef<Record<string, Record<string, string>>>({})
const agentSendInFlightRef = useRef(false)
const agentSendSetupOwnerRef = useRef<{ id: symbol; agentRef: string } | null>(null)
// (Phase-2 AbortController + `recoveringTaskIdByKeyRef` removed in Fase 5b: the
// reconcile gate's per-call `isRelevant` covers the A→B→A abort, and the
// epoch-anchored zombie-ack in `settleIdle` (R2) covers the residual-recreated-
// during-await case without taskId bookkeeping.)
// D.5 / D.4-AC11: the user input behind each in-flight task (so a "ghost"
// terminal can offer a one-click Resend) now lives in the coordinator with an
// explicit lifecycle (spec §4.2, B15) — `tracker.setResend`/`getResend`, cleared
// on `release`. No longer a hook-owned ref (B15/B16 shed one of the two refs).
const activeChatVisibilityRef = useRef<ActiveChatVisibility>({
activeChatId: null,
currentTeamId,
navItem,
selectedAgent,
})
// #1091 A9: per-mount, like the FSM store, so test renders stay isolated.
const transcriptMemoRef = useRef<ReturnType<typeof createTranscriptMemo> | null>(null)
if (!transcriptMemoRef.current) {
transcriptMemoRef.current = createTranscriptMemo(TRANSCRIPT_MEMO_LIMITS)
}
const transcriptMemo = transcriptMemoRef.current
const chatTranscriptMemoKey = useCallback(
(agentRef: string, chatId: string) =>
transcriptMemoKey(currentAuthScopeRef.current, agentRef, chatId),
[]
)
// Every change to the visible transcript (send, stream, hydrate, older page)
// goes through `chatMessages`, so recording each settled commit keeps the memo
// current. A commit whose state does not match the visible selection is a
// transition between chats and is skipped. A held Host or a deleted chat is
// never recorded: its entry was withdrawn and must not come back on release.
useEffect(() => {
if (chatMessagesLoading || !activeChatId || !selectedAgent) return
if (isHostAccessBlocked(selectedAgent) || isChatDeleted(selectedAgent, activeChatId)) return
const visible = activeChatVisibilityRef.current
if (visible.activeChatId !== activeChatId || visible.selectedAgent !== selectedAgent) return
transcriptMemo.set(chatTranscriptMemoKey(selectedAgent, activeChatId), {
messages: chatMessages,
hasOlderMessages,
loadedLocalMessageCount: loadedLocalMessageCountRef.current,
})
}, [
activeChatId,
chatMessages,
chatMessagesLoading,
chatTranscriptMemoKey,
hasOlderMessages,
isChatDeleted,
isHostAccessBlocked,
selectedAgent,
transcriptMemo,
])
const rememberedTranscript = useCallback(
(agentRef: string, chatId: string): TranscriptMemoEntry | undefined => {
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return undefined
return transcriptMemo.get(chatTranscriptMemoKey(agentRef, chatId))
},
[chatTranscriptMemoKey, isChatDeleted, isHostAccessBlocked, transcriptMemo]
)
/** Show a newly selected chat: its remembered transcript, or a blank list with the spinner. */
const presentSelectedTranscript = useCallback(
(remembered: TranscriptMemoEntry | undefined) => {
cancelOlderMessagesLoad()
if (remembered) {
chatMessagesRef.current = remembered.messages
setChatMessages(remembered.messages)
setChatMessagesLoading(false)
setHasOlderMessages(remembered.hasOlderMessages)
loadedLocalMessageCountRef.current = remembered.loadedLocalMessageCount
return
}
setChatMessages([])
setChatMessagesLoading(true)
setHasOlderMessages(false)
loadedLocalMessageCountRef.current = 0
},
[cancelOlderMessagesLoad, setChatMessagesLoading]
)
// Correlate the visible local page to the switch request that loaded it.
const activeChatLocalPageRequestRef = useRef<{
request: symbol
} | null>(null)
// Latest `pushToast` for the hoisted tracker callbacks (onTrackerTerminal reads
// it) so that `tracker.setCallbacks` can run once (cross-ref D.3 M1) without
// closing over a stale toast fn. Assigned in an effect, not the render body
// (closes R-F12): the `useRef` initializer already holds the mount-time value
// and onTrackerTerminal can only fire after the tracker callbacks are
// registered in a later effect, so no read ever precedes the first assignment.
const liveDepsRef = useRef({ pushToast })
useEffect(() => {
liveDepsRef.current = { pushToast }
}, [pushToast])
// §4.3 single-flight reconciler. Created ONCE (its single-flight/coalescing
// state must survive re-renders), reading live branch callbacks through a ref
// (assigned in an effect, not the render body — R-F12) so the instance stays
// stable while the closures it calls track the latest state.
const reconcileBranchesRef = useRef<{
loadSessionMessages: ReconcileChatDeps['loadSessionMessages']
attachLiveTask: ReconcileChatDeps['attachLiveTask']
settleIdle: ReconcileChatDeps['settleIdle']
revokeAccess: ReconcileChatDeps['revokeAccess']
holdAccess: ReconcileChatDeps['holdAccess']
} | null>(null)
const reconcileChatRef = useRef<ReconcileChat | null>(null)
if (!reconcileChatRef.current) {
reconcileChatRef.current = createReconcileChat({
fsm,
loadSessionMessages: (agentRef, chatId, query, stillRelevant) =>
reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId, query, stillRelevant),
attachLiveTask: (chatKey, resp, epoch, stillRelevant) =>
reconcileBranchesRef.current!.attachLiveTask(chatKey, resp, epoch, stillRelevant),
settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>
reconcileBranchesRef.current!.settleIdle(chatKey, resp, epoch, hint, stillRelevant),
revokeAccess: chatKey => reconcileBranchesRef.current!.revokeAccess(chatKey),
holdAccess: chatKey => reconcileBranchesRef.current!.holdAccess(chatKey),
isNetworkError,
isHttp404,
isAuthorizationError,
isConfirmedHostAccessRevoked,
telemetry: (event, data) => console.log(`[telemetry] ${event}`, data),
})
}
const reconcileChat = useCallback(
(chatKey: string, args: ReconcileChatArgs) => reconcileChatRef.current!(chatKey, args),
[]
)
// GAP-D1 (§4.5-4): OS sleep/resume or screen-unlock leaves SSE sockets dead
// before the 30s watchdog or the bridge reconnect notices. On the `system:resume`
// tick, reconcile every chat whose FSM phase is not `idle` (matrix §5:
// "reconcile de todos los chats con phase !== idle") — a single-flight,
// idempotent `reconcileChat` that re-attaches a still-live task or settles a
// finished one. `offline` chats are included: resume is exactly when the network
// is likely back, and the reconcile falls back to offline on its own if it is
// still down. Subscribed once: `fsm` and `reconcileChatRef` are render-stable
// refs, read live at fire time.
useEffect(() => {
const unsub = window.clerum.system?.onResume?.(() => {
const snapshot = fsm.getSnapshot()
for (const [chatKey, entry] of Object.entries(snapshot)) {
if (entry.phase === 'idle') continue
void reconcileChatRef.current?.(chatKey, {
reason: 'system_resume',
taskIdHint: entry.activeTaskId,
})
}
})
return () => unsub?.()
}, [fsm])
// Per-chat view state: clearing a stale send-error/resend banner as the user
// resumes typing OR adds/updates a composer attachment. Defined before the
// composer hook so it can be handed in as `clearSendError`.
const clearComposerSendError = useCallback(() => {
if (agentError) setAgentError(null)
if (failedAgentSend) setFailedAgentSend(null)
}, [agentError, failedAgentSend])
// Selected-agent activity/progress slices — memoized with a shared EMPTY
// constant so an agent with no entries keeps a stable identity (R-F3).
const activityByMessageId = useMemo(
() =>
selectedAgent
? (activityByAgentMessage[selectedAgent] ?? EMPTY_ACTIVITY_MAP)
: EMPTY_ACTIVITY_MAP,
[activityByAgentMessage, selectedAgent]
)
const progressByMessageId = useMemo(
() =>
selectedAgent
? (progressByAgentMessage[selectedAgent] ?? EMPTY_PROGRESS_MAP)
: EMPTY_PROGRESS_MAP,
[progressByAgentMessage, selectedAgent]
)
const {
composerImageAttachments,
composerFileAttachments,
composerFileRefusals,
composerAttachmentRevisionRef,
composerReferenceAttachments,
resetComposerAttachments,
clearComposerDraft,
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
handleAddComposerFiles,
handleRemoveComposerFileAttachment,
handleRestoreComposerFiles,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
restoreComposerImageAttachments,
restoreComposerReferenceAttachments,
} = useComposerAttachments({ selectedAgent, clearSendError: clearComposerSendError })
// R2-M1 — cancel-restorations parked while their originating chat is not the
// active one, keyed `${agentRef}::${chatId}`. Memory-only, same lifetime as
// composer state (cleared on session/agent-scope reset, never persisted): a
// cancel settling while another chat is viewed PRESERVES the kept
// attachments and applies them when the originating chat is active again.
//
// R3-M4 — the parked value is a QUEUE of restoration batches, not a single
// batch: two cancellations settling for the SAME originating chat while the
// user views another chat must not overwrite one another. Each batch keeps
// its own attachments, its own caps and its own toast.
const parkedRestorationsRef = useRef(
new Map<
string,
{
agentRef: string
chatId: string | null
batches: Array<{
images: ComposerImageAttachment[]
references: ComposerReferenceAttachment[]
}>
}
>()
)
/**
* Applies one kept-attachment restoration to the composer the user is
* currently viewing, with the atomic merge, honest drop reporting, and a
* Discard-all action bound to the originating agent AND chat. Shared by the
* settle-now path and the parked path (spec: round-2 extensions).
*/
const applyKeptAttachments = useCallback(
(
agentRef: string,
chatId: string | null,
images: ComposerImageAttachment[],
references: ComposerReferenceAttachment[]
) => {
const stillViewingOrigin = () =>
activeChatVisibilityRef.current.selectedAgent === agentRef &&
activeChatVisibilityRef.current.activeChatId === chatId
if (!stillViewingOrigin()) return
// One merge per kind against the live composer snapshot — the counts and
// the committed state can never disagree (R1-M4), and the reference cap
// is enforced while restoring so the composer stays sendable (R1-M5).
const imageOutcome = restoreComposerImageAttachments(images)
const referenceOutcome = restoreComposerReferenceAttachments(references)
const droppedParts: string[] = []
if (imageOutcome.dropped > 0) {
droppedParts.push(
`${imageOutcome.dropped} of ${images.length} ${imageOutcome.dropped === 1 ? 'image exceeds' : 'images exceed'} the ${COMPOSER_MAX_ATTACHMENTS}-attachment limit`
)
}
if (referenceOutcome.dropped > 0) {
droppedParts.push(
`${referenceOutcome.dropped} of ${references.length} ${referenceOutcome.dropped === 1 ? 'reference exceeds' : 'references exceed'} the ${FILE_REFERENCE_MAX_COUNT}-file limit`
)
}
const totalDropped = imageOutcome.dropped + referenceOutcome.dropped
const message = droppedParts.length
? `Attachments kept — ${droppedParts.join('; ')} and ${totalDropped === 1 ? 'was' : 'were'} dropped.`
: 'Attachments kept'
pushToast(message, 'info', {
action: {
label: 'Discard all',
onAction: () => {
if (!stillViewingOrigin()) return
resetComposerAttachments()
},
},
})
},
[
pushToast,
resetComposerAttachments,
restoreComposerImageAttachments,
restoreComposerReferenceAttachments,
]
)
const readyComposerFiles = useMemo(
() =>
composerFileAttachments.filter(
(file): file is ReadyComposerFileAttachment => file.status === 'ready'
),
[composerFileAttachments]
)
const composerFilesBlockSend = composerFileAttachments.some(file => file.status !== 'ready')
const { chatEndRef, scrollChatToBottom } = useChatScroll({
selectedAgent,
activeChatId,
chatMessages,
chatMessagesLoading,
agentSending,
activeChatProgress: progressByMessageId,
})
const { pushAssistantReplyNotification, pushApprovalNotification, resetReplyNotificationDedupe } =
useChatNotifications({
activeChatVisibilityRef,
currentTeamId,
currentTeamName,
// Catalog display-name resolver (spec.host) for desktop toast titles.
// Reads the shared cache-backed catalog query — no new fetch. The
// notification payloads themselves stay keyed by the identifier.
agentDisplayName,
pushNotification,
canDeliverChatResponseNotification,
showDesktopNotification,
openAgentConversationFromNotification,
decideApprovalFromNotification,
})
// Public projection (§4.1): the sidebar/header read `sessionStateByChatKey`
// exactly as before — it is now derived from the FSM map, keeping the shape.
const sessionStateByChatKey = useMemo<Record<string, SessionStateLite>>(() => {
const out: Record<string, SessionStateLite> = {}
for (const [key, entry] of Object.entries(fsmMap)) {
out[key] = projectSessionState(entry)
}
return out
}, [fsmMap])
// Effects module (§4.1 / §4.7): the ONLY place that acts on the reducer's pure
// effect descriptors — unread mirror to disk (GAP-N2), approval-notification
// emission with (taskId,requestId) dedupe (GAP-N3), coordinator release (R5).
const runSessionEffects = useCallback(
(chatKey: string, effects: SessionFsmEffect[]) => {
for (const effect of effects) {
switch (effect.type) {
case 'mark_unread': {
const { agentRef, chatId } = parseTaskKey(chatKey)
void chatStore.markUnreadTerminal(agentRef, chatId)
markUnreadInList(chatId)
break
}
case 'clear_unread': {
const { agentRef, chatId } = parseTaskKey(chatKey)
void chatStore.clearUnreadTerminal(agentRef, chatId)
clearUnreadInList(chatId)
break
}
case 'emit_approval_notification': {
const { agentRef, chatId } = parseTaskKey(chatKey)
pushApprovalNotification({
agentName: agentRef,
chatId,
taskId: effect.taskId,
requestId: effect.requestId,
text: effect.displayName,
displayName: effect.displayName,
})
break
}
case 'coordinator_release':
tracker.ack(chatKey as TaskKey)
break
case 'schedule_reconcile':
// §4.3: the FSM's reconcile order routes to the single-flight
// `reconcileChat` gate. Fires for events dispatched through THIS effects
// runner that emit `schedule_reconcile` — the `window 'online'` →
// BACK_ONLINE recovery above. The approval-decision path reconciles via
// `decideApproval`'s own `reconcile` dep (approvalDecision.ts).
void reconcileChatRef.current?.(chatKey, { reason: effect.reason })
break
}
}
},
[
chatStore.markUnreadTerminal,
chatStore.clearUnreadTerminal,
markUnreadInList,
clearUnreadInList,
pushApprovalNotification,
tracker,
]
)
const dispatchSession = useCallback(
(chatKey: string, event: SessionFsmEvent) => {
const effects = fsm.dispatch(chatKey, event)
if (effects.length) runSessionEffects(chatKey, effects)
// B14 (§4.1 cleanup): a task terminal is the natural GC point — prune the
// agent's per-message activity/progress maps back under the cap.
if (event.type === 'STREAM_TERMINAL') {
const { agentRef } = parseTaskKey(chatKey)
setActivityByAgentMessage(prev => {
const byMessage = prev[agentRef]
if (!byMessage) return prev
const pruned = pruneToLastN(byMessage, MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT)
return pruned === byMessage ? prev : { ...prev, [agentRef]: pruned }
})
setProgressByAgentMessage(prev => {
const byMessage = prev[agentRef]
if (!byMessage) return prev
const pruned = pruneToLastN(byMessage, MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT)
return pruned === byMessage ? prev : { ...prev, [agentRef]: pruned }
})
}
},
[fsm, runSessionEffects]
)
// §4.1 BACK_ONLINE dispatcher: when the OS reports the network is back, dispatch
// BACK_ONLINE for every chat currently parked `offline`. The event's
// `schedule_reconcile` effect runs through `dispatchSession` → `runSessionEffects`
// → reconcileChat, re-deriving server truth and lifting the offline banner. This
// is the "auto-recovery" the reconcile 'offline' branch relies on.
useEffect(() => {
const handleOnline = () => {
for (const [chatKey, entry] of Object.entries(fsm.getSnapshot())) {
if (entry.phase === 'offline') {
dispatchSession(chatKey, { type: 'BACK_ONLINE' })
}
}
}
window.addEventListener('online', handleOnline)
return () => window.removeEventListener('online', handleOnline)
}, [fsm, dispatchSession])
useEffect(() => {
activeChatVisibilityRef.current = {
activeChatId,
currentTeamId,
navItem,
selectedAgent,
}
}, [activeChatId, currentTeamId, navItem, selectedAgent])
// R2-M1 — a parked cancel-restoration applies when its originating chat
// becomes active again (runs after the visibility sync above, so the ref it
// guards through is current).
//
// R3-M4 — EVERY parked batch is applied, in the order the cancellations
// settled. A single batch would let a later cancellation overwrite an
// earlier one's attachments, losing them for good.
useEffect(() => {
if (!selectedAgent) return
const key = `${selectedAgent}::${activeChatId}`
const parked = parkedRestorationsRef.current.get(key)
if (!parked) return
parkedRestorationsRef.current.delete(key)
for (const batch of parked.batches) {
applyKeptAttachments(parked.agentRef, parked.chatId, batch.images, batch.references)
}
}, [activeChatId, selectedAgent, applyKeptAttachments])
// Cleanup activity streams on unmount
useEffect(() => {
return () => {
const streams = Object.values(activityUnsubByAgentRef.current)
for (const stop of streams) {
void stop().catch(() => undefined)
}
activityUnsubByAgentRef.current = {}
activityInFlightByAgentRef.current = {}
activityTaskToMessageByAgentRef.current = {}
}
}, [])
// Clear the per-chat error/resend banner on agent change. Composer attachments
// are cleared by `useComposerAttachments`' own selectedAgent effect.
useEffect(() => {
setAgentError(null)
setFailedAgentSend(null)
}, [selectedAgent])
const stopAllActivityStreams = useCallback(async () => {
const streams = Object.values(activityUnsubByAgentRef.current)
await Promise.all(streams.map(stop => stop().catch(() => undefined)))
activityUnsubByAgentRef.current = {}
activityInFlightByAgentRef.current = {}
activityTaskToMessageByAgentRef.current = {}
}, [])
const resetChat = useCallback(() => {
beginSelectionIntent()
clearAllComposerDrafts()
setActivityByAgentMessage({})
setProgressByAgentMessage({})
resetComposerAttachments()
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
}
activeChatSwitchRequestRef.current = null
activeChatLocalPageRequestRef.current = null
autoSelectedChatIdRef.current = null
setActiveChatId(null)
clearList()
// R-F13 renderer half (spec §4.5-3): tear down EVERY tracked task so a late
// terminal (a stream that reconnects post-logout and 401s) can't run side
// effects — append a message, push a toast — after the session is gone. The
// main-process half (`stopAllStreams` on logout) is Fase 4.
tracker.releaseAll()
sendScopeGeneration.current += 1
agentSendSetupOwnerRef.current = null
agentSendInFlightRef.current = false
retainedSends.resetRetainedSendStore()
parkedRestorationsRef.current.clear()
// Abort any in-flight reconcile so a run mid-backoff can't resurrect a
// just-cleared tracker/FSM entry after this teardown (security review).
reconcileChatRef.current?.reset()
// Drop per-chat session lifecycle so the badge map can't accumulate dead
// agent/chat keys across login/logout cycles.
fsm.reset()
// Clear the reply-notification dedupe set so taskIds don't accumulate across
// login/logout / team-switch cycles (security review, hygiene).
resetReplyNotificationDedupe()
chatStore.clearCachedRemoteData()
transcriptMemo.clear()
setChatMessages([])
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
// The error/resend banner is per-chat view state — drop it when the active
// chat is torn down (logout / unauth boot) so it can't survive into the next.
setAgentError(null)
setFailedAgentSend(null)
}, [
resetComposerAttachments,
beginSelectionIntent,
clearList,
tracker,
fsm,
resetReplyNotificationDedupe,
chatStore.clearCachedRemoteData,
cancelOlderMessagesLoad,
transcriptMemo,
])
// Unified switch (post-D.4): cache-first render → server reconcile → tracker
// rejoin. No `isRemote` branch — the server is the source of truth for every
// chat, and a task in flight is rejoined via the tracker D.3 already mounts.
const switchToChatForIntent = useCallback(
async (
agentRef: string,
chatId: string,
selectionIntentRevision: number,
inherited: ProvisionalSelection | null = null
) => {
const deleted = isChatDeleted(agentRef, chatId)
if (deleted) transcriptMemo.delete(chatTranscriptMemoKey(agentRef, chatId))
if (deleted || isHostAccessBlocked(agentRef)) {
settleChatMessagesLoading(selectionIntentRevision)
return
}
const key = makeTaskKey(agentRef, chatId)
const visibleBeforeSwitch = activeChatVisibilityRef.current
const reopeningActiveChat =
visibleBeforeSwitch.selectedAgent === agentRef &&
visibleBeforeSwitch.activeChatId === chatId
const switchKey = `${currentTeamId}\u0000${key}`
const canReuseActiveSwitch =
reopeningActiveChat && activeChatSwitchKeyRef.current === switchKey
const switchRequest = canReuseActiveSwitch
? activeChatSwitchRequestRef.current!
: Symbol(`${agentRef}:${chatId}`)
if (!canReuseActiveSwitch) {
activeChatSwitchRequestRef.current = switchRequest
activeChatSwitchKeyRef.current = switchKey
activeChatLocalPageRequestRef.current = null
}
// A same-chat click must coalesce onto an already-running loud recovery.
// Superseding it would discard the stream-loss caller that owns the Resend
// or durable-result UX. Genuine chat changes still cancel stale work.
if (!reopeningActiveChat) reconcileChatRef.current!.supersede(key)
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: chatId,
currentTeamId,
selectedAgent: agentRef,
}
setActiveChatId(chatId)
// #1091 A9/A17: a remembered transcript is shown at once and stays
// provisional until the last-active write and the first local page below
// settle; without one the view is blank with the spinner. History is read
// only after the write.
const remembered = canReuseActiveSwitch ? undefined : rememberedTranscript(agentRef, chatId)
if (!canReuseActiveSwitch) {
presentSelectedTranscript(remembered)
provisionalSelectionRef.current = remembered
? { request: switchRequest, revision: selectionIntentRevision, agentRef, chatId }
: null
} else if (inherited?.request === switchRequest) {
provisionalSelectionRef.current = { ...inherited, revision: selectionIntentRevision }
}
const ownsProvisionalSelection = () =>
provisionalSelectionRef.current?.request === switchRequest &&
provisionalSelectionRef.current.revision === selectionIntentRevision
// The error/resend banner is per-chat view state, not global: clear it on
// every chat switch (same-agent switches don't trip the selectedAgent
// cleanup effect, so without this a stream error from chat A would bleed
// into chat B). The Phase-2 reconcile below re-derives state for this chat.
setAgentError(null)
setFailedAgentSend(null)
try {
await chatStore.setLastActive(agentRef, chatId)
} catch (error) {
if (ownsProvisionalSelection()) withdrawProvisionalSelection()
throw error
}
if (
(isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) &&
ownsProvisionalSelection()
) {
withdrawProvisionalSelection()
}
if (selectionIntentRevisionRef.current !== selectionIntentRevision) return
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) {
settleChatMessagesLoading(selectionIntentRevision)
return
}
unfillableServerGapUpperBoundsRef.current.delete(key)
// Renderer-local relevance guard for a fast A→B→A switch: THIS switch's
// reconcile is aborted the moment the user switches away. Passed into
// `reconcileChat` as a per-call `isRelevant` (replaces the Phase-2
// AbortController) so a background reconcile — system:resume, or a bell
// approval on a NON-visible chat — is never subject to an active-chat guard.
const isStillActive = () => {
const visible = activeChatVisibilityRef.current
return (
!isHostAccessBlocked(agentRef) &&
activeChatSwitchRequestRef.current === switchRequest &&
visible.selectedAgent === agentRef &&
visible.activeChatId === chatId
)
}
// PHASE 1 — render only the newest local page. The authoritative reconcile
// below requests a delta after the newest cached server turn. A reused
// switch reads the visible page only when this request rendered it; Phase 1
// writes chatMessagesRef together with the state it renders.
const activeLocalPage = activeChatLocalPageRequestRef.current
const reuseVisibleMessages =
canReuseActiveSwitch && activeLocalPage?.request === switchRequest
let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []
let loadedLocalPage = false
try {
if (reuseVisibleMessages) {
cached = [...chatMessagesRef.current] as AgentChatMessage[]
} else {
cached = (await chatStore.loadMessages(
agentRef,
chatId,
LOCAL_MESSAGE_PAGE_SIZE
)) as AgentChatMessage[]
}
loadedLocalPage = true
} catch (error) {
console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })
}
// #1091 A9: the remembered transcript is already on screen. Keep it only
// when the disk page is its newest part; otherwise the disk page wins,
// e.g. a reply persisted while the chat was hidden. An empty page also
// wins: `loadMessages` returns [] for a durably tombstoned chat, which
// this session may not have loaded into `deletedChatIdsByAgentRef` yet,
// and recording [] drops the memo entry. A rejected read is not an empty
// page: it says nothing about the chat, so the remembered transcript
// stays. The Host reconcile below runs in every case.
const keepRemembered =
remembered !== undefined &&
(!loadedLocalPage ||
(cached.length > 0 &&
sameMessageSequence(
remembered.messages.slice(-cached.length),
cached as AgentChatMessage[]
)))
if (keepRemembered) {
cached = remembered.messages as typeof cached
if (!isStillActive()) return
if (loadedLocalPage) activeChatLocalPageRequestRef.current = { request: switchRequest }
} else {
const hasOlderServerMessages =
nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined
const hasOlderLocalMessages =
!hasOlderServerMessages &&
cached.length === LOCAL_MESSAGE_PAGE_SIZE &&
(await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))
if (!isStillActive()) return
if (loadedLocalPage && !reuseVisibleMessages) {
activeChatLocalPageRequestRef.current = { request: switchRequest }
}
loadedLocalMessageCountRef.current = cached.length
setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
if (!reuseVisibleMessages) {
// Hydrate merges onto the ref, so a replaced memo must not linger there.
chatMessagesRef.current = cached as AgentChatMessage[]
setChatMessages(cached as AgentChatMessage[])
}
}
// Phase 1 rendered the cache → clear the blocking spinner. The reconcile
// runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the
// reconcile gate) instead. The selection is confirmed from here on.
if (ownsProvisionalSelection()) provisionalSelectionRef.current = null
settleChatMessagesLoading(selectionIntentRevision)
// D.5: opening the chat clears its "completed_unread" badge. CHAT_OPENED
// resets the FSM's `unreadTerminal` flag so a LATER hidden terminal re-marks
// (without it the flag is write-once-true and the badge never reappears) and
// its `clear_unread` effect mirrors the clear to disk+sidebar. The
// unconditional clear below ALSO runs because on a cold reload the FSM flag
// is fresh-`false` while the persisted disk badge is `true` — CHAT_OPENED's
// flag-gated effect wouldn't fire, so the badge must still be cleared here.
dispatchSession(key, { type: 'CHAT_OPENED' })
void chatStore.clearUnreadTerminal(agentRef, chatId)
clearUnreadInList(chatId)
scrollChatToBottom()
// A deliberate user re-open grants a fresh re-rejoin quota — the cap only
// exists to stop the automatic stream-loss → rejoin loop (P1-stall). A
// capped chat therefore clears its offline banner when reopened + reconciled
// clean.
tracker.resetRejoinAttempts(key)
// PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,
// offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /
// epoch-anchored zombie-ack) and the live rejoin (approval re-seed).
// `taskIdHint` = the pre-await zombie's task, which drives the durable
// getTaskResult fallback + response-file attachment load; the zombie-ack
// itself no longer needs a taskId to match (R2's epoch replaces the old
// `recoveringTaskIdByKeyRef` bookkeeping).
//
// The gate re-reads the same bounded local page inside hydrate so an SSE
// terminal that lands between Phase 1 and reconciliation is included
// without transferring the complete local transcript over IPC. Note
// (best-effort): `reconcileChat` is single-flight per key — if a background
// reconcile is already in flight for THIS key, this call coalesces onto it
// and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s
// own `isActive()` guard still prevents rendering into the wrong chat.
const zombieBefore = tracker.get(key)
const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])
const reconcileFromTurn =
latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)
await reconcileChat(key, {
reason: 'switch_to_chat',
taskIdHint: zombieBefore?.taskId,
isRelevant: isStillActive,
messagesQuery: {
limit: SERVER_TURN_PAGE_SIZE,
...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),
},
})
},
[
currentTeamId,
isHostAccessBlocked,
isChatDeleted,
dispatchSession,
tracker,
reconcileChat,
scrollChatToBottom,
clearUnreadInList,
rememberedTranscript,
presentSelectedTranscript,
transcriptMemo,
chatTranscriptMemoKey,
withdrawProvisionalSelection,
settleChatMessagesLoading,
chatStore.setLastActive,
chatStore.loadMessages,
chatStore.clearUnreadTerminal,
]
)
const runSwitchForIntent = useCallback(
(
agentRef: string,
chatId: string,
revision: number,
onCurrentError: (error: unknown) => void,
isRelevant: () => boolean = () => true,
inherited: ProvisionalSelection | null = null
) => {
const scope = currentAuthScopeRef.current
return runChatSwitchRequest(
() => switchToChatForIntent(agentRef, chatId, revision, inherited),
() =>
selectionIntentRevisionRef.current === revision &&
currentAuthScopeRef.current === scope &&
isRelevant(),
error => {
settleChatMessagesLoading(revision)
onCurrentError(error)
}
)
},
[settleChatMessagesLoading, switchToChatForIntent]
)
const switchToChat = useCallback(
async (
agentRef: string,
chatId: string,
options: { onCurrentError?: (error: unknown) => void } = {}
) => {
// A rejected target does not take ownership of the visible view. Check
// these guards before advancing the history-selection revision so a
// blocked or deleted chat cannot cancel another chat's pending load.
if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
// A same-row click takes over the live mark of the click it supersedes.
const inherited = provisionalSelectionFor(agentRef, chatId)
const selectionIntentRevision = beginSelectionIntent(true)
clearPendingSelection(agentRef, chatId)
const promise = runSwitchForIntent(
agentRef,
chatId,
selectionIntentRevision,
error => {
options.onCurrentError?.(error)
},
undefined,
inherited
)
const request: PendingChatSwitchRequest = {
agentRef,
chatId,
revision: selectionIntentRevision,
scope: currentAuthScopeRef.current,
state: 'pending',
promise,
}
pendingChatSwitchRequestRef.current = request
try {
await promise
// Settle this execution, not whatever successor now occupies the ref.
request.state = 'fulfilled'
} catch (error) {
request.state = 'rejected'
throw error
}
},
[
beginSelectionIntent,
clearPendingSelection,
isChatDeleted,
isHostAccessBlocked,
provisionalSelectionFor,
runSwitchForIntent,
]
)
// §5d: chat CRUD (handleCreateChat / handleRename[ForAgent] / handleDelete[ForAgent])
// now lives in `useChatListController` — it owns both lists and mutates them
// in sync. The active-chat concerns it needs (switchToChat, scrollChatToBottom,
// dispatchSession, clearComposerDraft, the live activeChatId) reach it through
// `chatListHostRef`, assigned just below now that switchToChat is defined.
const {
handleCreateChat,
handleRenameChat,
handleRenameChatForAgent,
applyLocalTitleOnly,
captureChatDeleteFence,
handleDeleteChat,
handleDeleteChatForAgent,
} = chatListCtl
useEffect(() => {
chatListHostRef.current = {
switchToChat,
beginSelectionIntent,
getSelectionIntentRevision: () => selectionIntentRevisionRef.current,
clearPendingSelection,
clearActiveChat,
scrollChatToBottom,
dispatchSession,
clearComposerDraft,
getActiveChatId: () => activeChatVisibilityRef.current.activeChatId,
getChatSwitchInFlight: () => {
const view = activeChatVisibilityRef.current
return (
chatMessagesLoadingRef.current ||
provisionalSelectionFor(view.selectedAgent, view.activeChatId) !== null
)
},
getAutoSelectedChatId: () => autoSelectedChatIdRef.current,
markAutoSelectedChat: chatId => {
autoSelectedChatIdRef.current = chatId
},
shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,
pushToast,
agentDisplayName,
}
})
const handleSelectChat = useCallback(
async (chatId: string) => {
if (
!selectedAgent ||
isHostAccessBlocked(selectedAgent) ||
isChatDeleted(selectedAgent, chatId)
)
return
autoSelectedChatIdRef.current = null
await switchToChat(selectedAgent, chatId, {
onCurrentError: error => {
pushToast(
`Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
'error'
)
},
}).catch(() => undefined)
},
[selectedAgent, isHostAccessBlocked, isChatDeleted, switchToChat, pushToast]
)
const handleLoadOlderMessages = useCallback(async () => {
if (!selectedAgent || !activeChatId || olderMessagesRequestRef.current) return
// An unconfirmed selection is read-only: no history is read before its write.
if (provisionalSelectionFor(selectedAgent, activeChatId)) return
const requestAgent = selectedAgent
const requestChatId = activeChatId
const requestScope = sendScopeGeneration.current
const requestScopeIdentity = currentAuthScopeRef.current
const requestToken = Symbol(`${requestAgent}:${requestChatId}`)
olderMessagesRequestRef.current = requestToken
const isStillRelevant = () => {
const visible = activeChatVisibilityRef.current
return (
olderMessagesRequestRef.current === requestToken &&
visible.selectedAgent === requestAgent &&
visible.activeChatId === requestChatId
)
}
setOlderMessagesLoading(true)
try {
const visibleIds = new Set(chatMessages.map(message => message.id))
const localPage = (await chatStore
.loadMessages(
requestAgent,
requestChatId,
LOCAL_MESSAGE_PAGE_SIZE,
loadedLocalMessageCountRef.current
)
.catch(() => [])) as AgentChatMessage[]
if (!isStillRelevant()) return
const unseenLocal = localPage.filter(message => !visibleIds.has(message.id))
if (unseenLocal.length) {
const nextLoadedLocalMessageCount = loadedLocalMessageCountRef.current + localPage.length
const currentMessages = chatMessagesRef.current
const previewMerged = mergeUniqueMessages(currentMessages, unseenLocal, 'before')
const hasOlderServerMessages = nextServerBackfillBeforeTurn(previewMerged) !== undefined
const hasOlderLocalMessages =
!hasOlderServerMessages &&
localPage.length === LOCAL_MESSAGE_PAGE_SIZE &&
(await hasLocalMessagesBeyond(
chatStore,
requestAgent,
requestChatId,
nextLoadedLocalMessageCount
))
if (!isStillRelevant()) return
loadedLocalMessageCountRef.current = nextLoadedLocalMessageCount
const merged = mergeUniqueMessages(chatMessagesRef.current, unseenLocal, 'before')
chatMessagesRef.current = merged
setChatMessages(merged)
setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
return
}
const beforeBackfillMessages = chatMessagesRef.current
const beforeBackfillOldestTurn = oldestServerTurnNumber(beforeBackfillMessages)
const beforeTurn = nextServerBackfillBeforeTurn(
beforeBackfillMessages,
ignoredServerGapUpperBounds(requestAgent, requestChatId)
)
if (beforeTurn === undefined) {
setHasOlderMessages(false)
return
}
const response = await chatStore.loadSessionMessages(
requestAgent,
requestAgent,
requestChatId,
{ limit: SERVER_TURN_PAGE_SIZE, beforeTurn }
)
if (!isStillRelevant()) return
const older = turnsToChatMessages(response.turns) as AgentChatMessage[]
const activeTaskId = tracker.get(makeTaskKey(requestAgent, requestChatId))?.taskId
const merged = mergeServerMessages(
chatMessagesRef.current,
older,
activeTaskId ? new Set([activeTaskId]) : undefined
)
chatMessagesRef.current = merged
setChatMessages(merged)
if (activeTaskId) {
await chatStore.replaceMessages(requestAgent, requestChatId, merged, {
activeTaskIds: [activeTaskId],
})
} else {
await chatStore.replaceMessages(requestAgent, requestChatId, merged)
}
if (!isStillRelevant()) return
loadedLocalMessageCountRef.current = merged.length
const nextBackfillBeforeTurn = nextServerBackfillBeforeTurn(merged)
const oldestMergedTurn = oldestServerTurnNumber(merged)
const loweredOldestTurn =
oldestMergedTurn !== undefined &&
(beforeBackfillOldestTurn === undefined || oldestMergedTurn < beforeBackfillOldestTurn)
if (nextBackfillBeforeTurn === beforeTurn && !loweredOldestTurn) {
markServerGapUnfillable(requestAgent, requestChatId, beforeTurn)
}
const ignoredGaps = ignoredServerGapUpperBounds(requestAgent, requestChatId)
setHasOlderMessages(
nextServerBackfillBeforeTurn(merged, ignoredGaps) !== undefined ||
(Boolean(response.hasMoreBefore) &&
oldestMergedTurn !== undefined &&
oldestMergedTurn > 1)
)
} catch (error) {
if (
isAuthorizationError(error) &&
requestScope === sendScopeGeneration.current &&
requestScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(requestAgent)
) {
hideHostAccessRef.current!(
requestAgent,
isConfirmedHostAccessRevoked(error) ? 'revoked' : 'uncertain'
)
return
}
console.warn('[chat-history] failed to load older messages', {
agentRef: requestAgent,
chatId: requestChatId,
error,
})
} finally {
if (olderMessagesRequestRef.current === requestToken) {
olderMessagesRequestRef.current = null
setOlderMessagesLoading(false)
}
}
}, [
activeChatId,
chatMessages,
chatStore.loadMessages,
chatStore.loadSessionMessages,
chatStore.replaceMessages,
ignoredServerGapUpperBounds,
markServerGapUnfillable,
selectedAgent,
isHostAccessBlocked,
provisionalSelectionFor,
tracker,
])
// Agent selection → load chats
useEffect(() => {
if (!selectedAgent || isHostAccessBlocked(selectedAgent)) {
beginSelectionIntent()
autoSelectedChatIdRef.current = null
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
currentTeamId,
selectedAgent: null,
}
setActiveChatId(null)
clearList()
setChatListLoading(false)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
return
}
let cancelled = false
const selectionIntentRevision = selectionIntentRevisionRef.current
const requestedSelection = readPendingSelection(selectedAgent)
const pendingSwitch = pendingChatSwitchRequestRef.current
// Public registration preserves only a matching same-agent specific intent;
// a later specific write advances revision, so its destination cannot drift.
const sharesPendingSwitch = Boolean(
requestedSelection?.mode === 'specific' &&
pendingSwitch?.state !== 'rejected' &&
pendingSwitch?.revision === selectionIntentRevision &&
pendingSwitch.scope === currentAuthScopeRef.current &&
pendingSwitch.agentRef === selectedAgent
)
const switchForEffect = (chatId: string) => {
if (sharesPendingSwitch) return pendingSwitch!.promise
return runSwitchForIntent(
selectedAgent,
chatId,
selectionIntentRevision,
error =>
liveDepsRef.current.pushToast(
`Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
'error'
),
() => !cancelled
)
}
if (requestedSelection?.mode === 'specific' && !sharesPendingSwitch) {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: requestedSelection.chatId,
currentTeamId,
selectedAgent,
}
setActiveChatId(requestedSelection.chatId)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
setChatMessagesLoading(true)
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
if (requestedSelection.title) {
upsertProvisionalEntry(
requestedSelection.chatId,
requestedSelection.title,
requestedSelection.isRemote === true
)
}
} else if (requestedSelection?.mode !== 'specific') {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
currentTeamId,
selectedAgent,
}
setActiveChatId(null)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
settleChatMessagesLoading(selectionIntentRevision)
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
}
setChatListLoading(true)
;(async () => {
const result = await loadChatList(selectedAgent, selectionIntentRevision)
if (cancelled || isHostAccessBlocked(selectedAgent)) return
setChatListLoading(false)
// A newer selection intent, including an explicit blank New chat, owns
// the active chat even when its chatId is null. Do not consume its pending
// selection or replay this older request after the list load completes.
if (selectionIntentRevisionRef.current !== selectionIntentRevision) return
if (!result) {
settleChatMessagesLoading(selectionIntentRevision)
return
}
const { merged } = result
const visibleChatId = activeChatVisibilityRef.current.activeChatId
const visibleAgent = activeChatVisibilityRef.current.selectedAgent
const staleSpecificSelection =
requestedSelection?.mode === 'specific' && visibleChatId !== requestedSelection.chatId
const staleLatestSelection = requestedSelection?.mode === 'latest' && Boolean(visibleChatId)
const staleImplicitLoad = !requestedSelection
if (
visibleAgent === selectedAgent &&
visibleChatId &&
(staleSpecificSelection || staleLatestSelection || staleImplicitLoad)
) {
if (requestedSelection) {
clearPendingSelection(selectedAgent)
}
settleChatMessagesLoading(selectionIntentRevision)
return
}
if (requestedSelection?.mode === 'specific' && requestedSelection.title) {
applyEntryTitle(requestedSelection.chatId, requestedSelection.title)
}
clearPendingSelection(selectedAgent)
if (requestedSelection?.mode === 'none') {
settleChatMessagesLoading(selectionIntentRevision)
return
}
if (requestedSelection?.mode === 'latest') {
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
await switchForEffect(latest.id)
}
settleChatMessagesLoading(selectionIntentRevision)
return
}
if (requestedSelection?.mode === 'specific') {
autoSelectedChatIdRef.current = null
// Server-only chats may not appear in the local index or first server
// catalog page yet. `switchToChat` already owns the cache-first →
// server-hydrate path, so open the requested id directly.
await switchForEffect(requestedSelection.chatId)
return
}
if (navItem === DESKTOP_ROUTES.chat) {
const latest = merged[0]
if (latest) {
autoSelectedChatIdRef.current = latest.id
await switchForEffect(latest.id)
}
}
settleChatMessagesLoading(selectionIntentRevision)
// List failures are normalized by loadChatList; switch failures are reported
// by their request. This continuation observes rejection without a second owner.
})().catch(() => undefined)
return () => {
cancelled = true
}
}, [
beginSelectionIntent,
cancelOlderMessagesLoad,
currentTeamId,
navItem,
selectedAgent,
isHostAccessBlocked,
settleChatMessagesLoading,
runSwitchForIntent,
])
// ─── Activity / progress state updaters (hoisted from sendAgentMessage so the
// tracker subscription effect and tracker callbacks can share them) ───
const updateMessageActivity = useCallback(
(
agentName: string,
messageId: string,
updater: (previous: AgentMessageActivity) => AgentMessageActivity
) => {
setActivityByAgentMessage(previous => {
const byMessage = previous[agentName] || {}
const current = byMessage[messageId] || {
status: 'waiting',
events: [],
redactionCount: 0,
}
return {
...previous,
[agentName]: { ...byMessage, [messageId]: updater(current) },
}
})
},
[]
)
const updateMessageProgress = useCallback(
(agentName: string, messageId: string, updater: (prev: TaskProgress) => TaskProgress) => {
setProgressByAgentMessage(prev => {
const agentProgress = prev[agentName] || {}
const current = agentProgress[messageId] || {
status: 'connecting',
steps: [],
currentIteration: 0,
}
return {
...prev,
[agentName]: { ...agentProgress, [messageId]: updater(current) },
}
})
},
[]
)
const resolveActivityMessageId = useCallback(
(agentName: string, event: HostActivityEvent): string | null => {
const taskId = typeof event.taskId === 'string' ? event.taskId : ''
if (taskId && activityTaskToMessageByAgentRef.current[agentName]?.[taskId]) {
return activityTaskToMessageByAgentRef.current[agentName]?.[taskId] || null
}
const inFlight = activityInFlightByAgentRef.current[agentName] || []
const latest = inFlight[inFlight.length - 1]
if (!latest) return null
if (taskId) {
activityTaskToMessageByAgentRef.current[agentName] = {
...(activityTaskToMessageByAgentRef.current[agentName] || {}),
[taskId]: latest,
}
}
return latest
},
[]
)
const reconcileTaskOwnership = useCallback(
(agentName: string, taskId: string, ownerMessageId: string) => {
setActivityByAgentMessage(previous => {
const byMessage = previous[agentName] || {}
const nextByMessage: Record<string, AgentMessageActivity> = { ...byMessage }
const moved: HostActivityEvent[] = []
for (const [messageId, activity] of Object.entries(byMessage)) {
if (messageId === ownerMessageId) continue
const ownedElsewhere = activity.events.filter(event => event.taskId === taskId)
if (!ownedElsewhere.length) continue
moved.push(...ownedElsewhere)
nextByMessage[messageId] = {
...activity,
events: activity.events.filter(event => event.taskId !== taskId),
}
}
if (!moved.length) return previous
const owner = nextByMessage[ownerMessageId] || {
status: 'waiting',
events: [],
redactionCount: 0,
}
nextByMessage[ownerMessageId] = {
...owner,
taskId,
events: [...owner.events, ...moved].slice(-MAX_ACTIVITY_EVENTS_PER_MESSAGE),
}
return { ...previous, [agentName]: nextByMessage }
})
},
[]
)
const maybeStopAgentActivityStream = useCallback(async (agentName: string) => {
const inFlight = activityInFlightByAgentRef.current[agentName] || []
if (inFlight.length) return
const stop = activityUnsubByAgentRef.current[agentName]
if (!stop) return
delete activityUnsubByAgentRef.current[agentName]
await stop().catch(() => undefined)
}, [])
const ensureAgentActivityStream = useCallback(
async (agentName: string) => {
if (activityUnsubByAgentRef.current[agentName]) return
const unsubscribe = await window.clerum.rpc.subscribeHostActivity(
agentName,
[agentName],
event => {
const typed = event as HostActivityStreamEvent
const inFlight = activityInFlightByAgentRef.current[agentName] || []
if (typed.type === 'open') {
for (const messageId of inFlight) {
updateMessageActivity(agentName, messageId, previous => ({
...previous,
status: 'streaming',
errorMessage: undefined,
}))
}
return
}
if (typed.type === 'activity') {
const messageId = resolveActivityMessageId(agentName, typed.activity)
if (!messageId) return
updateMessageActivity(agentName, messageId, previous => ({
...previous,
status: 'streaming',
taskId: typed.activity.taskId || previous.taskId,
events: [...previous.events, typed.activity].slice(-MAX_ACTIVITY_EVENTS_PER_MESSAGE),
redactionCount: previous.redactionCount + (typed.activity.redactions?.length || 0),
errorMessage: undefined,
}))
return
}
if (typed.type === 'error' || typed.type === 'closed') {
for (const messageId of inFlight) {
updateMessageActivity(agentName, messageId, previous => ({
...previous,
status: typed.type === 'closed' ? 'reconnecting' : 'error',
errorMessage:
typed.type === 'error' ? typed.message : 'Stream disconnected, reconnecting.',
}))
}
}
}
)
activityUnsubByAgentRef.current[agentName] = unsubscribe
},
[resolveActivityMessageId, updateMessageActivity]
)
const appendAssistantMessage = useCallback(
async (agentName: string, chatId: string | null, message: AgentChatMessage) => {
const messageScope = sendScopeGeneration.current
const messageScopeIdentity = currentAuthScopeRef.current
const mayAppend = () =>
messageScope === sendScopeGeneration.current &&
messageScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(agentName) &&
(!chatId || !isChatDeleted(agentName, chatId))
if (!mayAppend()) return
// Update the in-memory view FIRST (synchronously), then persist. For a
// rejoined task the in-flight placeholder hides the moment the tracker
// emits 'completed'; landing the reply before the await closes the visual
// gap that would otherwise last a disk-write IPC round-trip (D.5 review #2).
const view = activeChatVisibilityRef.current
if (view.selectedAgent === agentName && view.activeChatId === chatId) {
setChatMessages(previous => [...previous, message])
}
if (chatId) {
try {
await chatStore.appendMessages(agentName, chatId, [message])
if (!mayAppend()) return
bumpActivity(agentName, chatId, new Date(message.timestamp).toISOString())
} catch {
// persistence is best-effort; the in-memory view already updated
}
}
// Best-effort: keep this from throwing so the sole awaited call in
// onTrackerTerminal can't escape before its final tracker.ack(key) — a
// throw here would otherwise leak the tracked (agent, chat) entry.
try {
if (!mayAppend()) return
pushAssistantReplyNotification(agentName, message, chatId)
} catch {
// notification delivery is best-effort
}
},
[bumpActivity, chatStore, pushAssistantReplyNotification, isHostAccessBlocked, isChatDeleted]
)
// ─── reconcileChat branch callbacks (§4.3) ───
// The single-flight gate above delegates the side-effectful precedence branches
// here. These track the latest hook state; the gate reads them through
// `reconcileBranchesRef` (assigned in the effect below), keeping the gate
// instance — and its coalescing state — stable across renders.
// Shared hydration (§4.3 / A.4.4): materialize the server's page into the
// active view, append a delta when the cache has durable server turn IDs, and
// merge server windows into legacy/random-ID caches. It also auto-titles a
// fresh hydration from turn one and upserts the sidebar (S4).
// Both reconcile branches use it: `settleIdle` (idle replace) and
// `attachLiveTask` (render in-flight turns so a rejoin can anchor to the
// rendered user bubble — P1-A). Returns the rendered set + whether it replaced,
// so the live branch can anchor and the idle branch can decide the durable
// fallback. Replace is guarded on: chat active, server strictly grew, and NO
// live tracker entry (a running task holds an optimistic turn a replace would
// drop) — re-checked after every await (TOCTOU).
const hydrateActiveChatFromServer = useCallback(
async (
chatKey: TaskKey,
resp: SessionMessagesResult,
taskIdHint: string | undefined,
stillRelevant: () => boolean
): Promise<{
rendered: AgentChatMessage[]
replaced: boolean
cached: AgentChatMessage[]
stale: boolean
}> => {
const { agentRef, chatId } = parseTaskKey(chatKey)
const isActive = () => {
const v = activeChatVisibilityRef.current
return v.selectedAgent === agentRef && v.activeChatId === chatId
}
const mayHydrate = () =>
stillRelevant() && !isHostAccessBlocked(agentRef) && !isChatDeleted(agentRef, chatId)
const cached = (await chatStore
.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
.catch(error => {
console.warn('[chat-history] failed to read local reconciliation window', {
agentRef,
chatId,
error,
})
return []
})) as AgentChatMessage[]
const visible = isActive() ? chatMessagesRef.current : []
const latestPageFallback =
(resp as ReconciliationMessagesResult)[LATEST_PAGE_FALLBACK_WINDOW] === true
const deltaWindow =
(resp as ReconciliationMessagesResult)[DELTA_RECONCILIATION_WINDOW] === true
const hasOlderFromServer = !deltaWindow && Boolean(resp.hasMoreBefore)
const localMessages = mergeUniqueMessages(visible, cached)
const staleResult = (rendered: AgentChatMessage[] = localMessages) => ({
rendered,
replaced: false,
cached: localMessages,
stale: true,
})
if (!mayHydrate()) return staleResult()
if (!isActive() || tracker.get(chatKey)) {
return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]
if (!hydrated.length) {
return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
const localHasServerTurns = localMessages.some(
message => serverTurnNumber(message) !== undefined
)
const responseContainsAllTurns =
resp.totalTurns !== undefined ? resp.turns.length >= resp.totalTurns : !resp.hasMoreBefore
if (!localHasServerTurns && localMessages.length > 0) {
if (responseContainsAllTurns && hydrated.length <= localMessages.length) {
return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
}
const hydratedWithAttachments = withResponseFileAttachments(
hydrated,
taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : []
)
if (!mayHydrate()) return staleResult()
if (!isActive() || tracker.get(chatKey)) {
return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
// Pre-paging caches have no server-turn identity, so ordinary local
// user/assistant rows cannot be compared safely with an authoritative
// window. Preserve the old replace behavior for settled sessions instead
// of persisting both copies. A reported live task keeps the merge path so
// its optimistic bubbles remain visible until task-scoped reconciliation.
const replaceSettledLegacyCache =
localMessages.length > 0 &&
!localHasServerTurns &&
!resp.activeTaskId &&
responseContainsAllTurns
const rendered =
localMessages.length > 0
? mergeServerMessages(
localMessages,
hydratedWithAttachments,
resp.activeTaskId ? new Set([resp.activeTaskId]) : undefined,
replaceSettledLegacyCache
)
: hydratedWithAttachments
const hasOlderAfterMerge =
hasOlderFromServer || nextServerBackfillBeforeTurn(rendered) !== undefined
if (!mayHydrate()) return staleResult(rendered)
if (latestPageFallback) {
setHasOlderMessages(hasOlderAfterMerge)
} else {
setHasOlderMessages(previous => previous || hasOlderAfterMerge)
}
if (sameMessageSequence(rendered, localMessages)) {
return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }
}
if (!mayHydrate()) return staleResult(rendered)
chatMessagesRef.current = rendered
setChatMessages(rendered)
const meta = await chatStore.createChat(agentRef, chatId)
if (!mayHydrate()) return staleResult(rendered)
if (resp.activeTaskId) {
await chatStore.replaceMessages(agentRef, chatId, rendered, {
activeTaskIds: [resp.activeTaskId],
})
} else {
await chatStore.replaceMessages(agentRef, chatId, rendered)
}
if (!mayHydrate()) return staleResult(rendered)
if (!isActive()) {
return { rendered, replaced: true, cached: localMessages, stale: false }
}
loadedLocalMessageCountRef.current = rendered.length
// Auto-title a fresh hydration (empty cache) from the first user turn, so a
// server-only chat shows a meaningful name at open instead of "New Chat".
// spec 15 §2.2/A19: this is EPHEMERAL (sidebar state only) — NOT persisted
// via renameChat. The server title is authoritative (case C), so persisting
// a client-derived title would only (a) diverge from the server's own
// auto-title and (b) linger as a stale case-D fallback. On the next catalog
// load the §2.2 merge shows the server title when the host reports one.
// The index holds the server's title when one was reported
// (`ChatStore.upsertServerSessions`), so the first user turn names the
// chat only while it has no title yet.
let title = meta.title
if (
title === 'New Chat' &&
localMessages.length === 0 &&
(resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1
) {
const firstUserInput = resp.turns.find(t => t.user_input?.trim())?.user_input?.trim() || ''
const hydratedTitle = truncateTitle(firstUserInput)
if (hydratedTitle) {
title = hydratedTitle
applyLatestTitle(agentRef, chatId, hydratedTitle)
}
}
// S4: upsert into the sidebar. A chat opened via a notification for the
// already-selected agent may not be in chatList yet; a bare `.map` drops it.
upsertHydratedEntry(meta, title)
return { rendered, replaced: true, cached: localMessages, stale: false }
},
[
tracker,
isHostAccessBlocked,
isChatDeleted,
chatStore.loadMessages,
chatStore.createChat,
chatStore.replaceMessages,
applyLatestTitle,
upsertHydratedEntry,
]
)
const reconcileAttachLiveTask = useCallback<ReconcileChatDeps['attachLiveTask']>(
async (chatKey, resp, snapshotEpoch, stillRelevant) => {
// Staleness guard for the TRACKER (the FSM has R2, the coordinator does not):
// if a newer local `SEND_STARTED` bumped the epoch since this reconcile's
// fetch began, the server's `activeTaskId` is stale — calling `attach` would
// RELEASE the fresher task's live SSE and re-open the old one (attach-clobber
// race). Bail before touching the tracker; the SERVER_SNAPSHOT below would be
// R2-dropped anyway. `epoch` only advances on `SEND_STARTED`, so a mismatch
// is unambiguously "a new send took over".
if ((fsm.getState(chatKey)?.epoch ?? 0) !== snapshotEpoch) return 'stale_drop'
// Materialize any in-flight turns into the active view FIRST so the rejoin
// can anchor to the rendered user bubble (P1-A). No zombie-ack on this path:
// the residual IS the live task we're (re-)attaching, and the helper's
// `!tracker.get` guard leaves a genuine live entry's optimistic turn intact.
// Crucially, hydrate BEFORE the `SERVER_SNAPSHOT` below: the snapshot flips
// the chat to `awaiting_approval`, which — during hydrate's awaits — would
// let the sticky re-seed effect race in a `'<unknown>'`-anchored rejoin
// before this entry exists (P1-A regression).
const { rendered, stale } = await hydrateActiveChatFromServer(
chatKey as TaskKey,
resp,
resp.activeTaskId,
stillRelevant
)
if (stale) return 'stale_drop'
// R-F13 / spec §4.5-3: the hydrate above yields (IPC round-trip). If a
// `reset()` (logout / team-switch) or a switch-away landed during that
// await, bail BEFORE re-opening a live stream — otherwise `tracker.attach`
// would resurrect a task (and its SSE) in a torn-down session. `isActive`
// can't cover this: a legitimate background rejoin is also "not active".
if (!stillRelevant()) return 'stale_drop'
const anchor = [...rendered].reverse().find(m => m.role === 'user')?.id
fsm.dispatch(chatKey, {
type: 'SERVER_SNAPSHOT',
state: resp.state ?? 'idle',
activeTaskId: resp.activeTaskId,
pendingApproval: resp.pendingApproval,
tokens: resp.tokens,
snapshotEpoch,
})
// reason:'rejoin' → the coordinator consumes the bounded re-rejoin budget
// (P1-stall guard). Idempotent when the same task is already attached.
const attached = tracker.attach(
chatKey as TaskKey,
resp.activeTaskId!,
anchor ?? '<unknown>',
{ reason: 'rejoin' }
)
if (!attached) {
fsm.dispatch(chatKey, { type: 'WENT_OFFLINE', underlying: resp.state ?? 'idle' })
return 'rejoin_capped_offline'
}
// No manual re-seed of the approval gate: the `SERVER_SNAPSHOT` above already
// set the FSM projection's `pendingApproval` (the immediate optimistic paint,
// §8-R2), which the progress mirror surfaces as `suspendedInfo`; the rejoined
// SSE's replayed sticky `suspended` (V2) is the definitive gate. `seedSuspended`
// is gone (§4.7.3 / §8-R2).
return 'reconcile_rejoined'
},
[fsm, tracker, hydrateActiveChatFromServer]
)
const reconcileSettleIdle = useCallback<ReconcileChatDeps['settleIdle']>(
async (chatKey, resp, snapshotEpoch, taskIdHint, stillRelevant) => {
fsm.dispatch(chatKey, {
type: 'SERVER_SNAPSHOT',
state: 'idle',
tokens: resp.tokens,
snapshotEpoch,
})
const { agentRef, chatId } = parseTaskKey(chatKey)
// Zombie-ack (epoch-anchored — correction > healing): the server reports
// idle, so any residual tracker entry is a zombie (a stream-loss reconcile
// that rejoined a still-`processing` task but whose rejoined SSE never
// reached a clean terminal) UNLESS a fresher local `SEND_STARTED` bumped the
// epoch DURING this reconcile's await — in which case the residual is that
// brand-new live task and must never be torn down (P2 over-heal regression).
// R2's epoch replaces the old taskId-matching + `recoveringTaskIdByKeyRef`
// bookkeeping: a re-rejoin during the await does NOT bump the epoch, so its
// residual is still acked (P2-B); only a real send does.
const epochUnchanged = (fsm.getState(chatKey)?.epoch ?? 0) === snapshotEpoch
if (epochUnchanged && tracker.get(chatKey as TaskKey)) tracker.ack(chatKey as TaskKey)
// Active chat → reflect any newly-persisted server turns into the visible
// view (replace-never-append parity with switchToChat Phase 2, A.4.4).
const { replaced, cached, stale } = await hydrateActiveChatFromServer(
chatKey as TaskKey,
resp,
taskIdHint,
stillRelevant
)
if (stale) return 'stale_drop'
if (replaced) return 'reconcile_replaced'
// GAP-H1 durable fallback (rama 4): a task whose result the server never
// reflected as a turn (deny pre-executor) is materialized + PERSISTED
// locally so it survives the 10-min result TTL / host restart. Guarded so a
// task already covered by an assistant message (turn, or a prior recovery)
// never double-renders — R3 dedupe by `task_id` (sourceTaskId marker).
if (!taskIdHint) return 'noop'
if (cached.some(m => m.role === 'assistant' && m.task_id === taskIdHint)) return 'noop'
const taskResult = await window.clerum.rpc
.getTaskResult(agentRef, taskIdHint, [agentRef])
.catch(error => {
if (isAuthorizationError(error)) throw error
return null
})
if (!taskResult) return 'fell_through_to_resend'
// Post-await teardown guard (parity with attachLiveTask): a `reset()` during
// the getTaskResult await must not let the durable materialization persist a
// message into a torn-down session's chat.
if (!stillRelevant()) return 'noop'
const durableError = taskResult.error
if (durableError) {
const message = typeof durableError === 'string' ? durableError : durableError.message
const errorCode = typeof durableError === 'string' ? undefined : durableError.code
const errorProvider = typeof durableError === 'string' ? undefined : durableError.provider
markRetainedSendReason(taskIdHint ?? '', 'async_task_failed', message, 'upstream')
const attachments = buildResponseFileAttachments(taskResult)
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: message,
timestamp: Date.now(),
task_id: taskIdHint,
...(attachments.length ? { attachments } : {}),
isError: true,
...(errorCode ? { errorCode } : {}),
...(errorProvider ? { errorProvider } : {}),
})
// Loud toast parity with the stream-loss terminal path (SR-7): a durable
// failure the stream never delivered is still a failed send. Silent on the
// switch path is not an option — the user asked and it errored.
liveDepsRef.current.pushToast(`Message to ${agentRef} failed: ${message}`, 'error')
// Distinct outcome so the loud caller paints the stepper red (not green).
return 'recovered_error'
}
const reply = extractAssistantReply(taskResult)
const attachments = buildResponseFileAttachments(taskResult)
const hasResponse =
typeof taskResult.response === 'string' && taskResult.response.trim().length > 0
if (hasResponse || attachments.length) {
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: reply,
timestamp: Date.now(),
task_id: taskIdHint,
...(attachments.length ? { attachments } : {}),
})
return 'recovered_from_task_result'
}
return 'fell_through_to_resend'
},
[fsm, tracker, hydrateActiveChatFromServer, appendAssistantMessage]
)
const hideHostAccess = useCallback(
(agentRef: string, kind: 'revoked' | 'uncertain') => {
for (const chatKey of Object.keys(fsm.getSnapshot())) {
if (parseTaskKey(chatKey).agentRef !== agentRef) continue
tracker.release(chatKey as TaskKey)
reconcileChatRef.current?.supersede(chatKey)
fsm.dispatch(chatKey, { type: 'RESET' })
}
// A held Host's transcripts must not reappear from memory once it is released.
transcriptMemo.deleteAgent(agentRef)
const stopActivity = activityUnsubByAgentRef.current[agentRef]
if (stopActivity) {
delete activityUnsubByAgentRef.current[agentRef]
void stopActivity().catch(() => undefined)
}
delete activityInFlightByAgentRef.current[agentRef]
delete activityTaskToMessageByAgentRef.current[agentRef]
setActivityByAgentMessage(previous => {
const { [agentRef]: _removed, ...remaining } = previous
return remaining
})
setProgressByAgentMessage(previous => {
const { [agentRef]: _removed, ...remaining } = previous
return remaining
})
if (kind === 'revoked') {
hideAgent(agentRef)
}
const view = activeChatVisibilityRef.current
if (view.selectedAgent === agentRef) {
beginSelectionIntent()
}
if (kind === 'revoked') {
if (agentSendSetupOwnerRef.current?.agentRef === agentRef) {
agentSendSetupOwnerRef.current = null
agentSendInFlightRef.current = false
setAgentSending(false)
}
if (view.selectedAgent === agentRef) {
chatStore.clearCachedRemoteData()
clearList()
resetComposerAttachments()
activeChatVisibilityRef.current = { ...view, selectedAgent: null, activeChatId: null }
setActiveChatId(null)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
setHasOlderMessages(false)
cancelOlderMessagesLoad()
}
}
if (kind === 'revoked') onHostAccessRevoked(agentRef)
else onHostAuthorityUncertain(agentRef)
},
[
tracker,
fsm,
transcriptMemo,
hideAgent,
chatStore.clearCachedRemoteData,
clearList,
resetComposerAttachments,
cancelOlderMessagesLoad,
beginSelectionIntent,
onHostAccessRevoked,
onHostAuthorityUncertain,
]
)
const revokeHostAccess = useCallback(
(agentRef: string) => hideHostAccess(agentRef, 'revoked'),
[hideHostAccess]
)
const holdHostAccess = useCallback(
(agentRef: string) => hideHostAccess(agentRef, 'uncertain'),
[hideHostAccess]
)
useEffect(() => {
hideHostAccessRef.current = hideHostAccess
}, [hideHostAccess])
const reconcileRevokeAccess = useCallback<ReconcileChatDeps['revokeAccess']>(
chatKey => {
const { agentRef } = parseTaskKey(chatKey)
revokeHostAccess(agentRef)
},
[revokeHostAccess]
)
const reconcileHoldAccess = useCallback<ReconcileChatDeps['holdAccess']>(
chatKey => {
const { agentRef } = parseTaskKey(chatKey)
holdHostAccess(agentRef)
},
[holdHostAccess]
)
useEffect(() => {
reconcileBranchesRef.current = {
loadSessionMessages: async (agentRef, chatId, query, stillRelevant = () => true) => {
let requestedQuery = query ?? { limit: SERVER_TURN_PAGE_SIZE }
if (requestedQuery.beforeTurn === undefined && requestedQuery.afterTurn === undefined) {
const cached = (await chatStore
.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
.catch(error => {
console.warn('[chat-history] failed to read local delta cursor', {
agentRef,
chatId,
error,
})
return []
})) as AgentChatMessage[]
const latestCachedTurn = latestServerTurnNumber(cached)
const reconcileFromTurn =
latestCachedTurn === undefined ? undefined : Math.max(0, latestCachedTurn - 1)
requestedQuery = {
...requestedQuery,
...(reconcileFromTurn !== undefined ? { afterTurn: reconcileFromTurn } : {}),
}
}
let response = await chatStore.loadSessionMessages(
agentRef,
agentRef,
chatId,
requestedQuery
)
if (!stillRelevant()) return undefined
if (requestedQuery.afterTurn === undefined || !response.hasMoreAfter) {
if (requestedQuery.afterTurn !== undefined) {
return {
...response,
[DELTA_RECONCILIATION_WINDOW]: true,
} satisfies ReconciliationMessagesResult
}
return response
}
const turns = [...response.turns]
const seenCursors = new Set<number>()
let cursor = response.latestTurnNumber ?? turns.at(-1)?.number
if (response.hasMoreAfter && (!turns.length || cursor === undefined)) {
// A host claiming another page without returning an advancing cursor
// is malformed. Preserve the local cache instead of replacing it with
// an unrelated latest window.
return {
...response,
[DELTA_RECONCILIATION_WINDOW]: true,
} satisfies ReconciliationMessagesResult
}
let pagesLoaded = 1
while (
stillRelevant() &&
response.hasMoreAfter &&
cursor !== undefined &&
!seenCursors.has(cursor) &&
pagesLoaded < MAX_RECONCILE_DELTA_PAGES
) {
seenCursors.add(cursor)
const previousCursor = cursor
response = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
afterTurn: cursor,
})
if (!stillRelevant()) return undefined
turns.push(...response.turns)
cursor = response.latestTurnNumber ?? response.turns.at(-1)?.number
pagesLoaded += 1
if (
response.hasMoreAfter &&
(!response.turns.length || cursor === undefined || cursor === previousCursor)
) {
return {
...response,
turns,
oldestTurnNumber: turns[0]?.number,
latestTurnNumber: turns.at(-1)?.number,
[DELTA_RECONCILIATION_WINDOW]: true,
}
}
}
if (!stillRelevant()) return undefined
if (response.hasMoreAfter) {
const latest = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
})
if (!stillRelevant()) return undefined
const combinedTurns = mergeUniqueSessionTurns(turns, latest.turns)
return {
...latest,
turns: combinedTurns,
oldestTurnNumber: combinedTurns[0]?.number ?? latest.oldestTurnNumber,
latestTurnNumber: combinedTurns.at(-1)?.number ?? latest.latestTurnNumber,
[LATEST_PAGE_FALLBACK_WINDOW]: true,
} satisfies ReconciliationMessagesResult
}
return {
...response,
turns,
oldestTurnNumber: turns[0]?.number,
latestTurnNumber: turns.at(-1)?.number,
hasMoreAfter: false,
[DELTA_RECONCILIATION_WINDOW]: true,
}
},
attachLiveTask: reconcileAttachLiveTask,
settleIdle: reconcileSettleIdle,
revokeAccess: reconcileRevokeAccess,
holdAccess: reconcileHoldAccess,
}
}, [
chatStore.loadSessionMessages,
chatStore.loadMessages,
reconcileAttachLiveTask,
reconcileSettleIdle,
reconcileRevokeAccess,
reconcileHoldAccess,
])
// ─── Tracker callbacks + subscription (the post-D.3 fire & forget glue) ───
const onTrackerTerminal = useCallback(
async (key: TaskKey, state: TaskState) => {
const { agentRef, chatId } = parseTaskKey(key)
const terminalScope = sendScopeGeneration.current
const terminalScopeIdentity = currentAuthScopeRef.current
const terminalStillAuthorized = () =>
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(agentRef) &&
!isChatDeleted(agentRef, chatId)
// `task_duration_seconds` telemetry is now emitted by the coordinator
// (`fireTerminal`, §4.8) — the lifecycle owner — so it is not duplicated here.
const result = state.terminalResult
if (result?.kind === 'error' && result.source === 'authority') {
if (
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(agentRef)
) {
if (result.authority === 'revoked') revokeHostAccess(agentRef)
else holdHostAccess(agentRef)
}
return
}
// ── stream-recovery: a lost progress stream is NOT a task failure ──
// The task is durable server-side (D.1/T2.1), so before surfacing the scary
// "Progress stream error" + Resend, route through the single reconcile gate
// (§4.3): rejoin a task that's still alive, replace with the durable reply if
// it completed, or render the durable per-task result. Only a genuinely-gone
// task falls through to today's error UX.
if (result?.kind === 'error' && result.source === 'stream') {
// Capture the Resend payload BEFORE any release below clears it (B15) — it
// must outlive the reconcile so `applyFallback` (and, on a NON-visible
// chat, the reopen reconcile) can still offer it.
const resend = tracker.getResend(state.taskId)
const isActive = () => {
const v = activeChatVisibilityRef.current
return v.selectedAgent === agentRef && v.activeChatId === chatId
}
// Drop the per-agent activity in-flight entry. NOT called on the rejoin
// path — the task keeps running there, so its activity stream stays up.
const dropActivity = () => {
activityInFlightByAgentRef.current[agentRef] = (
activityInFlightByAgentRef.current[agentRef] || []
).filter(id => id !== state.userMessageId)
void maybeStopAgentActivityStream(agentRef)
}
// STREAM_TERMINAL settles the FSM to idle; when the chat is NOT visible
// it also emits the `mark_unread` effect (badge mirror, GAP-N2). Status
// is 'failed' here (stream-loss recovery) — the reducer only distinguishes
// 'cancelled' (which never marks), so failed vs completed is equivalent
// for the idle transition on a visible chat.
const setIdle = () =>
dispatchSession(key, {
type: 'STREAM_TERMINAL',
taskId: state.taskId,
status: 'failed',
chatVisible: isActive(),
})
// Today's failure UX — only when the server confirms nothing recoverable.
// Telemetry for this recovery is emitted once by the reconcile gate (§4.8,
// `deps.telemetry`) with the real outcome, so no manual log here.
const applyFallback = () => {
if (!terminalStillAuthorized()) return
dropActivity()
liveDepsRef.current.pushToast(`Message to ${agentRef} failed.`, 'error')
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: 'error',
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
}))
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'error',
errorMessage: result.message,
}))
if (resend && isActive()) {
setAgentError(
'Lost connection to the task — it may not have completed. Resend your message?'
)
setFailedAgentSend({
content: resend.content,
attachments: resend.attachments,
files: resend.files,
references: resend.references,
message: result.message,
kind: 'network',
timestamp: Date.now(),
})
}
setIdle()
}
// Fix B — durable-task-result fallback for a pre-executor denial.
// A budget-deny (and any pre-executor failure) is durable server-side as
// a per-task result (`getTaskResult` → `error:{code,message,provider}`)
// but never writes a session TURN (turns are written by the executor,
// which never runs on a deny). So the `loadSessionMessages` reconcile
// above can't grow past the cache and we'd wrongly fall through to the
// scary "Resend" UX. Before that, consult the durable task result: render
// it as a terminal message (failed or, rarely, a reply) instead. Returns
// true when it rendered something — only then do we skip `applyFallback`.
// Mirrors taskTracker's interpretation of `getTaskResult` (source:'failed'
// vs a durable reply) so the rendered bubble matches the direct path.
const recoverFromDurableTaskResult = async (): Promise<boolean> => {
const mayRecover = () =>
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(agentRef) &&
!isChatDeleted(agentRef, chatId)
let taskResult: Awaited<ReturnType<typeof window.clerum.rpc.getTaskResult>>
try {
taskResult = await window.clerum.rpc.getTaskResult(agentRef, state.taskId, [agentRef])
} catch (error) {
if (isAuthorizationError(error)) {
if (
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(agentRef)
) {
hideHostAccessRef.current!(
agentRef,
isConfirmedHostAccessRevoked(error) ? 'revoked' : 'uncertain'
)
}
return true
}
return false
}
if (!mayRecover()) return true
if (!taskResult) return false
// The awaits in this branch (incl. `getTaskResult` above) open a window
// in which the user can start a NEW task on this same chat — `ack(key)`
// already ran at the top of the handler, so the send re-entry guard no
// longer blocks a fresh `tracker.start`. Never let this STALE task's
// terminal render/settle stomp a fresher task's live state. Mirrors the
// reconcile_replaced guard (`residual.taskId === state.taskId`): a fresh
// task has a different (newer) taskId under the same key.
const freshTaskTookOver = () => {
const current = tracker.get(key)
return !!current && current.taskId !== state.taskId
}
if (freshTaskTookOver()) return true
const durableError = taskResult.error
if (durableError) {
const message = typeof durableError === 'string' ? durableError : durableError.message
const errorCode = typeof durableError === 'string' ? undefined : durableError.code
markRetainedSendReason(state.taskId, 'async_task_failed', message, 'upstream')
const errorProvider =
typeof durableError === 'string' ? undefined : durableError.provider
const attachments = buildResponseFileAttachments(taskResult)
dropActivity()
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: message,
timestamp: Date.now(),
task_id: state.taskId,
...(attachments.length ? { attachments } : {}),
isError: true,
...(errorCode ? { errorCode } : {}),
...(errorProvider ? { errorProvider } : {}),
})
if (!mayRecover()) return true
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: 'error',
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
}))
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'error',
errorMessage: message,
}))
liveDepsRef.current.pushToast(`Message to ${agentRef} failed: ${message}`, 'error')
// Settle the session to idle so it can't linger dirty (spinner /
// "processing") until the next switchToChat — that's exactly the bug
// this fix targets. Re-check first: a fresh task could have started
// during the append await, and it now owns the live state (its own
// onTerminal will settle it).
if (!freshTaskTookOver()) setIdle()
return true
}
// Rare: a durable SUCCESS reply the stream never delivered and that
// hydration didn't surface (no turn). Render it as a normal reply.
const reply = extractAssistantReply(taskResult)
const attachments = buildResponseFileAttachments(taskResult)
const hasResponse =
typeof taskResult.response === 'string' && taskResult.response.trim().length > 0
if (hasResponse || attachments.length) {
dropActivity()
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: reply,
timestamp: Date.now(),
task_id: state.taskId,
...(attachments.length ? { attachments } : {}),
})
if (!mayRecover()) return true
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: 'completed',
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
}))
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'completed',
errorMessage: undefined,
}))
liveDepsRef.current.pushToast(`Message sent to ${agentRef}.`, 'success')
if (!freshTaskTookOver()) setIdle()
return true
}
// No usable durable result (pending / 404 / empty) → let the caller
// fall through to the existing "Resend" UX (no regression).
return false
}
// Repaint the stepper as done once a reconcile branch materialized the
// reply/error (the branch's SERVER_SNAPSHOT idle is R2-ignored while the
// FSM phase is still `processing` — `setIdle` below flips it for real).
const paintProgressDone = () =>
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: 'completed',
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
}))
// B11 (§4.1 R4): a stream loss on a NON-visible chat is not recovered in
// the foreground. Mark it unread + settle the projection to idle, but DO
// NOT release the coordinator — the task may still be live server-side and
// its Resend payload must survive to the reopen reconcile (switchToChat →
// reconcileChat). Recovery is deferred to reopen, avoiding N concurrent
// background reconciles.
if (!isActive()) {
dropActivity()
// setIdle → STREAM_TERMINAL(chatVisible:false) settles idle AND mirrors
// the unread badge to disk via the `mark_unread` effect (GAP-N2).
setIdle()
return
}
// Active chat → the single reconcile gate (§4.3) owns fetch/retry, rejoin,
// durable replace, durable per-task result and 404 evict. ack the zombie
// FIRST so `attachLiveTask` opens a fresh SSE (idempotent-attach would
// no-op on the dead entry); the Resend payload was already captured above.
tracker.ack(key)
const outcome = await reconcileChat(key, {
reason: 'stream_lost',
taskIdHint: state.taskId,
isRelevant: isActive,
})
if (!terminalStillAuthorized()) return
switch (outcome) {
case 'reconcile_rejoined':
case 'rejoin_capped_offline':
// Task still live (rejoined SSE continues) or offline (WENT_OFFLINE was
// already dispatched by the branch) — leave activity up, no terminal
// paint; the rejoined stream's own onTerminal (or a reopen reconcile)
// settles it.
break
case 'reconcile_replaced':
case 'recovered_from_task_result':
// The reconcile branch materialized a durable reply. Repaint the
// stepper green and flip the FSM to idle. #654 M6 — the durable reply
// exists, so this is as terminal as the `reply` branch below: release
// the retained payload instead of leaving it to accumulate, together
// with the older failures of this chat that the reply supersedes.
releaseSucceededRetainedSendsForTask(state.taskId)
dropActivity()
paintProgressDone()
setIdle()
break
case 'recovered_error':
// The reconcile branch rendered (and toasted) a durable ERROR (budget
// deny etc.). Repaint the stepper + activity red — a green "completed"
// under an error bubble would misreport (code-review Should-fix).
// The payload stays retained for recovery; `reconcileChat` already
// recorded the durable error as its reason before returning here.
dropActivity()
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: 'error',
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
}))
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'error',
errorMessage: result.message,
}))
setIdle()
break
case 'noop':
case 'stale_drop':
// The turn already covered the task, or the chat switched away
// mid-reconcile — settle without re-rendering (a reopen reconcile
// re-derives if a newer send didn't already take over via R1).
// #654 M6 — either way this task will never produce another terminal,
// so its retained payload has no reader left, except documents the
// Host never received (kept for Recover files).
releaseRetainedSendsForTask(state.taskId)
dropActivity()
setIdle()
break
case 'revoked':
case 'authority_unverified':
// The authorization rejection hid the protected chat + reset the FSM.
dropActivity()
break
case 'offline':
// Network down (reconcile dispatched WENT_OFFLINE, phase `offline`).
// Leave the offline banner in place — do NOT `setIdle`/Resend (that
// would erase the offline affordance the reconcile just set up). Stop
// the spinner; recovery comes from the hook's `window 'online'`
// listener dispatching BACK_ONLINE (which schedules a reconcile), or a
// later system:resume / reopen reconcile re-deriving (code-review
// Should-fix).
dropActivity()
break
case 'fell_through_to_resend':
// settleIdle already consulted `getTaskResult` and it was empty → the
// task is genuinely lost. Today's Resend UX.
applyFallback()
break
default:
// 'error': the session-messages fetch THREW (non-network, non-404)
// before settleIdle could reach `getTaskResult`. A durable per-task
// result may still exist (e.g. a budget deny) — consult it before the
// Resend UX.
if (!(await recoverFromDurableTaskResult())) applyFallback()
}
return
}
if (result?.kind === 'reply') {
// Terminal success: the durable reply exists, so the retained send
// payload for this task can be released (idempotent — duplicate SSE/poll
// terminals only release once). The success also supersedes the older
// failures of this chat, which would otherwise resurface under the reply.
releaseSucceededRetainedSendsForTask(state.taskId)
if (result.content && result.content !== 'Message failed') {
const toolSteps = toMessageToolSteps(state.steps)
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: result.content,
timestamp: Date.now(),
task_id: state.taskId,
...(result.attachments?.length ? { attachments: result.attachments } : {}),
...(toolSteps ? { toolSteps } : {}),
})
}
if (!terminalStillAuthorized()) return
liveDepsRef.current.pushToast(`Message sent to ${agentRef}.`, 'success')
} else if (result?.kind === 'error') {
// Terminal failure: the payload stays retained for explicit recovery.
markRetainedSendReason(
state.taskId,
result.source === 'failed' ? 'async_task_failed' : 'stream_lost',
result.message,
'upstream'
)
if (result.source === 'failed') {
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: result.message,
timestamp: Date.now(),
task_id: state.taskId,
isError: true,
...(result.attachments?.length ? { attachments: result.attachments } : {}),
errorCode: result.code,
errorProvider: result.provider,
})
if (!terminalStillAuthorized()) return
liveDepsRef.current.pushToast(`Message to ${agentRef} failed: ${result.message}`, 'error')
} else if (result.source === 'result_fetch') {
await appendAssistantMessage(agentRef, chatId, {
id: crypto.randomUUID(),
role: 'assistant',
content: 'Failed to retrieve task result after completion',
timestamp: Date.now(),
task_id: state.taskId,
isError: true,
})
if (!terminalStillAuthorized()) return
liveDepsRef.current.pushToast(`Failed to retrieve result for ${agentRef}.`, 'error')
}
// `source: 'stream'` is intercepted + reconciled at the top of this handler.
}
if (!terminalStillAuthorized()) return
// The Resend payload is dropped by the coordinator on `release` below (B15).
// Reflect the terminal state into progress/activity directly. The live
// subscription also does this, but a task can finish before its chat's
// subscribe effect attaches (freshly auto-created chat) — onTerminal always
// runs and holds the full state, so this closes that race (idempotent).
updateMessageProgress(agentRef, state.userMessageId, () => ({
taskId: state.taskId,
status: mapTrackerStatusToProgress(state.status),
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
cancelReason:
state.terminalResult?.kind === 'cancelled' ? state.terminalResult.reason : undefined,
}))
if (state.status === 'completed') {
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'completed',
errorMessage: undefined,
}))
} else if (state.status === 'failed') {
const failMessage =
state.terminalResult?.kind === 'error' ? state.terminalResult.message : undefined
updateMessageActivity(agentRef, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'error',
errorMessage: failMessage,
}))
}
// Task finished — drop it from the activity in-flight set and stop the
// per-agent activity stream if nothing else is running on that agent.
activityInFlightByAgentRef.current[agentRef] = (
activityInFlightByAgentRef.current[agentRef] || []
).filter(id => id !== state.userMessageId)
void maybeStopAgentActivityStream(agentRef)
// STREAM_TERMINAL clears the live "Running"/"Awaiting" badge (→ idle,
// dropping taskId/approval) and, when the chat was NOT the active view,
// mirrors the "completed_unread" badge to disk via the `mark_unread` effect
// (persisted, survives a restart). Skips 'cancelled' — the user initiated
// that, it's not "news".
const view = activeChatVisibilityRef.current
const chatVisible = view.selectedAgent === agentRef && view.activeChatId === chatId
dispatchSession(key, {
type: 'STREAM_TERMINAL',
taskId: state.taskId,
status:
state.status === 'completed'
? 'completed'
: state.status === 'cancelled'
? 'cancelled'
: 'failed',
chatVisible,
})
tracker.ack(key)
},
[
appendAssistantMessage,
maybeStopAgentActivityStream,
dispatchSession,
tracker,
updateMessageProgress,
updateMessageActivity,
reconcileChat,
isHostAccessBlocked,
isChatDeleted,
revokeHostAccess,
holdHostAccess,
]
)
const onTrackerSuspended = useCallback(
(key: TaskKey, state: TaskState) => {
const approval = state.pendingApproval
if (!approval) return
// STREAM_SUSPENDED flips the sidebar badge to "Awaiting approval" (for any
// chat's task, not just the active one) AND emits the approval notification
// through the effect module — deduped by (taskId, requestId) so a sticky
// re-emit / re-seed no longer re-notifies (GAP-N3 / §4.7.3). A snapshot that
// already established the gate pre-arms the dedupe, so it stays silent.
const label = approval.displayName || 'Tool'
dispatchSession(key, {
type: 'STREAM_SUSPENDED',
taskId: state.taskId,
approval: { ...approval, displayName: label },
})
},
[dispatchSession]
)
const onTrackerResumed = useCallback(
(key: TaskKey, state: TaskState) => {
// The task moved past its approval — decided on ANY surface (in-chat,
// notification, notification center, another device). STREAM_RESUMED settles
// the badge back to `processing` and marks any optimistic local decision as
// superseded (R3) so a stale APPROVAL_DECISION_FAILED can't resurrect the
// gate — closing the C.2 rejoin loop.
fsm.dispatch(key, { type: 'STREAM_RESUMED', taskId: state.taskId })
},
[fsm]
)
useEffect(() => {
tracker.setCallbacks({
onTerminal: onTrackerTerminal,
onSuspended: onTrackerSuspended,
onResumed: onTrackerResumed,
})
}, [tracker, onTrackerTerminal, onTrackerSuspended, onTrackerResumed])
// Mirror the active chat's tracked task into progress/activity React state.
// Switching chats only unsubscribes this listener — the task keeps running in
// the tracker (cross-ref D.3 M2); onTrackerTerminal still fires for it.
//
// §8-R2: `seedSuspended` is gone. The approve/deny affordance (in-chat + the
// in-flight placeholder) is driven by the progress `suspendedInfo`, which now
// falls back to the FSM projection's `pendingApproval` when the tracker doesn't
// (yet) hold one — the immediate optimistic paint from the reconcile's
// `SERVER_SNAPSHOT` on a rejoin, before the rejoined SSE replays the sticky
// `suspended` (V2). The tracker's own `pendingApproval` (live/replayed suspended)
// wins when present.
const activeSuspendKey =
selectedAgent && activeChatId ? makeTaskKey(selectedAgent, activeChatId) : null
const activeFsmApproval = activeSuspendKey
? sessionStateByChatKey[activeSuspendKey]?.pendingApproval
: undefined
useEffect(() => {
if (!selectedAgent || !activeChatId) return
const key = makeTaskKey(selectedAgent, activeChatId)
return tracker.subscribe(key, state => {
// A stream-loss terminal is owned by `onTrackerTerminal` (reconcile →
// rejoin / render the durable reply, or paint the error itself only if
// nothing is recoverable). Mirroring `failed` here would flash "Progress
// stream error" on the message for a frame before the reconcile lands.
if (
state.status === 'failed' &&
state.terminalResult?.kind === 'error' &&
state.terminalResult.source === 'stream'
) {
return
}
const suspendedInfo = state.pendingApproval
? {
requestId: state.pendingApproval.requestId,
displayName: state.pendingApproval.displayName || 'Unknown Tool',
// U5: carry the connect_required discriminator (+ server) so the
// live message ProgressStepper renders "Connect <server>" instead of a
// generic Approve/Deny prompt. Absent on ordinary approval suspensions.
reason: state.pendingApproval.reason,
mcpServerName: state.pendingApproval.mcpServerName,
inputPreview: readApprovalInputPreview(state.pendingApproval.inputPreview),
}
: activeFsmApproval
? {
requestId: activeFsmApproval.requestId,
displayName: activeFsmApproval.displayName || 'Unknown Tool',
// U5 — the optimistic-paint fallback (rejoin, SERVER_SNAPSHOT before the
// sticky `suspended` SSE replays) must ALSO carry the connect_required
// discriminator so the live-message stepper renders "Connect <server>",
// not a generic Approve/Deny, during that window. Mirrors the tracker
// branch above and InFlightAssistantPlaceholder's fallback.
reason: activeFsmApproval.reason,
mcpServerName: activeFsmApproval.mcpServerName,
inputPreview: readApprovalInputPreview(activeFsmApproval.inputPreview),
}
: undefined
updateMessageProgress(selectedAgent, state.userMessageId, () => ({
taskId: state.taskId,
status: mapTrackerStatusToProgress(state.status),
steps: state.steps,
currentIteration: state.currentIteration,
llmElapsedMs: state.llmElapsedMs,
suspendedInfo,
cancelReason:
state.terminalResult?.kind === 'cancelled' ? state.terminalResult.reason : undefined,
}))
if (state.status === 'completed') {
updateMessageActivity(selectedAgent, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'completed',
errorMessage: undefined,
}))
} else if (state.status === 'failed') {
const message =
state.terminalResult?.kind === 'error' ? state.terminalResult.message : undefined
updateMessageActivity(selectedAgent, state.userMessageId, previous => ({
...previous,
taskId: state.taskId,
status: 'error',
errorMessage: message,
}))
}
})
}, [
selectedAgent,
activeChatId,
tracker,
updateMessageProgress,
updateMessageActivity,
activeFsmApproval,
])
const sendAgentMessage = useCallback(
async (
content: string,
attachments: ComposerImageAttachment[] = composerImageAttachments,
files: ReadyComposerFileAttachment[] = readyComposerFiles,
references: ComposerReferenceAttachment[] = composerReferenceAttachments,
preserveComposer = false
) => {
const sendScope = sendScopeGeneration.current
const sendScopeIdentity = currentAuthScopeRef.current
const originalDraftChat = activeChatVisibilityRef.current.activeChatId
const originalDraftAgent = selectedAgent
const originalDraftRevision = getComposerDraftRevision(
originalDraftChat,
originalDraftAgent ?? undefined
)
const originalAttachmentRevision = composerAttachmentRevisionRef.current
const trimmedContent = content.trim()
const effectiveAttachments = [...attachments]
const effectiveFiles = [...files]
const effectiveReferences = [...references]
if (
!selectedAgent ||
isHostAccessBlocked(selectedAgent) ||
(!trimmedContent &&
!effectiveAttachments.length &&
!effectiveFiles.length &&
!effectiveReferences.length)
)
return
// Per-(agent, chat) re-entry guard: a chat with a running task can't start
// another. Concurrent sends to *different* chats are allowed (the feature).
// Read the chat id from the ref (updated synchronously by auto-create /
// switchToChat) rather than state, which may not have committed yet.
const currentChatId = activeChatVisibilityRef.current.activeChatId
if (currentChatId && isChatDeleted(selectedAgent, currentChatId)) return
// An unconfirmed selection is read-only; the draft stays in the composer.
if (currentChatId && provisionalSelectionFor(selectedAgent, currentChatId)) return
if (currentChatId && tracker.get(makeTaskKey(selectedAgent, currentChatId))) return
if (agentSendInFlightRef.current) return
const sendAgent = selectedAgent
const sendSetupOwner = { id: Symbol('agent-send-setup'), agentRef: sendAgent }
agentSendSetupOwnerRef.current = sendSetupOwner
agentSendInFlightRef.current = true
const releaseSendSetup = () => {
if (agentSendSetupOwnerRef.current !== sendSetupOwner) return
agentSendSetupOwnerRef.current = null
agentSendInFlightRef.current = false
setAgentSending(false)
}
// Issue #654 — send-time image guard. Runs BEFORE the chat is created (a
// blocked visual send must not leave a stray empty chat) and long before
// the optimistic message/attachment clear. `readHostModelSelection` is the
// same shared source the composer and the selector read, so what is
// enforced here is exactly what the chip shows. Text-only sends keep the
// previous behavior and are never blocked by a missing capability.
let visualModelForSend: string | undefined
let visualModelRevisionForSend: number | undefined
if (effectiveAttachments.length > 0) {
const selection = readHostModelSelection(
sendAgent,
activeChatVisibilityRef.current.activeChatId ?? null
)
if (selection.visualSendBlocked) {
const blocker =
selection.imageBlockMessage ??
'Image attachments are not available for the selected model yet.'
setAgentError(blocker)
pushToast(blocker, 'error')
releaseSendSetup()
return
}
// Capture the model the guard just validated; the request below must
// carry exactly this identity (no re-reading an intent after the awaits).
visualModelForSend = selection.intentModel ?? selection.effectiveModel ?? undefined
visualModelRevisionForSend = selection.confirmedRevision ?? undefined
}
// #666 — build the structured references before anything is cleared or
// created. A selection past the shared limit (or an invalid reference)
// must leave the composer and its draft as the user typed them, with the
// reason on screen, instead of failing after the send cleared the composer.
let fileReferencesForSend: ReturnType<typeof buildComposerFileReferences>
try {
fileReferencesForSend = buildComposerFileReferences(effectiveReferences)
} catch (error) {
const blocker = error instanceof Error ? error.message : String(error)
setAgentError(blocker)
pushToast(blocker, 'error')
releaseSendSetup()
return
}
// #678 — the content the Host receives is fixed before anything is created
// or cleared, so the shared per-message limits are checked against the
// exact request and a refusal leaves the composer as the user typed it.
const baseContentForRequest = composerRequestBaseContent(
trimmedContent,
effectiveAttachments.length,
effectiveFiles.length
)
const effectiveContentForRequest = buildComposerRequestContent(
baseContentForRequest,
effectiveReferences
)
// The limits rpc-proxy and mcp-host enforce, most specific first: the
// count, the file quota, the share left for text and attachment details,
// then the whole body (images included), so the reason names what to
// remove. The share and the whole body apply to every send, so images
// alone that fill the body are refused here rather than by the proxy;
// the count and the file quota only when files are attached.
const requestForBudget = {
content: effectiveContentForRequest,
fileReferences: fileReferencesForSend,
hostRef: sendAgent,
files: effectiveFiles,
images: effectiveAttachments,
}
const hasFiles = effectiveFiles.length > 0
let budgetBlocker: string | null = null
if (
hasFiles &&
effectiveAttachments.length + effectiveFiles.length > COMPOSER_MAX_ATTACHMENTS
) {
budgetBlocker = `A message can carry at most ${COMPOSER_MAX_ATTACHMENTS} attachments.`
} else if (
hasFiles &&
composerFileBase64Bytes(effectiveFiles) > COMPOSER_MAX_TOTAL_FILE_BASE64_BYTES
) {
budgetBlocker = `The attached files take more than ${formatFileSize(COMPOSER_MAX_TOTAL_FILE_BASE64_BYTES)} once encoded. Remove a file.`
} else if (composerNonImageShareBytes(requestForBudget) > COMPOSER_MAX_NON_IMAGE_BODY_BYTES) {
budgetBlocker = `The message text and attachment details take more than ${formatFileSize(COMPOSER_MAX_NON_IMAGE_BODY_BYTES)} once encoded. Shorten the message or remove an attachment.`
} else if (
composerRequestBodyBytes(
requestForBudget,
effectiveAttachments.reduce((total, image) => total + image.dataBase64.length, 0)
) > COMPOSER_MAX_REQUEST_BODY_BYTES
) {
budgetBlocker = `The attachments and text take more than ${formatFileSize(COMPOSER_MAX_REQUEST_BODY_BYTES)} once encoded. Remove an attachment or shorten the message.`
}
if (budgetBlocker) {
setAgentError(budgetBlocker)
pushToast(budgetBlocker, 'error')
releaseSendSetup()
return
}
// This ref is the synchronous authority for the send target. A blank
// composer send also supersedes a pending latest/blank selection so an old
// list response cannot replace the chat created by this send. Capture this
// intent only after validation has accepted the exact request.
let sendChatId = currentChatId
const sendSelectionIntentRevision = currentChatId ? null : beginSelectionIntent()
if (sendSelectionIntentRevision !== null) clearPendingSelection(sendAgent)
const sendStillAuthorized = () =>
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(sendAgent) &&
(!sendChatId || !isChatDeleted(sendAgent, sendChatId))
const sendChatIsVisible = () =>
activeChatVisibilityRef.current.selectedAgent === sendAgent &&
activeChatVisibilityRef.current.activeChatId === sendChatId
// Captured for the retention snapshot: the model this attempt actually
// asked for (issue #654), readable from the catch below.
let requestModelForRetention: string | undefined
// B10: when a chat is auto-created by this send, the `chatList` captured in
// this closure predates it, so the auto-title lookup below would miss it and
// never title the chat on message 1 (then mis-title it on message 2). Keep
// the freshly-created meta so the lookup can fall back to it.
let autoCreatedMeta: Awaited<ReturnType<typeof chatStore.createChat>> | undefined
if (!sendChatId) {
const wasSendChatVisible = sendChatIsVisible()
try {
const chatId = crypto.randomUUID()
const meta = await chatStore.createChat(sendAgent, chatId)
sendChatId = chatId
if (!sendStillAuthorized()) {
releaseSendSetup()
return
}
chatStore.clearCachedRemoteData()
autoCreatedMeta = meta
appendNewEntry(sendAgent, meta)
// R2 new-chat composer: a per-session model picked BEFORE this chat
// existed was held in the agent-keyed pre-chat slot (no chatId to key a
// pending entry, no session to POST to). Now that the chatId exists,
// migrate it into this chat's pending slot so the standard piggyback
// logic below attaches it as `message.model` on message 1 and clears it
// on a successful POST (a thrown POST leaves it for the retry).
const preChatModel = chatStore.getPreChatModel(sendAgent)
if (preChatModel) {
chatStore.setPendingModel(sendAgent, chatId, preChatModel)
chatStore.clearPreChatModel(sendAgent)
}
if (
wasSendChatVisible &&
sendSelectionIntentRevision !== null &&
selectionIntentRevisionRef.current === sendSelectionIntentRevision &&
activeChatVisibilityRef.current.selectedAgent === sendAgent &&
activeChatVisibilityRef.current.activeChatId === null
) {
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: chatId,
selectedAgent: sendAgent,
}
setActiveChatId(chatId)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
}
await chatStore.setLastActive(sendAgent, chatId)
if (!sendStillAuthorized()) {
releaseSendSetup()
return
}
} catch (error) {
if (!sendStillAuthorized()) {
releaseSendSetup()
return
}
const message = error instanceof Error ? error.message : String(error)
pushToast(`Could not create a chat session: ${message}`, 'error')
releaseSendSetup()
return
}
}
if (!sendStillAuthorized()) {
releaseSendSetup()
return
}
const userMessageId = crypto.randomUUID()
const displayAttachments = buildChatMessageAttachments(
effectiveAttachments,
effectiveReferences,
effectiveFiles
)
const userMessage: AgentChatMessage = {
id: userMessageId,
role: 'user',
content: trimmedContent,
timestamp: Date.now(),
...(displayAttachments.length ? { attachments: displayAttachments } : {}),
}
// Persist before the async POST so a Host wake, approval, tab switch, or
// Desktop restart cannot erase the only copy of the user's outgoing turn.
// The acknowledgement below updates this same ID with its task id.
if (sendChatId) {
try {
await chatStore.upsertMessages(sendAgent, sendChatId, [userMessage])
} catch (error) {
console.warn('[chat-history] failed to persist outgoing message before send', {
agentRef: sendAgent,
chatId: sendChatId,
error,
})
pushToast('Could not save this message locally. Please retry.', 'error')
releaseSendSetup()
return
}
}
// Sidebar freshness (dev): bump this chat's updatedAt/messageCount so the
// cross-agent list and the chat list re-sort to the top on send. The user
// message is already durably staged by the upsert above and is updated in
// place when the send acknowledgement carries its task_id.
if (selectedAgent && sendChatId) {
const updatedAt = new Date(userMessage.timestamp).toISOString()
bumpActivity(selectedAgent, sendChatId, updatedAt)
}
if (sendChatIsVisible()) {
setChatMessages(prev => [...prev, userMessage])
}
// Auto-title on first message
if (selectedAgent && sendChatId) {
// B10: fall back to the meta just returned by createChat — the closure's
// `chatList` doesn't yet include a chat auto-created by this very send.
const chat =
chatList.find(c => c.id === sendChatId) ??
(autoCreatedMeta && autoCreatedMeta.id === sendChatId ? autoCreatedMeta : undefined)
if (chat && chat.title === 'New Chat') {
// Without text, the title names every kind of attachment the send
// carried: images and documents together, else the context references.
const attachmentTitleParts = [
effectiveAttachments.length > 0
? `Images: ${effectiveAttachments.map(att => att.name).join(', ')}`
: '',
effectiveFiles.length > 0
? `Files: ${effectiveFiles.map(file => file.filename).join(', ')}`
: '',
].filter(Boolean)
const autoTitleSeed =
trimmedContent ||
(attachmentTitleParts.length > 0
? attachmentTitleParts.join('; ')
: effectiveReferences.length > 0
? `Context: ${effectiveReferences.map(ref => ref.label).join(', ')}`
: '')
const autoTitle = truncateTitle(autoTitleSeed)
if (autoTitle) {
// spec 15 §2.5/B19: the client-derived auto-title stays LOCAL only —
// it must not be pushed by RPC (un-redacted, and it would race the
// server's own COALESCE auto-title). Only an explicit user rename
// syncs. The server materializes the authoritative title on turn 1.
void applyLocalTitleOnly(selectedAgent, sendChatId, autoTitle)
}
}
}
setActivityByAgentMessage(previous => ({
...previous,
[sendAgent]: {
...(previous[sendAgent] || {}),
[userMessageId]: {
status: 'waiting',
events: [],
redactionCount: 0,
},
},
}))
activityInFlightByAgentRef.current[sendAgent] = [
...(activityInFlightByAgentRef.current[sendAgent] || []),
userMessageId,
]
if (!activityTaskToMessageByAgentRef.current[sendAgent]) {
activityTaskToMessageByAgentRef.current[sendAgent] = {}
}
const pendingModelForSend = sendChatId
? chatStore.getPendingModel(sendAgent, sendChatId)
: undefined
requestModelForRetention = effectiveAttachments.length
? visualModelForSend
: pendingModelForSend
retainSendSnapshot({
agentRef: sendAgent,
chatId: sendChatId ?? null,
userMessageId,
content: trimmedContent,
attachments: effectiveAttachments,
files: effectiveFiles,
references: effectiveReferences,
model: requestModelForRetention,
reason: 'awaiting_terminal',
timestamp: Date.now(),
draftRevision: originalDraftRevision,
})
lastRetainedSendIdRef.current = userMessageId
// The accepted text belongs to its captured origin, while attachments
// belong to the selected agent. Navigation can change the visible chat
// without changing either owner.
const canConsumeComposer = !preserveComposer && sendStillAuthorized()
const shouldClearOriginDraft =
canConsumeComposer &&
getComposerDraftRevision(originalDraftChat, originalDraftAgent ?? undefined) ===
originalDraftRevision
const shouldResetAttachments =
canConsumeComposer && composerAttachmentRevisionRef.current === originalAttachmentRevision
if (shouldClearOriginDraft) {
clearComposerDraft(originalDraftChat, originalDraftAgent ?? undefined)
}
if (shouldResetAttachments) resetComposerAttachments()
setAgentError(null)
setFailedAgentSend(null)
setAgentSending(true)
try {
await ensureAgentActivityStream(sendAgent)
// R2 "Option A": a per-session model chosen while the host was suspended
// couldn't be persisted server-side, so it was held as pending. Piggyback
// it here — this send wakes the host and applies the model to this task.
if (!sendStillAuthorized()) return
const pendingModel = pendingModelForSend
const requestModel = requestModelForRetention
const fileReferences = fileReferencesForSend
const request = {
content: effectiveContentForRequest,
channelType: 'rpc',
channelId: sendAgent,
threadId: sendChatId || undefined,
attachments:
effectiveAttachments.length > 0 || effectiveFiles.length > 0
? mapComposerAttachmentsToHostRequest(effectiveAttachments, effectiveFiles)
: undefined,
...(requestModel ? { model: requestModel } : {}),
...(visualModelRevisionForSend === undefined
? {}
: { modelSelectionRevision: visualModelRevisionForSend }),
...(fileReferences.length > 0 ? { fileReferences } : {}),
}
const response = await window.clerum.rpc.invokeHostMessage(
sendAgent,
request,
[sendAgent],
{
async: true,
}
)
// A successful send creates or updates the durable server session. Do not
// let the short-lived sidebar cache hide that new catalog state.
chatStore.clearCachedRemoteData()
if (!sendStillAuthorized()) return
const responseRecord = response as Record<string, unknown>
const ackOk = !responseRecord.error && responseRecord.success !== false
// #654 H1 — the send IS the write. Its ack carries the revision that
// write produced, and adopting it is what arms the NEXT conditional
// write correctly; without it the client keeps the revision it read
// before sending and loses a race it already won. A send on the model
// the session already runs on writes nothing and acks the current,
// unchanged revision, which confirms the same state.
const ackRevision = responseRecord.modelSelectionRevision
if (ackOk && requestModel && typeof ackRevision === 'number') {
confirmHostModelSelectionFromSend(
sendAgent,
sendChatId || null,
requestModel,
ackRevision
)
} else if (ackOk && pendingModel) {
// #654 L8 — a success with no revision after a piggyback is the Host
// saying it ignored the model. Drop the intent instead of resending it
// on every subsequent message.
dropIgnoredHostModelIntent(sendAgent, sendChatId || null, pendingModel)
}
// Confirm a held intent against a fresh authoritative read. An HTTP
// acknowledgement alone can contain a structured failure or an ignored
// legacy model selection; it must not clear a newer intent.
if (ackOk && pendingModel && sendChatId) {
void loadHostModels(
{
getHostModels: chatStore.getHostModels,
setHostModel: chatStore.setHostModel,
},
sendAgent,
sendChatId,
{ force: true }
)
}
// #666 M1 — a Host or rpc-proxy that predates fileReferences drops them
// and still accepts the message. The ack lists the reference ids the
// Host admitted; a sent id missing from it never reached the Host. The
// send itself stands and is not retried.
const taskId =
(typeof responseRecord.taskId === 'string' ? responseRecord.taskId : undefined) ||
(typeof responseRecord.id === 'string' ? responseRecord.id : undefined)
// An ack with no fields at all is not a Host ack: rpc-proxy answers `{}`
// when the Host's 2xx body is not JSON. It says nothing about which
// references the Host received, so it is not read as a drop. An older
// Host's ack still carries `success`, a `taskId` or a reply.
const ackIsEmpty = Object.keys(responseRecord).length === 0
let fileReferencesDropped = false
if (ackOk && !ackIsEmpty && fileReferences.length > 0) {
const acceptedFileReferenceIds = new Set<string>(
Array.isArray(response.acceptedFileReferenceIds)
? response.acceptedFileReferenceIds
: []
)
const droppedFiles = fileReferences.filter(
reference => !acceptedFileReferenceIds.has(reference.id)
)
if (droppedFiles.length > 0) {
fileReferencesDropped = true
const droppedMessage =
droppedFiles.length === fileReferences.length
? FILE_REFERENCES_NOT_RECEIVED_MESSAGE
: `The Host did not receive ${droppedFiles.length} of the selected Global Files; the message was sent without them.`
setAgentError(droppedMessage)
pushToast(droppedMessage, 'error')
}
}
// #678 D13 — the same rule for documents. An ack that lists which
// attachments the Host admitted and omits a sent file means an older
// Host dropped it. Unlike a Global File reference, the document exists
// only in this composer, so the send keeps its snapshot and shows the
// failure instead of looking delivered.
let filesNotDeliveredMessage: string | null = null
let undeliveredFileIds: string[] = []
if (ackOk && !ackIsEmpty && effectiveFiles.length > 0) {
const acceptedAttachmentIds = new Set<string>(
Array.isArray(response.acceptedAttachmentIds) ? response.acceptedAttachmentIds : []
)
const undelivered = effectiveFiles.filter(file => !acceptedAttachmentIds.has(file.id))
undeliveredFileIds = undelivered.map(file => file.id)
if (undelivered.length > 0) {
filesNotDeliveredMessage =
undelivered.length === effectiveFiles.length
? HOST_FILE_ATTACHMENTS_DROPPED_MESSAGE
: `The Host did not receive ${undelivered.length} of the attached files; the message was sent without them. Recover the files to attach them again.`
setAgentError(filesNotDeliveredMessage)
pushToast(filesNotDeliveredMessage, 'error')
}
}
if (!taskId) {
// Synchronous (non-async) response — a direct reply or a structured error.
const errorRecord = responseRecord.error as
| { message?: string; code?: string; provider?: string }
| undefined
// Issue #654: a synchronous failure can arrive as `{error: …}` OR as
// `{success: false}` without an error object. Both are failures — HTTP
// 200 or a missing `success` boolean never imply success.
const explicitFailure = responseRecord.success === false
const isErrorResponse = Boolean(errorRecord) || explicitFailure
const content =
typeof errorRecord?.message === 'string'
? errorRecord.message
: extractAssistantReply(response)
const responseAttachments = buildResponseFileAttachments(response)
const assistantMessage: AgentChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content,
timestamp: Date.now(),
...(responseAttachments.length ? { attachments: responseAttachments } : {}),
...(isErrorResponse && {
isError: true,
errorCode: errorRecord?.code,
errorProvider: errorRecord?.provider,
}),
}
if (sendChatId) {
await chatStore.upsertMessages(sendAgent, sendChatId, [userMessage])
}
await appendAssistantMessage(sendAgent, sendChatId, assistantMessage)
if (isErrorResponse) {
// #654 M3 — a CAS conflict is not a capability verdict. Adopt the
// winning revision the Host reported (so an explicit retry is armed
// without a separate read) and re-read the authoritative selection.
if (errorRecord?.code === 'LLM_MODEL_SELECTION_CONFLICT') {
const conflictRevision = responseRecord.modelSelectionRevision
noteHostModelSelectionConflict(
{
getHostModels: chatStore.getHostModels,
setHostModel: chatStore.setHostModel,
},
sendAgent,
sendChatId || null,
requestModel ?? '',
typeof conflictRevision === 'number' ? conflictRevision : undefined
)
}
// The input was cleared before the round-trip: retain it (memory
// only) so the failure is recoverable, and restore the text into the
// composer only when it is still the same chat with no newer draft.
// #678 D13 — a Host that predates `kind:'file'` rejects the send
// with LLM_INVALID_ATTACHMENT; say what that means for the files.
const hostRejectedFiles =
effectiveFiles.length > 0 && errorRecord?.code === HOST_INVALID_ATTACHMENT_CODE
const failureMessage = hostRejectedFiles
? HOST_FILE_ATTACHMENTS_UNSUPPORTED_MESSAGE
: typeof errorRecord?.message === 'string'
? errorRecord.message
: content
failRetainedSend(
sendAgent,
sendChatId ?? null,
userMessageId,
hostRejectedFiles ? 'host_files_unsupported' : 'sync_error_envelope',
failureMessage,
'upstream'
)
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
status: 'error',
errorMessage: failureMessage,
}))
pushToast(`Message to ${sendAgent} failed: ${failureMessage || 'error'}`, 'error')
} else if (filesNotDeliveredMessage) {
// The Host answered but never received the documents: keep the
// snapshot (and its files) with the failure instead of releasing it.
failRetainedSend(
sendAgent,
sendChatId ?? null,
userMessageId,
'host_files_dropped',
filesNotDeliveredMessage,
'upstream',
undeliveredFileIds
)
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
status: 'error',
errorMessage: filesNotDeliveredMessage,
}))
} else {
// Terminal success: release this payload and the older failures of
// the chat it supersedes.
releaseSucceededRetainedSend(sendAgent, sendChatId ?? null, userMessageId)
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
status: previous.events.length ? 'completed' : 'no_activity',
errorMessage: undefined,
}))
// The dropped-files error above already told the user what happened;
// a success toast right after it would contradict it.
if (!fileReferencesDropped) pushToast(`Message sent to ${sendAgent}.`, 'success')
}
activityInFlightByAgentRef.current[sendAgent] = (
activityInFlightByAgentRef.current[sendAgent] || []
).filter(id => id !== userMessageId)
void maybeStopAgentActivityStream(sendAgent)
return
}
// Async task accepted. Persist the user message once, now carrying its
// task_id (schema v2), then hand the SSE lifecycle to the tracker.
const persistedUserMessage: AgentChatMessage = { ...userMessage, task_id: taskId }
if (sendChatIsVisible()) {
setChatMessages(prev =>
prev.map(m => (m.id === userMessageId ? persistedUserMessage : m))
)
}
if (sendChatId) {
await chatStore.upsertMessages(sendAgent, sendChatId, [persistedUserMessage])
}
attachTaskIdToRetainedSend(sendAgent, sendChatId ?? null, userMessageId, taskId)
if (filesNotDeliveredMessage) {
// The task runs without the documents; the snapshot survives its
// success (see releaseSucceededRetainedSendsForTask).
markRetainedSendReason(
taskId,
'host_files_dropped',
filesNotDeliveredMessage,
'upstream',
undeliveredFileIds
)
}
activityTaskToMessageByAgentRef.current[sendAgent] = {
...(activityTaskToMessageByAgentRef.current[sendAgent] || {}),
[taskId]: userMessageId,
}
reconcileTaskOwnership(sendAgent, taskId, userMessageId)
updateMessageProgress(sendAgent, userMessageId, () => ({
taskId,
status: 'connecting',
steps: [],
currentIteration: 0,
}))
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
taskId,
status: 'streaming',
}))
if (sendChatId) {
// Stash the original input so a ghost terminal can offer a Resend (AC11).
// Owned by the coordinator now (B15): cleared when the key is released.
tracker.setResend(taskId, {
content: trimmedContent,
attachments: effectiveAttachments,
files: effectiveFiles,
references: effectiveReferences,
})
const taskKey = makeTaskKey(sendAgent, sendChatId)
tracker.start(taskKey, taskId, userMessageId)
// SEND_STARTED bumps the epoch (R2 snapshot staleness anchor), adopts
// the new taskId (R1 then drops the previous task's late events) and
// clears any prior approval/offline residue; TASK_CREATED flips to
// `processing` so
// the sidebar "Running" badge shows even while viewing another chat.
fsm.dispatch(taskKey, { type: 'SEND_STARTED', taskId })
fsm.dispatch(taskKey, { type: 'TASK_CREATED', taskId })
}
} catch (error) {
if (
isAuthorizationError(error) &&
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(sendAgent)
) {
if (isConfirmedHostAccessRevoked(error)) {
revokeHostAccess(sendAgent)
return
}
if (!isHttp403(error)) {
holdHostAccess(sendAgent)
return
}
try {
await chatStore.listSessions(sendAgent, { agent: sendAgent, limit: 1 }, { force: true })
} catch (readError) {
if (
isAuthorizationError(readError) &&
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
!isHostAccessBlocked(sendAgent)
) {
if (isConfirmedHostAccessRevoked(readError)) revokeHostAccess(sendAgent)
else holdHostAccess(sendAgent)
return
}
}
}
if (!sendStillAuthorized()) return
const message = error instanceof Error ? error.message : String(error)
const normalized = message.toLowerCase()
const isRequestEntityTooLarge =
normalized.includes('request entity too large') ||
normalized.includes('payload too large')
const kind = classifyErrorKind(message)
const fallback = isRequestEntityTooLarge
? 'Send fewer or smaller attachments. If small attachments are refused too, the rpc-proxy and mcp-host deployments may predate the current payload limits.'
: errorRecoveryHint(kind)
const friendlyMessage = isRequestEntityTooLarge
? 'The message is larger than the deployed runtime accepts (images or attached files).'
: kind === 'waking'
? 'Agent is waking up.'
: kind === 'network'
? 'Temporary connection issue while sending to the agent.'
: kind === 'auth'
? 'Access issue while sending to this agent.'
: 'Unable to send message to this agent.'
setAgentError(`${friendlyMessage} ${fallback}`)
// Issue #654 — keep the payload recoverable and record WHO it belongs
// to, so recovery can never overwrite a different chat's composer or a
// newer draft. Memory only; released on terminal success/discard.
failRetainedSend(sendAgent, sendChatId ?? null, userMessageId, 'post_failed', message, kind)
setFailedAgentSend({
content: trimmedContent,
attachments: effectiveAttachments,
files: effectiveFiles,
references: effectiveReferences,
message,
kind,
timestamp: Date.now(),
agentRef: sendAgent,
chatId: sendChatId ?? null,
userMessageId,
model: requestModelForRetention,
})
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
status: 'error',
errorMessage: fallback,
}))
pushToast(
kind === 'waking'
? 'Agent is waking up — message not sent yet.'
: `Message failed (${kind}).`,
'error'
)
// Durability: the POST threw before either success branch persisted the
// user message (post-D.3 persists once, after the taskId is known). Write
// it now so a transient send failure doesn't silently drop the user's
// typed input on reload — matches pre-D.3 eager-persist. Best-effort.
if (sendChatId) {
try {
const failedUserMessage: AgentChatMessage = { ...userMessage, preserveLocal: true }
if (sendChatIsVisible()) {
setChatMessages(prev =>
prev.map(message => (message.id === userMessageId ? failedUserMessage : message))
)
}
await chatStore.upsertMessages(sendAgent, sendChatId, [failedUserMessage])
} catch {
// persistence is best-effort; the in-memory view still shows it
}
}
// The POST failed — no background task exists, so retire the activity
// stream now. (For a started task, onTrackerTerminal does this instead.)
activityInFlightByAgentRef.current[sendAgent] = (
activityInFlightByAgentRef.current[sendAgent] || []
).filter(messageId => messageId !== userMessageId)
void maybeStopAgentActivityStream(sendAgent)
} finally {
// Fire & forget: release the synchronous setup guard immediately. The
// task (if any) keeps running in the tracker.
releaseSendSetup()
}
},
[
selectedAgent,
beginSelectionIntent,
clearPendingSelection,
isHostAccessBlocked,
isChatDeleted,
provisionalSelectionFor,
revokeHostAccess,
holdHostAccess,
composerImageAttachments,
readyComposerFiles,
composerReferenceAttachments,
chatList,
chatStore,
resetComposerAttachments,
markRetainedSendReason,
fsm,
applyLocalTitleOnly,
pushToast,
tracker,
ensureAgentActivityStream,
maybeStopAgentActivityStream,
reconcileTaskOwnership,
updateMessageActivity,
updateMessageProgress,
appendAssistantMessage,
appendNewEntry,
bumpActivity,
]
)
const handleSendAgentMessage = useCallback(
async (text: string) => {
// A document still being read is not part of the message yet: sending
// now would silently leave it out.
if (composerFilesBlockSend) return
await sendAgentMessage(
text,
composerImageAttachments,
readyComposerFiles,
composerReferenceAttachments
)
},
[
composerFilesBlockSend,
composerImageAttachments,
readyComposerFiles,
composerReferenceAttachments,
sendAgentMessage,
]
)
const visibleRetainedFailure = useMemo(() => {
const snapshot = selectedAgent
? retainedSends.getLatestRetainedSendSnapshotForChat(selectedAgent, activeChatId)
: undefined
if (!snapshot?.failure) return null
return {
...snapshot,
message: snapshot.failure.message,
kind: snapshot.failure.kind,
answeredWithoutFiles: snapshot.reason === 'host_files_dropped',
} satisfies FailedAgentSend
}, [retainedSends, retainedRevision, selectedAgent, activeChatId])
const visibleFailure =
visibleRetainedFailure ??
(failedAgentSend &&
(!failedAgentSend.agentRef ||
(failedAgentSend.agentRef === selectedAgent && failedAgentSend.chatId === activeChatId))
? failedAgentSend
: null)
// #654 M5 — a retry re-sends under a NEW `userMessageId`, so the snapshot the
// failed attempt retained is not the one the retry writes. Without an explicit
// release the old snapshot stays in the store forever, holding its attachment
// bytes and still answering `getLatestRetainedSendSnapshotForChat` (which picks
// the newest snapshot *carrying a failure*).
const handleRetryFailedAgentSend = useCallback(async () => {
// The Host already answered this text; only its documents are recoverable.
if (!visibleFailure || visibleFailure.answeredWithoutFiles) return
const previous = visibleFailure
const retainedBefore = lastRetainedSendIdRef.current
// The retained files are already read and hashed: a retry never reads them again.
await sendAgentMessage(
previous.content,
previous.attachments,
previous.files,
previous.references,
true
)
// A retry refused before dispatch (image guard, running task, a send already
// in flight) retained nothing, so the old snapshot is still the only copy of
// the payload: keep it and the failure it shows. Once a newer send has
// retained its own snapshot, the old one is redundant whatever that send's
// outcome — on failure the payload lives on in the newer snapshot.
if (lastRetainedSendIdRef.current === retainedBefore) return
if (previous.agentRef && previous.userMessageId) {
releaseRetainedSend(previous.agentRef, previous.chatId ?? null, previous.userMessageId)
}
setFailedAgentSend(null)
}, [visibleFailure, sendAgentMessage, releaseRetainedSend])
const handleDiscardFailedAgentSend = useCallback(() => {
if (visibleFailure?.agentRef && visibleFailure.userMessageId) {
releaseRetainedSend(
visibleFailure.agentRef,
visibleFailure.chatId ?? null,
visibleFailure.userMessageId
)
// The visible failure is the newest one of this chat; the older failures
// behind it would otherwise resurface one by one after each discard. An
// older snapshot holding documents the Host never received stays: those
// files exist nowhere else, so it resurfaces with Recover files.
releaseRetainedFailuresForChat(
visibleFailure.agentRef,
visibleFailure.chatId ?? null,
visibleFailure.timestamp,
{ keepUndeliveredFiles: true }
)
}
setFailedAgentSend(null)
setAgentError(null)
}, [visibleFailure, releaseRetainedSend, releaseRetainedFailuresForChat])
const handleRecoverFailedAgentSend = useCallback(() => {
if (
!visibleFailure ||
visibleFailure.agentRef !== activeChatVisibilityRef.current.selectedAgent ||
visibleFailure.chatId !== activeChatVisibilityRef.current.activeChatId
)
return
if (visibleFailure.answeredWithoutFiles) {
// The text and the other attachments were answered: bring back only the
// documents the Host never received, and send nothing. Restoring replaces
// the composer's documents, so only documents already there block it; a
// new draft or other attachments stay as they are.
if (composerFileAttachments.length) {
pushToast(
'Remove the documents in the composer before recovering the earlier files.',
'error'
)
return
}
const undelivered = new Set(visibleFailure.undeliveredFileIds ?? [])
handleRestoreComposerFiles(visibleFailure.files.filter(file => undelivered.has(file.id)))
handleDiscardFailedAgentSend()
return
}
if (
getComposerDraft(activeChatId, selectedAgent ?? undefined) ||
composerImageAttachments.length ||
composerFileAttachments.length ||
composerReferenceAttachments.length
) {
pushToast('Keep or clear the current draft before recovering the earlier input.', 'error')
return
}
setComposerDraft(activeChatId, visibleFailure.content, selectedAgent ?? undefined)
handleAddComposerImageAttachments(
visibleFailure.attachments.map(attachment => ({
...attachment,
previewDataUrl: `data:${attachment.mimeType};base64,${attachment.dataBase64}`,
}))
)
handleRestoreComposerFiles(visibleFailure.files)
handleAddComposerReferenceAttachments(visibleFailure.references)
handleDiscardFailedAgentSend()
}, [
visibleFailure,
activeChatId,
composerImageAttachments,
composerFileAttachments,
composerReferenceAttachments,
pushToast,
handleRestoreComposerFiles,
handleAddComposerImageAttachments,
handleAddComposerReferenceAttachments,
handleDiscardFailedAgentSend,
])
/**
* STORY-38 — a cancel is terminal for DELIVERY (the snapshot below is still
* released), but the attachments of the canceled message return to the
* composer so the user can reuse them. In-memory only: the composer state,
* not GFS or any persisted store, owns the kept attachments.
*
* The restore and its Discard-all action are bound to BOTH the originating
* agent and the originating chat (the retained snapshot's chatId). When the
* cancel settles while a different agent or chat is viewed, the restoration
* is PARKED under that identity instead of dropped, and applies when the
* originating chat is active again (R2-M1 — preservation, not loss; see
* work-tracker/specs/folder-zip-and-cancel-restore-budget.md).
*/
const restoreComposerAttachmentsAfterCancel = useCallback(
(taskId: string, agentRef: string) => {
const snapshots = getRetainedSendsForTask(taskId)
const images = snapshots.flatMap(snapshot => snapshot.attachments)
const references = snapshots.flatMap(snapshot => snapshot.references)
if (!images.length && !references.length) return
const originChatId = snapshots[0]?.chatId ?? null
const stillViewingOrigin =
activeChatVisibilityRef.current.selectedAgent === agentRef &&
activeChatVisibilityRef.current.activeChatId === originChatId
const preparedImages = images.map(attachment => ({
...attachment,
previewDataUrl: `data:${attachment.mimeType};base64,${attachment.dataBase64}`,
}))
if (!stillViewingOrigin) {
// Preserve: the task snapshot is released by the caller, but the kept
// payload survives here until its chat is viewed again.
//
// R3-M4: the batch is APPENDED to the chat's queue. Two
// cancellations settling for the same originating chat while another
// chat is viewed must both survive — the later one does not replace
// the earlier one's attachments.
const key = `${agentRef}::${originChatId}`
const parked = parkedRestorationsRef.current.get(key)
if (parked) {
parked.batches.push({ images: preparedImages, references })
} else {
parkedRestorationsRef.current.set(key, {
agentRef,
chatId: originChatId,
batches: [{ images: preparedImages, references }],
})
}
return
}
applyKeptAttachments(agentRef, originChatId, preparedImages, references)
},
[getRetainedSendsForTask, applyKeptAttachments]
)
const cancelTask = useCallback(
async (taskId: string) => {
const hostRef = selectedAgent
if (!hostRef) return
const markCancelled = (reason?: string) => {
setProgressByAgentMessage(previous => {
const byMessage = previous[hostRef] || {}
let changed = false
const nextByMessage = Object.fromEntries(
Object.entries(byMessage).map(([messageId, progress]) => {
if (progress.taskId !== taskId) return [messageId, progress]
changed = true
return [
messageId,
{
...progress,
status: 'cancelled' as const,
cancelReason: reason ?? progress.cancelReason,
},
]
})
)
return changed ? { ...previous, [hostRef]: nextByMessage } : previous
})
setActivityByAgentMessage(previous => {
const byMessage = previous[hostRef] || {}
let changed = false
const nextByMessage = Object.fromEntries(
Object.entries(byMessage).map(([messageId, activity]) => {
if (activity.taskId !== taskId) return [messageId, activity]
changed = true
return [
messageId,
{
...activity,
status: 'completed' as const,
errorMessage: undefined,
},
]
})
)
return changed ? { ...previous, [hostRef]: nextByMessage } : previous
})
}
try {
await window.clerum.rpc.cancelTask(hostRef, taskId)
markCancelled('Cancelled by user.')
// #654 M6 — a cancel is terminal by intent: the user does not want this
// payload resent, so nothing will read the retained snapshot again. The
// attachments themselves return to the composer (STORY-38) before the
// snapshot that carried them is released. A snapshot holding documents
// the Host never received stays for Recover files (see
// releaseRetainedSendsForTask).
restoreComposerAttachmentsAfterCancel(taskId, hostRef)
releaseRetainedSendsForTask(taskId)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
if (message.includes('404') || message.toLowerCase().includes('task not found')) {
markCancelled('Task already finished or is no longer active.')
// The task is gone upstream, so it can no longer produce a terminal
// event — same reasoning as the successful cancel above.
restoreComposerAttachmentsAfterCancel(taskId, hostRef)
releaseRetainedSendsForTask(taskId)
pushToast('That task is no longer active.', 'info')
return
}
console.error('[useAgentChatController] cancelTask failed', err)
pushToast(`Failed to cancel task: ${message}`, 'error')
}
},
[pushToast, selectedAgent, releaseRetainedSendsForTask, restoreComposerAttachmentsAfterCancel]
)
const setPendingChatSelection = useCallback(
(
agentName: string,
chatId: string | null,
options: {
selectLatest?: boolean
suppressAutoSelect?: boolean
deferSwitch?: boolean
title?: string
isRemote?: boolean
} = {}
) => {
if (isHostAccessBlocked(agentName) || (chatId && isChatDeleted(agentName, chatId))) return
const selectionMode = options.selectLatest
? 'latest'
: options.suppressAutoSelect || !chatId
? 'none'
: 'specific'
const selectsSpecificChat = selectionMode === 'specific'
const preservesCurrentChatRoute = Boolean(
!chatId &&
selectionMode === 'none' &&
selectedAgent === agentName &&
navItem === DESKTOP_ROUTES.chat
)
if (
selectsSpecificChat &&
!options.deferSwitch &&
selectedAgent === agentName &&
navItem === DESKTOP_ROUTES.chat
) {
clearPendingSelection(agentName)
if (options.title) {
upsertProvisionalEntry(chatId!, options.title, options.isRemote === true)
}
void switchToChat(agentName, chatId!, {
onCurrentError: error => {
pushToast(
`Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
'error'
)
},
}).catch(() => undefined)
return
}
// A same-agent no-chat notification can record a pending none selection
// while the chat route continues an implicit/latest or visible history
// load. The explicit clear path owns blanking the view; do not steal its
// history completion here. Route/agent changes and specific/latest
// selections still advance selection ownership before their effects run.
if (!preservesCurrentChatRoute) beginSelectionIntent(selectsSpecificChat)
if (selectionMode === 'latest') {
writePendingSelection(agentName, { mode: 'latest', chatId: null })
return
}
if (selectionMode === 'none') {
writePendingSelection(agentName, { mode: 'none', chatId: null })
return
}
const specificSelection: Extract<PendingChatSelection, { mode: 'specific' }> = {
mode: 'specific',
chatId: chatId!,
}
if (options.title) specificSelection.title = options.title
if (options.isRemote !== undefined) specificSelection.isRemote = options.isRemote
writePendingSelection(agentName, specificSelection)
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: chatId,
currentTeamId,
selectedAgent: agentName,
}
setActiveChatId(chatId)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
setChatMessagesLoading(true)
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
if (options.title) {
upsertProvisionalEntry(chatId!, options.title, options.isRemote === true)
}
},
[
cancelOlderMessagesLoad,
beginSelectionIntent,
clearPendingSelection,
currentTeamId,
writePendingSelection,
pushToast,
upsertProvisionalEntry,
selectedAgent,
navItem,
switchToChat,
isHostAccessBlocked,
isChatDeleted,
]
)
const clearActiveChat = useCallback(() => {
beginSelectionIntent()
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
activeChatId: null,
}
autoSelectedChatIdRef.current = null
setActiveChatId(null)
activeChatLocalPageRequestRef.current = null
setChatMessages([])
setHasOlderMessages(false)
cancelOlderMessagesLoad()
loadedLocalMessageCountRef.current = 0
// Deselecting the active chat (e.g. team switch) must also drop its per-chat
// error/resend banner so it doesn't bleed into the next active chat.
setAgentError(null)
setFailedAgentSend(null)
}, [beginSelectionIntent, cancelOlderMessagesLoad])
const groupedMessages = useMemo(() => {
const groups: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }> = []
for (const item of chatMessages) {
const previous = groups[groups.length - 1]
if (!previous || previous.role !== item.role) groups.push({ role: item.role, items: [item] })
else previous.items.push(item)
}
return groups
}, [chatMessages])
// D.5: session state for the SELECTED agent's chats, re-keyed by plain chatId
// (the same key as chatList entries / activeChatId) so the sidebar + header can
// look it up without recomputing makeTaskKey per chat.
const sessionStateByChatId = useMemo(() => {
if (!selectedAgent) return {} as Record<string, SessionStateLite>
const out: Record<string, SessionStateLite> = {}
for (const [taskKey, value] of Object.entries(sessionStateByChatKey)) {
const { agentRef, chatId } = parseTaskKey(taskKey)
if (agentRef === selectedAgent) out[chatId] = value
}
return out
}, [sessionStateByChatKey, selectedAgent])
return {
activeChatId,
chatList,
chatListLoading,
chatListMoreLoading,
chatListHasMoreRemoteSessions,
latestChatSessions,
latestChatSessionsLoading,
chatMessages,
chatMessagesLoading,
hasOlderMessages,
olderMessagesLoading,
sessionStateByChatKey,
sessionStateByChatId,
// Fase 2b (§4.7.4): the app-shell builds the central `decideApproval` bound to
// THIS store so all four decision surfaces converge the same FSM projection.
sessionFsmStore: fsm,
progressByAgentMessage,
composerImageAttachments,
composerFileAttachments,
composerFileRefusals,
composerReferenceAttachments,
agentSending,
// A fresh send-time error (a blocked image send, a new POST failure) wins;
// the retained failure's message covers the banner only when nothing newer
// has been reported.
agentError: agentError ?? visibleRetainedFailure?.message ?? null,
failedAgentSend: visibleFailure,
chatEndRef,
scrollChatToBottom,
activityByMessageId,
progressByMessageId,
groupedMessages,
switchToChat,
reconcileChat,
stopAllActivityStreams,
resetChat,
setPendingChatSelection,
clearActiveChat,
handleCreateChat,
handleRenameChat,
handleRenameChatForAgent,
applyLocalTitleOnly,
captureChatDeleteFence,
handleDeleteChat,
handleDeleteChatForAgent,
handleSelectChat,
handleLoadOlderMessages,
loadMoreChatSessions,
handleSendAgentMessage,
handleRetryFailedAgentSend,
handleRecoverFailedAgentSend,
handleDiscardFailedAgentSend,
clearComposerSendError,
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
handleAddComposerFiles,
handleRemoveComposerFileAttachment,
handleRestoreComposerFiles,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
handleClearComposerAttachments: resetComposerAttachments,
cancelTask,
}
}