Skip to content

The agent that grows with you

6.3 KB
Raw Blame
import { writeAgentTerminalChunk } from '@/app/right-sidebar/terminal/agent-terminal-stream'
import { closeAgentTerminalByProc } from '@/app/right-sidebar/terminal/terminals'
import { revealDesktopPane } from '@/store/pane-focus'
import { reactionOverlayScope, recordAgentReaction } from '@/store/reactions-local'
import { setMessages } from '@/store/session'
import { $tipsEnabled, type ActiveTip, agentTipId, showTip } from '@/store/tips'

import type { GatewayEventContext } from './types'

const DESKTOP_BRIDGE_HANDLERS: Record<string, (ctx: GatewayEventContext) => void> = {
  'agent.terminal.output': ({ payload }) => {
    // Live chunk from a background process → its read-only agent terminal tab.
    writeAgentTerminalChunk(payload?.process_id ?? '', payload?.chunk ?? '')
  },

  'terminal.close': ({ payload }) => {
    // Agent closed its own read-only tab via the desktop-gated close_terminal tool.
    // The process is untouched — this only drops the view.
    closeAgentTerminalByProc(payload?.process_id ?? '')
  },

  'tip.show': ({ payload, isActiveEvent }) => {
    // tip tool: point the accent bubble at something and say one line about
    // it. Fire-and-forget — a tip is not a question, and blocking the turn on
    // one would stall the sentence the agent is in the middle of, so there is
    // nothing to answer and a refusal is simply a bubble that never appears.
    // Active session only: a background turn must never paint on the user's
    // screen (desktop AGENTS.md: offer, don't hijack).
    const selector = typeof payload?.selector === 'string' ? payload.selector : ''
    const text = typeof payload?.text === 'string' ? payload.text : ''

    // A tip with nothing to point at is just a notification, and the app
    // already has those. Dropping it here also stops a malformed event from
    // replacing a rotation tip with a bubble that dismisses itself a frame
    // later.
    if ($tipsEnabled.get() && isActiveEvent && selector && text) {
      showTip({
        side: (payload?.side as ActiveTip['side']) ?? 'top',
        targets: [selector],
        text,
        tipId: agentTipId(selector, text),
        title: typeof payload?.title === 'string' ? payload.title : undefined
      })
    }
  },

  'pane.reveal': ({ payload, isActiveEvent }) => {
    // Agent revealed a pane via the desktop-gated focus_pane tool, in
    // response to an explicit user request. Active session only — a
    // background turn must never move the user's focus (desktop AGENTS.md:
    // offer, don't hijack).
    if (isActiveEvent) {
      revealDesktopPane(payload?.pane ?? '')
    }
  },

  'message.reaction': ({ payload, isActiveEvent, fromActiveSource, event }) => {
    // The agent reacted to a message via the desktop-gated
    // react_to_message tool. Already persisted — this only paints it now
    // instead of at the next resume. Fresh ChatMessage object per change:
    // the runtime repository caches normalized ThreadMessages in a WeakMap
    // keyed by ChatMessage identity. Active session only (same gate as
    // tip.show/pane.reveal): $messages is the visible transcript and the
    // reaction overlay is keyed by bare row id, so a background session's
    // event would stamp its row id and reactions onto this session's
    // optimistic bubble, or onto a coincidental same-rowid message from a
    // different profile's DB. The owning session paints it from the
    // persisted write on its next load.
    //
    // `isActiveEvent` alone proves the RUNTIME id matches, not the SOURCE:
    // two connections can report the same session id, and a reaction from
    // source B would mutate the transcript source A is showing. The
    // dispatcher's `fromActiveSource()` compares the composite
    // (connectionId, profile) scope — same gate as the setup.ready /
    // skin.changed broadcasts — so only the source that owns the visible
    // session paints. The overlay entry carries that scope, and a read
    // keys the displayed session's own source (see agentLiveReactions), so
    // a stale entry can never outrank a different source's persisted
    // reaction at the same row id.
    const reactedRowId = payload?.row_id

    if (isActiveEvent && fromActiveSource() && typeof reactedRowId === 'number') {
      const nextReactions = Array.isArray(payload?.reactions) ? payload.reactions : []
      const reactedRole = payload?.role === 'assistant' ? 'assistant' : 'user'
      const overlayScope = reactionOverlayScope(event)

      setMessages(messages => {
        // Preferred leg: the message already knows its durable row id
        // (rehydrated transcript, or a live row that has round-tripped).
        const byRowId = messages.find(message => message.rowId === reactedRowId)

        if (byRowId) {
          // Overlay survives the end-of-turn resume, which rebuilds from
          // in-memory history that doesn't carry this mid-turn DB write.
          recordAgentReaction(reactedRowId, nextReactions, overlayScope)

          return messages.map(message =>
            message.rowId === reactedRowId ? { ...message, reactions: nextReactions } : message
          )
        }

        // Live leg: the targeted message is still optimistic (no rowId —
        // it hasn't round-tripped through a resume). The agent's default
        // target is the newest message of that role, so stamp the reaction
        // AND the now-known row id onto it. Without this the event matches
        // nothing and the reaction only appears after a reload.
        const lastIndex = messages.findLastIndex(message => message.role === reactedRole && message.rowId === undefined)

        if (lastIndex === -1) {
          return messages
        }

        recordAgentReaction(reactedRowId, nextReactions, overlayScope)

        return messages.map((message, index) =>
          index === lastIndex ? { ...message, rowId: reactedRowId, reactions: nextReactions } : message
        )
      })
    }
  }
}

/** Desktop-surface bridge events: agent terminal streaming, tips, pane
 *  reveal and message reactions. The read-back REQUESTS the agent
 *  blocks on (terminal/preview/window/tour) live in `server-requests.ts`. */
export function handleDesktopBridgeEvent(ctx: GatewayEventContext): boolean {
  if (!Object.hasOwn(DESKTOP_BRIDGE_HANDLERS, ctx.event.type)) {
    return false
  }

  DESKTOP_BRIDGE_HANDLERS[ctx.event.type](ctx)

  return true
}