Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
Channel Block — Reference Notes for the Agent Block
How block-channel / features/channel is wired, as a template for giving block-agent
real state (live updates, send path, scroll, input). All paths relative to apps/web/src
unless absolute. Line numbers are as of commit 254b60f339.
These are historical design notes, not a current implementation inventory.
Section 5 and the scroll recommendation below were refreshed against 17a1dc1848.
The agent now has a live reconciled feed, wired composer, and shared TanStack
ThreadList; the remaining proposed factories/API names below describe the earlier
design exploration and must be checked against current code before reuse.
1. Block entry & composition
features/block-channel/definition.ts defineBlock({ name:'channel', component: NewChannelBlockAdapter })
└─ block-channel/component/NewChannelBlockAdapter.tsx (adapter: tabs, header, persistence, orchestrator)
└─ features/channel/Channel/Channel.tsx (the actual channel surface, "pure-ish")
definition.ts (features/block-channel/definition.ts)
Trivial: load accepts a dss source and returns ok({ id }). liveTrackingEnabled: true.
The agent block's definition.ts is already the same shape.
The adapter layer (NewChannelBlockAdapter.tsx)
Everything "block-shaped" lives here, NOT in Channel.tsx:
| Concern | Where | Mechanism |
|---|---|---|
| Hotkey scope ownership | :194–196 | useHotkeyDOMScope('channel') → blockHotkeyScopeSignal.set(scope) + useBlockEntityCommands(). Channel block doesn't render BlockContainer, so it owns the scope itself (comment at :190). |
| Block id | :201 | useBlockId() — the channel id. |
| Tabs | :242–265, :449–477 | Local createSignal<ChannelTabId> + ChannelTabProvider (Channel/ChannelTabContext.tsx); <Switch> mounts one tab at a time. Switching away from messages clears the Channel handle (setMessagesHandle(undefined)). |
| Header | NewTop :125–187 |
Rendered inside the block via split-layout portals: ChannelTopLeft, SplitHeaderRight + HeaderIsland, ChannelTopBarLiveIndicators. |
| Entry-state persistence | :216–218, :408–427 | splitPanel.handle.registerEntryStateCaptor(CHANNEL_STATE_ENTRY_KEY, () => snapshot) — the split layout calls this captor on history navigation; on mount the adapter reads splitPanel.handle.currentEntryState()?.[key] and hydrates. onCleanup(dispose). Snapshot = { activeTab, messages: ChannelMessagesStateSnapshot }. |
| Orchestrator methods | :354–380 | createMethodRegistration(blockHandle, { goToLocationFromParams, goToLatest }). External navigation (mention click, inbox row) lands here. |
| Handle await | :345–350 | awaitCondition(() => messagesHandle() !== undefined, 10_000) — the Messages tab may not have mounted yet; orchestrator methods wait for the child handle via a signal. |
| Target-message resolution | :308–341 | resolveTargetMessage: cache-first (findTopLevelMessageInChannelMessages, findThreadIdInChannelMessages), falls back to fetchResolvedChannelMessage roundtrip. |
| Initial load gate | Channel.tsx |
The channel's existing TanStack message query feeds <EntityLoadGate> directly, so the content request supplies the loading/access/not-found/gone state without a separate adapter query. Other tabs mount and authorize through their own content queries. |
| Autofocus | :454 | autofocus={canAutofocusSplitContent && !navigatedFromJK()} — split layout + j/k navigation decide, not the component. |
The child-handle pattern (the key adapter↔component contract)
Channel exposes an imperative handle instead of the adapter reaching in:
// Channel.tsx:151–155
export type ChannelHandle = {
goToMessage: (messageId: string, replyId?: string) => void;
goToLatest: () => void;
getMessagesStateSnapshot: () => ChannelMessagesStateSnapshot | undefined;
};
- Channel calls
props.onHandleReady(handle)onceisChannelReady()(query fetched + navigation ready + initial scroll done) — Channel.tsx:694–711. - Adapter stores it in a signal (
setMessagesHandle) soawaitConditioncan wait on it. - Adapter also keeps
lastMessagesStateSnapshotso the captor still answers after the Messages tab unmounts (:257, :412–415).
Props crossing the adapter → Channel boundary (ChannelProps, Channel.tsx:133–142)
channelId, targetMessageId?, targetMessageReplyId?, initialMessagesStateSnapshot?,
onHandleReady?, autofocus?. That's it — everything else the Channel derives itself.
2. Context structure
Consumed (global, cache-backed — Channel does NOT own these)
| Hook | Source | Backing |
|---|---|---|
useChannelName / useChannelType / useChannelActivity |
lib/core/context/channels.ts:68–81 |
ChannelsContextProvider — app-level provider over useListChannelsQuery + useChannelsActivityQuery (whole channel list, memoized byId maps). Per-channel hooks are just memos over it. |
useUserId |
@core/context/user |
app-level |
useChannelParticipants |
features/channel/use-channel-participants.ts |
thin memo over useChannelParticipantsQuery → { users, ids } accessors |
useSplitPanel / useSplitLayout |
@components/app/split-layout |
split-layout contexts (insets, popoverSplit, openWithSplit) |
queryClient |
@queries/client |
module-global TanStack client — all cache surgery goes through it |
Created by Channel itself (component-local providers, Channel.tsx:713–984)
<StaticMarkdownContext> one shared lexical static-markdown editor for all messages
<SearchHighlightTermsProvider value={findBar.getSearchTermsForMessage}>
<foldedMessages.Provider> fold lookup context + Suspense gate (see §4)
<MaybeMessageActionDrawerManager> mobile action drawer
<ChannelDropZone dragState=...> entity/file drop
Rule of thumb the channel follows: identity/list data is global context; everything
interactive is component-local state created by factories. The agent block already uses
StaticMarkdownContext (Block.tsx:17) — correct instinct.
3. The create* factory pattern (the main thing to copy)
Channel.tsx is ~990 lines but owns almost no logic — it is a composition root. Each
factory is a plain function called during setup (component scope, so onCleanup/effects
work), taking accessors + callbacks in and returning accessors + methods out.
Signals are the interface; no factory imports another factory's file — Channel wires them.
| Factory | File | Owns (state) | Takes | Returns | Wired to |
|---|---|---|---|---|---|
createTargetMessageController |
create-target-message-controller.ts:47 |
store {activeTargetMessageId, activeTargetMessageReplyId, loadAroundMessageId, pendingScrollTargetId, pendingTargetReplyId} + flash timer (1s highlight) |
channelId, initial target, messageKeys, navigation, didInitialScroll |
accessors + goToMessage/completePendingScroll/clearActiveTarget/reset |
drives loadAroundMessageId into the messages query; internal effect executes the scroll via navigation() once the key is loaded and initial scroll is done; also swaps the load-around cache back to the default key (restoreDefaultChannelPaginationAfterTargetLoad, :214) |
useChannelMessagesQuery + createMessageIndex |
@queries/channel/channel-messages.ts:146, :807 |
reconciled store {items, keys, byId} |
query data accessor | oldest-first flat index (pages/items arrive newest-first; dedupe + double reverse); reconcile() keeps row identity stable; guards the transient empty-data flash during refetch (:843) |
everything renders from keys/byId |
createFoldedMessagesScope |
create-folded-messages-scope.tsx:40 |
delegates to createFoldedMessages (§4) |
channelId |
{ readyLookup, Provider } — readyLookup never suspends; Provider = <AwaitFold/> (forces Suspense to wait) + context provider |
placeholder rows look up their folded body via context |
createUnifiedInputManager |
unified-input-manager.ts:24 |
replyTarget signal (at most one reply binding channel-wide) |
initialReplyTarget snapshot, onReplyThreadReleased |
replyTarget, bindReply(message), closeReply, getReplyTargetSnapshot |
bottom input face switching (§6); snapshot goes into entry-state |
createThreadManager |
thread-manager.ts:16 |
store of per-thread ThreadState (isExpanded, isReplying, replyInputState/El/Handle, focusRequest), lazily created |
initialSnapshot |
getOrCreateThreadState(threadId), getSnapshot() |
each ThreadList row pulls its state; snapshot → entry-state |
createThreadPaginator |
thread-paginator.ts:41 |
per-direction {pending, is, more} signals |
the infinite query | isPrepending/isShifting/prependPaginate/shiftPaginate/hasMore* |
shift = fetch older (top, virtua shift mode), prepend = fetch newer (bottom); coalesces re-entrant calls via pending do/while loop |
createMessageEditor |
create-message-editor.ts:43 |
editState signal {messageId, message, snapshot} |
channelId, participantIds, patchMessage (mutation.mutate), onEditEnded |
state/start/update/cancel/save — save diffs content+attachments and no-ops when unchanged |
UnifiedEditInput + inline editor + hotkey e |
createMessageSelection |
create-message-selection.ts:16 |
selectedId signal; auto-clears when id leaves keys |
keys accessor |
selectedId/select/clear/selectFirst/selectPrevious/selectNext |
keyboard nav, highlight |
createDeleteMessageConfirmation |
create-delete-message-confirmation.tsx:19 |
pending signal |
deleteMessage fn |
{ requestDelete, ConfirmationDialog } — returns a component; mounted once at Channel root (:715) |
all delete entry points route through it |
createChannelMessageActions |
create-channel-message-actions.ts:92 |
none (pure closure + injectable effects for tests) |
mutations, onReply/onEdit/onCreateTask/onChat callbacks |
(message) => MessageActions — per-message action set with capability gating (canEdit/canDelete/...) |
context menus, hotkeys, mobile drawer |
createChannelFindBar |
create-channel-find-bar.ts:46 |
wraps createFindBarController + search query; active-match memo |
channelId, goToMessage, clearSelection, isMessageLoaded |
FindBarController + getSearchTermsForMessage |
prefetches next result pages, thread replies, and load-around windows ahead of the cursor |
createChannelHotkeys |
create-channel-hotkeys.ts:47 |
two DOM hotkey scopes (message list, input) | selection, navigation, messageById, getMessageActions, isEditing, isInputEmpty, callbacks |
{ messageListScopeId, attachMessageListRef, attachInputRef } — refs attached to DOM in JSX |
arrows/enter/e/backspace/escape/shift+g/cmd+f |
createChannelKeyboardHandler |
create-channel-keyboard-handler.ts:47 |
pending-reveal signal; returns void, pure effect | navigation, isNearBottom, boundMessageId |
— (iOS-only virtual keyboard scroll behavior) | |
createStickyScrollEffect |
sticky-scroll.tsx:29 |
none — one createEffect(on(messages, ...)) |
isNearBottom, hasMoreBelow, messages, scrollToBottom |
void. Scrolls only when a message was appended at the bottom AND user was near the true bottom (no more pages below) | the live-follow behavior |
createActivityTracker |
activity-tracker.ts:20 |
newMessagesDismissed signal; freezes lastViewedAt/openedAt at first read (so the mark-as-viewed mutation can't hide the "new" divider) |
lastViewedAt, userId |
isNewMessage(message), dismissNewMessages |
new-message divider in list meta |
createChannelDragState |
create-channel-drag-state.ts:27 |
plain mutable refs (not signals — never rendered) | channelId |
drop zone + late-bound setters the input handle fills in onReady |
ChannelDropZone |
createInputAttachmentTracker |
Input/attachment-tracker (via Channel.tsx:366) |
attachment list, persisted | persistenceKey |
tracker passed into the input |
Conventions worth imitating:
- Options objects with
Accessor<T>fields; return objects mixing accessors and plain methods. - Late-bound capabilities as signals:
threadListNavigation,threadListScrollState,channelInputHandle,channelInputSnapshotare allcreateSignal<X|undefined>()filled by childonReady/onNavigationReadycallbacks; every factory that needs them takes the accessor and null-checks (navigation()?.scrollToBottom()). - Factories that need cleanup use
onCleanupinternally (target controller's flash timer, keyboard handler's listener) — hence they must be called in component scope. - Factories that render something return a component (
ConfirmationDialog,foldedMessages.Provider). - Snapshot/restore is a first-class concern:
getSnapshot()on any factory whose state should survive split-history navigation, and aninitialSnapshotoption to hydrate.
4. Data layer
Query (lib/queries/channel/channel-messages.ts)
- Infinite query keyed by
channelKeys.messages(channelId, loadAroundMessageId)— the load-around id is part of the key, so navigating to an old message creates a second cache entry (a 50-row window centered on it);restoreDefaultChannelPaginationAfterTargetLoadlater copies that entry over the default key and deletes the variant (create-target-message-controller.ts:214–230). - Bidirectional cursors:
getNextPageParam(older) /getPreviousPageParam(newer).staleTime: Infinity— the cache is maintained by hand (mutations + websocket), never by refetch-on-focus. setChannelMessagesData(channelId, updater)(:194) applies an updater to every cached variant via key prefix — the core cache-surgery primitive. A big family of pureinsert/remove/replace/mark*InChannelMessages(data, ...)helpers (:255–602) all preserve reference equality when nothing changed.createMessageIndex(:807) — see §3 table.
Mutations (lib/queries/channel/message.ts) — the optimistic send flow
useSendMessageMutation (:422):
- onMutate:
registerMessageNonces(optimisticId, ...)(nonce = the optimisticId);queryClient.cancelQueries(prefix);optimisticInsertChannelMessagebuilds a fakeApiChannelMessage(id = optimisticId,created_at = now, empty thread) and inserts it at the bottom of every cached variant — but only if the newest page has noprevious_cursor(i.e. we're actually at the bottom of the conversation, channel-messages.ts:278). Returns rollback context. - mutationFn:
postMessage({ ..., id: optimisticId, nonce: optimisticId })— the server keeps the id and echoes the nonce in the WS broadcast. - onSuccess: no id swap, since the optimistic message already carries its final id (
newMessageId); refresh soup entity so channel lists re-sort. - onError: toast +
rollbackInsertChannelMessage(remove the optimistic row). - onSettled:
softInvalidateTargetCaches—invalidateQueries({ refetchType: 'inactive' }), i.e. mark stale for the next mount, don't refetch under the user.
Patch/delete follow the same shape with createMutationNonce (lib/queries/nonce.ts:141,
prepare-in-onMutate / use-in-mutationFn / cleanup-in-onSettled; 60s TTL). Delete captures a
positional snapshot for rollback; soft-deletes (sets deleted_at) when the message has replies.
reconcile.ts is the fan-out layer: resolveMessageTarget classifies top-level vs thread-reply,
and each *InTargetCaches helper applies the change to all three cache families
(paginated channel-messages, thread-replies, by-ids).
Realtime: socket → cache
lib/queries/sync/SyncProvider.tsx— app-level component usingcreateConnectionWebsocketEffect,match(data.type):comms_message→handleCommsMessage(lib/queries/channel/sync.ts:64)agent_session_log→handleAgentSessionLog(agent-session-stream.ts:220)comms_reaction/comms_attachment/comms_typing/ etc.
handleCommsMessage:consumeNonce(...)— if the nonce is ours, the optimistic update already applied, so skip the write; otherwise insert/update/delete in cache directly. AlwayssoftInvalidateTargetCachesat the end for eventual consistency.- Adoption: before anything, a payload carrying
agent_session_messagecallsadoptAgentSessionPlaceholder(sync.ts:69–77) so a client-synthesized placeholder row is re-keyed to the server row id instead of duplicated.
The agent-session fold pipeline (already exists — the agent block should reuse it)
createFoldedMessages(folded-messages.ts:68): resource + store. FetchesgetAgentChannelLog, opens a fold machine in the worker, then follows live WS frames through the same machine. Reactivity: acreateStorekeyedbySessionId[sessionId][turn][authorKind] → FoldedMessage; consumers read through thelookupclosure so only changed rows re-render. Resource resolves once; the store keeps updating.agent-session-stream.ts: the buffering seam.beginAgentSessionStream(channelId)before the fetch, buffer frames,followAgentSessionaligns buffer against snapshot (RustLogIngestionreconciles durable snapshot/live row overlap), one machine per session shared across split views, refcounted release. AlsosubscribeAgentSessionLog(sessionId, sink)(:90) for raw-frame consumers.agent-session-placeholders.ts: synthesizes a placeholder comms row when the fold derives a new message live (ensureAgentSessionPlaceholder) and re-keys it when the real row arrives (adoptAgentSessionPlaceholder).rememberSessionBotrecords sender identity.
5. Scroll & list (summary)
- Virtualization:
@tanstack/solid-virtualinChannel/ThreadList.tsx, withanchorTo: 'end', a 96px estimate, six-row overscan, and measured variable heights. SolidKeyowns rows by message ID rather than virtual-range index. - Contract:
keys: Accessor<string[]>, a row render prop,onReady(navigation)(scrollToLatest/scrollToMessage/scrollToElement), andonScroll(state, snapshot).initialPositionsupports latest, element, and restore;targetIdkeeps a navigation target mounted.onReadycan return cleanup. - Initial layout:
createScrollLifecyclewaits for a nonempty measured list; the initial offset seeds the latest range even when data arrives asynchronously. - Following: core end anchoring handles measured streaming growth and
followOnAppendfollows new keys only near the end (50px). No one-second agent settle loop or independent growth observer is needed. - Mobile: numeric
insetsparticipate in measurements and navigation; viewport and floating-inset changes preserve the pin only when previously near the end. Short lists bottom-align within these insets. - Snapshots:
{scrollOffset, measurements, isNearBottom}; channel persists them, but the agent transcript currently opens at latest rather than restoring history. - Chrome:
CustomScrollbarandScrollToBottomOverlay; the overlay requires explicit downward scrolling while more than one viewport from the bottom. - Agent reuse:
component/Transcript.tsxrenders this same ThreadList with session/turn/author keys, shared message width, andReplyToSelection. Do not reintroduce the former Virtua implementation or duplicate the list machinery.
6. Input wiring
- Component stack:
ChannelInput(Input/ChannelInput.tsx, lexical markdown editor + mentions tracker + attachment tracker + typing tracker + hotkeys) →Inputprimitives. - Contract:
InputSnapshot = { value, mentions, attachments }(Input/types.ts:52);InputHandle = { clear, focus, send, attachFiles, restoreSnapshot, insertEntityMention?, ... }(:97). Channel stores bothonChange-mirrored snapshot andonReadyhandle in signals (Channel.tsx:204–207). - Send (Channel.tsx:623–648):
buildPostMessageSendPayload({ snapshot, participantIds })(Input/message-payload.ts:96) expands mentions (@herefan-out, bot re-tagging) and maps attachments; thensendMessageMutation.mutate({ channelID, senderId, optimisticId: newMessageId(), ...payload }, { onError }).- Restore-on-error: the input cleared itself on send;
onErrorrestores the failed snapshot viahandle.restoreSnapshot(snapshot)— but only if the user hasn't typed new sendable content meanwhile (hasSendableInputContent(current)check, :643).
- Restore-on-error: the input cleared itself on send;
- Persistence: localStorage-backed draft via
persistenceKey={makeInputValuePersistenceKey({ channelId })}(Input/utils/persistence.ts— versioned keysinput-value-channel:<id>[-thread:<id>]); separate keys for attachment tracker, task draft, task mode. - Typing indicators:
ChannelInputrunscreateTypingTracker(debounced start/stop) callingonStartTyping/onStopTypingprops →usePostTypingUpdateMutation(Channel.tsx:961–972). Inbound:comms_typingWS events feed a module-level signal store (@queries/channel/typing.ts), 8s timeout. - Input face switching (Channel.tsx:873–975):
<Switch>over unified-input mode — editing face (UnifiedEditInput) > reply face (UnifiedReplyInput) > default composer. The bottom bar is one surface whose content rebinds; state for each face lives in messageEditor / unifiedInput / threadManager, not in the input.
7. Synthesis: what the agent block should take (and skip)
Current agent block (features/block-agent/): one-shot useAgentSessionBlockQuery
(data/queries.ts:23 — fetch session + log, foldSession once, frozen), plain <For> over
messages in a Scroll (component/Block.tsx), AgentInput with an unwired onSend.
Copy directly
- Adapter / component split. Keep
Block.tsxas the adapter (header, entry-state captor, orchestrator method registration if deep links matter, hotkey scope) and grow anAgentSession.tsxcomposition root that takes{ sessionId, onHandleReady?, initialStateSnapshot?, autofocus? }and exposes a small handle (goToLatest,getStateSnapshot, maybegoToTurn). - The factory decomposition. Build the stateful surface as
create*factories with accessor-in/accessor-out interfaces, composed in the root:createAgentSession(context/create-agent-session.ts) — the Solid face of the sharedAgentSessionclass (lib/core/agent-session/AgentSession.ts): the class owns the fold machine, the realtime subscription, the REST calls, and speculation; the wrapper owns a reconciled ordered store and applies fold events to it. One instance per session id, refcounted across the block, the agents view, and the magic chip.- There is no status or composer controller. "What is the agent doing" is the fold's
metadata.turndiscriminant (idle | starting | running | stopping | blocked | disconnected), and "is this message still on the wire" ismessage.pending. The composer reads both and keeps no state. createElicitationController— the live question and the one POST that answers it.createQueueController— the server-side action queue, baselined once per socket.
- Late-bound handles as signals for anything the child publishes upward (input handle,
scroll navigation), with
awaitConditionin the adapter if orchestrator methods need them. - Optimistic send (implemented, in the fold).
AgentSession.issuespeculates the action into the machine before the POST: the machine forks its confirmed state, folds the frame the harness will log (built by the sameAgentAction::to_runtime), and marks the derived messagespending. The confirmed row promotes it in place by action id (by content for a stop), a foreign row rebases the suffix behind it, a failed POST retracts it. Nothing is predicted about the runtime's answer: a pending stop reads asstopping, never as a closed turn. Seecrates/folds/agent_fold/src/domain/speculation.rs. - Scroll (implemented): reuse
ThreadListdirectly, as described in section 5. If history restoration is later added, use itsmeasurementssnapshot contract, not the retired Virtua cache or a second pinning loop. - Entry-state captor (
splitPanel.handle.registerEntryStateCaptor) for scroll position + composer-adjacent state so split history restore doesn't reset the view. - Input: reuse
ChannelInputor keepAgentInputbut adopt theInputSnapshot/InputHandlecontract,persistenceKeydraft persistence (makeInputValuePersistenceKey-style, keyed by session id), and the send/restore flow. - WS routing: nothing new needed —
SyncProvideralready routesagent_session_logframes; subscribe throughagent-session-stream.tsrather than adding a new socket path.
Do NOT copy
- Threads — thread-manager, thread-paginator's dual direction, thread previews, reply
inputs,
UnifiedReplyInput/UnifiedEditInputand the whole unified-input-mode face switching. Agent sessions are linear. - Reactions, message editing, message deletion — and with them most of
create-channel-message-actions(a slim per-message actions factory for copy-text/copy-link is still worth the shape). - The multi-variant load-around query machinery (
loadAroundMessageIdin the query key,restoreDefaultChannelPaginationAfterTargetLoad,clearStaleRestoredChannelData) — the session log is fetched whole and folded; there is no cursor pagination to windows. If logs ever need windowing, revisit; don't pre-build it. - Nonce infrastructure in full — the channel needs it because every mutation is echoed on
a shared multi-user socket. A session block likely needs one dedup point (prompt echo), not
the whole
createMutationNoncefamily. - Find bar, typing indicators, drag/drop entity mentions, task mode, calls, activity tracking / new-message dividers, mobile swipe-to-reply — channel-specific surface area.
hide-duplicate-prompts— explicitly a stopgap; solve prompt identity properly instead.
Where our extra state slots in (channel-analog map)
| Agent block concern | Channel analog |
|---|---|
| session status / turn running | threadListScrollState + typing indicators (derived signal fed by a stream) |
| streaming fold | createFoldedMessagesScope + createFoldedMessages store (reuse, reshape to ordered list) |
| permission prompts | createDeleteMessageConfirmation (pending store + returned dialog component) |
| composer busy state | channelInputSnapshot/channelInputHandle signals + onSend gating (Channel.tsx:204–207, 623) |
| optimistic prompt row | optimisticInsertChannelMessage + placeholder adopt (agent-session-placeholders.ts) |
| live follow scroll | createStickyScrollEffect + pinToBottom |
| split restore | entry-state captor + getStateSnapshot handle method |