SSH와 tmux로 맥미니를 원격 AI 작업실로 쓰기

노트북을 닫아도 맥미니의 CLI 작업을 이어가고 싶다면 SSH와 tmux를 함께 사용해 보자. 첫 연결부터 세션 복귀, Claude Code·Hermes·Ollama 실행, 기본 명령어와 설정, 대체 도구 선택까지 차근차근 따라가는 안내서다.
목표는 간단하다. 노트북에서는 접속하고, 맥미니에서는 작업을 실행하며, 연결이 끊기면 같은 작업 화면으로 돌아온다. 여기서 Hermes는 Nous Research의 Hermes Agent를 뜻한다. 명령과 제품 기능은 2026년 10월 25일 공식 문서를 기준으로 확인했다. 독자의 원격 맥미니에 접속하거나 모델 인증·추론까지 실행한 실측 후기는 아니다.
1. SSH, tmux, AI 도구는 각각 무엇을 할까
| 구성 요소 | 맡는 일 | 이 글에서 실행하는 위치 |
|---|---|---|
| OpenSSH | 다른 컴퓨터의 셸에 암호화된 연결 제공 | 노트북의 클라이언트 ↔ 맥미니의 서버 |
| tmux | 터미널 세션·창·분할 화면 유지 | 맥미니 |
| Claude Code | 코드 읽기, 수정, 명령 실행을 돕는 에이전트 | 맥미니의 프로젝트 폴더 |
| Hermes Agent | 모델과 도구·메모리·스킬을 연결하는 에이전트 | 맥미니 |
| Ollama | 로컬 모델 실행 및 모델 API 제공 | 맥미니 |
Laptop terminal
└─ SSH connection
└─ Mac mini
└─ tmux session: ai
├─ window: claude → Claude Code
├─ window: ollama → Ollama server
└─ window: hermes → Hermes → Ollama
SSH 연결이 종료되어도 맥미니의 tmux 서버와 그 안의 프로그램은 계속 실행될 수 있다. 다시 SSH로 접속해 세션에 붙으면 된다. 노트북에만 tmux를 실행하고 그 안에서 SSH를 여는 것으로는 원격 프로그램의 수명을 같은 방식으로 보호하지 못한다. 이 글에서는 SSH 접속 후 맥미니에서 tmux를 시작한다. (tmux 소개)
tmux는 인터넷 단절, 맥미니의 잠자기, 재부팅, 프로그램 충돌을 모두 해결하는 도구가 아니다. 맥미니가 잠들면 연산이 진행되지 않으며, 재부팅하면 기존 프로세스는 사라진다. 모델 응답이나 사용자 승인을 기다리던 에이전트도 저절로 다음 단계로 넘어가지는 않는다.
2. 세션·윈도·패널과 접두 키 익히기
세션(session)은 작업 묶음, 윈도(window)는 그 안의 탭, 패널(pane)은 한 윈도를 나눈 터미널 영역이다. 프로젝트별로 세션을 만들고, 도구별로 윈도를 나누며, 로그를 옆에 볼 때만 패널을 쓰면 관리하기 쉽다.
아래 공식 예제는 한 윈도에 편집기·셸·매뉴얼을 함께 배치한 모습이다. AI 도구에도 같은 배치 원리를 적용할 수 있다.

tmux 공식 Getting Started 문서가 제공하는 분할 화면 예제. 이 글의 AI 실습 결과 화면은 아니다. (출처: tmux, 2026-10-25 확인 · 원본 크게 보기)
기본 접두 키는 Ctrl+b다. Ctrl+b를 함께 누른 뒤 두 키를 놓고 다음 키를 누른다. 예를 들어 Ctrl+b → d는 세 키를 동시에 누르는 동작이 아니다. Mac에서도 Command가 아닌 Control을 쓴다.
가장 먼저 기억할 것은 Ctrl+b → d로 분리하고, tmux attach -t 이름으로 돌아온다는 두 가지다.
3. 준비: 어느 컴퓨터에서 입력하는지 구분하기
이 글의 복사 가능한 셸 명령은 로컬 Mac의 zsh/bash와 원격 맥미니를 기준으로 한다. Windows에서도 OpenSSH로 접속할 수 있지만, 아래 키 등록 파이프라인과 pbcopy 예제는 macOS용이다.
맥미니에는 전원과 네트워크, 로그인 가능한 macOS 사용자, Homebrew가 필요하다. 첫 설치는 Apple Silicon 맥미니를 기준으로 한다. Intel Mac은 Ollama의 GPU 가속·Homebrew 패키지 제공·Hermes 플랫폼 지원이 다를 수 있으므로 각 공식 지원표부터 확인한다. Ollama의 공식 macOS 앱 요구 사항과 Homebrew의 지원 OS도 서로 같다고 가정하지 않는다. (Ollama macOS 안내, Hermes 설치 안내)
예제의 your_user는 맥미니의 계정 짧은 이름, 192.168.0.20은 맥미니의 실제 IP로 바꾼다. 두 컴퓨터가 같은 네트워크에 있는 상태에서 먼저 연결해 보자.
맥미니: 원격 로그인 켜기
시스템 설정 → 일반 → 공유 → 원격 로그인을 켜고, 접속을 허용할 사용자를 지정한다. 표시되는 SSH 접속 명령도 확인한다. 기본 실습을 위해 모든 사용자나 전체 디스크 접근을 허용할 필요는 없다. (Apple 원격 로그인 안내)
CLI로 설정할 경우 맥미니에서 직접 다음 명령을 실행한다. 관리자 권한이나 터미널의 전체 디스크 접근 권한을 요구하는 환경에서는 시스템 설정에서 처리하는 편이 간단하다.
sudo systemsetup -getremotelogin
sudo systemsetup -setremotelogin on
whoami
노트북: 첫 SSH 연결
ssh your_user@192.168.0.20
첫 접속의 호스트 키 지문은 맥미니에서 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub로 확인한 값과 대조한다. 비밀번호를 입력할 때 글자가 보이지 않는 것은 정상이다. 접속 후 hostname과 whoami로 대상 컴퓨터·사용자를 확인한다. exit를 입력하면 노트북으로 돌아온다.
집 밖에서는 같은 사설 IP로 바로 연결되지 않는다. Tailscale 공식 시작 안내에 따라 두 장치를 같은 사설 네트워크에 연결한 뒤, 맥미니의 Tailscale IP 또는 이름으로 기존 macOS SSH 서버에 접속할 수 있다. 별도 기능인 Tailscale SSH를 반드시 켤 필요는 없다. 먼저 이 방식으로 연결하면 공유기의 SSH 포트 개방을 직접 구성하는 단계를 줄일 수 있다.
4. 자주 접속할 수 있도록 SSH 키와 별칭 만들기
노트북에서 전용 키를 만든다. 같은 파일이 이미 있다면 덮어쓰지 말고 재사용하거나 다른 이름을 쓴다. 암호 문구도 설정한다.
ssh-keygen -t ed25519 -f ~/.ssh/macmini_ed25519 -C "macmini-access"
cat ~/.ssh/macmini_ed25519.pub | ssh your_user@192.168.0.20 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys'
ssh -i ~/.ssh/macmini_ed25519 your_user@192.168.0.20
등록하는 것은 .pub 공개 키다. 확장자가 없는 개인 키는 노트북에 남긴다. 마지막 명령으로 로그인되는 것을 확인하고 exit로 돌아온다.
노트북에서 nano ~/.ssh/config를 열고 다음 블록을 추가한다. 기존 파일이 있으면 내용을 지우지 않는다. nano에서는 Ctrl+O, Enter로 저장하고 Ctrl+X로 닫는다.
Host macmini
HostName 192.168.0.20
User your_user
IdentityFile ~/.ssh/macmini_ed25519
IdentitiesOnly yes
ServerAliveInterval 30
ServerAliveCountMax 3
chmod 600 ~/.ssh/config
ssh macmini
이제 주소 대신 macmini라고 입력한다. ServerAliveInterval은 서버에 주기적으로 응답을 요청한다. 연결 문제 감지에 도움이 되지만 끊긴 연결을 자동 복원하지는 않는다. (OpenSSH 설정 매뉴얼)
5. 첫 실습: 작업을 남겨 두고 돌아오기
맥미니: tmux 설치
Homebrew가 없다면 공식 홈페이지의 현재 설치 명령과 설치 후 안내를 먼저 따른다. Apple Silicon 기본 설치에서 brew가 검색되지 않으면 현재 셸에서 eval "$(/opt/homebrew/bin/brew shellenv)"를 실행한다. 이후 로그인에도 적용하려면 설치 안내대로 ~/.zprofile에 설정한다.
brew install tmux
tmux -V
tmux new -s practice
하단에 상태 표시줄이 생기면 tmux 안이다. 그 안에서 시간을 계속 기록하는 연습 작업을 실행한다.
mkdir -p ~/tmux-demo
while true; do date; sleep 2; done | tee -a ~/tmux-demo/ticks.log
다음 순서로 연결을 분리하고 복귀한다.
Ctrl+b → d를 누른다. 맥미니의 일반 셸로 돌아오며 작업은 계속된다.exit로 SSH 연결을 닫는다. 이제 노트북의 셸이다.- 잠시 후 노트북에서
ssh macmini를 실행한다. - 맥미니에서
tmux ls로practice가 남아 있는지 확인한다. tmux attach -t practice로 들어간다. 시간 출력이 이어지고 있으면 성공이다.
확인 후 Ctrl+C로 연습 루프를 멈춘다. 같은 패널에서 tail ~/tmux-demo/ticks.log로 연결을 닫았던 동안의 기록도 볼 수 있다. exit로 마지막 셸을 닫으면 연습 세션이 끝난다.
detach는 화면에서 떨어지는 동작이고, exit는 셸을 종료하는 명령이다. 실제 작업을 남겨 둘 때는 둘을 혼동하지 말자. (tmux 세션 동작)
6. Claude Code·Ollama·Hermes 작업 공간 만들기
아래 단계는 모두 SSH로 접속한 맥미니에서 진행한다. 먼저 연습용 프로젝트 폴더와 AI 세션을 만든다.
mkdir -p ~/ai-work/demo
cd ~/ai-work/demo
tmux new -s ai -n claude
이미 ai가 있다면 새로 만들지 않고 tmux attach -t ai로 들어간다. 설정을 바꾸지 않은 기본 환경에서는 첫 윈도 번호가 0이다.
윈도 claude: Claude Code 실행
설치되어 있다면 설치 명령은 생략한다. 아래는 Claude Code 공식 설치 안내의 네이티브 설치 방식이다. 다운로드한 설치 스크립트를 실행하는 명령이므로 출처를 확인하고 진행한다.
curl -fsSL https://claude.ai/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
claude --version
claude
처음 실행하면 인증 안내를 따른다. 원격 환경에서 브라우저가 열리지 않으면 CLI에 표시되는 로그인 URL을 노트북 브라우저에서 열고, 이어지는 CLI 안내를 완료한다. 기본 Claude 서비스 사용에는 해당 계정의 이용 권한과 과금 조건이 적용된다.
처음에는 “현재 폴더를 확인하고, 파일은 수정하지 말고 가능한 작업을 설명해 줘”처럼 결과를 확인하기 쉬운 요청을 해 보자. 일반적인 원격 실행에서도 코드와 명령은 맥미니에서 처리되지만, 선택한 모델 공급자가 클라우드라면 모델 추론은 클라우드에서 수행된다.
윈도 ollama: 모델 서버 실행
Claude Code를 종료하지 않고 Ctrl+b → c로 새 윈도를 만든다. Ctrl+b → ,를 누르고 ollama라고 이름을 붙인다.
CLI 중심 설치에는 Homebrew의 Ollama 패키지를 사용할 수 있다. Ollama 공식 앱으로 이미 설치했다면 중복 설치하지 말고 기존 ollama 명령을 사용한다.
brew install ollama
ollama --version
ollama serve
서버 로그가 보이며 프롬프트로 돌아오지 않는 것이 정상이다. 서버는 이 윈도에서 계속 실행된다. 이미 앱이나 서비스가 11434 포트를 사용 중이라면 서버를 또 켜지 않는다. 다음 단계의 API 확인으로 기존 서버를 사용하면 된다.
윈도 hermes: 모델을 확인하고 에이전트 연결
다시 Ctrl+b → c로 새 윈도를 만들고, Ctrl+b → ,로 hermes라고 이름 붙인다.
cd ~/ai-work/demo
curl http://127.0.0.1:11434/api/tags
ollama pull qwen3:4b
ollama run qwen3:4b
API에서 JSON이 나오면 서버에 연결된 것이다. 모델에 짧은 질문을 하고 /bye로 대화를 끝낸다. 여기서 qwen3:4b는 작은 연결 확인용 예시이지 모든 코딩 작업에 대한 추천 모델은 아니다. 다운로드 크기와 실제 메모리 사용량은 다르며, 컨텍스트 길이와 동시 실행 수가 늘면 메모리가 더 필요하다. 에이전트 작업에는 도구 호출 지원과 실제 작업 정확도도 확인해야 한다.
최신 Ollama에서 다음 명령으로 Hermes 설치·모델 연결 안내를 시작할 수 있다. (공식 연동 문서)
ollama launch hermes
모델 선택 화면에서는 로컬 실행이 목표라면 다운로드한 로컬 모델을 선택한다. :cloud 모델은 원격 모델이다. 메시지 플랫폼 연결은 이 CLI 실습에 필요하지 않으므로 건너뛰어도 된다.
이미 Hermes를 설치했거나 수동 구성을 원하면 다음 경로도 사용할 수 있다. 설치 후 명령이 보이지 않으면 새 SSH 연결을 연 뒤 계속한다.
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
hermes model
모델 설정에서 Ollama 또는 사용자 지정 엔드포인트를 선택한다. 수동 입력 항목은 API 주소 http://127.0.0.1:11434/v1, 모델 이름 qwen3:4b, 로컬 Ollama의 API 키는 비워 두는 구성이 기준이다. 메뉴 문구는 버전에 따라 다를 수 있다. 저장 후 hermes를 실행한다. (Hermes 로컬 모델 안내)
아래 공식 화면에서는 모델 이름, 도구 목록, 스킬 목록을 볼 수 있다. 특히 모델 이름을 확인하는 습관이 중요하다. 예제 이미지의 kimi-k2.5:cloud는 클라우드 모델이며 위의 로컬 모델 실습 결과가 아니다.

Ollama 공식 Hermes 연동 문서 제공 화면. 화면 속 버전과 모델은 문서 예시이며 현재 설치 버전이나 로컬 추론을 뜻하지 않는다. (출처: Ollama, 2026-10-25 확인 · 원본 크게 보기)
Hermes에도 먼저 현재 폴더의 파일 이름만 확인하도록 요청한다. 기존 설정에서 터미널 백엔드를 별도 서버나 컨테이너로 바꾼 적이 있다면 실제 도구 실행 위치도 확인한다. 모델이 로컬이어도 웹 검색·외부 API·메시징 도구를 쓰면 네트워크 요청은 발생할 수 있다.
Claude Code도 Ollama 모델로 실행할 수 있을까
Ollama는 Claude Code를 위한 Anthropic 호환 API 연동도 제공한다. 새 연습 윈도에서 다음 명령으로 모델을 선택할 수 있다.
ollama launch claude
이 구성은 Claude Code라는 인터페이스에서 선택한 Ollama 모델을 사용하는 것이다. Claude 모델 자체가 맥미니에 다운로드되는 것은 아니다. 도구 지원, 추론 품질, 메모리 요구량은 선택한 모델에 달려 있다. 공식 안내의 큰 컨텍스트 권장값을 작은 메모리의 맥미니에 무조건 적용하지 말고, 먼저 작은 작업으로 확인한다. (Ollama의 Claude Code 연동)
7. 매일 쓰는 명령어와 단축키
다음 셸 명령은 맥미니에서 입력한다. -t는 대상 세션을 지정하며, -s는 생성할 세션의 이름을 지정한다.
| 명령 | 용도 |
|---|---|
tmux new -s ai | ai 세션 만들고 연결 |
tmux ls | 세션 목록 확인 |
tmux attach -t ai | 기존 세션에 연결 |
tmux new -A -s ai | 있으면 연결, 없으면 생성 |
tmux detach-client | 현재 클라이언트 분리 |
tmux rename-session -t ai ai-main | 세션 이름 변경 |
tmux list-windows -t ai | 윈도 목록 확인 |
tmux kill-session -t practice | 연습 세션과 그 안의 작업 종료 |
kill-session은 작업을 끝내는 명령이다. 잠시 자리를 비우는 용도로 사용하지 않는다. kill-server는 모든 세션에 영향을 주므로 일반 복귀 절차에 넣지 않는다.
아래 단축키는 기본 키 설정 기준이며, 화살표 앞에서 Ctrl+b를 놓는다.
| 단축키 | 동작 |
|---|---|
Ctrl+b → d | 작업을 남겨 두고 분리 |
Ctrl+b → c | 새 윈도 |
Ctrl+b → , | 현재 윈도 이름 변경 |
Ctrl+b → n / p | 다음 / 이전 윈도 |
Ctrl+b → 0 … 9 | 해당 번호 윈도로 이동 |
Ctrl+b → w | 윈도 목록에서 선택 |
Ctrl+b → % | 좌우로 나누기 |
Ctrl+b → " | 위아래로 나누기 |
Ctrl+b → 방향키 | 다른 패널로 이동 |
Ctrl+b → z | 현재 패널 확대 / 복원 |
Ctrl+b → [ | 스크롤·복사 모드 진입 |
Ctrl+b → ] | tmux 버퍼 붙여넣기 |
Ctrl+b → : | tmux 명령 입력 |
Ctrl+b → ? | 키 도움말; q로 닫기 |
단축키와 명령 전체는 설치된 버전의 man tmux와 공식 매뉴얼을 기준으로 확인한다.
노트북에서 한 번에 접속하려면 다음과 같이 쓴다. -t는 대화형 터미널을 할당한다.
ssh -t macmini 'tmux new -A -s ai'
여기서만 tmux: command not found가 나면 비대화형 SSH 명령의 PATH가 원인일 수 있다. 평소 SSH 접속 후 command -v tmux로 경로를 확인하고, Apple Silicon 기본 Homebrew 경로라면 다음처럼 지정한다.
ssh -t macmini '/opt/homebrew/bin/tmux new -A -s ai'
8. 사용감을 개선하는 작은 설정
맥미니에서 nano ~/.tmux.conf를 열어 아래 설정을 추가한다. 기본 접두 키와 윈도 번호는 바꾸지 않아 앞의 실습과 일치시킨다.
set -g mouse on
set -g history-limit 50000
setw -g mode-keys vi
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind r source-file ~/.tmux.conf
tmux 안의 셸에서 다음 명령으로 적용한다.
tmux source-file ~/.tmux.conf
마우스로 패널을 선택하고 크기를 바꿀 수 있다. Ctrl+b → |와 Ctrl+b → -는 현재 경로에서 새 패널을 열고, Ctrl+b → c도 현재 경로를 유지한다. 히스토리 상한은 새로 만든 윈도·패널에서 확인한다.
vi 복사 모드는 Ctrl+b → [로 들어가 방향키로 이동하고, Space로 선택을 시작한 뒤 Enter로 복사한다. q로 빠져나오고 Ctrl+b → ]로 붙여넣는다. 이것은 tmux 내부 버퍼이며 노트북의 클립보드와 항상 같은 것은 아니다.
로컬 Mac 클립보드로 짧은 텍스트 결과만 가져올 때는 노트북의 새 터미널에서 다음 방식도 쓸 수 있다. 활성 패널의 최근 히스토리를 복사하므로 비밀 값이 포함되지 않았는지 확인한다.
ssh macmini '/opt/homebrew/bin/tmux capture-pane -p -S -200 -t ai:claude' | pbcopy
경로는 command -v tmux 결과에 맞춘다. pbcopy가 SSH 따옴표 밖에 있기 때문에 노트북에서 실행된다. 터미널 클립보드 연동을 더 설정하려면 tmux 공식 Clipboard 안내를 참고한다.
9. 모델 서버를 안정적으로 운영하기
맥미니가 잠들지 않도록 하기
노트북이 잠드는 것과 맥미니가 잠드는 것은 다르다. 장시간 작업에는 맥미니의 시스템 설정에서 디스플레이가 꺼졌을 때 자동 잠자기를 방지하는 옵션을 확인한다. 메뉴와 제공 옵션은 기종·macOS 버전에 따라 다르다. (Apple 잠자기 설정)
일시적으로는 맥미니의 별도 tmux 윈도에서 다음 명령을 실행한다.
caffeinate -i
실행 중 유휴 잠자기를 막으며, Ctrl+C로 끝내면 해제된다. 수동 잠자기·전원 차단·재부팅까지 막아 주지는 않는다. 다른 작업이 진행 중일 때 접속한 tmux 클라이언트에만 caffeinate를 묶으면 detach와 함께 방지 효과도 끝날 수 있으므로 별도 윈도로 유지하는 편이 이해하기 쉽다.
계속 쓸 Ollama는 서비스로 전환하기
학습 중에는 ollama serve 로그를 직접 보는 편이 쉽다. 계속 사용할 서버라면 tmux와 별도로 macOS 서비스 관리자인 launchd를 통한 실행을 고려한다. Homebrew 패키지를 설치했다면 기존 serve 윈도에서 Ctrl+C로 서버를 멈춘 뒤 다음 명령을 사용한다.
brew services start ollama
brew services list
curl http://127.0.0.1:11434/api/tags
일반 사용자로 실행하는 Homebrew 서비스는 로그인 시 자동 실행하는 방식이다. 로그인 전 부팅 서비스와 동일하지 않으며, 재부팅 후 FileVault 잠금 해제나 사용자 로그인 조건은 별도로 확인해야 한다. sudo를 붙여 서비스의 실행 계정을 바꾸는 것을 기본 해결책으로 삼지 않는다. (Homebrew 서비스 설명)
모델 상태를 확인할 때는 ollama list, ollama ps, 필요 없어진 모델을 메모리에서 내릴 때는 ollama stop qwen3:4b를 쓴다. stop은 다운로드한 모델 파일 삭제와 다르다. (Ollama CLI)
10. 노트북에서 맥미니의 Ollama API 사용하기
SSH 안에서 ollama나 Hermes를 쓸 때는 터널이 필요 없다. 노트북의 앱이나 스크립트가 맥미니의 모델 API를 호출할 때만 로컬 포워딩을 추가한다.
노트북의 별도 터미널에서 다음을 실행하고 열어 둔다. 노트북에 이미 Ollama가 있어도 충돌을 피하도록 로컬 포트는 11435로 지정했다.
ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:11435:127.0.0.1:11434 macmini
노트북의 또 다른 터미널에서 확인한다.
curl http://127.0.0.1:11435/api/tags
첫 번째 127.0.0.1:11435는 노트북이 받는 주소이고, 뒤의 127.0.0.1:11434는 SSH 서버인 맥미니에서 접근할 주소다. 노트북 앱에는 http://127.0.0.1:11435를 넣고, OpenAI 호환 형식을 요구하면 /v1을 붙인다. Ollama를 0.0.0.0에 노출하거나 공유기의 11434 포트를 열 필요가 없다. (OpenSSH 로컬 포워딩)
이 터널은 노트북의 SSH 프로세스가 유지하는 연결이다. 끊기면 다시 실행해야 하며, 원격 tmux가 노트북의 터널까지 복구하지는 않는다.
11. tmux보다 더 잘 맞는 도구가 있을까
아래 선택 기준은 각 도구의 공식 기능을 바탕으로 한 이 글의 판단이다. 모든 용도에서 더 좋은 단일 도구가 있는 것은 아니다.
| 도구 | 이런 경우에 고려 | tmux와의 관계·한계 |
|---|---|---|
| tmux | SSH 중심 작업, 키보드 조작, 셸 스크립트로 작업 공간 구성 | 학습할 접두 키가 있지만 원격 CLI의 출발점으로 적합 |
| Zellij | 화면에 보이는 키 안내와 레이아웃을 선호 | 터미널 작업 공간 대안. 키 모드와 CLI 앱 단축키 충돌을 확인 |
| Mosh | Wi-Fi 전환·이동통신·지연이 큰 연결 | 연결 계층을 개선. tmux와 함께 사용 가능; SSH 포트 포워딩 대체는 아님 |
| iTerm2 tmux 통합 | 로컬 Mac에서 탭·분할 UI로 원격 작업을 다루고 싶음 | tmux를 서버로 사용하며 클라이언트 UI를 바꿈 |
| tmux-resurrect | 재시작 후 윈도·경로·배치를 복원하고 싶음 | 레이아웃과 일부 프로그램 복원 보조. 실행 중 모델의 메모리 상태를 저장하는 기능은 아님 |
Zellij를 비교해 보고 싶으면 맥미니에 설치해 별도 세션을 만든다. 아래 명령은 tmux에 들어가지 않은 원격 셸에서 실행한다.
brew install zellij
zellij --session ai-test
이동 중 연결 품질이 문제라면 Mosh를 양쪽 컴퓨터에 설치한 뒤 다음처럼 사용할 수 있다. SSH로 인증한 다음 UDP로 통신하므로 방화벽·사설 네트워크에서 필요한 UDP 통신이 허용되어야 한다. 기본 포트 범위는 60000–61000이다.
mosh your_user@192.168.0.20
tmux new -A -s ai
포트 포워딩에는 앞 절의 SSH를 별도로 사용한다. Mosh도 맥미니의 재부팅으로 사라진 프로세스를 되살리지는 않는다. (Mosh 공식 안내)
로컬 터미널이 iTerm2라면 다음 통합 모드를 시험할 수 있다. 일반 터미널에 그대로 적용하는 옵션은 아니다.
ssh -t macmini '/opt/homebrew/bin/tmux -CC new -A -s ai'
처음에는 기본 SSH + tmux를 익힌 뒤, 키 안내가 필요하면 Zellij, 이동 중 끊김이 잦으면 Mosh, Mac의 창 조작을 선호하면 iTerm2 통합을 추가하는 순서를 권한다. 서버 자동 시작은 별도의 서비스 관리 문제로 다룬다.
12. 자주 막히는 상황
| 증상 | 먼저 확인할 것 |
|---|---|
| SSH 연결 거부·시간 초과 | 원격 로그인, 사용자, 실제 IP, 맥미니 전원·잠자기, 같은 네트워크 여부 |
Permission denied (publickey) | 원격 사용자 이름, 공개 키 등록, IdentityFile, .ssh 권한 |
| tmux 안에서만 명령을 찾지 못함 | 설치 후 생긴 PATH 변경이 오래된 셸에 반영됐는지 확인. 새 셸에서 재시도 |
sessions should be nested with care | 이미 tmux 안인지 확인하고 Ctrl+b → s로 세션 선택 |
| 스크롤하면 셸 기록만 움직임 | Ctrl+b → [로 tmux 복사 모드 진입, q로 종료 |
| 한글·색상·화면이 깨짐 | 로컬 터미널의 UTF-8·폰트·terminfo 지원 확인. Ctrl+b → r은 이 글의 설정에서 재로딩이지 화면 복구가 아님 |
11434가 이미 사용 중 | 기존 Ollama 앱·서비스 확인. 서버를 중복 실행하지 않기 |
| 모델이 지나치게 느림 | ollama ps와 맥미니의 메모리 상태 확인. 모델·컨텍스트·동시 실행 수 축소 |
| tmux에 돌아왔는데 에이전트가 멈춰 있음 | 승인 요청·모델 오류·네트워크 오류 대기인지 확인 |
재부팅 후 no server running | 예상된 동작. 새 tmux 세션을 만들고 도구의 대화 재개 기능 사용 |
프로세스가 종료된 Claude Code는 프로젝트 폴더에서 claude -c로 최근 대화를 이어가거나 claude -r로 대화를 선택할 수 있다. 이것은 살아 있는 화면에 다시 붙는 tmux attach와 다르다. (Claude Code CLI) Hermes의 대화 관리 명령은 설치 버전의 hermes --help와 공식 CLI 안내를 확인한다.
동시에 여러 에이전트를 쓰더라도 같은 파일을 서로 덮어쓰지 않도록 작업 폴더나 Git worktree를 나누는 방법을 함께 고려하자. tmux는 터미널을 나눌 뿐 파일 충돌까지 막지는 않는다.
13. 오늘 익힐 최소 루틴
첫날에는 연습 루프가 SSH 연결을 닫은 동안에도 계속되는지만 확인해도 충분하다. 다음에는 도구 하나를 실행하고, 익숙해지면 윈도를 늘린다.
- 노트북에서
ssh macmini로 접속한다. - 맥미니에서
tmux new -A -s ai로 작업 공간에 들어간다. Ctrl+b → w로 필요한 도구의 윈도를 고른다.- 자리를 비울 때는
Ctrl+b → d, 이어서exit를 입력한다. - 돌아오면 같은 두 연결 명령으로 이전 작업을 확인한다.
이 흐름이 익숙해지면 노트북을 바꾸거나 네트워크 연결을 다시 맺어도 맥미니의 작업 공간을 같은 방식으로 사용할 수 있다. 이후에는 Hermes 자동화 실전처럼 반복 작업을 하나씩 추가하면 된다.

Want CLI tasks on your Mac mini to keep running after you close your laptop? Combine SSH with tmux. This guide walks through the first connection, returning to sessions, running Claude Code, Hermes and Ollama, essential commands, configuration, and alternative tools.
The goal is straightforward: connect from your laptop, run the work on your Mac mini, and return to the same workspace after disconnecting. Hermes here means Nous Research's Hermes Agent. Commands and product features were checked against official documentation on October 25, 2026. This is not a report of connecting to your remote Mac mini or testing model authentication and inference end to end.
1. What do SSH, tmux, and the AI tools each do?
| Component | Responsibility | Where it runs in this guide |
|---|---|---|
| OpenSSH | Encrypted access to another computer's shell | Laptop client ↔ Mac mini server |
| tmux | Maintains terminal sessions, windows, and panes | Mac mini |
| Claude Code | An agent for reading code, editing files, and running commands | Project directory on the Mac mini |
| Hermes Agent | Connects models with tools, memory, and skills | Mac mini |
| Ollama | Runs local models and provides a model API | Mac mini |
Laptop terminal
└─ SSH connection
└─ Mac mini
└─ tmux session: ai
├─ window: claude → Claude Code
├─ window: ollama → Ollama server
└─ window: hermes → Hermes → Ollama
When SSH disconnects, the tmux server and programs inside it can keep running on the Mac mini. Reconnect over SSH and attach to the session. Running tmux only on your laptop and opening SSH inside it does not provide the same protection for remote processes. Here, you start tmux on the Mac mini after connecting over SSH. (Introduction to tmux)
tmux does not solve every internet outage, host sleep, reboot, or application crash. Computation pauses when the Mac mini sleeps, and its existing processes disappear after a reboot. An agent waiting for a model response or your approval also cannot automatically move past that requirement.
2. Sessions, windows, panes, and the prefix key
A session groups your work, a window acts like a tab within it, and a pane is one terminal region inside a split window. A useful arrangement is one session per project, one window per tool, and split panes when you need a log beside your main task.
The official example below places an editor, shell, and manual in one window. You can use the same arrangement for AI tools.

Split-pane example supplied by the official tmux Getting Started documentation, not a result of this AI tutorial. (Source: tmux, checked 2026-10-25 · View full-size image)
The default prefix is Ctrl+b. Press those two keys together, release both, then press the next key. Ctrl+b → d does not mean pressing all three simultaneously. On a Mac, use Control, not Command.
Start with two actions: detach with Ctrl+b → d, and return with tmux attach -t name.
3. Preparation: know which computer receives each command
Copyable shell commands assume a local Mac running zsh/bash and a remote Mac mini. Windows can also connect through OpenSSH, but the key-registration pipeline and pbcopy example below target macOS.
The Mac mini needs power, network access, a macOS account you can log into, and Homebrew. Installation examples assume Apple Silicon. On Intel Macs, Ollama GPU acceleration, Homebrew packages, and Hermes platform support may differ; check the official support information first. Do not assume the official Ollama macOS app and Homebrew support exactly the same OS versions. (Ollama macOS guide, Hermes installation)
Replace your_user with the short account name on the Mac mini, and 192.168.0.20 with its actual IP address. Make the first connection while both computers are on the same network.
On the Mac mini: enable Remote Login
Open System Settings → General → Sharing → Remote Login, turn it on, and specify which users may connect. Note the displayed SSH command. This basic exercise does not require allowing all users or granting full disk access. (Apple's Remote Login instructions)
For CLI configuration, run the following directly on the Mac mini. If your environment requires administrative access or Full Disk Access for the terminal, using System Settings may be easier.
sudo systemsetup -getremotelogin
sudo systemsetup -setremotelogin on
whoami
On the laptop: make the first SSH connection
ssh your_user@192.168.0.20
Compare the host-key fingerprint shown on first connection with the output of ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub on the Mac mini. Password characters are not displayed while you type; that is normal. Once connected, use hostname and whoami to check the computer and account. Enter exit to return to the laptop.
Away from home, that private IP will not ordinarily be reachable directly. Follow the official Tailscale quickstart to connect both devices to the same private network, then use the Mac mini's Tailscale address or name to access its existing macOS SSH server. You do not have to enable the separate Tailscale SSH feature. This can simplify access without manually configuring SSH port forwarding on your router.
4. Set up an SSH key and a convenient alias
Create a dedicated key on the laptop. If the file already exists, reuse it or choose another name instead of overwriting it. Set a passphrase too.
ssh-keygen -t ed25519 -f ~/.ssh/macmini_ed25519 -C "macmini-access"
cat ~/.ssh/macmini_ed25519.pub | ssh your_user@192.168.0.20 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys'
ssh -i ~/.ssh/macmini_ed25519 your_user@192.168.0.20
The .pub file is the public key you register. Keep the private key, without that extension, on your laptop. Confirm the final command logs in, then enter exit.
On the laptop, open nano ~/.ssh/config and add this block without removing existing content. In nano, save with Ctrl+O, then Enter, and close with Ctrl+X.
Host macmini
HostName 192.168.0.20
User your_user
IdentityFile ~/.ssh/macmini_ed25519
IdentitiesOnly yes
ServerAliveInterval 30
ServerAliveCountMax 3
chmod 600 ~/.ssh/config
ssh macmini
You can now type macmini instead of the address. ServerAliveInterval periodically requests a response from the server. It helps detect connection problems but does not automatically restore a broken connection. (OpenSSH configuration manual)
5. First exercise: leave a task running and return
On the Mac mini: install tmux
If Homebrew is missing, follow the current installation command and post-install instructions on its official website. With the default Apple Silicon installation, if brew is not found, run eval "$(/opt/homebrew/bin/brew shellenv)" in the current shell. Follow the installer instructions to add the configuration to ~/.zprofile for future logins.
brew install tmux
tmux -V
tmux new -s practice
A status line at the bottom means you are inside tmux. Inside that session, start a practice task that keeps recording the time.
mkdir -p ~/tmux-demo
while true; do date; sleep 2; done | tee -a ~/tmux-demo/ticks.log
Disconnect and return in this order:
- Press
Ctrl+b → d. You return to the Mac mini's ordinary shell while the task continues. - Enter
exitto close SSH. You are now at the laptop's shell. - After a short while, run
ssh macminion the laptop. - On the Mac mini, use
tmux lsto confirmpracticestill exists. - Run
tmux attach -t practice. Continuing time output means it worked.
When finished, stop the loop with Ctrl+C. In the same pane, tail ~/tmux-demo/ticks.log shows entries recorded during the disconnection. Enter exit to close the last shell and end the practice session.
Detach disconnects your view; exit terminates a shell. Keep that distinction in mind when leaving real work running. (tmux session behavior)
6. Build a Claude Code, Ollama, and Hermes workspace
Perform all these steps on the Mac mini over SSH. Create a practice project directory and an AI session first.
mkdir -p ~/ai-work/demo
cd ~/ai-work/demo
tmux new -s ai -n claude
If ai already exists, use tmux attach -t ai. With unmodified defaults, the first window is numbered 0.
The claude window: run Claude Code
Skip installation if it is already installed. This is the native method from the official Claude Code installation guide. It executes a downloaded installation script, so verify its source before proceeding.
curl -fsSL https://claude.ai/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
claude --version
claude
Follow the authentication instructions on first launch. If a browser cannot open remotely, open the login URL displayed by the CLI in your laptop's browser and complete the remaining CLI instructions. Standard Claude service access follows your account's eligibility and billing conditions.
Begin with an easy-to-check request such as “Inspect the current directory and describe what you can do without modifying files.” Code and commands execute on the Mac mini, but inference happens in the cloud if the selected model provider is a cloud service.
The ollama window: run the model server
Leave Claude Code running and press Ctrl+b → c to create a new window. Press Ctrl+b → , and name it ollama.
For CLI-focused installation, use the Homebrew Ollama formula. If you already installed the official Ollama app, use its existing ollama command instead of installing a second copy.
brew install ollama
ollama --version
ollama serve
It is normal to see server logs without returning to the shell prompt: the server keeps running in this window. If an app or service already occupies port 11434, do not start another server. Check the existing API in the next step instead.
The hermes window: check a model and connect the agent
Create another window with Ctrl+b → c, then name it hermes with Ctrl+b → ,.
cd ~/ai-work/demo
curl http://127.0.0.1:11434/api/tags
ollama pull qwen3:4b
ollama run qwen3:4b
JSON from the API confirms the server connection. Ask the model a short question, then end the conversation with /bye. qwen3:4b is a small connectivity-test example, not a recommendation for every coding task. Download size differs from actual memory use; longer contexts and concurrent tasks require more memory. For agent work, also check tool-calling support and accuracy on your tasks.
Recent Ollama versions can guide you through installing Hermes and connecting a model with this command. (Official integration guide)
ollama launch hermes
If you want local inference, choose a downloaded local model in the selector. A :cloud model runs remotely. Messaging-platform setup is unnecessary for this CLI exercise and can be skipped.
If Hermes is already installed or you prefer manual configuration, use this alternative path. Open a new SSH connection if the command is not available after installation.
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
hermes model
Choose Ollama or a custom endpoint in the model settings. For manual entry, use API URL http://127.0.0.1:11434/v1, model name qwen3:4b, and leave the API key empty for local Ollama. Menu labels may vary by version. Save, then run hermes. (Hermes local-model guide)
The official screen below shows the model name, tools, and skills. Checking the model name matters: kimi-k2.5:cloud in this example is a cloud model, not a result from the local-model exercise above.

Screen supplied by Ollama's official Hermes integration documentation. Its version and model are documentation examples, not the current installed version or evidence of local inference. (Source: Ollama, checked 2026-10-25 · View full-size image)
Start by asking Hermes only to list filenames in the current directory. If you previously changed its terminal backend to another server or container, verify where tools actually execute. Even with a local model, web search, external APIs, and messaging tools can still make network requests.
Can Claude Code also use an Ollama model?
Ollama provides an Anthropic-compatible API integration for Claude Code. In a new practice window, select a model with:
ollama launch claude
This means using a selected Ollama model through the Claude Code interface. It does not download the Claude model itself onto your Mac mini. Tool support, reasoning quality, and memory needs depend on the selected model. Do not blindly apply the official large-context recommendation to a low-memory Mac mini; test a small task first. (Ollama's Claude Code integration)
7. Everyday commands and shortcuts
Run these shell commands on the Mac mini. -t specifies a target session; -s names a session you are creating.
| Command | Purpose |
|---|---|
tmux new -s ai |
Create and attach to ai |
tmux ls |
List sessions |
tmux attach -t ai |
Attach to an existing session |
tmux new -A -s ai |
Attach if present, create if missing |
tmux detach-client |
Detach the current client |
tmux rename-session -t ai ai-main |
Rename a session |
tmux list-windows -t ai |
List windows |
tmux kill-session -t practice |
Terminate the practice session and its work |
kill-session terminates work; do not use it to step away temporarily. kill-server affects every session and does not belong in a routine reconnection procedure.
These shortcuts assume default bindings. Release Ctrl+b before the arrow's following key.
| Shortcut | Action |
|---|---|
Ctrl+b → d |
Detach while leaving work running |
Ctrl+b → c |
New window |
Ctrl+b → , |
Rename current window |
Ctrl+b → n / p |
Next / previous window |
Ctrl+b → 0 … 9 |
Go to that window number |
Ctrl+b → w |
Choose from the window list |
Ctrl+b → % |
Split left and right |
Ctrl+b → " |
Split top and bottom |
Ctrl+b → arrow key |
Move between panes |
Ctrl+b → z |
Zoom / restore current pane |
Ctrl+b → [ |
Enter scroll/copy mode |
Ctrl+b → ] |
Paste the tmux buffer |
Ctrl+b → : |
Enter a tmux command |
Ctrl+b → ? |
Show key help; close with q |
Check your installed version's man tmux and the official manual for the complete command and key reference.
To connect in one command from your laptop, use the following. -t allocates an interactive terminal.
ssh -t macmini 'tmux new -A -s ai'
If only this command reports tmux: command not found, the PATH for non-interactive SSH commands may be responsible. After a normal SSH login, check command -v tmux. With the default Apple Silicon Homebrew location, use:
ssh -t macmini '/opt/homebrew/bin/tmux new -A -s ai'
8. Small configuration changes that improve usability
On the Mac mini, open nano ~/.tmux.conf and add the following. Keep the default prefix and window numbering so the earlier instructions remain consistent.
set -g mouse on
set -g history-limit 50000
setw -g mode-keys vi
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind r source-file ~/.tmux.conf
Apply it from a shell inside tmux:
tmux source-file ~/.tmux.conf
You can now select and resize panes with the mouse. Ctrl+b → | and Ctrl+b → - open panes in the current directory, and Ctrl+b → c preserves that directory for new windows. Check the history limit in newly created windows or panes.
Enter vi copy mode with Ctrl+b → [, move with arrow keys, begin selection with Space, and copy with Enter. Leave with q and paste with Ctrl+b → ]. This is the tmux buffer, which is not necessarily your laptop's clipboard.
To copy a short text result to your local Mac clipboard, run the following in a new terminal on the laptop. It copies recent history from the active pane, so check that it does not contain secrets.
ssh macmini '/opt/homebrew/bin/tmux capture-pane -p -S -200 -t ai:claude' | pbcopy
Adjust the path to match command -v tmux. Because pbcopy is outside the SSH quotation marks, it runs on the laptop. For further clipboard integration, see the official tmux Clipboard guide.
9. Keep the model server available
Keep the Mac mini awake
Your laptop sleeping is different from the Mac mini sleeping. For long-running work, check the Mac mini's setting to prevent automatic sleep when its display is off. The location and available options depend on the hardware and macOS version. (Apple sleep settings)
For a temporary measure, run this in a separate tmux window on the Mac mini:
caffeinate -i
It prevents idle sleep while running; Ctrl+C releases it. It does not prevent manual sleep, power loss, or reboot. If you tie caffeinate only to an attached tmux client, detaching can also end that sleep assertion while other work remains. A separate window makes its lifetime easier to understand.
Move a regularly used Ollama server to a service
While learning, watching ollama serve logs is helpful. For ongoing use, consider running it through launchd, the macOS service manager, separately from tmux. If you installed the Homebrew formula, stop the existing foreground server with Ctrl+C in its window, then run:
brew services start ollama
brew services list
curl http://127.0.0.1:11434/api/tags
A Homebrew service started as a normal user is configured to start at login. This differs from a pre-login boot service; FileVault unlocking and user-login requirements after reboot need separate checking. Adding sudo to change the service account should not be the default fix. (Homebrew services)
Use ollama list and ollama ps to inspect models, and ollama stop qwen3:4b to unload an unneeded model from memory. Stopping it does not delete the downloaded model files. (Ollama CLI)
10. Access the Mac mini's Ollama API from your laptop
No tunnel is necessary when using ollama or Hermes inside SSH. Add local forwarding only when an app or script on the laptop needs the Mac mini's model API.
Run the following in a separate laptop terminal and leave it open. Local port 11435 avoids colliding with an Ollama server already running on your laptop.
ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:11435:127.0.0.1:11434 macmini
Check it from another laptop terminal:
curl http://127.0.0.1:11435/api/tags
The first 127.0.0.1:11435 is the laptop's listening address; the later 127.0.0.1:11434 is reached from the Mac mini, the SSH server. Configure your laptop app with http://127.0.0.1:11435, adding /v1 if it expects an OpenAI-compatible endpoint. You do not need to expose Ollama on 0.0.0.0 or open router port 11434. (OpenSSH local forwarding)
This tunnel belongs to the laptop's SSH process. Restart it if disconnected; remote tmux cannot restore the laptop's tunnel.
11. Could another tool fit better?
These selection criteria are the article's judgments based on officially documented features. No single tool is better for every situation.
| Tool | Consider it when | Relationship to tmux and limitations |
|---|---|---|
| tmux | Your work centers on SSH, keyboard control, and scripted workspaces | Requires learning the prefix but is a useful starting point for remote CLI work |
| Zellij | You prefer visible key hints and layouts | Alternative terminal workspace; check mode keys for conflicts with CLI applications |
| Mosh | You switch Wi-Fi networks, use cellular data, or face high latency | Improves the connection layer and can accompany tmux; does not replace SSH forwarding |
| iTerm2 tmux integration | You want native tabs and split-window controls on a local Mac | Uses tmux as the server while changing the client UI |
| tmux-resurrect | You want windows, directories, and layouts restored after a restart | Helps restore layouts and some programs; does not save a running model's memory state |
To compare Zellij, install it on the Mac mini and create a separate session. Run these from a remote shell outside tmux.
brew install zellij
zellij --session ai-test
If roaming connection quality is the problem, install Mosh on both computers, then try the following. It authenticates over SSH before communicating over UDP, so the firewall or private network must allow that traffic. The default port range is 60000–61000.
mosh your_user@192.168.0.20
tmux new -A -s ai
Keep using separate SSH connections for port forwarding. Mosh also cannot revive processes lost when the Mac mini reboots. (Official Mosh guide)
If your local terminal is iTerm2, try this integration mode. It is not an option to apply blindly in other terminal applications.
ssh -t macmini '/opt/homebrew/bin/tmux -CC new -A -s ai'
Start with ordinary SSH and tmux. Then try Zellij for key hints, Mosh for unreliable roaming connections, or iTerm2 integration for Mac window controls. Treat automatic server startup as a separate service-management concern.
12. Common problems
| Symptom | First checks |
|---|---|
| SSH connection refused or timed out | Remote Login, account, actual IP, Mac mini power/sleep, and network reachability |
Permission denied (publickey) |
Remote username, registered public key, IdentityFile, and .ssh permissions |
| A command is missing only inside tmux | An old shell may not have the PATH changes made by installation; try a new shell |
sessions should be nested with care |
Check whether you are already in tmux; select a session with Ctrl+b → s |
| Scrolling moves shell history | Enter tmux copy mode with Ctrl+b → [; leave with q |
| Broken Korean text, colors, or display | Check local terminal UTF-8, fonts, and terminfo; this guide binds Ctrl+b → r to config reload, not screen repair |
Port 11434 is already occupied |
Check the existing Ollama app or service; avoid duplicate servers |
| Model is excessively slow | Inspect ollama ps and memory pressure; reduce model size, context, or concurrency |
| The agent seems stopped after attaching | Check for pending approval, model errors, or network errors |
no server running after reboot |
Expected: create a new tmux session and use the application's conversation-resume feature |
If Claude Code exited, use claude -c in the project directory to continue its recent conversation, or claude -r to choose one. This differs from tmux attach, which returns to a live terminal session. (Claude Code CLI) For Hermes conversation management, check the installed version's hermes --help and official CLI guide.
When running multiple agents, separate working directories or consider Git worktrees so they do not overwrite the same files. tmux separates terminals, not conflicting file edits.
13. The minimum daily routine
On your first day, simply verify that the practice loop keeps running while SSH is closed. Next, run one tool, then add windows as you become comfortable.
- Run
ssh macminion the laptop. - Run
tmux new -A -s aion the Mac mini. - Choose a tool's window with
Ctrl+b → w. - Before leaving, press
Ctrl+b → d, then enterexit. - Return with the same two connection commands and check your previous work.
Once familiar, this routine gives you the same Mac mini workspace after switching laptops or reconnecting the network. You can then add recurring work one task at a time, as in the practical Hermes automation guide.

希望合上笔记本后,Mac mini 上的 CLI 任务仍然继续?可以把 SSH 与 tmux 配合使用。本文从首次连接、恢复会话讲起,逐步介绍 Claude Code、Hermes、Ollama 的运行方式、常用命令、实用配置与替代工具。
目标很明确:用笔记本连接,在 Mac mini 上执行任务,断开后再回到同一个工作界面。 文中的 Hermes 指 Nous Research 的 Hermes Agent。命令和产品功能依据 2026 年 10 月 25 日的官方文档核对;本文并非连接读者的远程 Mac mini、完成模型认证与推理后的实测报告。
1. SSH、tmux 和 AI 工具分别负责什么
| 组件 | 职责 | 本文中的运行位置 |
|---|---|---|
| OpenSSH | 加密连接另一台计算机的 Shell | 笔记本客户端 ↔ Mac mini 服务端 |
| tmux | 保持终端会话、窗口和分屏 | Mac mini |
| Claude Code | 帮助阅读代码、修改文件和执行命令的智能体 | Mac mini 的项目目录 |
| Hermes Agent | 连接模型、工具、记忆和技能的智能体 | Mac mini |
| Ollama | 运行本地模型并提供模型 API | Mac mini |
Laptop terminal
└─ SSH connection
└─ Mac mini
└─ tmux session: ai
├─ window: claude → Claude Code
├─ window: ollama → Ollama server
└─ window: hermes → Hermes → Ollama
SSH 连接结束后,Mac mini 上的 tmux 服务端及其中的程序仍可继续运行。再次通过 SSH 登录并附加到会话即可。如果只在笔记本上运行 tmux,再从里面打开 SSH,并不能以同样方式保护远程进程的生命周期。本文是在 SSH 登录后,在 Mac mini 上启动 tmux。(tmux 入门说明)
tmux 无法解决所有网络中断、Mac mini 睡眠、重启或程序崩溃问题。Mac mini 睡眠时计算不会继续,重启后原有进程也会消失。等待模型响应或用户批准的智能体,同样不会自动跳过这些等待条件。
2. 理解会话、窗口、窗格与前缀键
会话(session)是一组工作,窗口(window)类似其中的标签页,窗格(pane)则是窗口分割后的一个终端区域。可以按项目建立会话、按工具划分窗口,只有需要同时看日志时才使用分屏。
下面的官方示例在同一个窗口中展示了编辑器、Shell 和手册。AI 工具也可以采用相同的排列方式。

tmux 官方 Getting Started 文档提供的分屏示例,并非本文 AI 实验的运行结果。(来源:tmux,2026-10-25 核对 · 查看原图)
默认前缀键是 Ctrl+b。同时按下这两个键,松开后再按下一键。例如 Ctrl+b → d 不是同时按三个键。在 Mac 上也应使用 Control,不是 Command。
先记住两件事:用 Ctrl+b → d 分离,再用 tmux attach -t 名称 返回。
3. 准备:分清命令在哪台计算机输入
文中可复制的 Shell 命令以本地 Mac 的 zsh/bash 和远程 Mac mini 为基础。Windows 也可以通过 OpenSSH 连接,但下文的公钥注册管道和 pbcopy 示例针对 macOS。
Mac mini 需要电源、网络、可登录的 macOS 账户和 Homebrew。安装示例以 Apple Silicon 为准。Intel Mac 在 Ollama GPU 加速、Homebrew 软件包及 Hermes 平台支持方面可能不同,应先查看官方支持说明。也不要假设 Ollama 官方 macOS 应用与 Homebrew 支持完全相同的系统版本。(Ollama macOS 指南、Hermes 安装指南)
把 your_user 替换为 Mac mini 账户的短名称,把 192.168.0.20 替换为 Mac mini 的实际 IP。先让两台设备处于同一个网络,再尝试首次连接。
Mac mini:开启远程登录
打开系统设置 → 通用 → 共享 → 远程登录,启用后指定允许登录的用户,并记下显示的 SSH 命令。基础练习不需要允许所有用户,也不需要授予完全磁盘访问权限。(Apple 远程登录说明)
如果通过 CLI 设置,请直接在 Mac mini 上运行以下命令。若环境要求管理员权限或终端的完全磁盘访问权限,通过系统设置完成可能更简单。
sudo systemsetup -getremotelogin
sudo systemsetup -setremotelogin on
whoami
笔记本:首次 SSH 连接
ssh your_user@192.168.0.20
首次连接时,将显示的主机密钥指纹与 Mac mini 上运行 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub 得到的结果核对。输入密码时不显示字符是正常现象。登录后,用 hostname 和 whoami 确认目标计算机与账户。输入 exit 即可返回笔记本。
离开家后,通常不能直接使用该私有 IP。可按 Tailscale 官方入门指南把两台设备连接到同一个私有网络,再用 Mac mini 的 Tailscale IP 或名称访问已有的 macOS SSH 服务。不必启用另一个独立功能 Tailscale SSH。这种方式可以减少手动配置路由器 SSH 端口转发的步骤。
4. 配置 SSH 密钥与连接别名
在笔记本上生成专用密钥。如果同名文件已存在,请复用或换一个名称,不要覆盖,并设置密钥口令。
ssh-keygen -t ed25519 -f ~/.ssh/macmini_ed25519 -C "macmini-access"
cat ~/.ssh/macmini_ed25519.pub | ssh your_user@192.168.0.20 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys'
ssh -i ~/.ssh/macmini_ed25519 your_user@192.168.0.20
注册的是 .pub 公钥。没有该扩展名的私钥留在笔记本上。确认最后一条命令可以登录后,输入 exit 返回。
在笔记本上运行 nano ~/.ssh/config,添加下面的配置,不要删除已有内容。在 nano 中按 Ctrl+O、Enter 保存,再按 Ctrl+X 退出。
Host macmini
HostName 192.168.0.20
User your_user
IdentityFile ~/.ssh/macmini_ed25519
IdentitiesOnly yes
ServerAliveInterval 30
ServerAliveCountMax 3
chmod 600 ~/.ssh/config
ssh macmini
之后只需输入 macmini,无需记住地址。ServerAliveInterval 会定期请求服务器响应,有助于发现连接问题,但不会自动恢复已经断开的连接。(OpenSSH 配置手册)
5. 第一次练习:留下任务,再回来
Mac mini:安装 tmux
如果还没有 Homebrew,请先按照官方网站当前的安装命令及安装后提示操作。Apple Silicon 默认安装中若找不到 brew,可在当前 Shell 执行 eval "$(/opt/homebrew/bin/brew shellenv)"。再按安装提示将设置加入 ~/.zprofile,以便以后登录时生效。
brew install tmux
tmux -V
tmux new -s practice
底部出现状态栏后,就进入了 tmux。在其中运行持续记录时间的练习任务。
mkdir -p ~/tmux-demo
while true; do date; sleep 2; done | tee -a ~/tmux-demo/ticks.log
按以下顺序断开并返回:
- 按
Ctrl+b → d。回到 Mac mini 的普通 Shell,任务仍在运行。 - 输入
exit关闭 SSH,此时位于笔记本的 Shell。 - 稍等片刻,在笔记本运行
ssh macmini。 - 在 Mac mini 上运行
tmux ls,确认practice仍然存在。 - 用
tmux attach -t practice返回。若时间输出仍在继续,就成功了。
确认后按 Ctrl+C 停止循环。在同一个窗格运行 tail ~/tmux-demo/ticks.log,还可以查看断开期间的记录。输入 exit 关闭最后一个 Shell,练习会话随之结束。
detach 是离开当前界面,exit 是结束 Shell。 需要保留真实任务时,不要混淆两者。(tmux 会话行为)
6. 创建 Claude Code、Ollama 与 Hermes 工作空间
以下步骤都在通过 SSH 登录的 Mac mini 上完成。先创建练习项目目录和 AI 会话。
mkdir -p ~/ai-work/demo
cd ~/ai-work/demo
tmux new -s ai -n claude
如果 ai 已存在,就用 tmux attach -t ai 进入,不要重复创建。未经修改的默认设置中,第一个窗口编号为 0。
claude 窗口:运行 Claude Code
如果已经安装,可以跳过安装命令。以下采用 Claude Code 官方安装指南中的原生安装方式。该命令会执行下载的安装脚本,因此先确认来源。
curl -fsSL https://claude.ai/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
claude --version
claude
首次启动时按提示认证。如果远程环境无法打开浏览器,就在笔记本浏览器打开 CLI 显示的登录 URL,再完成 CLI 后续步骤。使用标准 Claude 服务时,账户资格及计费条件照常适用。
可以先提出容易核验的请求,例如:“查看当前目录,不修改文件,说明可以做哪些工作。”代码和命令在 Mac mini 上处理,但如果所选模型提供商是云服务,模型推理仍在云端进行。
ollama 窗口:运行模型服务
保持 Claude Code 运行,按 Ctrl+b → c 新建窗口,再按 Ctrl+b → , 将其命名为 ollama。
面向 CLI 的安装可使用 Homebrew Ollama 软件包。如果已经安装 Ollama 官方应用,就使用现有的 ollama 命令,避免重复安装。
brew install ollama
ollama --version
ollama serve
屏幕持续显示服务日志、不返回 Shell 提示符是正常现象,服务器会一直在此窗口运行。如果已有应用或服务占用 11434 端口,就不要再次启动;下一步检查已有服务的 API 即可。
hermes 窗口:确认模型并连接智能体
再次按 Ctrl+b → c 新建窗口,用 Ctrl+b → , 命名为 hermes。
cd ~/ai-work/demo
curl http://127.0.0.1:11434/api/tags
ollama pull qwen3:4b
ollama run qwen3:4b
API 返回 JSON 表示已连接服务器。向模型提一个简短问题,再输入 /bye 结束对话。qwen3:4b只是用于验证连接的小模型示例,并非适合所有编程任务的推荐。下载大小与实际内存占用不同,上下文长度和并发数量增加都会提高内存需求。智能体任务还需要确认工具调用支持和实际任务准确率。
较新的 Ollama 可以通过下面的命令引导安装 Hermes 并连接模型。(官方集成文档)
ollama launch hermes
若目标是本地推理,请在选择器中选择已下载的本地模型。:cloud 模型在远程运行。此 CLI 练习不需要消息平台集成,可以跳过。
如果已有 Hermes,或希望手动配置,也可以采用以下路径。安装后若命令不可用,请新开一次 SSH 连接再继续。
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
hermes model
在模型设置中选择 Ollama 或自定义端点。手动配置时使用 API 地址 http://127.0.0.1:11434/v1、模型名称 qwen3:4b,本地 Ollama 的 API 密钥留空。菜单文字可能随版本变化。保存后运行 hermes。(Hermes 本地模型指南)
下面的官方界面展示了模型名称、工具列表和技能列表。尤其应养成检查模型名称的习惯:图中的 kimi-k2.5:cloud 是云端模型,不是上面本地模型练习的结果。

Ollama 官方 Hermes 集成文档提供的界面。图中的版本和模型仅为文档示例,不代表当前安装版本或本地推理。(来源:Ollama,2026-10-25 核对 · 查看原图)
也先让 Hermes 只列出当前目录中的文件名。如果之前把终端后端改成其他服务器或容器,还需确认工具实际在哪里运行。即使模型在本地,使用网页搜索、外部 API 或消息工具仍可能产生网络请求。
Claude Code 也能使用 Ollama 模型吗
Ollama 提供用于 Claude Code 的 Anthropic 兼容 API 集成。可以在新的练习窗口中运行下面的命令选择模型。
ollama launch claude
此配置是在 Claude Code 界面中使用所选的 Ollama 模型,并不是把 Claude 模型本身下载到 Mac mini。工具支持、推理质量及内存需求取决于所选模型。不要把官方的大上下文建议直接套用到低内存 Mac mini,先用小任务验证。(Ollama 的 Claude Code 集成)
7. 日常命令与快捷键
以下 Shell 命令都在 Mac mini 上输入。-t 指定目标会话,-s 指定要创建的会话名称。
| 命令 | 用途 |
|---|---|
tmux new -s ai |
创建并进入 ai 会话 |
tmux ls |
列出会话 |
tmux attach -t ai |
连接已有会话 |
tmux new -A -s ai |
存在则连接,不存在则创建 |
tmux detach-client |
分离当前客户端 |
tmux rename-session -t ai ai-main |
重命名会话 |
tmux list-windows -t ai |
列出窗口 |
tmux kill-session -t practice |
结束练习会话及其中任务 |
kill-session 会结束任务,不能把它用于临时离开。kill-server 会影响所有会话,也不应放进日常重连流程。
下表以默认键位为准,箭头前应先松开 Ctrl+b。
| 快捷键 | 动作 |
|---|---|
Ctrl+b → d |
分离并保留运行中的任务 |
Ctrl+b → c |
新建窗口 |
Ctrl+b → , |
重命名当前窗口 |
Ctrl+b → n / p |
下一个 / 上一个窗口 |
Ctrl+b → 0 … 9 |
转到对应编号的窗口 |
Ctrl+b → w |
从窗口列表选择 |
Ctrl+b → % |
左右分屏 |
Ctrl+b → " |
上下分屏 |
Ctrl+b → 方向键 |
切换窗格 |
Ctrl+b → z |
放大 / 还原当前窗格 |
Ctrl+b → [ |
进入滚动与复制模式 |
Ctrl+b → ] |
粘贴 tmux 缓冲区 |
Ctrl+b → : |
输入 tmux 命令 |
Ctrl+b → ? |
查看按键帮助;按 q 退出 |
完整命令与键位以已安装版本的 man tmux 及官方手册为准。
若要从笔记本一条命令直接进入,可用下面的方式。-t 用于分配交互式终端。
ssh -t macmini 'tmux new -A -s ai'
如果只有这一条命令提示 tmux: command not found,可能是非交互 SSH 命令的 PATH 不同。先普通登录,再用 command -v tmux 查看路径。Apple Silicon 默认 Homebrew 路径可写成:
ssh -t macmini '/opt/homebrew/bin/tmux new -A -s ai'
8. 改善使用体验的小配置
在 Mac mini 上打开 nano ~/.tmux.conf 并添加以下设置。保留默认前缀键和窗口编号,与前面的练习保持一致。
set -g mouse on
set -g history-limit 50000
setw -g mode-keys vi
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind r source-file ~/.tmux.conf
在 tmux 内的 Shell 中执行以下命令应用配置。
tmux source-file ~/.tmux.conf
现在可以用鼠标选择窗格、调整大小。Ctrl+b → | 和 Ctrl+b → - 会在当前目录打开新窗格,Ctrl+b → c 也会为新窗口保留当前目录。历史记录上限应在新建窗口或窗格中确认。
按 Ctrl+b → [ 进入 vi 复制模式,用方向键移动,按 Space 开始选择,按 Enter 复制。q 退出,Ctrl+b → ] 粘贴。这是 tmux 内部缓冲区,不一定等同于笔记本的剪贴板。
若只想把短文本结果复制到本地 Mac 剪贴板,也可在笔记本的新终端运行以下命令。它复制目标窗口活动窗格的近期历史记录,应先确认不含秘密信息。
ssh macmini '/opt/homebrew/bin/tmux capture-pane -p -S -200 -t ai:claude' | pbcopy
路径应按 command -v tmux 的结果调整。pbcopy 位于 SSH 引号之外,因此在笔记本上执行。更多剪贴板集成方式参见 tmux 官方 Clipboard 指南。
9. 稳定运行模型服务器
防止 Mac mini 进入睡眠
笔记本睡眠与 Mac mini 睡眠是两回事。长时间工作时,请在 Mac mini 的系统设置中检查显示器关闭后阻止自动睡眠的选项。菜单位置及可用选项随机型和 macOS 版本变化。(Apple 睡眠设置)
临时使用时,可在 Mac mini 的独立 tmux 窗口运行:
caffeinate -i
它在运行期间防止闲置睡眠,按 Ctrl+C 后解除。它不能阻止手动睡眠、断电或重启。如果仅把 caffeinate 绑定到已连接的 tmux 客户端,分离时可能连同睡眠保护一起结束,即使其他任务仍在运行。使用独立窗口更容易理解其生命周期。
把长期使用的 Ollama 转为服务
学习阶段直接观察 ollama serve 日志较为方便。长期使用时,可考虑通过 macOS 服务管理器 launchd 独立运行。如果安装的是 Homebrew 软件包,先在原来的 serve 窗口按 Ctrl+C 停止服务器,再执行:
brew services start ollama
brew services list
curl http://127.0.0.1:11434/api/tags
以普通用户启动的 Homebrew 服务是登录时自动启动,不等同于登录前的开机服务。重启后 FileVault 解锁和用户登录条件仍需单独确认。不要默认通过添加 sudo、改变服务运行账户来解决问题。(Homebrew 服务说明)
用 ollama list、ollama ps 查看模型状态,用 ollama stop qwen3:4b 从内存卸载不再需要的模型。stop 不会删除已经下载的模型文件。(Ollama CLI)
10. 在笔记本上调用 Mac mini 的 Ollama API
在 SSH 内使用 ollama 或 Hermes 时无需隧道。只有笔记本上的应用或脚本需要调用 Mac mini 的模型 API 时,才添加本地端口转发。
在笔记本的独立终端执行并保持运行。这里使用本地端口 11435,避免与笔记本上已有的 Ollama 冲突。
ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:11435:127.0.0.1:11434 macmini
在笔记本的另一个终端检查:
curl http://127.0.0.1:11435/api/tags
前一个 127.0.0.1:11435 是笔记本监听的地址;后一个 127.0.0.1:11434 是 SSH 服务端 Mac mini 所访问的地址。在笔记本应用中填写 http://127.0.0.1:11435,若要求 OpenAI 兼容端点则添加 /v1。无需把 Ollama 暴露到 0.0.0.0,也无需开放路由器的 11434 端口。(OpenSSH 本地转发)
该隧道由笔记本上的 SSH 进程维持。连接断开后需要重新执行,远程 tmux 不会恢复笔记本上的隧道。
11. 有没有比 tmux 更适合的工具
以下选择标准是本文依据官方功能说明作出的判断。没有一种工具适合所有情况。
| 工具 | 适合考虑的情况 | 与 tmux 的关系及限制 |
|---|---|---|
| tmux | 以 SSH、键盘操作和 Shell 脚本化工作空间为主 | 需要学习前缀键,但适合作为远程 CLI 的起点 |
| Zellij | 喜欢可见的按键提示和布局 | 替代终端工作空间;需检查键位模式与 CLI 应用是否冲突 |
| Mosh | 经常切换 Wi-Fi、使用移动网络或遇到高延迟 | 改善连接层,可与 tmux 配合;不替代 SSH 端口转发 |
| iTerm2 tmux 集成 | 希望在本地 Mac 用标签页和分屏界面操作远程任务 | 以 tmux 为服务端,改变客户端操作界面 |
| tmux-resurrect | 希望重启后恢复窗口、目录和布局 | 辅助恢复布局及部分程序,不保存运行中模型的内存状态 |
若想比较 Zellij,可以在 Mac mini 上安装并创建独立会话。以下命令应在尚未进入 tmux 的远程 Shell 中执行。
brew install zellij
zellij --session ai-test
如果问题在于移动时连接不稳定,可在两台计算机上安装 Mosh,再按下面的方式使用。它先通过 SSH 认证,再通过 UDP 通信,因此防火墙或私有网络需允许所需的 UDP 流量。默认端口范围为 60000–61000。
mosh your_user@192.168.0.20
tmux new -A -s ai
端口转发仍使用前文的独立 SSH 连接。Mosh 也不会复活 Mac mini 重启后消失的进程。(Mosh 官方说明)
若本地终端是 iTerm2,可以试用以下集成模式。不要直接在其他普通终端中照搬这一选项。
ssh -t macmini '/opt/homebrew/bin/tmux -CC new -A -s ai'
建议先掌握标准 SSH + tmux,再按需要选择:需要按键提示时尝试 Zellij,移动连接经常中断时加入 Mosh,偏好 Mac 窗口操作时使用 iTerm2 集成。服务器自动启动则作为独立的服务管理问题处理。
12. 常见问题
| 现象 | 优先检查 |
|---|---|
| SSH 拒绝连接或超时 | 远程登录、用户、实际 IP、Mac mini 电源与睡眠、网络是否可达 |
Permission denied (publickey) |
远程用户名、公钥注册、IdentityFile、.ssh 权限 |
| 只有 tmux 内找不到命令 | 安装后的 PATH 修改是否尚未进入旧 Shell;用新 Shell 重试 |
sessions should be nested with care |
检查是否已在 tmux 中;用 Ctrl+b → s 选择会话 |
| 滚动时只移动 Shell 历史 | 用 Ctrl+b → [ 进入 tmux 复制模式,q 退出 |
| 韩文、颜色或画面异常 | 检查本地终端的 UTF-8、字体、terminfo;本文的 Ctrl+b → r 是重载配置,并非修复画面 |
11434 已被占用 |
检查已有 Ollama 应用或服务,避免重复启动 |
| 模型过慢 | 检查 ollama ps 和内存状态,减少模型大小、上下文或并发 |
| 返回 tmux 后智能体不动 | 检查是否等待批准、模型错误或网络错误处理 |
重启后 no server running |
属于预期行为;新建 tmux 会话,再使用工具的对话恢复功能 |
如果 Claude Code 进程已退出,可以在项目目录运行 claude -c 继续最近的对话,或用 claude -r 选择对话。它与重新附加到仍存活终端的 tmux attach 不同。(Claude Code CLI) Hermes 的对话管理命令请查看已安装版本的 hermes --help 和官方 CLI 指南。
即使同时运行多个智能体,也应分离工作目录或使用 Git worktree,避免相互覆盖同一文件。tmux 只划分终端,不会防止文件编辑冲突。
13. 今天先掌握的最小流程
第一天只需确认练习循环在 SSH 关闭后仍继续即可。然后运行一个工具,熟悉后再增加窗口。
- 在笔记本运行
ssh macmini。 - 在 Mac mini 运行
tmux new -A -s ai。 - 用
Ctrl+b → w选择所需工具的窗口。 - 离开时按
Ctrl+b → d,再输入exit。 - 返回时用同样的两条连接命令查看之前的工作。
熟悉这一流程后,即使更换笔记本或重新连接网络,也能以同样方式使用 Mac mini 的工作空间。接下来可以参考 Hermes 自动化实战,逐项添加重复任务。

ノートPCを閉じてもMac miniのCLI作業を続けたいなら、SSHとtmuxを組み合わせてみよう。初回接続、セッションへの復帰、Claude Code・Hermes・Ollamaの実行、基本コマンド、設定、代替ツールの選び方まで順番に紹介する。
目標はシンプルだ。ノートPCから接続し、Mac miniで作業を実行し、接続が切れたら同じ作業画面に戻る。 本文のHermesはNous ResearchのHermes Agentを指す。コマンドと製品機能は2026年10月25日時点の公式ドキュメントで確認した。読者のリモートMac miniに接続し、モデルの認証や推論まで実測した記事ではない。
1. SSH、tmux、AIツールの役割
| 構成要素 | 役割 | 本文での実行場所 |
|---|---|---|
| OpenSSH | 別のコンピューターのシェルへの暗号化接続 | ノートPCのクライアント ↔ Mac miniのサーバー |
| tmux | ターミナルのセッション・ウィンドウ・ペインを維持 | Mac mini |
| Claude Code | コードの読み取り、編集、コマンド実行を支援するエージェント | Mac miniのプロジェクトフォルダー |
| Hermes Agent | モデルとツール・メモリ・スキルを接続するエージェント | Mac mini |
| Ollama | ローカルモデルの実行とモデルAPIの提供 | Mac mini |
Laptop terminal
└─ SSH connection
└─ Mac mini
└─ tmux session: ai
├─ window: claude → Claude Code
├─ window: ollama → Ollama server
└─ window: hermes → Hermes → Ollama
SSH接続が終了しても、Mac miniのtmuxサーバーとその中のプログラムは動き続けられる。再びSSHで接続し、セッションにアタッチすればよい。ノートPCだけでtmuxを起動し、その中からSSHを開いても、リモートプロセスの寿命を同じようには保護できない。本文ではSSH接続後、Mac miniでtmuxを起動する。(tmuxの紹介)
tmuxは、ネットワーク断、Mac miniのスリープ、再起動、アプリのクラッシュをすべて解決するものではない。Mac miniがスリープすると計算は進まず、再起動すると既存のプロセスは失われる。モデルの応答やユーザーの承認を待つエージェントも、その条件を自動で飛び越えることはない。
2. セッション・ウィンドウ・ペインとプレフィックスキー
セッション(session)は作業のまとまり、ウィンドウ(window)はその中のタブ、ペイン(pane)はウィンドウを分割したターミナル領域だ。プロジェクトごとにセッション、ツールごとにウィンドウを作り、ログを横に表示するときだけペインを分けると管理しやすい。
次の公式例では、エディター・シェル・マニュアルを1つのウィンドウに配置している。AIツールにも同じ考え方を使える。

tmux公式Getting Startedドキュメントが提供する分割画面の例。この記事のAI実習結果ではない。(出典:tmux、2026-10-25確認 · 原寸で見る)
標準のプレフィックスキーはCtrl+b。2つを同時に押してから両方を離し、次のキーを押す。Ctrl+b → dは3つを同時に押す操作ではない。MacでもCommandではなくControlを使う。
最初は、Ctrl+b → dでデタッチし、tmux attach -t 名前で戻るという2つを覚えよう。
3. 準備:どのコンピューターに入力するか
コピーできるシェルコマンドは、ローカルMacのzsh/bashとリモートMac miniを前提とする。WindowsからもOpenSSHで接続できるが、以下の公開鍵登録パイプラインとpbcopyの例はmacOS向けだ。
Mac miniには電源、ネットワーク、ログイン可能なmacOSアカウント、Homebrewが必要になる。インストール例はApple Siliconを前提とする。Intel MacではOllamaのGPUアクセラレーション、Homebrewパッケージ、Hermesの対応状況が異なる場合があるため、先に公式の対応情報を確認しよう。Ollama公式macOSアプリとHomebrewの対応OSが同じとも限らない。(Ollama macOSガイド、Hermesインストールガイド)
your_userはMac miniのアカウントの短い名前、192.168.0.20は実際のIPアドレスに置き換える。まずは両方を同じネットワークにつないで接続する。
Mac mini:リモートログインを有効にする
システム設定 → 一般 → 共有 → リモートログインを有効にし、接続を許可するユーザーを指定する。表示されるSSHコマンドも確認する。基本実習では、すべてのユーザーやフルディスクアクセスを許可する必要はない。(Appleのリモートログイン手順)
CLIで設定するなら、Mac mini上で直接次を実行する。管理者権限やターミナルのフルディスクアクセスが必要な環境では、システム設定から操作する方が簡単だ。
sudo systemsetup -getremotelogin
sudo systemsetup -setremotelogin on
whoami
ノートPC:初回のSSH接続
ssh your_user@192.168.0.20
初回に表示されるホスト鍵のフィンガープリントは、Mac miniでssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pubを実行した値と照合する。パスワード入力中に文字が表示されないのは正常だ。接続後、hostnameとwhoamiでコンピューターとアカウントを確認する。exitでノートPCに戻れる。
外出先からは、通常そのプライベートIPに直接接続できない。Tailscale公式クイックスタートで両端末を同じプライベートネットワークに接続し、Mac miniのTailscale IPや名前から既存のmacOS SSHサーバーに接続できる。別機能のTailscale SSHを必ず有効にする必要はない。この方法なら、ルーターでSSHポート転送を手動設定する手間を減らせる。
4. SSH鍵と接続用の別名を作る
ノートPCで専用の鍵を作る。同名ファイルがある場合は上書きせず、再利用するか別名にする。パスフレーズも設定しよう。
ssh-keygen -t ed25519 -f ~/.ssh/macmini_ed25519 -C "macmini-access"
cat ~/.ssh/macmini_ed25519.pub | ssh your_user@192.168.0.20 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys'
ssh -i ~/.ssh/macmini_ed25519 your_user@192.168.0.20
登録するのは.pubの公開鍵だ。拡張子のない秘密鍵はノートPCに残す。最後のコマンドでログインできることを確かめ、exitで戻る。
ノートPCでnano ~/.ssh/configを開き、既存の内容を消さずに次を追加する。nanoではCtrl+O、Enterで保存し、Ctrl+Xで閉じる。
Host macmini
HostName 192.168.0.20
User your_user
IdentityFile ~/.ssh/macmini_ed25519
IdentitiesOnly yes
ServerAliveInterval 30
ServerAliveCountMax 3
chmod 600 ~/.ssh/config
ssh macmini
以後はアドレスの代わりにmacminiと入力できる。ServerAliveIntervalはサーバーへ定期的に応答を要求する。接続障害の検知に役立つが、切れた接続を自動復旧する機能ではない。(OpenSSH設定マニュアル)
5. 最初の実習:作業を残して戻ってくる
Mac mini:tmuxをインストール
Homebrewがなければ、公式サイトの現在のインストールコマンドと完了後の案内に従う。Apple Siliconの標準インストールでbrewが見つからない場合は、現在のシェルでeval "$(/opt/homebrew/bin/brew shellenv)"を実行する。次回ログインにも適用するには、インストーラーの案内どおり~/.zprofileに設定する。
brew install tmux
tmux -V
tmux new -s practice
下部にステータス行が表示されればtmuxの中だ。その中で時刻を記録し続ける練習用の処理を起動する。
mkdir -p ~/tmux-demo
while true; do date; sleep 2; done | tee -a ~/tmux-demo/ticks.log
次の順番で接続を離れ、戻ってみよう。
Ctrl+b → dを押す。Mac miniの通常のシェルに戻るが、処理は続く。exitでSSHを閉じる。今いるのはノートPCのシェルだ。- 少し待ってからノートPCで
ssh macminiを実行する。 - Mac miniで
tmux lsを実行し、practiceが残っていることを確認する。 tmux attach -t practiceで戻る。時刻の出力が続いていれば成功だ。
確認後、Ctrl+Cでループを止める。同じペインでtail ~/tmux-demo/ticks.logを実行すると、切断中の記録も確認できる。exitで最後のシェルを閉じると、練習セッションが終了する。
detachは画面から離れる操作、exitはシェルを終了する命令だ。 作業を残したいときは混同しないようにしよう。(tmuxのセッション動作)
6. Claude Code・Ollama・Hermesの作業環境を作る
以下はすべてSSHで接続したMac mini上で行う。まず練習用フォルダーとAIセッションを作成する。
mkdir -p ~/ai-work/demo
cd ~/ai-work/demo
tmux new -s ai -n claude
すでにaiがある場合は、tmux attach -t aiで入る。標準設定では最初のウィンドウ番号は0だ。
claudeウィンドウ:Claude Codeを実行
インストール済みならインストールコマンドは省く。以下はClaude Code公式ガイドのネイティブインストール方式だ。ダウンロードしたスクリプトを実行するため、配布元を確認して進める。
curl -fsSL https://claude.ai/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
claude --version
claude
初回は認証の案内に従う。リモート環境でブラウザーが開かない場合は、CLIに表示されたログインURLをノートPCのブラウザーで開き、その後のCLI手順を完了する。通常のClaudeサービスには、アカウントの利用資格と課金条件が適用される。
最初は「現在のフォルダーを確認し、ファイルを変更せずにできる作業を説明して」のような、確認しやすい依頼を試そう。コードやコマンドはMac miniで処理されるが、選択したモデル提供元がクラウドなら、推論はクラウドで行われる。
ollamaウィンドウ:モデルサーバーを実行
Claude Codeを終了せず、Ctrl+b → cで新しいウィンドウを作る。Ctrl+b → ,を押してollamaと名付ける。
CLI中心のインストールにはHomebrewのOllamaパッケージを使える。公式Ollamaアプリをすでに導入しているなら、重複インストールせず既存のollamaコマンドを使う。
brew install ollama
ollama --version
ollama serve
サーバーログが表示され、プロンプトに戻らないのは正常だ。このウィンドウでサーバーが動き続ける。アプリやサービスがすでに11434ポートを使っている場合は、重ねて起動しない。次の手順で既存APIを確認すればよい。
hermesウィンドウ:モデルを確認してエージェントを接続
もう一度Ctrl+b → cでウィンドウを作り、Ctrl+b → ,でhermesと名付ける。
cd ~/ai-work/demo
curl http://127.0.0.1:11434/api/tags
ollama pull qwen3:4b
ollama run qwen3:4b
APIからJSONが返ればサーバーに接続できている。モデルに短い質問をし、/byeで対話を終了する。qwen3:4bは小さな接続確認用の例で、すべてのコーディング作業への推奨ではない。ダウンロード容量と実際のメモリ使用量は異なり、コンテキスト長や同時実行数を増やすと必要メモリも増える。エージェント用途ではツール呼び出しへの対応と実作業の精度も確認する。
最近のOllamaでは、次のコマンドからHermesの導入とモデル接続の案内を始められる。(公式連携ドキュメント)
ollama launch hermes
ローカル推論が目的なら、モデル選択画面でダウンロード済みのローカルモデルを選ぶ。:cloudモデルはリモートで動く。メッセージサービスとの連携はこのCLI実習には不要なので、スキップしてよい。
Hermesを導入済み、または手動で設定したい場合は次の方法も使える。インストール後にコマンドが見つからなければ、新しいSSH接続を開いて続ける。
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
hermes model
モデル設定でOllamaまたはカスタムエンドポイントを選ぶ。手動入力はAPI URL http://127.0.0.1:11434/v1、モデル名qwen3:4b、ローカルOllamaのAPIキーは空欄が基本だ。メニュー表記はバージョンによって変わる。保存後、hermesを実行する。(Hermesローカルモデルガイド)
次の公式画面では、モデル名、ツール、スキルの一覧を確認できる。特にモデル名を見る習慣が重要だ。例のkimi-k2.5:cloudはクラウドモデルであり、上のローカルモデル実習の結果ではない。

Ollama公式Hermes連携ドキュメントの提供画面。表示されているバージョンやモデルは文書の例であり、現在の導入バージョンやローカル推論を示すものではない。(出典:Ollama、2026-10-25確認 · 原寸で見る)
Hermesにも、まず現在のフォルダーのファイル名だけを確認するよう依頼しよう。以前にターミナルバックエンドを別サーバーやコンテナーに変更していたら、実際のツール実行場所も確認する。モデルがローカルでも、Web検索・外部API・メッセージングのツールを使えば通信は発生し得る。
Claude CodeもOllamaのモデルで動かせるか
OllamaはClaude Code向けのAnthropic互換API連携も提供している。新しい練習ウィンドウで次を実行すると、モデルを選択できる。
ollama launch claude
これはClaude Codeというインターフェースで、選んだOllamaモデルを使う構成だ。ClaudeモデルそのものをMac miniにダウンロードするわけではない。ツール対応、推論品質、必要メモリは選択したモデルに依存する。公式の大きなコンテキスト推奨値を少メモリのMac miniにそのまま適用せず、小さな作業から確かめよう。(OllamaのClaude Code連携)
7. 日常で使うコマンドとショートカット
次のシェルコマンドはMac miniで入力する。-tは対象セッション、-sは作成するセッションの名前を指定する。
| コマンド | 用途 |
|---|---|
tmux new -s ai |
aiを作成して接続 |
tmux ls |
セッション一覧 |
tmux attach -t ai |
既存セッションに接続 |
tmux new -A -s ai |
あれば接続、なければ作成 |
tmux detach-client |
現在のクライアントを切り離す |
tmux rename-session -t ai ai-main |
セッション名変更 |
tmux list-windows -t ai |
ウィンドウ一覧 |
tmux kill-session -t practice |
練習セッションと中の処理を終了 |
kill-sessionは作業を終了させる命令だ。一時的に離れるためには使わない。kill-serverはすべてのセッションに影響するため、普段の復帰手順に入れない。
次は標準キー設定を前提とする。矢印の前でCtrl+bを離す。
| ショートカット | 動作 |
|---|---|
Ctrl+b → d |
作業を残してデタッチ |
Ctrl+b → c |
新規ウィンドウ |
Ctrl+b → , |
現在のウィンドウ名変更 |
Ctrl+b → n / p |
次 / 前のウィンドウ |
Ctrl+b → 0 … 9 |
番号のウィンドウへ移動 |
Ctrl+b → w |
一覧からウィンドウを選択 |
Ctrl+b → % |
左右に分割 |
Ctrl+b → " |
上下に分割 |
Ctrl+b → 矢印キー |
ペイン間を移動 |
Ctrl+b → z |
現在のペインを拡大 / 復元 |
Ctrl+b → [ |
スクロール・コピーモード |
Ctrl+b → ] |
tmuxバッファーを貼り付け |
Ctrl+b → : |
tmuxコマンド入力 |
Ctrl+b → ? |
キーのヘルプ。qで閉じる |
全コマンドとキーは、導入済みバージョンのman tmuxと公式マニュアルで確認しよう。
ノートPCから一度に接続するなら、次のように書く。-tは対話用の端末を割り当てる。
ssh -t macmini 'tmux new -A -s ai'
このときだけtmux: command not foundになるなら、非対話SSHコマンドのPATHが原因かもしれない。通常のSSH接続後にcommand -v tmuxで場所を確認し、Apple Silicon標準のHomebrewなら次のように指定する。
ssh -t macmini '/opt/homebrew/bin/tmux new -A -s ai'
8. 使いやすくする小さな設定
Mac miniでnano ~/.tmux.confを開き、以下を追加する。先ほどの実習と一致するよう、標準プレフィックスとウィンドウ番号は変更しない。
set -g mouse on
set -g history-limit 50000
setw -g mode-keys vi
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind r source-file ~/.tmux.conf
tmux内のシェルで次を実行して適用する。
tmux source-file ~/.tmux.conf
マウスでペインを選択・リサイズできる。Ctrl+b → |とCtrl+b → -は現在のパスで新しいペインを開き、Ctrl+b → cもパスを維持する。履歴の上限は新規ウィンドウ・ペインで確認しよう。
viコピーモードにはCtrl+b → [で入り、矢印キーで移動、Spaceで選択開始、Enterでコピーする。qで抜け、Ctrl+b → ]で貼り付ける。これはtmux内部のバッファーであり、必ずしもノートPCのクリップボードと同じではない。
短いテキスト結果をローカルMacのクリップボードに取りたいときは、ノートPCの新しいターミナルで次も使える。対象ウィンドウのアクティブペインの最近の履歴をコピーするので、秘密情報が含まれないか確認する。
ssh macmini '/opt/homebrew/bin/tmux capture-pane -p -S -200 -t ai:claude' | pbcopy
パスはcommand -v tmuxの結果に合わせる。pbcopyはSSHの引用符の外にあるため、ノートPCで実行される。さらに連携するならtmux公式Clipboardガイドを参照しよう。
9. モデルサーバーを安定して動かす
Mac miniをスリープさせない
ノートPCのスリープとMac miniのスリープは別問題だ。長時間の作業では、Mac miniのシステム設定で、ディスプレイ消灯時の自動スリープを防ぐ項目を確認する。メニューや選択肢は機種とmacOSによって異なる。(Appleのスリープ設定)
一時的には、Mac miniの別のtmuxウィンドウで次を実行する。
caffeinate -i
実行中はアイドルスリープを防ぎ、Ctrl+Cで終了すると解除される。手動スリープ、電源断、再起動まで防ぐものではない。接続中のtmuxクライアントだけにcaffeinateを結び付けると、ほかの作業が続いていてもデタッチと同時に効果が終わる場合がある。別ウィンドウで維持すると寿命を理解しやすい。
継続利用するOllamaはサービスへ
学習中はollama serveのログを直接見ると分かりやすい。継続運用なら、tmuxとは別にmacOSのサービス管理機構launchdを使う方法を検討する。Homebrewパッケージを導入した場合は、元のserveウィンドウでCtrl+Cを押して停止してから次を実行する。
brew services start ollama
brew services list
curl http://127.0.0.1:11434/api/tags
通常ユーザーで起動するHomebrewサービスはログイン時の自動起動だ。ログイン前の起動サービスとは異なり、再起動後のFileVault解除やユーザーログイン条件は別途確認する。sudoを付けてサービスの実行ユーザーを変えることを標準の解決策にしない。(Homebrewのサービス説明)
モデル確認にはollama listとollama ps、不要になったモデルをメモリから降ろすにはollama stop qwen3:4bを使う。stopはダウンロード済みモデルファイルの削除ではない。(Ollama CLI)
10. ノートPCからMac miniのOllama APIを使う
SSH内でollamaやHermesを使うときはトンネル不要だ。ノートPCのアプリやスクリプトからMac miniのモデルAPIを呼ぶときだけ、ローカル転送を追加する。
ノートPCの別ターミナルで次を実行し、開いたままにする。ノートPCにOllamaがあっても競合しないよう、ローカルポートを11435にしている。
ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:11435:127.0.0.1:11434 macmini
ノートPCのもう1つのターミナルで確認する。
curl http://127.0.0.1:11435/api/tags
最初の127.0.0.1:11435はノートPCの待ち受け先、後ろの127.0.0.1:11434はSSHサーバーであるMac miniからアクセスする先だ。ノートPCのアプリにはhttp://127.0.0.1:11435を設定し、OpenAI互換形式が必要なら/v1を付ける。Ollamaを0.0.0.0に公開したり、ルーターで11434を開いたりする必要はない。(OpenSSHローカル転送)
このトンネルはノートPCのSSHプロセスが維持する。切れたら再実行が必要で、リモートtmuxがノートPCのトンネルまで復旧するわけではない。
11. tmuxより合うツールはあるか
以下は公式機能に基づくこの記事の選択基準だ。あらゆる用途で優れた単一のツールがあるわけではない。
| ツール | 検討したい場面 | tmuxとの関係・制約 |
|---|---|---|
| tmux | SSH中心、キーボード操作、シェルで作業環境を構成 | プレフィックスの学習は必要だが、リモートCLIの出発点に向く |
| Zellij | キー操作の画面案内やレイアウトが欲しい | ターミナル作業環境の代替。キーモードとCLIアプリの競合を確認 |
| Mosh | Wi-Fi切り替え、モバイル回線、高遅延の接続 | 接続層を改善し、tmuxと併用可能。SSHポート転送の代替ではない |
| iTerm2のtmux統合 | ローカルMacのタブ・分割UIで操作したい | tmuxをサーバーとして使い、クライアントUIを変える |
| tmux-resurrect | 再起動後にウィンドウ・パス・配置を戻したい | 配置や一部プログラムの復元を補助。実行中モデルのメモリ保存ではない |
Zellijを比較したければ、Mac miniに導入して別セッションを作る。次はtmuxの外にあるリモートシェルで実行する。
brew install zellij
zellij --session ai-test
移動中の接続品質が問題なら、Moshを両方のコンピューターに導入して次のように使える。SSH認証後はUDPで通信するため、ファイアウォールやプライベートネットワークが必要なUDP通信を許可していることが条件だ。標準ポート範囲は60000–61000。
mosh your_user@192.168.0.20
tmux new -A -s ai
ポート転送には前節のSSHを別途使う。Moshも、Mac miniの再起動で失われたプロセスを復活させない。(Mosh公式説明)
ローカルターミナルがiTerm2なら、次の統合モードを試せる。他の一般的なターミナルにそのまま適用するオプションではない。
ssh -t macmini '/opt/homebrew/bin/tmux -CC new -A -s ai'
最初は標準SSH + tmuxを覚え、キー案内が欲しければZellij、移動中の切断が多ければMosh、Macのウィンドウ操作を好むならiTerm2統合を追加する順番を勧める。サーバーの自動起動は、別のサービス管理の問題として扱おう。
12. よくあるつまずき
| 症状 | 最初に確認すること |
|---|---|
| SSH接続拒否・タイムアウト | リモートログイン、ユーザー、実IP、電源・スリープ、ネットワーク到達性 |
Permission denied (publickey) |
リモートユーザー名、公開鍵登録、IdentityFile、.sshの権限 |
| tmux内だけコマンドが見つからない | インストール後のPATHが古いシェルに未反映か確認し、新しいシェルで試す |
sessions should be nested with care |
すでにtmux内か確認し、Ctrl+b → sでセッション選択 |
| スクロールでシェル履歴だけが動く | Ctrl+b → [でコピーモード、qで終了 |
| 韓国語・色・画面が崩れる | ローカルのUTF-8・フォント・terminfoを確認。この記事のCtrl+b → rは設定再読み込みであり画面修復ではない |
11434が使用済み |
既存Ollamaアプリ・サービスを確認し、重複起動を避ける |
| モデルが遅すぎる | ollama psとメモリ状態を確認し、モデル・コンテキスト・同時実行数を減らす |
| tmuxに戻るとエージェントが止まっている | 承認待ち、モデルエラー、通信エラーを確認 |
再起動後にno server running |
想定内。新しいtmuxセッションを作り、ツールの対話再開機能を使う |
Claude Codeのプロセスが終了した場合は、プロジェクトフォルダーでclaude -cを実行して最近の対話を続けるか、claude -rで選ぶ。動作中の画面に戻るtmux attachとは別の機能だ。(Claude Code CLI) Hermesの対話管理コマンドは、導入バージョンのhermes --helpと公式CLIガイドを確認する。
複数のエージェントを同時に使う場合も、同じファイルを上書きし合わないよう、作業フォルダーを分けるかGit worktreeを検討しよう。tmuxはターミナルを分けるだけで、ファイルの編集競合までは防がない。
13. 今日覚える最小の手順
初日は、SSHを閉じている間も練習ループが続くことを確認できれば十分だ。次に1つのツールを動かし、慣れたらウィンドウを増やす。
- ノートPCで
ssh macminiを実行する。 - Mac miniで
tmux new -A -s aiを実行する。 Ctrl+b → wで必要なツールのウィンドウを選ぶ。- 離れるときは
Ctrl+b → d、続いてexitを入力する。 - 戻ったら同じ2つの接続コマンドで以前の作業を確認する。
この流れに慣れれば、ノートPCを変えたりネットワークをつなぎ直したりしても、同じ方法でMac miniの作業環境を使える。次はHermes自動化実践を参考に、繰り返し作業を1つずつ追加していこう。

Si quieres que las tareas CLI del Mac mini sigan funcionando al cerrar el portátil, combina SSH con tmux. Esta guía explica la primera conexión, cómo volver a una sesión, cómo ejecutar Claude Code, Hermes y Ollama, los comandos básicos, la configuración y las alternativas.
El objetivo es sencillo: conectarte desde el portátil, ejecutar el trabajo en el Mac mini y regresar al mismo espacio cuando se corte la conexión. Hermes se refiere aquí a Hermes Agent, de Nous Research. Los comandos y las funciones se contrastaron con documentación oficial el 25 de octubre de 2026. No es una prueba completa de conexión a tu Mac mini remoto, autenticación de modelos e inferencia.
1. Qué hacen SSH, tmux y las herramientas de IA
| Componente | Función | Dónde se ejecuta en esta guía |
|---|---|---|
| OpenSSH | Acceso cifrado al shell de otro equipo | Cliente del portátil ↔ servidor del Mac mini |
| tmux | Mantiene sesiones, ventanas y paneles de terminal | Mac mini |
| Claude Code | Agente que lee código, edita archivos y ejecuta comandos | Directorio del proyecto en el Mac mini |
| Hermes Agent | Conecta modelos con herramientas, memoria y habilidades | Mac mini |
| Ollama | Ejecuta modelos locales y ofrece una API | Mac mini |
Laptop terminal
└─ SSH connection
└─ Mac mini
└─ tmux session: ai
├─ window: claude → Claude Code
├─ window: ollama → Ollama server
└─ window: hermes → Hermes → Ollama
Al terminar la conexión SSH, el servidor tmux y sus programas pueden seguir funcionando en el Mac mini. Basta con volver a entrar por SSH y adjuntarse a la sesión. Ejecutar tmux solo en el portátil y abrir SSH dentro no protege de la misma forma la duración de los procesos remotos. Aquí iniciamos tmux en el Mac mini después de conectarnos por SSH. (Introducción a tmux)
tmux no resuelve cualquier corte de internet, suspensión del Mac mini, reinicio o fallo de una aplicación. Si el Mac mini se duerme, el cálculo se detiene; al reiniciarlo, desaparecen los procesos existentes. Un agente que espera una respuesta del modelo o tu autorización tampoco puede saltarse esa espera automáticamente.
2. Sesiones, ventanas, paneles y tecla de prefijo
Una sesión (session) agrupa el trabajo; una ventana (window) se parece a una pestaña dentro de ella; un panel (pane) es una región de terminal dentro de una ventana dividida. Resulta práctico crear una sesión por proyecto, una ventana por herramienta y dividir paneles cuando necesitas ver registros junto a la tarea principal.
El ejemplo oficial siguiente reúne un editor, un shell y un manual en la misma ventana. Puedes aplicar la misma distribución a las herramientas de IA.

Ejemplo de paneles proporcionado por la documentación oficial Getting Started de tmux; no es el resultado de este tutorial de IA. (Fuente: tmux, consultado el 2026-10-25 · Ver imagen original)
El prefijo predeterminado es Ctrl+b. Pulsa ambas teclas, suéltalas y después pulsa la siguiente. Ctrl+b → d no significa pulsar las tres a la vez. En Mac también se utiliza Control, no Command.
Recuerda primero dos acciones: separarte con Ctrl+b → d y volver con tmux attach -t nombre.
3. Preparación: identifica en qué equipo escribes
Los comandos copiables suponen un Mac local con zsh/bash y un Mac mini remoto. Windows también puede conectarse mediante OpenSSH, pero la tubería para registrar la clave y el ejemplo con pbcopy son para macOS.
El Mac mini necesita alimentación, red, una cuenta de macOS accesible y Homebrew. Los ejemplos de instalación suponen Apple Silicon. En equipos Intel pueden variar la aceleración GPU de Ollama, los paquetes de Homebrew y la compatibilidad de Hermes; revisa primero sus requisitos oficiales. Tampoco des por hecho que la aplicación oficial de Ollama y Homebrew admiten las mismas versiones de macOS. (Guía de Ollama para macOS, instalación de Hermes)
Sustituye your_user por el nombre corto de la cuenta del Mac mini, y 192.168.0.20 por su dirección IP real. Haz la primera prueba con ambos equipos en la misma red.
En el Mac mini: activa el inicio de sesión remoto
Abre Ajustes del Sistema → General → Compartir → Sesión remota, actívala y especifica los usuarios autorizados. Comprueba también el comando SSH mostrado. El ejercicio básico no exige permitir a todos los usuarios ni dar acceso completo al disco. (Instrucciones de Apple)
Para configurarlo por CLI, ejecuta esto directamente en el Mac mini. Si el entorno exige permisos de administrador o acceso completo al disco para el terminal, puede ser más sencillo usar Ajustes del Sistema.
sudo systemsetup -getremotelogin
sudo systemsetup -setremotelogin on
whoami
En el portátil: primera conexión SSH
ssh your_user@192.168.0.20
Compara la huella de la clave del servidor mostrada al conectar con la obtenida en el Mac mini mediante ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub. Es normal que no se vean caracteres al escribir la contraseña. Tras entrar, comprueba equipo y usuario con hostname y whoami. Escribe exit para volver al portátil.
Fuera de casa, esa IP privada normalmente no será accesible directamente. Sigue el inicio rápido oficial de Tailscale para unir ambos dispositivos a la misma red privada; después usa la IP o el nombre Tailscale del Mac mini para acceder a su servidor SSH existente de macOS. No es obligatorio activar la función independiente Tailscale SSH. Así puedes evitar configurar manualmente el reenvío del puerto SSH en el router.
4. Crea una clave SSH y un alias de conexión
Genera una clave dedicada en el portátil. Si el archivo ya existe, reutilízalo o elige otro nombre, sin sobrescribirlo. Configura también una frase de contraseña.
ssh-keygen -t ed25519 -f ~/.ssh/macmini_ed25519 -C "macmini-access"
cat ~/.ssh/macmini_ed25519.pub | ssh your_user@192.168.0.20 'umask 077; mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys; chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys'
ssh -i ~/.ssh/macmini_ed25519 your_user@192.168.0.20
Se registra la clave pública .pub. La clave privada, sin esa extensión, se queda en el portátil. Confirma que el último comando permite entrar y vuelve con exit.
En el portátil, abre nano ~/.ssh/config y añade este bloque sin borrar contenido existente. En nano, guarda con Ctrl+O, luego Enter, y cierra con Ctrl+X.
Host macmini
HostName 192.168.0.20
User your_user
IdentityFile ~/.ssh/macmini_ed25519
IdentitiesOnly yes
ServerAliveInterval 30
ServerAliveCountMax 3
chmod 600 ~/.ssh/config
ssh macmini
Ahora puedes escribir macmini en lugar de la dirección. ServerAliveInterval solicita periódicamente una respuesta al servidor. Ayuda a detectar problemas de conexión, pero no restablece una conexión interrumpida. (Manual de configuración OpenSSH)
5. Primer ejercicio: deja una tarea y vuelve a ella
En el Mac mini: instala tmux
Si falta Homebrew, sigue el comando de instalación actual y las instrucciones posteriores de su sitio oficial. En una instalación estándar de Apple Silicon, si no se encuentra brew, ejecuta eval "$(/opt/homebrew/bin/brew shellenv)" en el shell actual. Añade la configuración a ~/.zprofile según las indicaciones del instalador para futuros inicios de sesión.
brew install tmux
tmux -V
tmux new -s practice
Una barra de estado inferior indica que estás dentro de tmux. En esa sesión, inicia una tarea de práctica que registre continuamente la hora.
mkdir -p ~/tmux-demo
while true; do date; sleep 2; done | tee -a ~/tmux-demo/ticks.log
Desconecta y vuelve en este orden:
- Pulsa
Ctrl+b → d. Regresas al shell normal del Mac mini y la tarea continúa. - Escribe
exitpara cerrar SSH. Ya estás en el shell del portátil. - Tras un momento, ejecuta
ssh macminien el portátil. - En el Mac mini, usa
tmux lspara comprobar que sigue existiendopractice. - Ejecuta
tmux attach -t practice. Si continúan apareciendo horas, ha funcionado.
Al terminar, detén el bucle con Ctrl+C. En ese mismo panel, tail ~/tmux-demo/ticks.log permite revisar los registros del intervalo desconectado. Con exit cierras el último shell y terminas la sesión de práctica.
Detach separa tu vista; exit termina un shell. No confundas ambas acciones al dejar trabajo real en marcha. (Comportamiento de las sesiones tmux)
6. Crea el espacio de Claude Code, Ollama y Hermes
Realiza todos estos pasos en el Mac mini conectado por SSH. Primero crea un directorio de práctica y una sesión para IA.
mkdir -p ~/ai-work/demo
cd ~/ai-work/demo
tmux new -s ai -n claude
Si ai ya existe, entra con tmux attach -t ai. Con la configuración predeterminada, la primera ventana tiene el número 0.
Ventana claude: ejecuta Claude Code
Omite la instalación si ya está instalado. Este es el método nativo de la guía oficial de Claude Code. El comando ejecuta un script descargado; confirma su procedencia antes de continuar.
curl -fsSL https://claude.ai/install.sh | bash
export PATH="$HOME/.local/bin:$PATH"
claude --version
claude
Sigue la autenticación del primer inicio. Si el navegador no se abre en el entorno remoto, abre la URL mostrada por la CLI en el navegador del portátil y completa las instrucciones restantes. El servicio estándar de Claude se rige por los permisos de uso y la facturación de tu cuenta.
Empieza con una petición fácil de comprobar: «Revisa el directorio actual y explica qué puedes hacer sin modificar archivos». El código y los comandos se procesan en el Mac mini, pero si el proveedor de modelos elegido es un servicio en la nube, la inferencia ocurre en la nube.
Ventana ollama: ejecuta el servidor del modelo
Sin cerrar Claude Code, pulsa Ctrl+b → c para crear otra ventana. Usa Ctrl+b → , y llámala ollama.
Para una instalación centrada en CLI puedes usar la fórmula Ollama de Homebrew. Si ya instalaste la aplicación oficial de Ollama, usa su comando ollama existente y evita una segunda instalación.
brew install ollama
ollama --version
ollama serve
Es normal ver registros del servidor sin recuperar el prompt: el servidor continúa en esa ventana. Si una aplicación o servicio ya ocupa el puerto 11434, no inicies otro. Comprueba la API existente en el paso siguiente.
Ventana hermes: comprueba el modelo y conecta el agente
Crea otra ventana con Ctrl+b → c y llámala hermes mediante Ctrl+b → ,.
cd ~/ai-work/demo
curl http://127.0.0.1:11434/api/tags
ollama pull qwen3:4b
ollama run qwen3:4b
Si la API devuelve JSON, la conexión al servidor funciona. Haz una pregunta breve y termina la conversación con /bye. qwen3:4b es un ejemplo pequeño para comprobar la conexión, no una recomendación para todas las tareas de programación. El tamaño de descarga y la memoria utilizada son distintos; más contexto y más ejecuciones simultáneas requieren más memoria. Para agentes, comprueba también las llamadas a herramientas y la precisión en tareas reales.
Las versiones recientes de Ollama pueden guiar la instalación de Hermes y la conexión del modelo con este comando. (Guía oficial de integración)
ollama launch hermes
Si buscas inferencia local, selecciona un modelo local descargado. Un modelo :cloud se ejecuta de forma remota. La integración con mensajería no es necesaria para este ejercicio CLI y puedes omitirla.
Si ya tienes Hermes o prefieres configurarlo manualmente, también puedes seguir esta ruta. Abre otra conexión SSH si el comando no aparece después de instalarlo.
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
hermes model
Selecciona Ollama o un endpoint personalizado en la configuración del modelo. Para la entrada manual, usa URL de API http://127.0.0.1:11434/v1, modelo qwen3:4b y deja vacía la clave API de Ollama local. Las etiquetas del menú pueden cambiar según la versión. Guarda y ejecuta hermes. (Guía de modelos locales de Hermes)
La pantalla oficial siguiente muestra el modelo, las herramientas y las habilidades. Acostúmbrate a comprobar el nombre del modelo: kimi-k2.5:cloud en la imagen es un modelo en la nube, no el resultado del ejercicio local anterior.

Pantalla proporcionada por la documentación oficial de integración de Hermes con Ollama. La versión y el modelo son ejemplos documentales, no la versión instalada actual ni una prueba de inferencia local. (Fuente: Ollama, consultado el 2026-10-25 · Ver imagen original)
Pide también a Hermes que primero solo enumere los archivos del directorio actual. Si antes cambiaste su backend de terminal a otro servidor o contenedor, verifica dónde se ejecutan las herramientas. Aunque el modelo sea local, la búsqueda web, las API externas y la mensajería pueden generar tráfico de red.
¿Puede Claude Code usar también un modelo de Ollama?
Ollama ofrece una integración de API compatible con Anthropic para Claude Code. En una ventana de práctica nueva puedes elegir el modelo con:
ollama launch claude
Esta configuración significa usar un modelo de Ollama a través de la interfaz de Claude Code. No descarga el modelo Claude al Mac mini. El soporte de herramientas, la calidad del razonamiento y la memoria necesaria dependen del modelo seleccionado. No apliques automáticamente las recomendaciones oficiales de contexto amplio a un Mac mini con poca memoria: prueba primero una tarea pequeña. (Integración de Claude Code con Ollama)
7. Comandos y atajos cotidianos
Escribe estos comandos en el Mac mini. -t indica la sesión de destino; -s, el nombre de la sesión que vas a crear.
| Comando | Uso |
|---|---|
tmux new -s ai |
Crear y entrar en ai |
tmux ls |
Listar sesiones |
tmux attach -t ai |
Entrar en una sesión existente |
tmux new -A -s ai |
Entrar si existe; crear si falta |
tmux detach-client |
Separar el cliente actual |
tmux rename-session -t ai ai-main |
Cambiar el nombre de una sesión |
tmux list-windows -t ai |
Listar ventanas |
tmux kill-session -t practice |
Terminar la sesión de práctica y sus tareas |
kill-session termina el trabajo; no lo uses para ausentarte un momento. kill-server afecta a todas las sesiones y no debe formar parte de una reconexión rutinaria.
Estos atajos suponen la configuración predeterminada. Suelta Ctrl+b antes de pulsar la tecla que sigue a la flecha.
| Atajo | Acción |
|---|---|
Ctrl+b → d |
Separarte dejando el trabajo en marcha |
Ctrl+b → c |
Nueva ventana |
Ctrl+b → , |
Renombrar la ventana actual |
Ctrl+b → n / p |
Ventana siguiente / anterior |
Ctrl+b → 0 … 9 |
Ir al número de ventana |
Ctrl+b → w |
Elegir en la lista de ventanas |
Ctrl+b → % |
Dividir a izquierda y derecha |
Ctrl+b → " |
Dividir arriba y abajo |
Ctrl+b → tecla de dirección |
Cambiar de panel |
Ctrl+b → z |
Ampliar / restaurar el panel |
Ctrl+b → [ |
Entrar en modo de desplazamiento y copia |
Ctrl+b → ] |
Pegar el búfer de tmux |
Ctrl+b → : |
Introducir un comando tmux |
Ctrl+b → ? |
Mostrar ayuda de teclas; salir con q |
Consulta man tmux de tu versión instalada y el manual oficial para la referencia completa.
Para entrar con un solo comando desde el portátil, utiliza lo siguiente. -t asigna un terminal interactivo.
ssh -t macmini 'tmux new -A -s ai'
Si únicamente este comando devuelve tmux: command not found, puede deberse al PATH de los comandos SSH no interactivos. Entra normalmente y consulta command -v tmux. Con Homebrew en su ubicación predeterminada de Apple Silicon, usa:
ssh -t macmini '/opt/homebrew/bin/tmux new -A -s ai'
8. Pequeños ajustes para trabajar mejor
En el Mac mini, abre nano ~/.tmux.conf y añade esta configuración. Mantén el prefijo y la numeración predeterminados para que coincidan con el ejercicio anterior.
set -g mouse on
set -g history-limit 50000
setw -g mode-keys vi
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
bind c new-window -c "#{pane_current_path}"
bind r source-file ~/.tmux.conf
Aplícala desde un shell dentro de tmux:
tmux source-file ~/.tmux.conf
Puedes seleccionar paneles y cambiar su tamaño con el ratón. Ctrl+b → | y Ctrl+b → - abren paneles en el directorio actual; Ctrl+b → c también conserva ese directorio. Comprueba el límite del historial en ventanas o paneles recién creados.
Entra en el modo de copia vi con Ctrl+b → [, muévete con las flechas, inicia la selección con Space y copia con Enter. Sal con q y pega con Ctrl+b → ]. Es el búfer interno de tmux, que no siempre coincide con el portapapeles del portátil.
Para llevar un resultado de texto breve al portapapeles local del Mac, ejecuta esto en un terminal nuevo del portátil. Copia el historial reciente del panel activo de la ventana indicada; comprueba que no incluya secretos.
ssh macmini '/opt/homebrew/bin/tmux capture-pane -p -S -200 -t ai:claude' | pbcopy
Ajusta la ruta según command -v tmux. Como pbcopy está fuera de las comillas SSH, se ejecuta en el portátil. Para otras opciones de integración, consulta la guía oficial Clipboard de tmux.
9. Mantén disponible el servidor de modelos
Evita que el Mac mini se duerma
Que se duerma el portátil no es lo mismo que se duerma el Mac mini. Para tareas largas, revisa en el Mac mini la opción que evita la suspensión automática cuando la pantalla está apagada. La ubicación y las opciones dependen del equipo y de macOS. (Ajustes de suspensión de Apple)
Como medida temporal, ejecuta lo siguiente en otra ventana tmux del Mac mini:
caffeinate -i
Evita la suspensión por inactividad mientras se ejecuta; Ctrl+C libera la restricción. No impide la suspensión manual, un corte eléctrico ni un reinicio. Si vinculas caffeinate solo al cliente tmux conectado, al separarte puede terminar también la protección, aunque continúen otras tareas. Una ventana independiente facilita entender su duración.
Convierte Ollama en servicio para el uso habitual
Durante el aprendizaje resulta útil observar los registros de ollama serve. Para uso continuo, considera ejecutarlo mediante launchd, el gestor de servicios de macOS, independientemente de tmux. Si instalaste la fórmula Homebrew, detén antes el servidor existente con Ctrl+C en su ventana, y después ejecuta:
brew services start ollama
brew services list
curl http://127.0.0.1:11434/api/tags
Un servicio Homebrew iniciado como usuario normal se configura para arrancar al iniciar sesión. No equivale a un servicio de arranque previo al login; revisa por separado el desbloqueo de FileVault y los requisitos de inicio de sesión tras reiniciar. Añadir sudo para cambiar la cuenta del servicio no debería ser la solución predeterminada. (Servicios de Homebrew)
Consulta los modelos con ollama list y ollama ps; descarga de memoria un modelo innecesario con ollama stop qwen3:4b. Detenerlo no borra los archivos descargados. (CLI de Ollama)
10. Usa desde el portátil la API de Ollama del Mac mini
No necesitas un túnel para ejecutar ollama o Hermes dentro de SSH. Añade reenvío local solo cuando una aplicación o script del portátil necesite llamar a la API del Mac mini.
Ejecuta esto en otro terminal del portátil y déjalo abierto. El puerto local 11435 evita conflictos si ya tienes Ollama en el portátil.
ssh -N -o ExitOnForwardFailure=yes -L 127.0.0.1:11435:127.0.0.1:11434 macmini
Compruébalo desde un terminal adicional del portátil:
curl http://127.0.0.1:11435/api/tags
El primer 127.0.0.1:11435 es la dirección de escucha del portátil; el segundo 127.0.0.1:11434 se alcanza desde el servidor SSH, el Mac mini. Configura la aplicación local con http://127.0.0.1:11435 y añade /v1 si necesita un endpoint compatible con OpenAI. No hace falta exponer Ollama en 0.0.0.0 ni abrir el puerto 11434 del router. (Reenvío local de OpenSSH)
Este túnel depende del proceso SSH del portátil. Si se corta, debes iniciarlo otra vez; tmux remoto no restaura el túnel del portátil.
11. ¿Puede encajar mejor otra herramienta?
Estos criterios son una valoración del artículo basada en funciones documentadas oficialmente. No hay una herramienta superior para todos los casos.
| Herramienta | Cuándo considerarla | Relación con tmux y límites |
|---|---|---|
| tmux | Trabajo centrado en SSH, teclado y espacios definidos por scripts | Hay que aprender el prefijo, pero es un buen punto de partida para CLI remota |
| Zellij | Prefieres indicaciones de teclas visibles y diseños de paneles | Espacio de terminal alternativo; revisa conflictos entre modos de teclado y aplicaciones CLI |
| Mosh | Cambias de Wi-Fi, usas red móvil o tienes mucha latencia | Mejora la conexión y se combina con tmux; no sustituye el reenvío SSH |
| Integración tmux de iTerm2 | Quieres pestañas y paneles nativos en el Mac local | Utiliza tmux como servidor y cambia la interfaz del cliente |
| tmux-resurrect | Quieres restaurar ventanas, directorios y distribución tras reiniciar | Ayuda con diseños y algunos programas; no guarda la memoria de un modelo en ejecución |
Para comparar Zellij, instálalo en el Mac mini y crea otra sesión. Ejecuta estos comandos en un shell remoto fuera de tmux.
brew install zellij
zellij --session ai-test
Si el problema es la conexión durante desplazamientos, instala Mosh en ambos equipos y prueba lo siguiente. Se autentica por SSH y después utiliza UDP; la red privada o el cortafuegos deben permitir ese tráfico. El rango predeterminado es 60000–61000.
mosh your_user@192.168.0.20
tmux new -A -s ai
Para reenviar puertos, sigue utilizando SSH por separado. Mosh tampoco revive procesos perdidos al reiniciar el Mac mini. (Información oficial de Mosh)
Si tu terminal local es iTerm2, puedes probar este modo integrado. No es una opción para aplicar sin más en otros terminales.
ssh -t macmini '/opt/homebrew/bin/tmux -CC new -A -s ai'
Empieza por SSH convencional y tmux. Después considera Zellij para las indicaciones de teclas, Mosh para conexiones móviles inestables o iTerm2 para controles de ventana del Mac. Trata el inicio automático del servidor como un asunto independiente de gestión de servicios.
12. Problemas frecuentes
| Síntoma | Qué comprobar primero |
|---|---|
| SSH rechaza la conexión o agota el tiempo | Sesión remota, usuario, IP real, alimentación y suspensión del Mac mini, y acceso de red |
Permission denied (publickey) |
Usuario remoto, clave pública registrada, IdentityFile y permisos de .ssh |
| El comando falta solo dentro de tmux | El shell antiguo puede no incluir el nuevo PATH de instalación; prueba uno nuevo |
sessions should be nested with care |
Comprueba si ya estás en tmux y elige sesión con Ctrl+b → s |
| El desplazamiento mueve solo el historial del shell | Entra en copia con Ctrl+b → [ y sal con q |
| Texto coreano, colores o pantalla incorrectos | Comprueba UTF-8, fuentes y terminfo; aquí Ctrl+b → r recarga la configuración, no repara la pantalla |
El puerto 11434 está ocupado |
Revisa la aplicación o servicio Ollama existente y evita duplicados |
| El modelo es demasiado lento | Consulta ollama ps y la memoria; reduce tamaño del modelo, contexto o concurrencia |
| El agente parece detenido al volver | Revisa solicitudes de autorización, errores del modelo o de red |
no server running tras reiniciar |
Es normal: crea otra sesión tmux y usa la reanudación de conversaciones de la herramienta |
Si Claude Code terminó, usa claude -c en el proyecto para continuar la conversación reciente o claude -r para elegir una. Es distinto de tmux attach, que vuelve a un terminal todavía activo. (CLI de Claude Code) Para gestionar conversaciones de Hermes, consulta hermes --help de tu versión y su guía CLI oficial.
Aunque ejecutes varios agentes a la vez, separa los directorios o considera Git worktrees para que no sobrescriban los mismos archivos. tmux separa terminales; no evita conflictos de edición.
13. La rutina mínima para empezar hoy
El primer día basta con comprobar que el bucle de práctica continúa mientras SSH está cerrado. Después ejecuta una herramienta y añade ventanas cuando te resulte cómodo.
- Ejecuta
ssh macminien el portátil. - Ejecuta
tmux new -A -s aien el Mac mini. - Elige la ventana de la herramienta con
Ctrl+b → w. - Antes de irte, pulsa
Ctrl+b → dy luego escribeexit. - Al volver, utiliza los mismos dos comandos de conexión para revisar el trabajo anterior.
Con esta rutina podrás acceder al mismo espacio del Mac mini aunque cambies de portátil o restablezcas la red. Después puedes añadir tareas recurrentes una a una, como en la guía práctica de automatización con Hermes.