Files
hapi/ios/Packages/HapiKit/Sources/HapiClient/Stores/MessageWindowController.swift
T
Junmo KimandGitHub 523decdf86 fix(hub): fold repeated ACP tool-call updates into one row per callId (#2350)
* feat(shared): read the callId of a supersedable tool-call row

ACP agents re-emit the same tool call under a stable callId on every
state tick, and the timeline folds all of those rows into one card. The
hub and the web both need to recognise the rows that may be superseded,
so add `getToolCallId`, mirroring `getReasoningStreamId`/`getLiveReasoningStreamId`.

Only `codex`/`tool-call` payloads match. The `tool-call-result` that
shares the callId is a different row type that carries completion, so it
never matches and is never dropped. Anything unrecognised reads as null
("keep it").

* fix(hub): fold ACP tool-call updates into one row per callId

ACP agents re-emit a tool_call agent message for the first tool_call and
again for every tool_call_update, all under one callId, and the hub stored
each as its own row. History pages therefore filled with 2-4 duplicate
tool-call rows per call that the web then folded back into a single card
by callId.

Route agent tool-call messages (getToolCallId != null) through an upsert:
scan the session tail for a live tool-call row with the same callId,
stopping at a tool-call-result with that callId or at a user message row
(both mean the incoming message is a new call). On a match, merge the new
payload into the stored row in place — non-null new values win for
name/input/nativeTitle/nativeKind/nativeName/nativeArgs/status so a
status-only tick cannot erase an earlier tick's input — and keep the
row's id, seq, createdAt and localId. The content swap follows the
queued-message edit pattern (no new seq, no content_revision bump).

The post-store broadcast is unchanged (session-room update + web
message-received) and now carries the existing row's id/seq with the
merged content, which the web window store already upserts by id.
Nothing is deleted: result rows, permissions, localId resend handling
and non-tool messages behave exactly as before.

* fix(hub): never regress a merged tool-call row's status

A later tool-call tick that re-emits status pending (agents normalize a
missing/unknown status to pending, so OpenCode permission rounds resend
it after the call already ran) overwrote an earlier in_progress or
terminal status under the plain newest-non-null-wins merge.

Merge status by progression rank instead: pending < in_progress <
completed/failed. The merged row keeps the higher rank, so a running or
finished call never falls back to pending, and a terminal status always
wins over a non-terminal one in either direction. completed/failed share
the terminal tier and ties keep the newer value; unrecognized status
strings rank below every known state so they cannot regress one either.

Also pin the behaviors the upsert relies on with tests: the 200-row
lookback boundary on both sides, a tool-call-result for a different
callId not stopping the scan, nativeName/nativeArgs/progress merging,
and the handler re-broadcasting the existing row id/seq through both the
session-room update and web message-received without storing an extra
row.

* fix(hub): stamp derived tool state at merge time and skip no-op tool-call writes

A merged tool-call row keeps its first snapshot's createdAt for stable
ordering, but the session's derived TodoWrite/team versions gate on
strictly advancing timestamps (todos_updated_at and team_state_updated_at
only accept candidates greater than the stored watermark), so a refined
snapshot arriving on a later tick of the same callId was rejected and the
session's todo list stayed at its first snapshot. Stamp those versions at
merge time instead.

A re-emitted tick whose payload changes nothing now skips the row write
entirely: only observable content changes touch the database.

* fix(web): recover merged tool-call rows after an SSE replay gap

A gap resume (resume: 'gap') cannot prove continuity, and in-place
tool-call merges keep the row's original cursor position, so the
cursor-based tail sync after a gap re-delivered new rows but never the
merged content of rows the window already held. Tool cards could stay
stuck on their first snapshot until a reload.

On the gap path of both connect handlers, reconcile the window from an
authoritative latest page applied as an upsert: rows in the response
replace the held rows by id, while already-loaded rows older than the
latest page and the hasMore/oldest cursor and context survive; an older
load caught in flight is invalidated like on every tail sync and is
re-requested by the user's scroll. Replacing the whole window is not an
option here: a fresh session subscription is always a gap verdict, so
every session switch-back would throw away the user's scrolled-up
history. Rows older than the latest page are not re-fetched; a live
tool-call tick always updates a row inside the newest page, and a
failed recovery fetch leaves the flag set so the next sync retries the
latest page. Cold and structurally invalidated windows keep the plain
reset choreography.

* fix(web): catch up the disconnected interval before the gap-recovery upsert

Gap recovery fetched only the newest page and applied it as an upsert,
so a warm window whose cached tail sat below the page's oldest row kept
a permanent hole: rows that arrived while disconnected between the
cached tail and the page vanished, and the advanced newest cursor never
filled them (cursor syncs only return rows after their cursor).

Run a plain cursor sync first so the window catches up every row it
missed, then apply the authoritative latest page as an upsert to
refresh in-place merged rows. One extra round trip on reconnect; the
upsert alone stays correct for windows that are already contiguous.

* fix(web): replace retained rows when gap recovery observes a different epoch

The recovery upsert requested the latest page without an epoch and the
hub always answers reset:false for latest requests, so rows deleted
while disconnected survived: another client's rewind deletes rows and
bumps the epoch, but the missed messages-invalidated event left the
window's requiresLatestReset false and nothing detected the change.

Compare the response's epoch with the window's epoch in the latest-page
branch and fall back to a full replacement on mismatch. The cursor
catch-up that now precedes the upsert already carries the window epoch
and gets the hub's reset verdict, so this closes the remaining window
where the upsert runs without a preceding successful epoch-carrying
sync.

* fix(web): require a successful catch-up before the gap-recovery upsert

runTailSync resolves normally after catching a request error, so the
recovery continued to the latest-page reconciliation even when the
catch-up failed. With a cached tail at row 10 and the server head at
310, a failed after request followed by a successful latest request
retained row 10 alongside rows 111-310 and advanced the newest cursor
to 310: rows 11-110 became unreachable through ordinary tail or older
paging, and the successful latest response cleared the failure warning.

Fold the recovery into the tail sync itself: the pendingGapRecovery run
catches the window up through the ordinary cursor phase and only
reconciles the latest page once that phase completed without error. A
reset verdict inside the catch-up already replaced the window
authoritatively, so the recovery flag is simply consumed there. On a
catch-up failure the catch skips the reconciliation, keeping the
original cursor, the flag for the next sync's retry, and the visible
warning.

* fix(web): keep the loaded history budget across the gap-recovery upsert

applyLatestResponse always trimmed the merged window to the 400-row
tail budget, even when only refreshing it in place. A reader with 600
loaded history rows therefore lost the oldest rows on a same-epoch
reconnect with no new messages, shifting their reading anchor even
though nothing on the server changed.

Size the recovery upsert's trim to the window's own history budget,
capped at the 800-row older-load ceiling: rows the reader already
loaded are preserved on a no-news recovery instead of being re-evicted.
Full replacements keep the tail budget, since a replaced window holds
only the response rows anyway.

* fix(web): run the catch-up when gap recovery overlaps a cached activation

A cached session's activation asks for a direct latest page
(preferLatestOnActivation), and runTailSync's canIncrement excluded that
flag unconditionally. When gap recovery was requested on top of such an
activation, the recovery therefore took the activation shortcut: a
direct latest-page fetch with no cursor catch-up. With cached rows 1-10
and the server head at 310, the window retained rows 1-10 plus the
latest page 111-310 and advanced its newest cursor to 310, leaving rows
11-110 unreachable through ordinary tail or older paging; the recovery
flag was consumed without ever catching the window up.

Let a pending recovery claim the cursor path even when an activation
shortcut is pending, and defer the activation flag for that run: the
recovery's catch-up + latest-page reconciliation subsumes the
activation's refresh-from-latest, so consuming it there is equivalent.
The flag is also cleared when the recovery finishes through a reset
verdict or its latest-page reconciliation, so a mid-run activation
cannot linger into a later full replacement.

* fix(web): refresh out-of-page tool-call rows during gap recovery

A tool-call row cached before a disconnect can be enriched in place
afterwards; when more than a latest page of newer rows follows before
reconnect, neither the catch-up (newer rows only) nor the latest page
reaches it, and the cached card keeps its stale input/status until the
session is reopened (review finding on hub messages.ts:378, the web
half of the documented jkRY limit).

After the recovery's latest-page reconciliation, sweep the window for
retained non-terminal tool-call rows older than the page bound and
older than the recovery cursor, and refresh each by id through the
existing message-context endpoint. Bounded at 20 (newest first),
best-effort (a failed or epoch-mismatched refresh leaves the row to the
next recovery), and generation-guarded like the rest of the run.

* fix(web): surface gap-recovery refresh failures as the usual sync warning

The out-of-page tool-call refresh sweep swallowed per-row context-fetch
errors, leaving a stale row silently. Let a rejected refresh propagate
to runTailSync's catch so the run's usual warning surfaces; the row
stays as is and the next sync retries the sweep. A refresh answered
under a different epoch, or one that no longer contains the row, stops
the sweep without touching the window. Terminal rows are never swept
(merge status only advances); tests pin the zero-request skip and the
warning on failure.

* fix(android): recover merged tool-call rows through the gap-recovery upsert

The Android window store's gap path recovered through a cursor sync
only: merged tool-call rows keep their original cursor position, so a
row enriched while disconnected kept its stale input/status until a
fresh page happened to include it (the same hole the web recovery
closed).

Port the web choreography: the gap entry point (resume: 'gap' on the
session pipe) flags the window (pendingGapRecovery) and runs
recoverAfterGapResume; the next tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
the tail-sync coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does. The queued
-state reconciliation keeps its own ensureAfterCurrent drain and runs
concurrently with the recovery, mirroring the web's two post-gap calls.

The bounded by-id refresh of out-of-page non-terminal rows stays
web-only (Limits follow-up; it needs the message-context endpoint in
the native API seam).

* fix(ios): recover merged tool-call rows through the gap-recovery upsert

Mirror of the Android recovery port for the HapiKit window controller:
the session layer's resume: 'gap' handling now flags the window
(pendingGapRecovery) and runs recoverAfterGapResume alongside the
queued-state reconciliation, and the tail sync catches up the missed
interval with the cursor sync, then fetches an authoritative latest
page and applies it as an upsert — rows present in the page are
replaced by id while rows older than the page, the hasMore/oldest
cursor and the loaded history budget (up to the 800-row older-load
ceiling, mirroring the web trim) survive. An epoch mismatch under the
page falls back to full replacement, a reset verdict during the
catch-up consumes the recovery, and a failed catch-up keeps the flag
and the original cursor so the next sync retries the whole recovery. A
recovery requested while a cached activation's preferLatestOnActivation
is set claims the cursor path and defers the activation shortcut, and
syncTail coalescing joins or replaces in-flight runs by their
snapshotted recovery/activation mode like the web does.

Tests run in CI (Swift toolchain is not available on this machine):
recovery converges the merged row through catch-up + latest page, and a
failed catch-up stops before the latest page and retries on the next
recovery. The bounded by-id refresh of out-of-page non-terminal rows
stays web-only (Limits follow-up).

* test(ios): read the window-message envelope from content, not wire

The new gap-recovery tests compared the merged tool-call row through a
`.wire` accessor that does not exist on WindowMessage (the
role-wrapped envelope lives on the public `content` field; `wire` is
only the convenience initializer's parameter name), which failed to
compile the whole HapiKit test target in CI. Compare the envelope
content values directly — still by value, not by WindowMessage
identity.

* test(ios): read the retry requests off the cumulative request list

provider.requests accumulates across the whole test: the failed first
catch-up stays at index 0, so the retry's catch-up and latest page sit
at indices 1 and 2 — the assertion counted from the retry point and
failed in CI even though the retry behaved exactly as pinned
([after, after, latest]).

* fix(web): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget:
history-mode trimming keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset
(mergeIntoWindow's prepend trim). The loop breaks on
requiresLatestReset without distinguishing that overflow from a
completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor (older paging descends from the window edge, the newest cursor
has already passed them).

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next sync's
authoritative replacement closes the hole and consumes the flags, the
same choreography as every other reset-marked window.

* fix(web): finish the sync when the gap-recovery refresh sweep stops early

The out-of-page tool-call refresh sweep early-returned when a context
response no longer contained the row or answered under a different
epoch, bypassing finishTailSync and leaving the window marked syncing
after the controller promise resolved — suppressing tool-history
hydration and read receipts until another sync ran.

Complete the run's bookkeeping on both exits: a missing row finishes
with the usual warning and the row as is; an epoch mismatch marks the
window for the authoritative replacement (server rows may have been
deleted since the page was fetched) and finishes with the warning
instead of reconciling against a stale snapshot.

* fix(android): keep the reset requirement when the recovery catch-up overflows

A recovery catch-up page can overflow the window's history budget: the
history-mode prepend trim keeps the reading anchor, drops the newer
caught-up rows, and marks the window for a reset. The catch-up loop
breaks on requiresLatestReset without distinguishing that overflow from
a completed catch-up, and the recovery then reconciled the latest page
on top anyway and consumed the recovery flags — stranding the rows
between the reset-marked window and the page, unreachable from either
cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags, the same choreography
as every other reset-marked window. Mirrors the web fix.

* fix(android): keep the earlier older cursor when the recovery upsert retains rows

When the recovery's latest-page upsert retains rows older than the
page (no trim), applyLatestResponse still preferred the response page's
own bound as the older-paging cursor, so an 800-row no-news recovery
re-pointed older loads at the page's oldest row and left the held rows
1-600 unpaged. Keep whichever side is older, like the web has since the
loaded-history-budget fix.

* fix(android): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the existing message-context endpoint — bounded at 20 newest-first, with
the same exit semantics the web sweep carries (a missing row finishes
the run with the usual warning and the row as is; a refresh answered
under a different epoch marks the window for the authoritative
replacement and finishes with the warning).

The seam gains getMessageContext (wire types MessageContextPage/
MessageContextResponse; the hub answers a bare null when the message
does not resolve), implemented by HapiApi and scripted null in the
fakes.

* fix(ios): keep the reset requirement when the recovery catch-up overflows

Mirror of the Android/web recovery overflow fix: a recovery catch-up
page can overflow the window's history budget — the history-mode
prepend trim keeps the reading anchor, drops the newer caught-up rows,
and marks the window for a reset — and the recovery then reconciled the
latest page on top anyway and consumed the recovery flags, stranding
the rows between the reset-marked window and the page, unreachable from
either cursor.

When the catch-up ends with the window reset-marked, leave the reset
requirement and the recovery flags intact: the next authoritative
replacement (on returning to the tail view, or on a sync that may reset
history) closes the hole and consumes the flags. Test rides CI — no
Swift toolchain on this machine.

* fix(ios): keep the earlier older cursor when the recovery upsert retains rows

Mirror of the Android/web cursor fix: when the recovery's latest-page
upsert retains rows older than the page (no trim), applyLatestResponse
still preferred the response page's own bound as the older-paging
cursor, so an 800-row no-news recovery re-pointed older loads at the
page's oldest row and left the held rows 1-600 unpaged. Keep whichever
side is older, like the web has since the loaded-history-budget fix.
Test rides CI.

* fix(ios): refresh out-of-page tool-call rows during gap recovery

Port the web sweep: after the recovery's latest-page reconciliation, the
window re-reads its retained non-terminal tool-call rows that sit older
than the page bound and were not delivered fresh by the catch-up through
the message-context endpoint — bounded at 20 newest-first, with the same
exit semantics the web sweep carries (a missing row finishes the run
with the usual warning and the row as is; a refresh answered under a
different epoch marks the window for the authoritative replacement and
finishes with the warning).

The transport gains the endpoint end to end: MessageContextPage/
MessageContextResponse wire types (the hub answers a bare null when the
message does not resolve), APIClient.messageContext, the MessagesProviding
requirement, and the row-swap helper on the window logic. agentMessage-
PayloadType becomes public so the controller can classify rows like the
web does. Tests ride CI — no Swift toolchain on this machine.
2026-11-11 13:05:04 +08:00

923 lines
42 KiB
Swift

import Foundation
import HapiProtocol
/// What the chat screen renders — mirror of the web `useMessages` return
/// shape (and the Android port's `MessageWindowUiState`); cursor/generation
/// internals stay off the render path. `Equatable` compares rows by identity
/// (see ``WindowMessage``), which is exactly the change signal the web uses.
public struct MessageWindowUIState: Equatable, Sendable {
public let messages: [WindowMessage]
public let hasMore: Bool
public let isSyncingTail: Bool
public let isLoadingMore: Bool
public let warning: String?
public let viewMode: MessageViewMode
public let messagesVersion: Int
public let historyVersion: Int
public let tailRevision: Int
}
extension MessageWindowState {
public var uiState: MessageWindowUIState {
MessageWindowUIState(
messages: messages,
hasMore: hasMore,
isSyncingTail: isSyncingTail,
isLoadingMore: isLoadingMore,
warning: warning,
viewMode: viewMode,
messagesVersion: messagesVersion,
historyVersion: historyVersion,
tailRevision: tailRevision
)
}
}
/// Non-transport failure of the tail-sync loop.
struct MessageWindowSyncError: Error, LocalizedError, Equatable {
let message: String
var errorDescription: String? { message }
/// Protocol violation guard: `nextAfter` did not advance past the cursor.
static let cursorDidNotAdvance = MessageWindowSyncError(
message: "Message tail cursor did not advance"
)
}
/// Per-session message window orchestration — the async half of the web
/// reference `web/src/lib/message-window-store.ts`, driving the pure
/// transitions in `MessageWindowLogic` over actor-isolated state. Mirrors
/// the Android port's `MessageWindowStore` (`core/data/.../store/`).
///
/// Concurrency model: the web store is single-threaded JS whose interleaving
/// points are its `await`s; here every synchronous read-modify-write segment
/// between transport calls runs on the actor, and the generation counters +
/// request-baseline identity checks (ported as-is) handle whatever
/// interleaves across the provider calls — which suspend the actor. Tail
/// syncs are single-flight per session with an optional trailing re-run,
/// exactly like the web `TailSyncController`.
public actor MessageWindowController {
/// Immutable and Sendable — same-module callers may read it without
/// `await` (SE-0306); cross-module callers go through the actor.
public let sessionId: String
private let provider: any MessagesProviding
private let snapshots: WindowSnapshotStore?
private let historyRetentionLimit: Int
private var stateValue: MessageWindowState
private var observers: [UUID: AsyncStream<MessageWindowState>.Continuation] = [:]
// MARK: - Lifecycle
public init(
sessionId: String,
provider: any MessagesProviding,
snapshots: WindowSnapshotStore? = nil,
initialState: MessageWindowState? = nil,
historyRetentionLimit: Int = MessageWindowConstants.historyWindowSize
) {
self.sessionId = sessionId
self.provider = provider
self.snapshots = snapshots
self.historyRetentionLimit = historyRetentionLimit
self.stateValue = initialState ?? MessageWindowLogic.createState(sessionId: sessionId)
self.stateValue.historyRetentionLimit = historyRetentionLimit
}
/// The full window state (UI projects what it needs; see
/// ``MessageWindowState/uiState``).
public var state: MessageWindowState { stateValue }
/// Stream of state changes, starting with the current state. Change
/// detection is instance-based (identity-`Equatable` rows), like the
/// web's `next !== previous` publication gate.
public func states() -> AsyncStream<MessageWindowState> {
let (stream, continuation) = AsyncStream.makeStream(of: MessageWindowState.self)
let id = UUID()
observers[id] = continuation
continuation.yield(stateValue)
continuation.onTermination = { [weak self] _ in
Task { await self?.removeObserver(id) }
}
return stream
}
private func removeObserver(_ id: UUID) {
observers.removeValue(forKey: id)
}
@discardableResult
private func update(
_ transform: (MessageWindowState) -> MessageWindowState
) -> MessageWindowState {
let previous = stateValue
var next = transform(previous)
next.historyRetentionLimit = historyRetentionLimit
stateValue = next
if next != previous {
for continuation in observers.values {
continuation.yield(next)
}
}
return next
}
// MARK: - Tail controller
private var runSerial = 0
private var runningTask: Task<Void, Never>?
private var runningRunId: Int?
private var runningPrefersLatest = false
private var runningPendingRecovery = false
private var trailingRequested = false
/// Bumped by ``clear()``/``seedFrom(_:)`` so a finished run stops
/// chaining trailing runs (web: controller replacement).
private var controllerEpoch = 0
/// Run (or join) a tail sync (web `syncTailMessages`). With
/// `ensureAfterCurrent` the call drains: if a run is already in flight, a
/// trailing run is requested and awaited, so the caller returns only
/// after a sync that STARTED at or after this call.
public func syncTail(ensureAfterCurrent: Bool = false, allowingHistoryReset: Bool = false) async {
if allowingHistoryReset {
let epoch = controllerEpoch
if let runningTask { await runningTask.value }
guard epoch == controllerEpoch, !Task.isCancelled else { return }
await startTailSync(allowingHistoryReset: true).value
return
}
guard let running = runningTask, let runningId = runningRunId else {
await startTailSync().value
return
}
if stateValue.preferLatestOnActivation || stateValue.pendingGapRecovery {
// A running sync snapshotted its mode at start; a newly requested
// latest reconciliation (cached re-entry or gap recovery) must not
// let that older run commit a plain cursor merge or a full
// replacement over it.
if runningPrefersLatest && !stateValue.pendingGapRecovery {
await running.value
return
}
if runningPendingRecovery && stateValue.pendingGapRecovery {
await running.value
return
}
trailingRequested = false
await startTailSync().value
return
}
guard ensureAfterCurrent else {
await running.value
return
}
trailingRequested = true
await drainTailSync(observedRunId: runningId, observed: running)
}
private var defersHistoryReset: Bool {
stateValue.viewMode == .history && stateValue.requiresLatestReset && stateValue.epoch != nil
}
private func startTailSync(allowingHistoryReset: Bool = false) -> Task<Void, Never> {
runSerial += 1
let runId = runSerial
let epoch = controllerEpoch
let prefersLatest = stateValue.preferLatestOnActivation
// Synchronous generation bump: the web executes `runTailSync` to its
// first true suspension (the api call) before `startTailSync`
// returns, and the Android port replicates that with an UNDISPATCHED
// coroutine start. Here `beginTailSync` lands before the Task is even
// created, so an in-flight run this one replaces can never commit
// another page in between.
update { MessageWindowLogic.beginTailSync($0) }
let generation = stateValue.syncGeneration
let task = Task { [weak self] in
guard let self else { return }
await self.runTailSync(generation: generation, allowingHistoryReset: allowingHistoryReset)
// Completion bookkeeping is the run's LAST actor-isolated act, so
// anyone resuming from `await task.value` observes the trailing
// handoff already done (web: `finish` runs via .then before
// external awaiters).
await self.tailSyncRunCompleted(runId: runId, epoch: epoch)
}
runningTask = task
runningRunId = runId
runningPrefersLatest = prefersLatest
runningPendingRecovery = stateValue.pendingGapRecovery
return task
}
private func tailSyncRunCompleted(runId: Int, epoch: Int) {
guard controllerEpoch == epoch, runningRunId == runId else { return }
runningTask = nil
runningRunId = nil
runningPrefersLatest = false
runningPendingRecovery = false
guard trailingRequested else { return }
trailingRequested = false
_ = startTailSync()
}
/// Web `waitForTailSyncDrain`: follow the chain until no newer run exists.
private func drainTailSync(observedRunId: Int, observed: Task<Void, Never>) async {
let epoch = controllerEpoch
var currentId = observedRunId
var current = observed
while true {
await current.value
guard controllerEpoch == epoch else { return }
guard let nextTask = runningTask, let nextId = runningRunId, nextId != currentId else {
return
}
currentId = nextId
current = nextTask
}
}
private func isCurrentTailSync(_ generation: Int) -> Bool {
stateValue.syncGeneration == generation
}
/// Body of one tail sync (web `runTailSync`, minus `beginTailSync`,
/// which ``startTailSync()`` already executed synchronously).
private func runTailSync(generation: Int, allowingHistoryReset: Bool) async {
do {
let initial = stateValue
let initialCursor = initial.newestPosition
let preferLatestOnActivation = initial.preferLatestOnActivation
let pendingGapRecovery = initial.pendingGapRecovery
let canIncrement = initialCursor != nil
&& initial.epoch != nil
&& !initial.requiresLatestReset
// A pending gap recovery must run its cursor catch-up even
// when a cached activation asked for a direct latest page: the
// activation shortcut fetches only the newest rows and leaves
// the interval between the cached tail and the page
// unreachable below the advanced newest cursor.
&& (!preferLatestOnActivation || pendingGapRecovery)
if canIncrement && preferLatestOnActivation {
// The recovery's catch-up + latest-page reconciliation
// subsumes the cached-activation refresh. Defer the activation
// shortcut for this run: left set, it would force-break the
// catch-up loop after its first chunk.
update { previous in
guard previous.syncGeneration == generation else { return previous }
var next = previous
next.preferLatestOnActivation = false
return next
}
}
if !canIncrement {
let requestBaseline = baseline()
let latestPageSize = initial.requiresLatestReset || pendingGapRecovery || initialCursor != nil
? MessageWindowConstants.pageSize
: MessageWindowConstants.initialPageSize
let response = try await provider.messages(
sessionId: sessionId,
query: .latest(limit: latestPageSize)
)
guard isCurrentTailSync(generation) else { return }
// A replay gap may have hidden messages-invalidated. Keep a
// truncated reading window only after checking the server's
// epoch, never by skipping the request (or its trailing run).
if !allowingHistoryReset, defersHistoryReset,
!response.page.reset, response.page.epoch == stateValue.epoch {
finishTailSync(generation: generation, warning: nil)
return
}
update { previous in
guard previous.syncGeneration == generation else { return previous }
var next = MessageWindowLogic.applyLatestResponse(
previous,
responseMessages: windowMessages(response),
page: response.page,
replaceServerRows: initial.requiresLatestReset
|| (preferLatestOnActivation && !pendingGapRecovery)
|| response.page.reset,
requestBaseline: requestBaseline
)
next.preferLatestOnActivation = false
next.pendingGapRecovery = false
return next
}
finishTailSync(generation: generation, warning: nil)
return
}
var after = initialCursor!
var until: MessagePosition?
var catchUpReset = false
while true {
let requestBaseline = baseline()
let response = try await provider.messages(
sessionId: sessionId,
query: .after(
afterAt: after.at,
afterSeq: after.seq,
untilAt: until?.at,
untilSeq: until?.seq,
epoch: initial.epoch!,
limit: MessageWindowConstants.pageSize
)
)
guard isCurrentTailSync(generation) else { return }
if response.page.reset || response.page.direction == .latest {
update { previous in
guard previous.syncGeneration == generation else { return previous }
var next = MessageWindowLogic.applyLatestResponse(
previous,
responseMessages: windowMessages(response),
page: response.page,
replaceServerRows: true,
requestBaseline: requestBaseline
)
next.pendingGapRecovery = false
next.preferLatestOnActivation = false
return next
}
catchUpReset = true
break
}
let nextAfter = MessageWindowLogic.pagePosition(
at: response.page.nextAfterAt,
seq: response.page.nextAfterSeq
)
let snapshotHead = MessageWindowLogic.pagePosition(
at: response.page.snapshotHeadAt,
seq: response.page.snapshotHeadSeq
)
if until == nil {
until = snapshotHead
}
update { previous in
guard previous.syncGeneration == generation else { return previous }
return MessageWindowLogic.applyAfterPage(
previous,
responseMessages: windowMessages(response),
page: response.page,
nextAfter: nextAfter
)
}
let current = stateValue
if current.requiresLatestReset
|| current.preferLatestOnActivation
|| !response.page.hasMore
|| nextAfter == nil {
break
}
if nextAfter! <= after {
throw MessageWindowSyncError.cursorDidNotAdvance
}
after = nextAfter!
}
if pendingGapRecovery {
if catchUpReset {
// A reset verdict already replaced the window
// authoritatively under the server's epoch; there is
// nothing left to refresh.
update { previous in
guard previous.syncGeneration == generation else { return previous }
var next = previous
next.pendingGapRecovery = false
next.preferLatestOnActivation = false
return next
}
} else if stateValue.requiresLatestReset {
// The catch-up overflowed the window's history budget:
// the prepend trim dropped the newer caught-up rows and
// marked the window for a reset. Reconciling the latest
// page on top would strand the rows between the
// reset-marked window and the page — unreachable from
// either cursor — so leave the reset requirement and the
// recovery flags intact: the next authoritative
// replacement closes the hole and consumes the flags.
} else {
// The cursor phase caught the window up without error.
// Only now may the recovery advance to the latest page:
// reconciling after a failed catch-up would strand the rows
// between the cached tail and the page below the advanced
// newest cursor. On a catch-up failure the catch below
// skips this block, the original cursor and the flag
// survive, and the next sync retries the whole recovery.
let requestBaseline = baseline()
let response = try await provider.messages(
sessionId: sessionId,
query: .latest(limit: MessageWindowConstants.pageSize)
)
guard isCurrentTailSync(generation) else { return }
update { previous in
guard previous.syncGeneration == generation else { return previous }
// The trim honors the window's loaded history budget
// (web `4d1d9e2025`): a no-news reconnect never evicts
// rows the reader already had.
let trimLimit = min(
MessageWindowConstants.olderLoadWindowSize,
max(MessageWindowConstants.visibleWindowSize, previous.messages.count)
)
var next = MessageWindowLogic.applyLatestResponse(
previous,
responseMessages: windowMessages(response),
page: response.page,
replaceServerRows: response.page.reset
|| (previous.epoch != nil && response.page.epoch != previous.epoch),
requestBaseline: requestBaseline,
trimLimit: trimLimit
)
next.pendingGapRecovery = false
next.preferLatestOnActivation = false
return next
}
// A tool-call row the client cached before the gap can be
// enriched in place afterwards; when more than a latest
// page of newer rows followed, neither the catch-up
// (newer rows only) nor the page reaches it, and the
// cached card keeps its stale input/status. Refresh those
// retained non-terminal rows by id through the
// message-context endpoint: bounded, newest first, and
// skipped for rows the catch-up already delivered fresh
// (at or after the recovery cursor).
let pageOldest = MessageWindowLogic.pagePosition(
at: response.page.nextBeforeAt,
seq: response.page.nextBeforeSeq
)
if let pageOldest {
let candidates = stateValue.messages.compactMap { message -> (position: MessagePosition, message: WindowMessage)? in
guard let position = MessageWindowLogic.messagePosition(message) else { return nil }
if position >= pageOldest { return nil }
if let initialCursor, position > initialCursor { return nil }
guard isNonTerminalToolCallRow(message) else { return nil }
return (position, message)
}
.sorted { $0.position > $1.position }
.prefix(MessageWindowConstants.gapRowRefreshLimit)
for (_, candidate) in candidates {
// A failed refresh propagates to the catch below
// and surfaces the usual warning; the row stays
// as is and the next sync retries the sweep.
let context = try await provider.messageContext(
sessionId: sessionId,
messageId: candidate.id
)
guard isCurrentTailSync(generation) else { return }
let refreshed = context?.messages.first(where: { $0.id == candidate.id })
if refreshed == nil {
// The row is no longer reachable through the
// context endpoint: leave it as is and finish
// the run's bookkeeping — an early return
// here would leave the window marked
// syncing.
finishTailSync(generation: generation, warning: "Failed to refresh a merged tool call")
return
}
if context!.page.epoch != stateValue.epoch {
// The refresh answered under a different
// epoch: server rows may have been deleted
// since the page was fetched. Mark the window
// for the authoritative replacement instead
// of reconciling against a stale snapshot,
// and finish the run's bookkeeping.
update { previous in
guard previous.syncGeneration == generation else { return previous }
var next = previous
next.requiresLatestReset = true
return next
}
finishTailSync(generation: generation, warning: "Failed to refresh a merged tool call")
return
}
update { previous in
guard previous.syncGeneration == generation else { return previous }
return MessageWindowLogic.mergeRefreshedRow(previous, WindowMessage(wire: refreshed!))
}
}
}
}
}
finishTailSync(generation: generation, warning: nil)
} catch {
guard isCurrentTailSync(generation) else { return }
finishTailSync(
generation: generation,
warning: Self.warningMessage(error, fallback: "Failed to synchronize messages")
)
}
}
private func finishTailSync(generation: Int, warning: String?) {
update { MessageWindowLogic.finishTailSync($0, generation: generation, warning: warning) }
persist()
}
// MARK: - Older pages
/// Load one older page (web `fetchOlderMessages`). On an epoch mismatch
/// the window is invalidated and a full tail sync (`ensureAfterCurrent`)
/// runs before the `stopped/epoch-reset` outcome is returned.
/// `onBeforeApply` runs synchronously inside the state transition (mirror
/// of the web's synchronous updater) — it must not call back into this
/// controller.
public func fetchOlder(
onBeforeApply: (@Sendable (Int) -> Bool)? = nil
) async -> OlderLoadOutcome {
let initial = stateValue
switch MessageWindowLogic.olderLoadPrecheck(initial) {
case .stop(let reason):
return .stopped(reason)
case .proceed(let before):
let generation = initial.olderGeneration + 1
update { MessageWindowLogic.beginOlderLoad($0, generation: generation) }
do {
let response = try await provider.messages(
sessionId: sessionId,
query: .before(
beforeAt: before.at,
beforeSeq: before.seq,
limit: MessageWindowConstants.pageSize
)
)
guard stateValue.olderGeneration == generation else {
return .stopped(.invalidated)
}
guard !Task.isCancelled else {
update { MessageWindowLogic.cancelOlderLoad($0) }
return .stopped(.invalidated)
}
if let epoch = initial.epoch, response.page.epoch != epoch {
update { MessageWindowLogic.applyOlderEpochMismatch($0, generation: generation) }
await syncTail(ensureAfterCurrent: true)
return .stopped(.epochReset)
}
if response.page.hasMore {
let at = response.page.nextBeforeAt
let seq = response.page.nextBeforeSeq
guard let at, let seq, MessagePosition(at: at, seq: seq) < before else {
update { MessageWindowLogic.failOlderLoad($0, generation: generation,
warning: "Message history cursor did not advance") }
return .stopped(.cursorDidNotAdvance)
}
}
var historyVersion = 0
var addedRenderableCount = 0
var applyRejected = false
update { previous in
guard previous.olderGeneration == generation else { return previous }
let incoming = windowMessages(response)
addedRenderableCount = MessageWindowLogic.countNewRenderableMessages(
previous,
incoming: incoming
)
let nextHistoryVersion = previous.historyVersion + 1
if let onBeforeApply, !onBeforeApply(nextHistoryVersion) {
applyRejected = true
return MessageWindowLogic.rejectOlderApply(previous)
}
historyVersion = nextHistoryVersion
return MessageWindowLogic.applyOlderResponse(
previous,
responseMessages: incoming,
page: response.page,
historyVersion: nextHistoryVersion
)
}
if applyRejected || historyVersion == 0 {
return .stopped(.invalidated)
}
persist()
return .applied(
historyVersion: historyVersion,
hasMore: response.page.hasMore,
addedRenderableCount: addedRenderableCount
)
} catch {
guard stateValue.olderGeneration == generation else {
return .stopped(.invalidated)
}
if Task.isCancelled || error is CancellationError {
update { MessageWindowLogic.cancelOlderLoad($0) }
return .stopped(.invalidated)
}
update {
MessageWindowLogic.failOlderLoad(
$0,
generation: generation,
warning: Self.warningMessage(error, fallback: "Failed to load older messages")
)
}
return .failed(error)
}
}
}
public func cancelOlderLoad() {
update { MessageWindowLogic.cancelOlderLoad($0) }
}
// MARK: - SSE ingest
/// Route one message-stream SSE event into this window. The caller
/// routes per session already; the guard is defensive — a foreign
/// session's rows must never corrupt this window.
/// `messages-invalidated` clears the window and starts a fresh tail
/// sync; `scheduled-matured` re-syncs so the released row (and its
/// consumption) lands even if the `message-received` frame was missed.
public func onMessageEvent(_ event: SyncEvent) {
switch event {
case .messageReceived(_, let eventSessionId, let message) where eventSessionId == sessionId:
ingestSSEMessages([WindowMessage(wire: message)])
case .messagesConsumed(_, let eventSessionId, let localIds, let invokedAt)
where eventSessionId == sessionId:
markConsumed(localIds: localIds, invokedAt: invokedAt)
case .messagesIndeterminate(_, let eventSessionId, let localIds)
where eventSessionId == sessionId:
markIndeterminate(localIds: localIds)
case .messagesRequeued(_, let eventSessionId, let localIds)
where eventSessionId == sessionId:
markRequeued(localIds: localIds)
case .messageCancelled(_, let eventSessionId, let messageId, _) where eventSessionId == sessionId:
removeMessage(localIdOrId: messageId)
case .messagesInvalidated(_, let eventSessionId) where eventSessionId == sessionId:
clear()
Task { await self.syncTail() }
case .scheduledMatured(_, let eventSessionId) where eventSessionId == sessionId:
Task { await self.syncTail(ensureAfterCurrent: true) }
default:
break
}
}
/// SSE `message-received` ingest (web `ingestIncomingMessages`).
public func ingestSSEMessages(_ messages: [WindowMessage]) {
guard !messages.isEmpty else { return }
update { MessageWindowLogic.ingestIncoming($0, incoming: messages) }
persist()
}
/// SSE `messages-consumed` (web `markMessagesConsumed`).
public func markConsumed(localIds: [String], invokedAt: Int) {
guard !localIds.isEmpty else { return }
update { MessageWindowLogic.markConsumed($0, localIds: localIds, invokedAt: invokedAt) }
persist()
}
public func markIndeterminate(localIds: [String]) {
update { MessageWindowLogic.markIndeterminate($0, localIds: localIds) }
persist()
}
public func markRequeued(localIds: [String]) {
update { MessageWindowLogic.markRequeued($0, localIds: localIds) }
persist()
}
/// SSE `message-cancelled` / optimistic DELETE removal
/// (web `removeOptimisticMessage`).
public func removeMessage(localIdOrId: String) {
update { MessageWindowLogic.removeByLocalIdOrId($0, localId: localIdOrId) }
persist()
}
// MARK: - Optimistic sends
/// Append a pre-built optimistic row (web `appendOptimisticMessage`).
public func appendOptimistic(_ message: WindowMessage) {
update { MessageWindowLogic.appendOptimistic($0, message: message) }
persist()
}
/// Append the standard optimistic row for a send
/// (`useSendMessage.createOptimisticMessage`): status `sending` until the
/// POST settles, then ``updateStatus(localId:status:)`` to
/// `queued`/`sent`/`failed`.
public func appendOptimistic(
localId: String,
text: String,
attachments: [AttachmentMetadata]? = nil,
scheduledAt: Int? = nil,
deliveryMode: String = "queue",
createdAt: Int = Int(Date().timeIntervalSince1970 * 1000)
) {
appendOptimistic(
buildOptimisticMessage(
localId: localId,
text: text,
createdAt: createdAt,
attachments: attachments,
scheduledAt: scheduledAt,
deliveryMode: deliveryMode,
status: .sending
)
)
}
public func updateStatus(localId: String, status: MessageStatus) {
update { MessageWindowLogic.updateStatus($0, localId: localId, status: status) }
persist()
}
/// A cancel DELETE answered `{"status":"invoked"}` — too late, the agent
/// consumed the row. Remove the queued snapshot and ingest the returned
/// authoritative row as `sent` (web `useCancelQueuedMessage`).
public func applyCancelInvoked(localId: String, message: WindowMessage) {
removeMessage(localIdOrId: localId)
appendOptimistic(message.withStatus(.sent))
}
// MARK: - Queued reconciliation
public func queuedReconcileCandidateLocalIds() -> [String] {
MessageWindowLogic.queuedReconcileCandidateLocalIds(stateValue)
}
public func reconcileQueuedLocalIds(candidateLocalIds: [String], queuedLocalIds: [String]) {
update {
MessageWindowLogic.reconcileQueuedLocalIds(
$0,
candidateLocalIds: candidateLocalIds,
queuedLocalIds: queuedLocalIds
)
}
persist()
}
/// One gap-recovery step for a session message window (web
/// `recoverWindowAfterGapResume`).
///
/// A resumed-with-gap connection (`resume: 'gap'`) cannot prove
/// continuity, and in-place row updates (merged tool-call ticks) keep the
/// row's original cursor position, so a plain cursor sync re-delivers new
/// rows but never the merged content of rows the window already holds.
/// Flag the window and let the next tail sync run the full recovery: the
/// cursor catch-up pulls every row the window missed, then an
/// authoritative latest page is applied as an upsert — rows present in
/// the page are replaced by id while already-loaded rows older than the
/// latest page and the hasMore/oldest cursor survive. A failed catch-up
/// keeps the flag and the original cursor, so the next sync retries the
/// whole recovery. Cold or structurally invalidated windows have nothing
/// to preserve and keep the plain reset choreography.
public func recoverAfterGapResume() async {
let previous = stateValue
if previous.requiresLatestReset || previous.newestPosition == nil || previous.epoch == nil {
await syncTail()
return
}
update { state in
var next = state
next.pendingGapRecovery = true
return next
}
await syncTail()
}
/// Queued-state recovery after a `resume: 'gap'` reconnect (port of
/// `web/src/lib/queued-state-reconciliation.ts`): tail-sync to the drain,
/// collect candidates, ask the hub for the verdict in ≤1000-id batches,
/// stamp invoked rows like `messages-consumed`, drop deleted candidates.
/// The window's gap recovery (``recoverAfterGapResume()``) is a separate
/// step the session layer runs first (web wires the two the same way).
public func reconcileQueuedState() async throws {
await syncTail(ensureAfterCurrent: true)
let candidateLocalIds = queuedReconcileCandidateLocalIds()
guard !candidateLocalIds.isEmpty else { return }
var queuedLocalIds: [String] = []
var indeterminateLocalIds: [String] = []
var invokedLocalMessages: [(localId: String, invokedAt: Int)] = []
var start = 0
while start < candidateLocalIds.count {
let end = min(start + Self.queuedStateBatchSize, candidateLocalIds.count)
let batch = Array(candidateLocalIds[start..<end])
let response = try await provider.queuedState(sessionId: sessionId, localIds: batch)
queuedLocalIds += response.queuedLocalIds
indeterminateLocalIds += response.indeterminateLocalIds ?? []
invokedLocalMessages += response.invokedLocalMessages.map { ($0.localId, $0.invokedAt) }
start = end
}
var timestamps: [Int] = []
var localIdsByTimestamp: [Int: [String]] = [:]
for (localId, invokedAt) in invokedLocalMessages {
if localIdsByTimestamp[invokedAt] == nil { timestamps.append(invokedAt) }
localIdsByTimestamp[invokedAt, default: []].append(localId)
}
for invokedAt in timestamps {
markConsumed(localIds: localIdsByTimestamp[invokedAt]!, invokedAt: invokedAt)
}
markIndeterminate(localIds: indeterminateLocalIds)
reconcileQueuedLocalIds(candidateLocalIds: candidateLocalIds, queuedLocalIds: queuedLocalIds + indeterminateLocalIds)
}
// MARK: - Lifecycle transitions
/// Switch view mode (web `setMessageViewMode`); tail re-entry trims.
public func setViewMode(_ mode: MessageViewMode) {
update { MessageWindowLogic.setViewMode($0, mode: mode) }
persist()
}
/// Session (re-)activation (web `activateMessageWindow`): trims back to
/// the visible window and, with usable persisted state, requests a
/// fresh-latest trailing run from an in-flight sync.
public func activate() {
var requestedLatest = false
update { previous in
let activation = MessageWindowLogic.activate(previous)
requestedLatest = activation.requestedLatest
return activation.state
}
if requestedLatest, runningTask != nil {
trailingRequested = true
}
}
/// Web `clearMessageWindow`: forget everything but keep generations
/// poisoned so in-flight work cannot commit.
public func clear() {
controllerEpoch += 1
runningTask = nil
runningRunId = nil
runningPrefersLatest = false
trailingRequested = false
snapshots?.delete(sessionId: sessionId)
update { previous in
var next = MessageWindowLogic.createState(sessionId: sessionId)
next.syncGeneration = previous.syncGeneration + 1
next.olderGeneration = previous.olderGeneration + 1
return next
}
}
/// Seed this window from another session's (web
/// `seedMessageWindowFromSession`) — resume/reopen can hand back a new
/// session id; the old rows render instantly and `requiresLatestReset`
/// forces a fresh latest page underneath.
public func seedFrom(_ source: MessageWindowController) async {
guard source.sessionId != sessionId else { return }
controllerEpoch += 1
runningTask = nil
runningRunId = nil
runningPrefersLatest = false
trailingRequested = false
let sourceState = await source.state
update { MessageWindowLogic.seededState(source: sourceState, target: $0) }
persist()
}
// MARK: - Internals
private static let queuedStateBatchSize = 1000
/// Identity baseline of the current rows, keyed by id
/// (web `requestBaseline`; duplicate ids cannot occur post-merge, but a
/// JS `Map` keeps the last insertion — mirrored here).
private func baseline() -> [String: WindowMessage] {
Dictionary(
stateValue.messages.map { ($0.id, $0) },
uniquingKeysWith: { _, last in last }
)
}
private nonisolated func windowMessages(_ response: MessagesResponse) -> [WindowMessage] {
response.messages.map { WindowMessage(wire: $0) }
}
/// A cached tool-call row that can still be enriched in place: its
/// payload is a live `tool-call` whose merged status has not reached a
/// terminal tier. Terminal rows are done; unknown or missing status
/// reads as pending.
private nonisolated func isNonTerminalToolCallRow(_ message: WindowMessage) -> Bool {
guard case .object(let envelope) = message.content else { return false }
guard case .string(let role) = envelope["role"] ?? .null, role == "agent" else { return false }
guard case .object(let payload) = envelope["content"] ?? .null else { return false }
guard case .string(let payloadType) = payload["type"] ?? .null,
payloadType == agentMessagePayloadType else { return false }
guard case .object(let data) = payload["data"] ?? .null else { return false }
guard case .string(let dataType) = data["type"] ?? .null, dataType == "tool-call" else { return false }
guard case .string(let status) = data["status"] ?? .null else { return true }
return status != "completed" && status != "failed"
}
private func persist() {
guard let snapshots else { return }
let state = stateValue
if MessageWindowLogic.shouldPersist(state) {
snapshots.save(sessionId: sessionId, snapshot: MessageWindowLogic.toPersisted(state))
} else {
snapshots.delete(sessionId: sessionId)
}
}
private static func warningMessage(_ error: any Error, fallback: String) -> String {
(error as? LocalizedError)?.errorDescription ?? fallback
}
}