Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

wezterm/bugabinga/wezterm_instances.nu

Raw
def fail [message: string] {
  error make { msg: $message }
}

def niri-windows [] {
  let result = (^niri msg --json windows | complete)
  if $result.exit_code != 0 {
    fail $"niri window query failed: ($result.stderr | str trim)"
  }

  try {
    $result.stdout | from json
  } catch {|error|
    fail $"invalid niri window response: ($error.msg)"
  }
}

def socket-path [gui_pid: int] {
  $env.XDG_RUNTIME_DIR | path join wezterm $"gui-sock-($gui_pid)"
}

def require-socket [gui_pid: int] {
  let socket = (socket-path $gui_pid)
  let kind = (try { $socket | path type } catch { null })
  if $kind != socket {
    fail $"missing WezTerm GUI socket for PID ($gui_pid)"
  }
  $socket
}

def window-panes [window: record] {
  let path = ($env.XDG_RUNTIME_DIR | path join wezterm $"instances-($window.pid).json")
  if not ($path | path exists) { return [] }

  open --raw $path | from json | get panes | each {|pane|
    {
      gui_pid: $window.pid
      niri_window_id: $window.id
      niri_workspace_id: $window.workspace_id
      niri_window_title: $window.title
      pane_id: $pane.pane_id
      workspace: $pane.workspace
      title: $pane.title
      agent: $pane.agent?
      process: $pane.process?
      state: $pane.state?
      priority: $pane.priority?
    }
  }
}

def wezterm-windows [] {
  # Runtime snapshots remove one CLI process per GUI; Niri remains the sole live inventory query.
  niri-windows | where pid != null | each {|window| window-panes $window } | flatten
}

def list-instances [] {
  print (wezterm-windows | to json --raw)
}

def activate-pane [gui_pid: int, pane_id: int] {
  let windows = (niri-windows | where pid == $gui_pid)
  if ($windows | length) != 1 {
    fail $"expected one niri window for WezTerm GUI PID ($gui_pid)"
  }

  let window = ($windows | first)
  let socket = (require-socket $gui_pid)
  let activation = (with-env { WEZTERM_UNIX_SOCKET: $socket } {
    ^wezterm cli activate-pane --pane-id $pane_id | complete
  })
  if $activation.exit_code != 0 {
    fail $"pane activation failed: ($activation.stderr | str trim)"
  }

  let focus = (^niri msg action focus-window --id $window.id | complete)
  if $focus.exit_code != 0 {
    fail $"niri focus failed: ($focus.stderr | str trim)"
  }

  print ({
    gui_pid: $gui_pid
    pane_id: $pane_id
    niri_window_id: $window.id
  } | to json --raw)
}

def main [command: string, gui_pid?: int, pane_id?: int] {
  match $command {
    list => { list-instances }
    activate => {
      if $gui_pid == null or $pane_id == null {
        fail 'activate requires GUI PID and pane ID'
      }
      activate-pane $gui_pid $pane_id
    }
    _ => { fail $"unknown command: ($command)" }
  }
}