Files
hapi/ios/Packages/HapiKit/Sources/HapiProtocol/Window/MessageWindowLogic.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

842 lines
34 KiB
Swift

import Foundation
/// Pure state transitions of the message window — a function-for-function
/// port of `web/src/lib/message-window-store.ts` (with the async
/// orchestration stripped out; `HapiClient`'s `MessageWindowController`
/// re-adds it), matching the Android reference port
/// (`window/MessageWindowLogic.kt`) one-to-one. Every function takes the
/// previous ``MessageWindowState`` and returns the next one; nothing here
/// touches clocks, I/O, or tasks, so the whole surface is fixture-comparable.
public enum MessageWindowLogic {
public enum TrimMode: Sendable {
case append
case prepend
}
public static func createState(sessionId: String) -> MessageWindowState {
MessageWindowState(sessionId: sessionId)
}
// MARK: - Helpers
/// Web `buildState`: swap the messages list, re-derive seq bounds, bump
/// the version. Every call site passes a freshly-built array (the web
/// counterpart always builds a new array instance too), so the version
/// bumps unconditionally.
private static func settingMessages(
_ previous: MessageWindowState,
_ messages: [WindowMessage]
) -> MessageWindowState {
var oldestSeq: Int?
var newestSeq: Int?
for message in messages {
guard let seq = message.seq else { continue }
oldestSeq = oldestSeq.map { min($0, seq) } ?? seq
newestSeq = newestSeq.map { max($0, seq) } ?? seq
}
var next = previous
next.messages = messages
next.oldestSeq = oldestSeq
next.newestSeq = newestSeq
next.messagesVersion = previous.messagesVersion + 1
return next
}
/// A row's compound position; rows without a server `seq` have none.
public static func messagePosition(_ message: WindowMessage) -> MessagePosition? {
guard let seq = message.seq else { return nil }
return MessagePosition(at: message.positionAt, seq: seq)
}
/// Swap one row's content in place (the gap-recovery sweep's by-id
/// refresh): merged by id, re-deriving the seq bounds and bumping the
/// messages version like every other messages change.
public static func mergeRefreshedRow(
_ previous: MessageWindowState,
_ row: WindowMessage
) -> MessageWindowState {
settingMessages(previous, MessageMerge.mergeMessages(previous.messages, [row]))
}
public enum PositionEnd: Sendable {
case oldest
case newest
}
public static func derivePosition(
_ messages: [WindowMessage],
_ end: PositionEnd
) -> MessagePosition? {
var selected: MessagePosition?
for message in messages {
guard let candidate = messagePosition(message) else { continue }
guard let current = selected else {
selected = candidate
continue
}
if (end == .oldest && candidate < current) || (end == .newest && candidate > current) {
selected = candidate
}
}
return selected
}
/// Pairwise page cursor (`pagePosition` in the web): both halves or nothing.
public static func pagePosition(at: Int?, seq: Int?) -> MessagePosition? {
guard let at, let seq else { return nil }
return MessagePosition(at: at, seq: seq)
}
private static func maxPosition(_ a: MessagePosition?, _ b: MessagePosition?) -> MessagePosition? {
switch (a, b) {
case (nil, let b): return b
case (let a, nil): return a
case (let a?, let b?): return a >= b ? a : b
}
}
// MARK: - Trims
private struct Trim {
let kept: [WindowMessage]
let dropped: [WindowMessage]
}
private static func sliceForTrim(
_ items: [WindowMessage],
limit: Int,
mode: TrimMode
) -> Trim {
if items.count <= limit { return Trim(kept: items, dropped: []) }
if limit <= 0 { return Trim(kept: [], dropped: items) }
switch mode {
case .prepend:
return Trim(
kept: Array(items[..<limit]),
dropped: Array(items[limit...])
)
case .append:
return Trim(
kept: Array(items[(items.count - limit)...]),
dropped: Array(items[..<(items.count - limit)])
)
}
}
/// Codex background-agent trace rows (`agent-run-*`) get their own trim
/// bucket so long traces do not evict chat (web `isCodexAgentRunMessage`).
public static func isCodexAgentRunMessage(_ message: WindowMessage) -> Bool {
guard let outer = message.content.objectValue,
outer["role"]?.stringValue == "agent",
let payload = outer["content"]?.objectValue,
payload["type"]?.stringValue == "codex",
let data = payload["data"]?.objectValue
else { return false }
let type = data["type"]?.stringValue
return type == "agent-run-start" || type == "agent-run-update" || type == "agent-run-trace"
}
/// Web `getReasoningStreamId`: the stream a reasoning row belongs to, or
/// `nil` for anything else. Unrecognised shapes read as `nil`, which means
/// "keep it".
private static func reasoningStreamId(_ message: WindowMessage) -> String? {
guard let outer = message.content.objectValue,
outer["role"]?.stringValue == "agent",
let payload = outer["content"]?.objectValue,
payload["type"]?.stringValue == "codex",
let data = payload["data"]?.objectValue,
data["type"]?.stringValue == "reasoning",
let id = data["id"]?.stringValue,
!id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else { return nil }
return id
}
/// Web `dropSupersededReasoningSnapshots`: collapse a reasoning stream to
/// the one snapshot that still says something. The CLI re-sends a growing
/// buffer under a stable stream id every few hundred milliseconds and the
/// timeline folds those rows into a single block, so spending window
/// budget on the older ones is what pushes the surrounding conversation
/// out of reach. Rows with no stream id are left alone.
private static func dropSupersededReasoningSnapshots(
_ messages: [WindowMessage]
) -> [WindowMessage] {
var newestByStream: [String: WindowMessage] = [:]
for message in messages {
guard let streamId = reasoningStreamId(message) else { continue }
guard let incumbent = newestByStream[streamId] else {
newestByStream[streamId] = message
continue
}
// Fall back to arrival order when either row predates seq
// numbering: `messages` is kept in display order, so later still
// means newer.
let newer: Bool
if let challengerAt = messagePosition(message),
let incumbentAt = messagePosition(incumbent) {
newer = !(challengerAt < incumbentAt)
} else {
newer = true
}
if newer { newestByStream[streamId] = message }
}
if newestByStream.isEmpty { return messages }
let survivors = Set(newestByStream.values.map(\.id))
return messages.filter { reasoningStreamId($0) == nil || survivors.contains($0.id) }
}
/// Trim to `regularLimit` while never dropping queued rows: superseded
/// reasoning snapshots are collapsed first, the regular budget shrinks by
/// the queued count, `agent-run-*` rows trim against their own bucket
/// (`agentRunWindowSize`), and queued rows are re-merged afterwards (web
/// `trimPreservingQueued`).
private static func trimPreservingQueued(
_ incoming: [WindowMessage],
regularLimit: Int,
mode: TrimMode
) -> Trim {
let messages = dropSupersededReasoningSnapshots(incoming)
let queued = messages.filter(\.isQueuedForInvocation)
let queuedIds = Set(queued.map(\.id))
let nonQueued = messages.filter { !queuedIds.contains($0.id) }
let agentRuns = nonQueued.filter { isCodexAgentRunMessage($0) }
let regular = nonQueued.filter { !isCodexAgentRunMessage($0) }
let regularTrim = sliceForTrim(regular, limit: max(0, regularLimit - queued.count), mode: mode)
let agentRunTrim = sliceForTrim(
agentRuns,
limit: MessageWindowConstants.agentRunWindowSize,
mode: mode
)
return Trim(
kept: MessageMerge.mergeMessages(regularTrim.kept + agentRunTrim.kept, queued),
dropped: regularTrim.dropped + agentRunTrim.dropped
)
}
// MARK: - Retention
/// Web `shouldRetainWindowMessage`: queued, or renderable by the chat
/// pipeline.
public static func shouldRetainWindowMessage(_ message: WindowMessage) -> Bool {
message.isQueuedForInvocation || MessageRetention.isRenderable(message.content)
}
/// How many of `incoming` would add a NEW renderable row (not already
/// represented by id or localId) — feeds the `applied` older-load outcome.
public static func countNewRenderableMessages(
_ previous: MessageWindowState,
incoming: [WindowMessage]
) -> Int {
var representedIds = Set(previous.messages.map(\.id))
var representedLocalIds = Set(previous.messages.compactMap(\.localId))
var count = 0
for message in incoming {
guard shouldRetainWindowMessage(message) else { continue }
if representedIds.contains(message.id) { continue }
if let localId = message.localId, representedLocalIds.contains(localId) { continue }
count += 1
representedIds.insert(message.id)
if let localId = message.localId { representedLocalIds.insert(localId) }
}
return count
}
// MARK: - Merge
/// Merge `incoming` into the window, trim per mode/limit, and repair
/// cursors/flags on overflow (web `mergeIntoWindow`): an append-side trim
/// flips `hasMore` and recomputes the older cursor from the oldest kept
/// row; a prepend-side trim drops tail rows, so the window no longer
/// reaches the live bottom — flag `requiresLatestReset` and pull the
/// newest cursor back to the newest kept row.
public static func mergeIntoWindow(
_ previous: MessageWindowState,
incoming: [WindowMessage],
mode: TrimMode? = nil,
regularLimit: Int? = nil,
advanceTailRevision: Bool = false
) -> MessageWindowState {
let retainedIncoming = incoming.filter { shouldRetainWindowMessage($0) }
if retainedIncoming.isEmpty {
return previous
}
let effectiveMode = mode
?? (previous.viewMode == .history ? .prepend : .append)
let effectiveLimit = regularLimit
?? (previous.viewMode == .history
? previous.historyRetentionLimit
: MessageWindowConstants.visibleWindowSize)
let merged = MessageMerge.mergeMessages(previous.messages, retainedIncoming)
let trim = trimPreservingQueued(merged, regularLimit: effectiveLimit, mode: effectiveMode)
var next = settingMessages(previous, trim.kept)
if advanceTailRevision {
next.tailRevision = previous.tailRevision + 1
}
if trim.dropped.isEmpty {
return next
}
if effectiveMode == .append {
let oldest = derivePosition(trim.kept, .oldest)
next.hasMore = true
next.oldestPosition = oldest ?? next.oldestPosition
return next
}
next.requiresLatestReset = true
next.newestPosition = derivePosition(trim.kept, .newest)
return next
}
// MARK: - Latest replace
/// Apply a `latest` page (cold start, activation refresh, or a reset
/// response). With `replaceServerRows` the page is authoritative: every
/// server row captured in `requestBaseline` (by **instance identity**) is
/// discarded, while optimistic rows and rows that changed since the
/// request left (concurrent SSE) survive the swap (web
/// `applyLatestResponse`).
public static func applyLatestResponse(
_ previous: MessageWindowState,
responseMessages: [WindowMessage],
page: MessagesPage,
replaceServerRows: Bool,
requestBaseline: [String: WindowMessage],
trimLimit: Int = MessageWindowConstants.visibleWindowSize
) -> MessageWindowState {
let retainedResponseMessages = responseMessages.filter { shouldRetainWindowMessage($0) }
let concurrentServerRows = previous.messages.filter { message in
!message.isOptimistic && requestBaseline[message.id] !== message
}
let preserved = replaceServerRows
? previous.messages.filter { message in
message.isOptimistic || requestBaseline[message.id] !== message
}
: previous.messages
let authoritative = MessageMerge.mergeMessages(preserved, retainedResponseMessages)
let incoming = MessageMerge.mergeMessages(authoritative, concurrentServerRows)
let trim = trimPreservingQueued(
incoming,
regularLimit: trimLimit,
mode: .append
)
let snapshotHead = pagePosition(at: page.snapshotHeadAt, seq: page.snapshotHeadSeq)
?? derivePosition(responseMessages, .newest)
let newestKept = derivePosition(trim.kept, .newest)
let newest = maxPosition(snapshotHead, newestKept)
let responseOldest = pagePosition(at: page.nextBeforeAt, seq: page.nextBeforeSeq)
let oldest: MessagePosition?
if !trim.dropped.isEmpty {
oldest = derivePosition(trim.kept, .oldest)
} else if replaceServerRows {
oldest = responseOldest
} else if responseOldest == nil {
oldest = previous.oldestPosition
} else if previous.oldestPosition == nil {
oldest = responseOldest
} else {
// An upsert keeps rows older than the response page, so the
// older-paging cursor must stay on whichever side is older
// instead of jumping to the response page's own bound.
oldest = responseOldest! <= previous.oldestPosition! ? responseOldest : previous.oldestPosition
}
var next = settingMessages(previous, trim.kept)
next.readThroughRevision = max(previous.readThroughRevision ?? 0, page.readThroughRevision ?? 0, trim.kept.compactMap(\.contentRevision).max() ?? 0)
next.hasMore = page.hasMore || (!replaceServerRows && previous.hasMore) || !trim.dropped.isEmpty
next.epoch = page.epoch
next.oldestPosition = oldest
next.newestPosition = newest
next.tailRevision = previous.tailRevision + 1
next.requiresLatestReset = false
next.isLoadingMore = replaceServerRows ? false : previous.isLoadingMore
next.olderGeneration = replaceServerRows ? previous.olderGeneration + 1 : previous.olderGeneration
next.warning = nil
return next
}
// MARK: - Tail sync
/// Web `beginTailSync`: claim a new sync generation. The older generation
/// bumps too — an older-page response captured before this point must not
/// commit while the tail request is in flight, or a reset can mistake it
/// for concurrent SSE.
public static func beginTailSync(_ previous: MessageWindowState) -> MessageWindowState {
var next = previous
next.syncGeneration = previous.syncGeneration + 1
next.olderGeneration = previous.olderGeneration + 1
next.isSyncingTail = true
next.isLoadingMore = false
next.warning = nil
return next
}
public static func finishTailSync(
_ previous: MessageWindowState,
generation: Int,
warning: String?
) -> MessageWindowState {
guard previous.syncGeneration == generation else { return previous }
var next = previous
next.isSyncingTail = false
next.warning = warning
return next
}
/// Loop body of the after-cursor catch-up (web `runTailSync` inner
/// updater): merge the page, adopt its epoch, and advance the newest
/// cursor to `max(current, nextAfter)` — unless a prepend-side trim just
/// flagged a latest reset, in which case the cursor stays pulled back.
public static func applyAfterPage(
_ previous: MessageWindowState,
responseMessages: [WindowMessage],
page: MessagesPage,
nextAfter: MessagePosition?
) -> MessageWindowState {
var merged = mergeIntoWindow(previous, incoming: responseMessages, advanceTailRevision: true)
if merged.requiresLatestReset {
merged.epoch = page.epoch
merged.warning = nil
return merged
}
merged.epoch = page.epoch
merged.readThroughRevision = max(merged.readThroughRevision ?? 0, page.readThroughRevision ?? 0, merged.messages.compactMap(\.contentRevision).max() ?? 0)
merged.newestPosition = maxPosition(nextAfter, merged.newestPosition)
merged.warning = nil
return merged
}
// MARK: - View mode
/// Re-enter tail mode (web `enterTailMode`): trim to the visible window;
/// when a history overflow flagged `requiresLatestReset`, drop epoch and
/// newest cursor so the next tail sync fetches a fresh latest page.
/// The flag itself is deliberately NOT cleared here (web quirk, pinned) —
/// `applyLatestResponse` clears it when the fresh page lands.
public static func enterTailMode(_ previous: MessageWindowState) -> MessageWindowState {
let trim = trimPreservingQueued(
previous.messages,
regularLimit: MessageWindowConstants.visibleWindowSize,
mode: .append
)
let forceLatest = previous.requiresLatestReset
let oldest = !trim.dropped.isEmpty
? derivePosition(trim.kept, .oldest)
: previous.oldestPosition
var next = settingMessages(previous, trim.kept)
next.hasMore = previous.hasMore || !trim.dropped.isEmpty
next.viewMode = .tail
next.epoch = forceLatest ? nil : previous.epoch
next.oldestPosition = oldest
next.newestPosition = forceLatest ? nil : previous.newestPosition
return next
}
public static func setViewMode(
_ previous: MessageWindowState,
mode: MessageViewMode
) -> MessageWindowState {
if previous.viewMode == mode { return previous }
if mode == .history {
var next = previous
next.viewMode = .history
return next
}
return enterTailMode(previous)
}
public struct Activation {
public let state: MessageWindowState
public let requestedLatest: Bool
}
/// Session (re-)activation (web `activateMessageWindow`): trim back to
/// the visible window, and when a usable persisted cursor exists, flag
/// `preferLatestOnActivation` — another client may have advanced the
/// session by many pages, so the next tail sync fetches the current tail
/// first and reconciles it through the reset-preservation path.
public static func activate(_ previous: MessageWindowState) -> Activation {
let trim = trimPreservingQueued(
previous.messages,
regularLimit: MessageWindowConstants.visibleWindowSize,
mode: .append
)
let forceLatest = previous.requiresLatestReset
let hasUsableCursor = previous.newestPosition != nil && previous.epoch != nil && !forceLatest
let preferLatestOnActivation = hasUsableCursor && !trim.kept.isEmpty
let requestedLatest = preferLatestOnActivation && !previous.preferLatestOnActivation
let invalidateRunningSync = requestedLatest && previous.isSyncingTail
func withActivationUpdates(_ state: MessageWindowState) -> MessageWindowState {
guard preferLatestOnActivation else { return state }
var flagged = state
flagged.preferLatestOnActivation = true
if invalidateRunningSync {
flagged.syncGeneration += 1
flagged.olderGeneration += 1
}
return flagged
}
if previous.viewMode == .tail
&& trim.kept.count == previous.messages.count
&& !forceLatest {
let state = preferLatestOnActivation ? withActivationUpdates(previous) : previous
return Activation(state: state, requestedLatest: requestedLatest)
}
let next = enterTailMode(previous)
let state = preferLatestOnActivation ? withActivationUpdates(next) : next
return Activation(state: state, requestedLatest: requestedLatest)
}
// MARK: - Older pages
public enum OlderPrecheck {
case proceed(before: MessagePosition)
case stop(OlderLoadOutcome.StopReason)
}
public static func olderLoadPrecheck(_ state: MessageWindowState) -> OlderPrecheck {
let before = state.oldestPosition
if state.isSyncingTail || state.isLoadingMore {
return .stop(.busy)
}
if !state.hasMore {
return .stop(.exhausted)
}
guard let before else {
return .stop(.unavailable)
}
return .proceed(before: before)
}
public static func beginOlderLoad(
_ previous: MessageWindowState,
generation: Int
) -> MessageWindowState {
var next = previous
next.olderGeneration = generation
next.isLoadingMore = true
next.warning = nil
return next
}
/// An older page answered with a different epoch: every cursor is
/// meaningless. Drop epoch + newest cursor and flag the latest reset;
/// the caller then runs a tail sync and reports `stopped/epoch-reset`.
public static func applyOlderEpochMismatch(
_ previous: MessageWindowState,
generation: Int
) -> MessageWindowState {
guard previous.olderGeneration == generation else { return previous }
var next = previous
next.isLoadingMore = false
next.epoch = nil
next.newestPosition = nil
next.requiresLatestReset = true
return next
}
/// The `onBeforeApply` veto path: invalidate this load, keep the window.
public static func rejectOlderApply(_ previous: MessageWindowState) -> MessageWindowState {
var next = previous
next.olderGeneration = previous.olderGeneration + 1
next.isLoadingMore = false
next.warning = nil
return next
}
public static func applyOlderResponse(
_ previous: MessageWindowState,
responseMessages: [WindowMessage],
page: MessagesPage,
historyVersion: Int
) -> MessageWindowState {
var merged = mergeIntoWindow(
previous,
incoming: responseMessages,
mode: .prepend,
regularLimit: MessageWindowConstants.olderLoadWindowSize
)
merged.hasMore = page.hasMore
merged.epoch = page.epoch
merged.oldestPosition = pagePosition(at: page.nextBeforeAt, seq: page.nextBeforeSeq)
merged.isLoadingMore = false
merged.historyVersion = historyVersion
merged.warning = nil
return merged
}
public static func failOlderLoad(
_ previous: MessageWindowState,
generation: Int,
warning: String
) -> MessageWindowState {
guard previous.olderGeneration == generation else { return previous }
var next = previous
next.isLoadingMore = false
next.warning = warning
return next
}
public static func cancelOlderLoad(_ previous: MessageWindowState) -> MessageWindowState {
guard previous.isLoadingMore else { return previous }
var next = previous
next.olderGeneration = previous.olderGeneration + 1
next.isLoadingMore = false
next.warning = nil
return next
}
// MARK: - Live rows
/// SSE `message-received` ingest (web `ingestIncomingMessages`): merge,
/// then — when an epoch is cached and no reset is pending — advance the
/// newest cursor past the incoming rows' positions, **including rows the
/// pipeline hides**, so a later tail sync does not refetch them.
public static func ingestIncoming(
_ previous: MessageWindowState,
incoming: [WindowMessage]
) -> MessageWindowState {
if incoming.isEmpty { return previous }
var merged = mergeIntoWindow(previous, incoming: incoming, advanceTailRevision: true)
if merged.epoch == nil || merged.requiresLatestReset {
return merged
}
if let revision = merged.readThroughRevision {
merged.readThroughRevision = max(revision, incoming.compactMap(\.contentRevision).max() ?? 0)
}
let incomingNewest = derivePosition(incoming, .newest)
let currentNewest = merged.newestPosition
if let incomingNewest, currentNewest == nil || incomingNewest > currentNewest! {
merged.newestPosition = incomingNewest
}
return merged
}
/// Optimistic append (web `appendOptimisticMessage`): never advances the
/// newest cursor.
public static func appendOptimistic(
_ previous: MessageWindowState,
message: WindowMessage
) -> MessageWindowState {
mergeIntoWindow(
previous,
incoming: [message],
mode: previous.viewMode == .history ? .prepend : .append,
advanceTailRevision: true
)
}
public static func updateStatus(
_ previous: MessageWindowState,
localId: String,
status: MessageStatus
) -> MessageWindowState {
if localId.isEmpty { return previous }
var changed = false
let messages = previous.messages.map { message -> WindowMessage in
if message.localId != localId || message.status == status {
return message
}
changed = true
return message.withStatus(status)
}
return changed ? settingMessages(previous, messages) : previous
}
public static func markIndeterminate(
_ previous: MessageWindowState,
localIds: [String]
) -> MessageWindowState {
if localIds.isEmpty { return previous }
let idSet = Set(localIds)
var changed = false
let messages = previous.messages.map { message -> WindowMessage in
guard let localId = message.localId, idSet.contains(localId), message.status != .indeterminate else {
return message
}
changed = true
return message.withStatus(.indeterminate)
}
return changed ? settingMessages(previous, messages) : previous
}
public static func markRequeued(
_ previous: MessageWindowState,
localIds: [String]
) -> MessageWindowState {
if localIds.isEmpty { return previous }
let idSet = Set(localIds)
var changed = false
let messages = previous.messages.map { message -> WindowMessage in
guard let localId = message.localId, idSet.contains(localId), message.status == .indeterminate else {
return message
}
changed = true
return message.withStatus(.queued)
}
return changed ? settingMessages(previous, messages) : previous
}
/// `message-cancelled` / optimistic DELETE removal: matches localId OR
/// id; idempotent.
public static func removeByLocalIdOrId(
_ previous: MessageWindowState,
localId: String
) -> MessageWindowState {
if localId.isEmpty { return previous }
let messages = previous.messages.filter { $0.localId != localId && $0.id != localId }
return messages.count == previous.messages.count
? previous
: settingMessages(previous, messages)
}
/// SSE `messages-consumed` (web `markMessagesConsumed`): stamp
/// `invokedAt` and flip status to `sent` on matching rows — including
/// server rows without a client status (web quirk, pinned) — skip
/// `failed`, then re-sort: the row moves from its enqueue position to its
/// invocation position. Never advances the newest cursor.
public static func markConsumed(
_ previous: MessageWindowState,
localIds: [String],
invokedAt: Int
) -> MessageWindowState {
if localIds.isEmpty { return previous }
let idSet = Set(localIds)
var changed = false
let updated = previous.messages.map { message -> WindowMessage in
guard let localId = message.localId, idSet.contains(localId), message.status != .failed else {
return message
}
let needsStatus = message.status != .sent
let needsInvokedAt = message.hasExplicitNullInvokedAt
if !needsStatus && !needsInvokedAt { return message }
changed = true
var next = message
if needsStatus { next = next.withStatus(.sent) }
if needsInvokedAt { next = next.withInvokedAt(invokedAt) }
return next
}
if !changed { return previous }
var next = settingMessages(previous, MessageMerge.mergeMessages([], updated))
next.tailRevision = previous.tailRevision + 1
return next
}
// MARK: - Queued reconciliation
/// Web `isQueuedReconcileCandidate`.
private static func isQueuedReconcileCandidate(_ message: WindowMessage) -> Bool {
guard message.localId != nil, message.isQueuedForInvocation else { return false }
if !message.isOptimistic { return true }
return message.status == .queued || message.status == .sent
}
/// Candidate localIds for the queued-state round trip, in window order.
public static func queuedReconcileCandidateLocalIds(_ state: MessageWindowState) -> [String] {
var seen = Set<String>()
var localIds: [String] = []
for message in state.messages where isQueuedReconcileCandidate(message) {
let localId = message.localId!
if seen.insert(localId).inserted {
localIds.append(localId)
}
}
return localIds
}
/// Apply the queued-state verdict (web `reconcileQueuedLocalIds`): drop
/// candidates that are in neither the still-queued list nor (post
/// `markConsumed`) invoked — they were deleted server-side.
public static func reconcileQueuedLocalIds(
_ previous: MessageWindowState,
candidateLocalIds: [String],
queuedLocalIds: [String]
) -> MessageWindowState {
if candidateLocalIds.isEmpty { return previous }
let candidates = Set(candidateLocalIds)
let queued = Set(queuedLocalIds)
let messages = previous.messages.filter { message in
guard let localId = message.localId, candidates.contains(localId) else { return true }
return queued.contains(localId) || !isQueuedReconcileCandidate(message)
}
return messages.count == previous.messages.count
? previous
: settingMessages(previous, messages)
}
// MARK: - Persistence
/// Web `shouldPersistState`.
public static func shouldPersist(_ state: MessageWindowState) -> Bool {
!state.messages.isEmpty
|| state.hasMore
|| state.epoch != nil
|| state.oldestPosition != nil
|| state.newestPosition != nil
}
public static func toPersisted(_ state: MessageWindowState) -> PersistedMessageWindow {
PersistedMessageWindow(
messages: state.messages,
hasMore: state.hasMore,
oldestPositionAt: state.oldestPosition?.at,
oldestPositionSeq: state.oldestPosition?.seq,
newestPositionAt: state.newestPosition?.at,
newestPositionSeq: state.newestPosition?.seq,
epoch: state.epoch
)
}
/// Rebuild a state from a persisted snapshot (web `hydrateState`):
/// interrupted `sending` rows restore to `queued`/`sent`, and a snapshot
/// with rows but no usable cursor/epoch starts flagged for a latest
/// reset.
public static func hydrate(
sessionId: String,
persisted: PersistedMessageWindow
) -> MessageWindowState {
let restored = persisted.messages.map { message -> WindowMessage in
guard message.status == .sending else { return message }
return message.withStatus(message.hasExplicitNullInvokedAt ? .queued : .sent)
}
let oldest = pagePosition(at: persisted.oldestPositionAt, seq: persisted.oldestPositionSeq)
let newest = pagePosition(at: persisted.newestPositionAt, seq: persisted.newestPositionSeq)
let epoch = persisted.epoch.flatMap { $0 >= 0 ? $0 : nil }
var next = settingMessages(
createState(sessionId: sessionId),
MessageMerge.mergeMessages([], restored)
)
next.hasMore = persisted.hasMore
next.oldestPosition = oldest
next.newestPosition = newest
next.epoch = epoch
next.requiresLatestReset = !persisted.messages.isEmpty && (newest == nil || epoch == nil)
return next
}
// MARK: - Seed
/// Seed a fresh window from another session's (web
/// `seedMessageWindowFromSession`) — resume/reopen may hand back a
/// different session id; the old rows render instantly while
/// `requiresLatestReset` forces a fresh latest page underneath. Cursor
/// epoch and newest position are NOT carried over.
public static func seededState(
source: MessageWindowState,
target: MessageWindowState
) -> MessageWindowState {
var next = settingMessages(createState(sessionId: target.sessionId), source.messages.map { message in
WindowMessage(id: message.id, seq: message.seq, localId: message.localId, content: message.content,
createdAt: message.createdAt, invokedAt: message.invokedAt,
scheduledAt: message.scheduledAt, status: message.status)
})
next.hasMore = source.hasMore
next.tailRevision = source.tailRevision
next.oldestPosition = source.oldestPosition
next.requiresLatestReset = true
next.syncGeneration = target.syncGeneration + 1
next.olderGeneration = target.olderGeneration + 1
return next
}
}