Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

9.7 KB
Raw Blame
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import {
  readDisabledTerminalLiveInputHandlesPreference,
  saveDisabledTerminalLiveInputHandles
} from '../storage/preferences'
import {
  applyDisabledTerminalLiveInputHandles,
  defaultTerminalLiveInputHandles,
  filterTerminalLiveInputDefaultCandidates,
  pruneTerminalLiveInputHandles
} from '../terminal/terminal-live-input'

type UseTerminalLiveInputModePreferenceOptions = {
  readonly hostId: string
  readonly worktreeId: string
  /** Terminals running an agent; they open in the composer instead of live keys. */
  readonly agentHandles?: ReadonlySet<string>
}

const NO_AGENT_HANDLES: ReadonlySet<string> = new Set()

export function useTerminalLiveInputModePreference({
  hostId,
  worktreeId,
  agentHandles = NO_AGENT_HANDLES
}: UseTerminalLiveInputModePreferenceOptions) {
  // The shell-level choice: live by default, minus persisted opt-outs.
  const [shellLiveInputHandles, setLiveInputTerminalHandles] = useState<Set<string>>(
    () => new Set()
  )
  const shellLiveInputHandlesRef = useRef<Set<string>>(new Set())
  // Agent tabs where the user picked live keys; the pick ends when the agent quits.
  const [agentLiveInputHandles, setAgentLiveInputHandles] = useState<ReadonlySet<string>>(
    () => new Set()
  )
  const agentHandlesRef = useRef(agentHandles)
  const liveInputTerminalHandles = useMemo(
    () =>
      new Set(
        [...shellLiveInputHandles].filter(
          (handle) => !agentHandles.has(handle) || agentLiveInputHandles.has(handle)
        )
      ),
    [agentHandles, agentLiveInputHandles, shellLiveInputHandles]
  )
  const liveInputTerminalHandlesRef = useRef<Set<string>>(liveInputTerminalHandles)
  useLayoutEffect(() => {
    agentHandlesRef.current = agentHandles
    liveInputTerminalHandlesRef.current = liveInputTerminalHandles
  }, [agentHandles, liveInputTerminalHandles])
  useEffect(() => {
    setAgentLiveInputHandles((prev) => {
      const kept = [...prev].filter((handle) => agentHandles.has(handle))
      return kept.length === prev.size ? prev : new Set(kept)
    })
  }, [agentHandles])
  const defaultedLiveInputTerminalHandlesRef = useRef<Set<string>>(new Set())
  const disabledLiveInputTerminalHandlesRef = useRef<Set<string>>(new Set())
  const disabledLiveInputHydratedRef = useRef(false)
  const pendingDisabledLiveInputHydrationEditsRef = useRef<Map<string, boolean>>(new Map())
  const pendingLiveInputDefaultHandlesRef = useRef<Set<string>>(new Set())

  const defaultTerminalHandlesToLiveInput = useCallback((handles: readonly string[]) => {
    // Terminal discovery can precede persisted opt-out hydration on worktree re-entry.
    if (!disabledLiveInputHydratedRef.current) {
      for (const handle of handles) {
        pendingLiveInputDefaultHandlesRef.current.add(handle)
      }
      return
    }
    const defaultableHandles = filterTerminalLiveInputDefaultCandidates(
      handles,
      disabledLiveInputTerminalHandlesRef.current
    )
    const result = defaultTerminalLiveInputHandles(
      shellLiveInputHandlesRef.current,
      defaultedLiveInputTerminalHandlesRef.current,
      defaultableHandles
    )
    if (!result.changed) {
      return
    }
    const nextEnabledHandles = new Set(result.enabledHandles)
    const nextDefaultedHandles = new Set(result.defaultedHandles)
    shellLiveInputHandlesRef.current = nextEnabledHandles
    defaultedLiveInputTerminalHandlesRef.current = nextDefaultedHandles
    setLiveInputTerminalHandles(nextEnabledHandles)
  }, [])

  const persistDisabledLiveInputHandles = useCallback(() => {
    void saveDisabledTerminalLiveInputHandles(
      hostId,
      worktreeId,
      disabledLiveInputTerminalHandlesRef.current
    ).catch(() => {})
  }, [hostId, worktreeId])

  const pruneTerminalHandlesFromLiveInput = useCallback(
    (liveHandles: ReadonlySet<string>) => {
      const result = pruneTerminalLiveInputHandles(
        shellLiveInputHandlesRef.current,
        defaultedLiveInputTerminalHandlesRef.current,
        liveHandles
      )
      let prunedDisabledHandles = false
      for (const handle of disabledLiveInputTerminalHandlesRef.current) {
        if (liveHandles.has(handle)) {
          continue
        }
        disabledLiveInputTerminalHandlesRef.current.delete(handle)
        if (!disabledLiveInputHydratedRef.current) {
          pendingDisabledLiveInputHydrationEditsRef.current.set(handle, false)
        }
        prunedDisabledHandles = true
      }
      if (prunedDisabledHandles && disabledLiveInputHydratedRef.current) {
        persistDisabledLiveInputHandles()
      }
      if (!result.changed) {
        return
      }
      const nextEnabledHandles = new Set(result.enabledHandles)
      const nextDefaultedHandles = new Set(result.defaultedHandles)
      shellLiveInputHandlesRef.current = nextEnabledHandles
      defaultedLiveInputTerminalHandlesRef.current = nextDefaultedHandles
      setLiveInputTerminalHandles(nextEnabledHandles)
    },
    [persistDisabledLiveInputHandles]
  )

  const clearTerminalLiveInputDefault = useCallback(
    (handle: string) => {
      const liveHandles = new Set([
        ...shellLiveInputHandlesRef.current,
        ...defaultedLiveInputTerminalHandlesRef.current
      ])
      liveHandles.delete(handle)
      if (!disabledLiveInputHydratedRef.current) {
        pendingDisabledLiveInputHydrationEditsRef.current.set(handle, false)
      }
      if (disabledLiveInputTerminalHandlesRef.current.delete(handle)) {
        if (disabledLiveInputHydratedRef.current) {
          persistDisabledLiveInputHandles()
        }
      }
      pruneTerminalHandlesFromLiveInput(liveHandles)
    },
    [persistDisabledLiveInputHandles, pruneTerminalHandlesFromLiveInput]
  )

  const toggleTerminalLiveInput = useCallback(
    (handle: string): boolean => {
      if (agentHandlesRef.current.has(handle)) {
        const nextEnabled = !liveInputTerminalHandlesRef.current.has(handle)
        setAgentLiveInputHandles((prev) => {
          const next = new Set(prev)
          if (nextEnabled) {
            next.add(handle)
          } else {
            next.delete(handle)
          }
          return next
        })
        // Live keys also need the shell-level choice on, or the pick would have no effect.
        if (!nextEnabled || shellLiveInputHandlesRef.current.has(handle)) {
          return nextEnabled
        }
      }
      const nextEnabled = !shellLiveInputHandlesRef.current.has(handle)
      if (nextEnabled) {
        disabledLiveInputTerminalHandlesRef.current.delete(handle)
      } else {
        disabledLiveInputTerminalHandlesRef.current.add(handle)
      }
      // Patch loaded preferences per handle so pre-hydration edits preserve other opt-outs.
      if (!disabledLiveInputHydratedRef.current) {
        pendingDisabledLiveInputHydrationEditsRef.current.set(handle, !nextEnabled)
      }
      // Persist only after hydration; the reset-empty ref would overwrite other opt-outs.
      if (disabledLiveInputHydratedRef.current) {
        persistDisabledLiveInputHandles()
      }
      const next = new Set(shellLiveInputHandlesRef.current)
      if (nextEnabled) {
        next.add(handle)
      } else {
        next.delete(handle)
      }
      shellLiveInputHandlesRef.current = next
      setLiveInputTerminalHandles(next)
      return nextEnabled
    },
    [persistDisabledLiveInputHandles]
  )

  useEffect(() => {
    shellLiveInputHandlesRef.current = new Set()
    defaultedLiveInputTerminalHandlesRef.current = new Set()
    disabledLiveInputTerminalHandlesRef.current = new Set()
    disabledLiveInputHydratedRef.current = false
    pendingDisabledLiveInputHydrationEditsRef.current = new Map()
    pendingLiveInputDefaultHandlesRef.current = new Set()
    setLiveInputTerminalHandles(new Set())
    setAgentLiveInputHandles(new Set())

    let disposed = false
    // Hydrate before subscriptions can default live-input mode over persisted choices.
    void readDisabledTerminalLiveInputHandlesPreference(hostId, worktreeId).then((preference) => {
      if (disposed) {
        return
      }
      const pendingEdits = pendingDisabledLiveInputHydrationEditsRef.current
      const hydratedDisabledHandles = new Set(preference.handles)
      for (const [handle, disabled] of pendingEdits) {
        if (disabled) {
          hydratedDisabledHandles.add(handle)
        } else {
          hydratedDisabledHandles.delete(handle)
        }
      }
      disabledLiveInputTerminalHandlesRef.current = hydratedDisabledHandles
      disabledLiveInputHydratedRef.current = true
      pendingDisabledLiveInputHydrationEditsRef.current = new Map()
      if (preference.loaded && pendingEdits.size > 0) {
        persistDisabledLiveInputHandles()
      }
      const result = applyDisabledTerminalLiveInputHandles(
        shellLiveInputHandlesRef.current,
        defaultedLiveInputTerminalHandlesRef.current,
        hydratedDisabledHandles
      )
      const nextEnabledHandles = new Set(result.enabledHandles)
      const nextDefaultedHandles = new Set(result.defaultedHandles)
      shellLiveInputHandlesRef.current = nextEnabledHandles
      defaultedLiveInputTerminalHandlesRef.current = nextDefaultedHandles
      setLiveInputTerminalHandles(nextEnabledHandles)
      const pendingDefaultHandles = [...pendingLiveInputDefaultHandlesRef.current]
      pendingLiveInputDefaultHandlesRef.current.clear()
      defaultTerminalHandlesToLiveInput(pendingDefaultHandles)
    })
    return () => {
      disposed = true
    }
  }, [defaultTerminalHandlesToLiveInput, hostId, persistDisabledLiveInputHandles, worktreeId])

  return {
    clearTerminalLiveInputDefault,
    defaultTerminalHandlesToLiveInput,
    liveInputTerminalHandles,
    liveInputTerminalHandlesRef,
    pruneTerminalHandlesFromLiveInput,
    toggleTerminalLiveInput
  }
}