04: Channel Lock
The channel lock enforces single-turn concurrency per Discord channel. It manages the Discord typing keepalive indicator, coordinates user interruptions and cancellations, and replays queued messages when the lock releases.
Flow and ownership
Section titled “Flow and ownership”runWithChannelLock() in src/utils/chat/channelQueue.ts wraps turn planning and execution inside a
per-channel mutex backed by the in-memory channelLocks map.
flowchart TD entry["runWithChannelLock(admission, callback)"] -->|"skipLock === true"| reuse["invoke callback(reuseOuterLock)"] entry -->|"skipLock !== true"| stale["releaseStaleChannelLockIfExpired()"] stale --> acquire["acquireChannelLockForTurn()<br/>sets isLocked, initializes AbortController"] acquire --> cb["callback(lockedTurn)<br/>requestChannelTyping() can start keepalive (8s cadence)"] cb --> release["finally: releaseChannelLockAndReplayQueue()<br/>stops typing, aborts turn controller, clears stop request"] release -->|"messageQueue has items"| replay["setImmediate(processQueuedMessage)"]Deliberate turns start typing alongside context building and wait for both before generation.
Spontaneous turns have shouldSurfaceUserErrors set to false by the planner. They wait for the
first reply text or a tool dispatch that calls for typing. Plain prose can start typing while
the stream buffers it. Markup and possible prefill echoes wait for segment cleanup, including
on turns that hold text for review.
Reactions and other tools marked to skip typing can finish without an indicator. Text delivery and
tool dispatch wait for the initial typing request. After one second, the lock cancels the request
and the reply proceeds. Cancelling the turn also cancels the request. The keepalive starts only
after a successful request from the current lock owner. A late interval callback clears only its
own timer.
The lock entry also owns a bounded history window for the busy stretch: the active turn and its
queued replays. Later personas and queued user or persona turns can reuse it. Release preserves the
window only while handing off to a queued replay; a replay that returns before acquiring the lock
drops it. Empty-queue release, stale recovery, queue clearing, and /kill free the window and its
gateway change signals. A new trigger from an idle channel always starts with a REST read.
Mutex acquisition and re-entrancy
Section titled “Mutex acquisition and re-entrancy”When an admitted turn arrives:
- Re-entrant turns share the lock’s typing request. An empty-response retry passing
skipLock=truecan start typing if the outer turn left it deferred. - Lock acquisition:
acquireChannelLockForTurn()setsisLocked = true, recordslockedAtandlastProgressAt, and creates a freshAbortController(activeTurnAbortController). The signal is available to executing tools viaToolContext.abortSignal. - Stale lock recovery:
releaseStaleChannelLockIfExpired()checks whetherlastProgressAtis older thanCHANNEL_LOCK_TIMEOUT_MS(180s). If expired, it aborts the active turn controller, fires the stream kill handle, clears queued messages, and resets the lock. It clears the expired turn’s stop request before the next acquisition. Active operations usingrunUnderWatchdog(such as streaming chunks and tool calls) suppress stale-lock recovery because they enforce their own timeouts.
Retry and Continue check live Discord history under the channel lock before claiming the reply controls row.
Interruption and cancellation ownership
Section titled “Interruption and cancellation ownership”Channel locks coordinate two forms of turn interruption:
- Follow-up interrupts:
queueFollowUpForLockedTurn()allows an inbound message from the same user to interrupt an active stream viaStreamOrchestrator.requestFollowUp(), up toMAX_FOLLOW_UP_INTERRUPTS(3). If the active turn is executing a tool (isInToolCallChain), the message is enqueued as the latest follow-up without interrupting the stream, protecting tool completion. Both paths preserve the active persona when replaying the follow-up. An incoming impersonation target takes precedence over the active turn’s impersonation identity; ordinary follow-ups retain it. - Hard cancellation:
killChannelProcessing()serves both/killand a stop phrase from the active turn’s speaker. It clears pending turns withclearChannelProcessingQueue(), registers a user stop withStreamOrchestrator.requestStop(), and callsforceKillChannelStream(). That abortsactiveTurnAbortControllerand callsactiveStreamKill(), which rejects the streaming race with an error. The stream can clear the stop request before the tool loop handles that rejection, so the tool loop reads the aborted turn signal to reportstopped_by_user. A stopped turn gets no retry, fallback, or timeout notice. Tools that generate media checkabortSignal.abortedbefore sending to avoid posting discarded media.
Release and queue replay
Section titled “Release and queue replay”When the turn completes or throws, releaseChannelLockAndReplayQueue() executes in a finally block:
- Resets lock metadata, clears
activeStreamKill, and abortsactiveTurnAbortController. - Stops the Discord typing keepalive timer.
- Clears the channel’s stop request, which would otherwise abort the next turn at its pre-stream check.
- Pops the next message from the FIFO
messageQueueand schedulesprocessQueuedMessage()viasetImmediate.
Shard ownership and shutdown
Section titled “Shard ownership and shutdown”The mutex and its live Discord messages and callbacks stay in the guild’s shard owner process. Admission, queue replay, persona queues, stop phrases, and follow-up requests require configured ownership and safe live leases. DMs map to shard 0. Re-entry must still belong to the active outer turn.
Lease uncertainty aborts turns and clears pending replay. Captured owner signals stay aborted after lease recovery, so an old continuation cannot dispatch as a new owner. Delivery paths check again after awaited preparation and before sending; already dispatched requests cannot be recalled.
Shutdown rejects new turns and discards pending replays while allowing active turns, including valid re-entry, up to 25 seconds to finish. It then aborts remaining turns through the existing terminal stream-stop path, suppressing cancellation retries and timeout notices. Stats and connection cleanup follow the drain; the Discord client remains connected until those phases finish.
Constraints and rationale
Section titled “Constraints and rationale”- Single active turn per channel: serializing turns prevents race conditions across message sends, webhook delivery, and conversational context ordering.
- Asynchronous queue unrolling: invoking queued replays through
setImmediateprevents call stack growth under heavy traffic. - Tool progress protection: suppressing stream interrupts while
isInToolCallChainis true ensures external tool effects finish cleanly before the user’s follow-up message processes.
Source pointers
Section titled “Source pointers”src/utils/chat/channelQueue.ts:runWithChannelLock(), queue storage, typing keepalive, release logic, andkillChannelProcessing().src/commands/kill.ts:/killcommand reply and media billing footer.src/utils/discord/streamOrchestrator.ts: stop and follow-up request state management.