Repository navigation
Event Sync
🌐 English · 简体中文
This page explains how Trizano propagates state changes from a Node's Session actor through the Hub's single aggregated stream to the web and Android clients, including incremental merging, delta batching, lazy timeline loading, and scoped resyncs. It is aimed at developers reading or modifying the synchronization pipeline.
Synchronization state is partitioned into three scopes: each Session protects timeline continuity with a monotonic rev, each Node maintains a host-local {boot, seq} replay window, and the Hub's replay window holds only Entry-level events without buffering or re-ordering Node events.
| Tier | Single owner | Sequence / cursor | Replay window | Events covered |
|---|---|---|---|---|
| Session timeline | Session actor goroutine (server/node/session/session.go) |
Per-session monotonic rev (persisted in Session.rev) |
No in-memory window; gaps resync via GetSessionView
|
ItemsChanged, ItemDelta
|
| Node event stream | Node eventlog.Log (server/node/node.go) |
{boot, seq} (in-process node_seq) |
16 MiB or 1 hour | Workspaces, Sessions, timelines, tasks, terminals, browser tabs, review, rate limits, settings, agent catalogs, Roster changes |
| Entry event stream | Hub eventlog.Log (server/hub/hub.go) |
{boot, seq} |
4 MiB or 1 hour |
NodeChanged, NodeRemoved, PairingsChanged, NodeEnrollmentsChanged, RosterChanged
|
-
Session actor and
rev: Every Session on a Node is owned exclusively by oneSession.run()goroutine. Callers send closures viado(which loads the timeline if sleeping) orlook(lightweight metadata reads). Every itemupsertor streaming flush incrementss.data.Revby exactly 1 and emits anItemsChangedorItemDeltacarrying thatrev(defined inproto/trizano/node/v1/event.proto). -
Node
bootand replay window:server/internal/eventlog/log.gogenerates a randomboottoken viarand.Text()on log creation and seedsseqfrom the process start timestamp in microseconds (time.Now().UnixMicro()). Subscribers pass{since, boot};Sub.Resumedistruewith pending events populated inBacklogonly ifbootmatches and all events aftersinceremain in the window. Otherwise the log setsResumed = falseand subscribes from the currentHead. Each subscriber channel buffers 1024 events; a slow consumer that overflows terminates withErrOverflow, forcing reconnect from its last applied cursor. -
Hub buffers Entry events only: The
eventlog.Logcreated inserver/hub/hub.go(4 MiB / 1 hour) records only Node state/removal, device pairings, Node enrollments, and Roster changes. Node events bypass the Hub buffer—when forwarded, the outerhubv1.Event.seqis always0while the inner Node event keeps its ownseq. As a result, when a Hub restarts or a client fails over to another Entry, every Node stream resumes cleanly as long as the Node itself did not restart and remains within its replay window.
A client holds a single long-lived trizano.hub.v1.EventService/Watch stream carrying its Entry cursor and a map of per-Node {boot, seq} cursors. Inside that stream, the Hub opens one Node Watch per online Node and multiplexes all events back to the client.
eventService.Watch in server/hub/events.go runs the following lifecycle:
- Subscribes to the Hub's own
eventlog.Logwithreq.Entry, immediately sends the EntryHello{resumed, boot}(seqis the resume point or currentHead), and flushes any Entry backlog in order. - Creates a
followersmanager scoped to thisWatchstream and seeds its per-Node cursor map fromreq.Nodes. For every Node already online—and whenever an Entry event later reportsNODE_STATE_ONLINE—it spawns afollowergoroutine callingtrizano.node.v1.EventService/Watch{since, boot}. - Wraps every Node event (including the Node's initial
Hello) inNodeEvent{node, event}on the outer stream. Eachfolloweradvances only its own cursor; ordering is strictly preserved within a Node, with no global ordering across Nodes. - If a Node stream ends unexpectedly while the Node is still online, the
followerreconnects automatically—immediately if the previous stream had already received the Node'sHello, or with 1 s to 30 s exponential backoff otherwise. When a Node goes offline, thefollowerexits and returns its latest cursor tofollowers.cursorsso it can resume once the Node comes back. OnNodeRemoved, thefolloweris canceled and its cursor is deleted. - While idle, the Hub emits a
Heartbeatevery 10 seconds (seq = 0, neither buffered nor cursor-advancing). Clients treat 25 seconds without any event (STALL_TIMEOUT_MS = 25_000on web; 25-second OkHttp streaming read timeout on Android) as a dead stream and reconnect.
The Hub's Node registry (
server/hub/nodes/node.go) also opens a separate internalWatchstarting from head on each online Node to monitor liveness and trigger deferred build replacements when the last active Turn finishes. That internal stream is never forwarded to clients (see Node Internals).
sequenceDiagram
participant C as Client
participant H as Hub
participant NA as Node A
participant NB as Node B
C->>H: Watch(entry={bootH, seqH}, nodes={A: cA, B: cB})
H-->>C: Hello(resumed, bootH) + Entry backlog
par Hub opens one follower stream per online Node
H->>NA: Watch(since=cA.seq, boot=cA.boot)
NA-->>H: Hello(resumed=true, bootA) + Backlog
H-->>C: NodeEvent(A, Hello) + live events
and
H->>NB: Watch(since=cB.seq, boot=cB.boot)
NB-->>H: Hello(resumed=false, bootB')
H-->>C: NodeEvent(B, Hello(resumed=false))
C->>H: Resync Node B metadata and visible timelines
end
Note over C,H: A Session rev gap triggers GetSessionView for that Session only
Each tier recovers independently so a missed cursor or transient error on one Node or Session never stalls the rest of the stream:
-
Level 1: Entry Resync
-
Trigger: Entry
Helloarrives withresumed == false(first connect, Hub restart with a newboot, or offline longer than the Hub's 1 hour / 4 MiB window). -
Action: Concurrently fetches
ListNodes,ListPairings, andListNodeEnrollments, updates Entry state, and prunes any removed Nodes from localnodeCursors. Individual Node data is not fetched here; each Node's subsequentHellodecides whether that Node needs a resync. -
Web-only behavior: If the Entry
bootchanged from the previous value, web callscheckWebBuild()(web/src/lib/webBuild.ts) to check whether static web assets were updated on the server.
-
Trigger: Entry
-
Level 2: Node Resync
-
Trigger:
NodeEvent(Hello)arrives for a Node withresumed == false, or that Node failed a previous resync and remains in thebehindset. - Action: Concurrently refetches metadata for that Node only (agent catalog, Workspaces, Session list, tasks, rate limits; web also fetches terminals, browser tabs, Node settings, project scripts, and review state).
-
Timeline handling: Web only refetches timelines currently mounted in the UI (tracked via
showTimelinereference counts) and drops cached timelines for hidden Sessions so they reload on demand when reopened. Android refetches Sessions currently present intimelines. If a Node resync fails, that Node stays inbehindwhile all other Nodes continue receiving events normally; the nextHellofrom that Node retries the resync. -
Catch-up on clean resume: Even when
resumed == trueand the Node is not inbehind, web callsloadMissing(nodeId)to retry any visible timelines or review states that previously failed to load; Android incrementsNodeData.hellosso active screens can fill in missing data.
-
Trigger:
-
Level 3: Session Resync
-
Trigger: When applying
ItemsChangedorItemDelta, the client compares localtimeline.revagainstev.rev:-
ev.rev <= timeline.rev: stale (already included in snapshot), ignored. -
ev.rev == timeline.rev + 1: applied normally, advancingrevtoev.rev. -
ev.rev > timeline.rev + 1: gap detected; triggersGetSessionViewfor that Session only without blocking events for other Sessions.
-
-
In-flight protection (
web/src/state/sync.ts): At most oneGetSessionViewrequest is in flight per Session (tracked in thefetchingmap). AnyItemsChanged/ItemDeltaarriving while the fetch is running is buffered inflight.missedand replayed in order once the snapshot returns. If replay hits another gap, the client retries automatically; more thanMAX_GAP_RETRIES = 3consecutive gaps surfaces an error asking the user to retry.
-
Trigger: When applying
Streaming output and long Sessions dominate sync overhead. Nodes and clients bound CPU, bandwidth, and memory with batching and lazy loading.
-
Node-side 50 ms batching (
server/node/session/session.go): Agents often emit a few characters at a time. Instead of bumpingrevon every chunk,Session.delta()accumulates text per item ins.streamedand arms astreamWindow = 50mstimer. When the timer fires—or earlier upon any external command (cmds), non-driver.Deltaevent, agent exit, or Session close—flushStreamed()appends the buffered text to the in-memory item (markedunsaved, avoiding per-chunk SQLite writes), incrementss.data.Rev, and emits oneItemDeltaper item. BecauseView()always flushes first, snapshots and subsequent stream events always agree onrev. -
Web per-task render coalescing (
web/src/state/store.ts):oncePerTask()wraps the zustand store with aMessageChannel. When dozens of events arrive in a burst, React subscribers re-render at most once per event-loop task, while non-UI listeners subscribed directly to the raw store (such as the notification coordinator) still observe every update immediately.
-
Node in-memory lazy load and eviction (
server/node/session/session.go): At startup, a Node loads only Session metadata rows; timelines stay in SQLite (itemsandindexremainnil). Listing, pinning, archiving, and renaming go throughlookwithout touching disk; operations that need timeline items go throughdo, which callswake(). When no agent process is attached, a Session idles fortimelineIdle = 5minutes beforesleep()flushesunsaveditems and frees timeline memory. When an agent process is alive but idle (State != RUNNINGand no background tasks),agentIdle = 30minutes closes the agent process and puts the timeline to sleep. -
Client tail loading: Both web (
web/src/state/sync.ts) and Android (android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt) passlastTurns = 2(TAIL_TURNS = 2) when first opening a Session.Session.View()truncates earlier Turns and returnsearlier_turns(omitted Turn count) plusearlier_changes(aggregated file changes from omitted Turns so the web composer can display file-change totals without loading full history). -
Expanding full history on demand: Clicking the "show earlier N turns" button at the top of the timeline—or opening timeline search (
SessionView.tsx) or the context breakdown (ContextPopover.tsx) on web—fetches withlastTurns = 0. On web, if a full-history request arrives while a tail fetch is still in flight, it setsflight.upgrade = truerather than issuing a duplicate request, immediately following up with the full fetch when the tail fetch completes. -
Filtering late events from unloaded Turns: In
applyItems(web/src/state/timeline.tsand AndroidTimeline.kt), whenearlier > 0and an incoming item does not exist locally and has acreate_timeolder than the first loaded item (typically a late update from an earlier Turn's subagent), the client drops it so it is never mis-inserted at the bottom of the timeline.
Web and Android maintain parallel, structurally equivalent synchronizers with matching state machines and rev-merging rules. Any change to the sync protocol or resync policy must be applied to both.
| Responsibility | Web implementation | Android implementation |
|---|---|---|
| Watch loop, cursor management, three-level resync, timeline fetches | web/src/state/sync.ts |
android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt |
ItemsChanged / ItemDelta rev validation, merging, newerSession check |
web/src/state/timeline.ts |
android/app/src/main/kotlin/top/onemolchuan/code/state/Timeline.kt |
| Global state store and derived views |
web/src/state/store.ts (zustand + oncePerTask) |
android/app/src/main/kotlin/top/onemolchuan/code/state/Store.kt (MutableStateFlow) |
Multi-Entry failover and Hello racing |
Handled by desktop proxy in desktop-go/internal/proxy/upstream.go; browser uses a single Entry |
android/app/src/main/kotlin/top/onemolchuan/code/state/Failover.kt and net/Hub.kt
|
| Unit tests |
web/src/state/sync.test.ts, sync.nodes.test.ts, sync.isolation.test.ts, timeline.test.ts
|
android/app/src/test/kotlin/top/onemolchuan/code/TimelineTest.kt, FailoverTest.kt, HubContractTest.kt
|
Intentional platform-specific differences:
-
Web: Uses
oncePerTaskrender coalescing, buffers in-flight updates infetching.missed, evicts hidden timelines viashowTimelineref-counts, and consumes terminal, managed-browser tab, and review (ReviewChanged) events. -
Android: Ignores
BROWSER_TAB,BROWSER_TAB_REMOVED, andREVIEWevents (Android previews via local port forwarding and does not host the streamed browser or IDE review pane). The stream is driven by the foregroundConnectionService(see Client Internals); on disconnect,FailoverandraceEntriesswitch across Entries automatically while preserving all cursors (see Multi-Entry & Failover).
Whenever you modify proto/trizano/hub/v1/event.proto, proto/trizano/node/v1/event.proto, GetSessionView semantics, or either client's resync rules, update both sets of files above and keep their unit tests in sync.
English
Getting Started
Deployment & Networking
Architecture & Nodes
Agents
Clients & Development
Project & Community
中文文档
新手指引
部署与网络
架构与节点
智能体
客户端与开发
项目与社区