Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 52 additions & 51 deletions Sources/WeiBei/Resources/Editor/editor-entry.js

Large diffs are not rendered by default.

12 changes: 6 additions & 6 deletions Sources/WeiBei/Resources/Editor/editor-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"assets": [
{
"name": "editor-entry.js",
"bytes": 598840,
"sha256": "6c58c364c03bee4f6f5c5ef16032518586f1a8d00bf4beb42b9106e7840522f0"
"bytes": 600656,
"sha256": "fd80d96d3e58e28bbbce60adb8e62ef3a20e9fd7f5bd410bd502f96e2cc5bee6"
},
{
"name": "editor.css",
Expand All @@ -13,8 +13,8 @@
},
{
"name": "index.html",
"bytes": 49020,
"sha256": "28437821549e01b3261c3bfb4322ef47d518484f6c97f1b0a0d97f92d9b54edb"
"bytes": 49158,
"sha256": "c1a77412b4ad72c60aa89e50770ea0aeda7847c0250b3b31fb1cc8fba7b17339"
},
{
"name": "KaTeX_AMS-Regular.ttf",
Expand Down Expand Up @@ -333,8 +333,8 @@
},
{
"name": "viewer-entry.js",
"bytes": 518708,
"sha256": "bacddcf53fea5d5b39c4a85bd73f4c558a0975692a1ae4f5b4c4a8c563f51705"
"bytes": 520523,
"sha256": "605195c83e59cf51b1d5d8941bb9204fcd06403079a63b8fc81a37c3539308d4"
}
]
}
9 changes: 8 additions & 1 deletion Sources/WeiBei/Resources/Editor/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,7 @@
dissolve simultaneously at typical Chinese output rates, bridging the
33ms arrival gaps into a continuous flow. Opacity-only = cheap. */
.wb-stream-in {
animation: wb-stream-in 260ms cubic-bezier(0.2, 0.7, 0.3, 1) both;
animation: wb-stream-in 200ms cubic-bezier(0.2, 0.7, 0.3, 1) both;
}

@keyframes wb-stream-in {
Expand All @@ -1287,6 +1287,7 @@
}

.wb-stream-caret {
position: absolute;
display: inline-block;
width: 2px;
height: 1.05em;
Expand All @@ -1296,6 +1297,12 @@
background: currentColor;
opacity: 0.7;
animation: wb-stream-caret-blink 1.06s ease-in-out infinite;
pointer-events: none;
}

.wb-stream-caret.is-finalized {
animation: none;
opacity: 0;
}

@keyframes wb-stream-caret-blink {
Expand Down
91 changes: 46 additions & 45 deletions Sources/WeiBei/Resources/Editor/viewer-entry.js

Large diffs are not rendered by default.

216 changes: 120 additions & 96 deletions Sources/WeiBei/Stores/AgentStreamingDisplayPump.swift
Original file line number Diff line number Diff line change
@@ -1,128 +1,152 @@
import Foundation

/// Meters accumulated agent streaming text onto the display surface at an
/// even, typewriter-like cadence.
///
/// The real text keeps accumulating in the store (`latestAgentStreamingText`);
/// only the display prefix published through `agentStreaming.text` is paced
/// here, so network burstiness never reaches the chat surface while
/// persistence, completion, and interruption keep reading the full text.
/// The only content pacer for an Agent reply. The store owns the complete
/// answer; this queue owns only the not-yet-visible characters.
@MainActor
final class AgentStreamingDisplayPump {
/// Tick interval; matches the historical 33 ms streaming publish gate (~30 Hz).
static let bufferNanoseconds: UInt64 = 80_000_000
static let tickNanoseconds: UInt64 = 33_000_000
/// Lag (in characters) that adds one extra character per tick of pace, so
/// the rate ramps continuously with backlog instead of jumping between
/// integer step sizes.
static let rampLagCharacters: Double = 10.0
/// Hard ceiling on characters per tick so huge backlogs drain as a fast
/// but readable rush instead of an instant dump.
static let maximumCharsPerTick = 12
static let charactersPerTick = 4
static let catchUpCharactersPerTick = 6
static let catchUpBacklogThreshold = 120
static let normalBacklogThreshold = 40

struct Hooks {
let targetText: @MainActor () -> String
let publish: @MainActor (String) -> Void
let canPublish: @MainActor () -> Bool
let append: @MainActor (String) -> Void
let replace: @MainActor (String) -> Void
let didDrain: @MainActor () -> Void
}

private let hooks: Hooks
private var task: Task<Void, Never>?
/// Prefix of the target published so far in this run. Only advances while
/// the target keeps it as a prefix; anomalies snap straight to full text.
private var displayedPrefix = ""
/// Fractional pacing credit carried between ticks so non-integer rates
/// (e.g. 1.5 characters per tick) render as an even character flow.
/// Clamped to ≤1 after each emit so stale credit cannot burst later.
private var pacingCredit = 0.0
private var receivedText = ""
private var pending: [Character] = []
private var pendingOffset = 0
private var inputFinished = false
private var isCatchingUp = false

init(hooks: Hooks) {
self.hooks = hooks
}

var isRunning: Bool { task != nil }
var pendingCharacterCount: Int { pending.count - pendingOffset }

/// Idempotent. Steps once immediately so the first character keeps its
/// historical published-on-arrival latency, then keeps ticking on
/// absolute deadlines so MainActor congestion cannot accumulate drift.
func start() {
guard task == nil else { return }
stepOnce()
task = Task { @MainActor [weak self] in
var nextTick = DispatchTime.now().uptimeNanoseconds &+ Self.tickNanoseconds
while !Task.isCancelled {
guard let self else { return }
self.stepOnce()
let now = DispatchTime.now().uptimeNanoseconds
if nextTick <= now {
nextTick = now &+ Self.tickNanoseconds
} else {
try? await Task.sleep(nanoseconds: nextTick - now)
}
nextTick &+= Self.tickNanoseconds
}
/// Accepts the cumulative model snapshot once per progress event and adds
/// only its new suffix to the display queue.
func enqueue(cumulativeText: String) {
guard cumulativeText != receivedText else { return }
guard cumulativeText.hasPrefix(receivedText) else {
// A provider rewrite is not an append stream. Land its authoritative
// snapshot once instead of mixing two incompatible queues.
receivedText = cumulativeText
pending.removeAll(keepingCapacity: true)
pendingOffset = 0
isCatchingUp = false
task?.cancel()
task = nil
hooks.replace(cumulativeText)
if inputFinished { hooks.didDrain() }
return
}

pending.append(contentsOf: cumulativeText.dropFirst(receivedText.count))
receivedText = cumulativeText
scheduleAfterBufferIfNeeded()
}

/// Marks data completion without waiting for the visual queue.
func finish(cumulativeText: String) {
enqueue(cumulativeText: cumulativeText)
inputFinished = true
if pendingCharacterCount == 0 {
task?.cancel()
task = nil
hooks.didDrain()
}
}

/// Reduced-motion mode keeps the same streaming document but skips content
/// pacing. It does not mark model input complete.
func replaceImmediately(cumulativeText: String) {
task?.cancel()
task = nil
receivedText = cumulativeText
pending.removeAll(keepingCapacity: true)
pendingOffset = 0
isCatchingUp = false
hooks.replace(cumulativeText)
if inputFinished { hooks.didDrain() }
}

/// Stopped/new-question paths land the complete text immediately and
/// retire this visual run.
func settleImmediately(cumulativeText: String) {
task?.cancel()
task = nil
receivedText = cumulativeText
pending.removeAll(keepingCapacity: true)
pendingOffset = 0
inputFinished = true
isCatchingUp = false
hooks.replace(cumulativeText)
hooks.didDrain()
}

/// Cancels the loop and forgets the current run. Callers own the rest of
/// the streaming-state cleanup around the request lifecycle.
func stopAndReset() {
task?.cancel()
task = nil
displayedPrefix = ""
pacingCredit = 0
receivedText = ""
pending.removeAll(keepingCapacity: true)
pendingOffset = 0
inputFinished = false
isCatchingUp = false
}

/// Publishes straight to the current target so a completion flip never
/// swaps "half-typed prefix" for the full text mid-surface. Call this on
/// the completion path right before the message leaves `.generating`.
func drainNow() {
guard hooks.canPublish() else { return }
let target = hooks.targetText()
guard target.hasPrefix(displayedPrefix) else {
// Non-append anomaly (rewrite or stale run): snap like stepOnce.
displayedPrefix = target
pacingCredit = 0
hooks.publish(target)
return
/// Consumes one normal or gentle-catch-up batch. Exposed for tests.
func stepOnce() {
guard pendingCharacterCount > 0 else { return }
if isCatchingUp {
if pendingCharacterCount < Self.normalBacklogThreshold {
isCatchingUp = false
}
} else if pendingCharacterCount > Self.catchUpBacklogThreshold {
isCatchingUp = true
}
guard target != displayedPrefix else { return }
displayedPrefix = target
pacingCredit = 0
hooks.publish(target)
let step = isCatchingUp
? Self.catchUpCharactersPerTick
: Self.charactersPerTick
let end = min(pending.count, pendingOffset + step)
hooks.append(String(pending[pendingOffset..<end]))
pendingOffset = end
guard pendingOffset == pending.count else { return }
pending.removeAll(keepingCapacity: true)
pendingOffset = 0
task?.cancel()
task = nil
if inputFinished { hooks.didDrain() }
}

/// Advances the display prefix by one tick. Exposed for deterministic tests.
func stepOnce() {
let target = hooks.targetText()
guard !target.isEmpty else { return }
// Hidden chat: no UI work; once shown again the deficit path catches up.
guard hooks.canPublish() else { return }
guard target.hasPrefix(displayedPrefix) else {
// Non-append anomaly (rewrite or stale run): never stall on it.
displayedPrefix = target
pacingCredit = 0
hooks.publish(target)
return
private func scheduleAfterBufferIfNeeded() {
guard pendingCharacterCount > 0, task == nil else { return }
task = Task { @MainActor [weak self] in
do {
try await Task.sleep(nanoseconds: Self.bufferNanoseconds)
} catch {
return
}
while !Task.isCancelled {
guard let self else { return }
self.stepOnce()
if self.pendingCharacterCount == 0 {
return
}
do {
try await Task.sleep(nanoseconds: Self.tickNanoseconds)
} catch {
return
}
}
}
let deficit = target.count - displayedPrefix.count
guard deficit > 0 else { return }
// One character per tick plus a continuous ramp with lag: near target
// this is plain single-character typing; sustained backlog settles at
// a constant fractional rate that the credit renders evenly.
let charsPerTick = min(
Double(Self.maximumCharsPerTick),
1.0 + Double(deficit) / Self.rampLagCharacters
)
pacingCredit += charsPerTick
let step = min(deficit, Int(pacingCredit.rounded(.down)))
pacingCredit -= Double(step)
if pacingCredit > 1 { pacingCredit = 1 }
let newIndex = target.index(
target.startIndex,
offsetBy: displayedPrefix.count + step,
limitedBy: target.endIndex
) ?? target.endIndex
displayedPrefix = String(target[..<newIndex])
hooks.publish(displayedPrefix)
}
}
26 changes: 26 additions & 0 deletions Sources/WeiBei/Stores/AgentStreamingState.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
import Combine
import Foundation

@MainActor
final class AgentStreamingState: ObservableObject {
@Published var text = ""
@Published var activityText: String?
@Published private(set) var displayingMessageID: UUID?
@Published private(set) var displayingChatID: UUID?

func begin(messageID: UUID, chatID: UUID) {
text = ""
displayingMessageID = messageID
displayingChatID = chatID
}

func isDisplaying(_ messageID: UUID) -> Bool {
displayingMessageID == messageID
}

func finishDisplaying() {
displayingMessageID = nil
displayingChatID = nil
activityText = nil
}

func reset() {
text = ""
activityText = nil
displayingMessageID = nil
displayingChatID = nil
}
}
Loading