Skip to content

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.

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.

When an admitted turn arrives:

  • Re-entrant turns share the lock’s typing request. An empty-response retry passing skipLock=true can start typing if the outer turn left it deferred.
  • Lock acquisition: acquireChannelLockForTurn() sets isLocked = true, records lockedAt and lastProgressAt, and creates a fresh AbortController (activeTurnAbortController). The signal is available to executing tools via ToolContext.abortSignal.
  • Stale lock recovery: releaseStaleChannelLockIfExpired() checks whether lastProgressAt is older than CHANNEL_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 using runUnderWatchdog (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.

Channel locks coordinate two forms of turn interruption:

  1. Follow-up interrupts: queueFollowUpForLockedTurn() allows an inbound message from the same user to interrupt an active stream via StreamOrchestrator.requestFollowUp(), up to MAX_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.
  2. Hard cancellation: killChannelProcessing() serves both /kill and a stop phrase from the active turn’s speaker. It clears pending turns with clearChannelProcessingQueue(), registers a user stop with StreamOrchestrator.requestStop(), and calls forceKillChannelStream(). That aborts activeTurnAbortController and calls activeStreamKill(), 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 report stopped_by_user. A stopped turn gets no retry, fallback, or timeout notice. Tools that generate media check abortSignal.aborted before sending to avoid posting discarded media.

When the turn completes or throws, releaseChannelLockAndReplayQueue() executes in a finally block:

  1. Resets lock metadata, clears activeStreamKill, and aborts activeTurnAbortController.
  2. Stops the Discord typing keepalive timer.
  3. Clears the channel’s stop request, which would otherwise abort the next turn at its pre-stream check.
  4. Pops the next message from the FIFO messageQueue and schedules processQueuedMessage() via setImmediate.

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.

  • 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 setImmediate prevents call stack growth under heavy traffic.
  • Tool progress protection: suppressing stream interrupts while isInToolCallChain is true ensures external tool effects finish cleanly before the user’s follow-up message processes.
  • src/utils/chat/channelQueue.ts: runWithChannelLock(), queue storage, typing keepalive, release logic, and killChannelProcessing().
  • src/commands/kill.ts: /kill command reply and media billing footer.
  • src/utils/discord/streamOrchestrator.ts: stop and follow-up request state management.