cmux workspace helpers: open a new workspace running a named, remote-controlled Claude Code session, and inject slash commands into already-running panes (one session or broadcast to all)

Install

/plugin install cmux-tools@powdream-plugins

Run it inside Claude Code after adding the marketplace with /plugin marketplace add powdream/claude-plugins.

Contents

Discovered from source

Skills 2

cmux-new-workspace

Create a new cmux workspace on a chosen project directory, boot Claude Code in it, and drive the fresh TUI through /rename <name> and /rc — so the session lands named and remote-controllable without the user typing anything.

CMUX binary: /Applications/cmux.app/Contents/Resources/bin/cmux

For a bare workspace with no agent in it, just run cmux new-workspace directly; this skill is for the full launch sequence.

Step 1 — Resolve the target directory

In priority order:

  1. Explicit path in the prompt — use it as-is, skip the scan.
  2. Project name, not a path — run the scan below, then match the name against the candidate paths: basename first, then substring. A single match is used directly; zero or several matches fall through to the picker.
  3. Nothing given — show the picker.

The scan

Rank by Claude Code session recency, read from ~/.claude/projects.

Do not use ~/.claude.json for this. Its projects map cannot order by recency: most entries carry no lastSessionModified at all, and worktree directories never appear there. The session logs are the reliable source — each *.jsonl transcript carries a cwd field with the original absolute path. The containing directory's name is useless on its own, because the encoding collapses /, -, and . all into - and cannot be decoded back.

python3 <<'PY'
import datetime, glob, json, os

base = os.path.expanduser('~/.claude/projects')
here = os.getcwd()
rows = []

for entry in os.listdir(base):
    project = os.path.join(base, entry)
    if not os.path.isdir(project):
        continue
    logs = glob.glob(os.path.join(project, '*.jsonl'))
    if not logs:
        continue
    newest = max(logs, key=os.path.getmtime)
    cwd = None
    with open(newest, errors='replace') as f:
        for line in f:
            try:
                obj = json.loads(line)
            except ValueError:
                continue
            if isinstance(obj, dict) and obj.get('cwd'):
                cwd = obj['cwd']
                break
    if cwd and os.path.isdir(cwd):
        rows.append((os.path.getmtime(newest), cwd))

rows.sort(reverse=True)
seen, out = set(), []
for mtime, cwd in rows:
    if cwd in seen:
        continue
    seen.add(cwd)
    out.append((mtime, cwd))

if not out:
    print('(no candidates)')
for i, (mtime, cwd) in enumerate(out[:10], 1):
    stamp = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M')
    tag = '   <- current session' if cwd == here else ''
    print(f'{i:2}. {stamp}  {cwd}{tag}')
PY

Print the table and ask the user to pick a number. The current session's own directory stays in the list — opening a second workspace on the same directory is a legitimate thing to do.

If the scan prints (no candidates), ask the user for a path outright.

Step 2 — Ask for the session name

Always ask; never infer it from the branch or directory. The answer is used twice: as the /rename argument and as the cmux workspace --name.

Step 3 — Pick the launch command

Default is claude. Use claude --continue only when the user explicitly asked to resume ("이어서", "resume", "--continue"). Do not ask otherwise.

Step 4 — Create the workspace and wait for the TUI

Fill in the three variables from steps 1-3, then run this block. It stops at one of three states and prints the state on the last line.

CMUX=/Applications/cmux.app/Contents/Resources/bin/cmux

DIR="<resolved path>"
NAME="<session name>"
LAUNCH="claude"          # or "claude --continue"

[ -x "$CMUX" ] || { echo "ABORT: cmux binary not found at $CMUX"; exit 1; }
[ -d "$DIR" ]  || { echo "ABORT: no such directory: $DIR"; exit 1; }

# Create the workspace. stdout is "OK workspace:<n>".
WS=$("$CMUX" new-workspace --name "$NAME" --cwd "$DIR" --command "$LAUNCH" --focus true | awk '{print $2}')
[ -n "$WS" ] || { echo "ABORT: new-workspace produced no workspace ref"; exit 1; }

# Resolve the surface to type into, plus its window.
PANELS=$("$CMUX" --json list-panels --workspace "$WS")
SURF=$(printf '%s' "$PANELS" | python3 -c 'import json,sys; print(json.load(sys.stdin)["surfaces"][0]["ref"])')
WIN=$(printf  '%s' "$PANELS" | python3 -c 'import json,sys; print(json.load(sys.stdin)["window_ref"])')
echo "workspace=$WS surface=$SURF window=$WIN cwd=$DIR"

# Wait until the TUI actually accepts input. Read the screen — do NOT poll for the
# claude process, which appears ~1s in, long before the input box is live and also
# while a blocking prompt is on screen.
STATE=timeout
for _ in $(seq 60); do
  SCREEN=$("$CMUX" read-screen --window "$WIN" --surface "$SURF" 2>/dev/null)
  if printf '%s' "$SCREEN" | grep -q "one you trust"; then
    STATE=trust-prompt
    break
  fi
  if printf '%s' "$SCREEN" | grep -qE "shift\+tab to cycle|\? for shortcuts"; then
    STATE=ready
    break
  fi
  sleep 1
done
echo "STATE=$STATE"

Branch on the last line:

  • STATE=ready → go to Step 5.
  • STATE=trust-prompt → go to Step 4a first.
  • STATE=timeout → stop. Leave the workspace open, say the injection did not happen, and print /rename <name> and /rc for the user to type themselves.

Step 4a — Trust prompt (only when STATE=trust-prompt)

Claude is showing:

❯ 1. Yes, I trust this folder
  2. No, exit

Ask the user before answering it. Use AskUserQuestion, quote the directory, and make the two outcomes explicit — accepting grants Claude read, edit, and execute rights in that folder from now on, so it is the user's call, not yours.

  • Approved → send Enter (option 1 is preselected), then poll for readiness again with the block below, and continue to Step 5.
  • Declined → send nothing. Leave the prompt on screen and tell the user the workspace is open at <dir> with the question still waiting; they can answer it or close the workspace.

Shell variables do not survive between blocks, so re-declare SURF/WIN from the values Step 4 printed.

CMUX=/Applications/cmux.app/Contents/Resources/bin/cmux
SURF="<surface from step 4>"
WIN="<window from step 4>"

"$CMUX" send-key --window "$WIN" --surface "$SURF" enter

STATE=timeout
for _ in $(seq 60); do
  if "$CMUX" read-screen --window "$WIN" --surface "$SURF" 2>/dev/null \
     | grep -qE "shift\+tab to cycle|\? for shortcuts"; then
    STATE=ready
    break
  fi
  sleep 1
done
echo "STATE=$STATE"

Step 5 — Inject and verify

CMUX=/Applications/cmux.app/Contents/Resources/bin/cmux
SURF="<surface from step 4>"
WIN="<window from step 4>"
NAME="<session name>"

"$CMUX" send     --window "$WIN" --surface "$SURF" -- "/rename $NAME"
"$CMUX" send-key --window "$WIN" --surface "$SURF" enter
sleep 2
"$CMUX" send     --window "$WIN" --surface "$SURF" -- "/rc"
"$CMUX" send-key --window "$WIN" --surface "$SURF" enter
sleep 3

# Verify the rename: Claude labels the input box's top border with the session name.
if "$CMUX" read-screen --window "$WIN" --surface "$SURF" 2>/dev/null | grep -qF "$NAME"; then
  echo "OK: renamed to '$NAME'; /rc sent."
else
  echo "WARN: '$NAME' is not on screen — /rename may not have landed. Check the pane."
fi

Notes on the mechanics:

  • --cwd puts the shell in the target directory directly; no follow-up cd.
  • --command sends text+Enter to the new workspace after it is created.
  • --window is required alongside a short surface:<n> ref. Without it the ref resolves against $CMUX_WORKSPACE_ID — the caller's own workspace — and the commands land in the wrong pane.
  • /rename takes its argument inline, so it is one line, not two.
  • Readiness must come from read-screen, not from process presence. The claude process shows up in cmux top about a second after launch, while the screen is still the trust-folder prompt (❯ 1. Yes, I trust this folder). Typing /rename … + Enter there answers that prompt instead. Both footer markers grepped above (shift+tab to cycle, ? for shortcuts) are rendered by Claude Code itself, so they work on any machine.
  • Do not verify against the status line. Strings like session:<name> or an /rc indicator come from a user-configured statusLine script, not from Claude Code — they are absent on a default setup. The input box border label is built in, so that is what the check above greps for.
  • Never answer the trust prompt on your own initiative. Accepting it grants Claude read, edit, and execute rights in that folder from then on — that is the user's decision. Ask first (Step 4a); send Enter only after they approve.
  • /rc is sent but not verified — there is no portable on-screen signal for it. Report it as sent, not as confirmed.

Step 6 — Report

Echo the resolved path, the session name, and the workspace/surface refs. Say plainly whether the injection succeeded; on timeout, say the workspace is open but the two commands were not sent. If the trust prompt came up, say whether the user approved it.

Failure handling

ConditionBehavior
cmux binary missingAbort before creating anything
Chosen path does not existAbort; never substitute a different directory
Scan returns nothingAsk the user for a path directly
Trust-folder prompt shownAsk the user; send Enter only if approved, otherwise leave it untouched
Readiness poll times outLeave the workspace open, report that injection did not happen
Name not on screen afterReport the warning as-is; do not claim the rename worked

Never claim the session was renamed or remote control started without the commands having actually been sent.

Related

  • worktree-cmux-workspace — new workspace for the git worktree in progress, no agent launch.
  • worktree-cmux-split — same, but as a split pane in the current workspace.
  • cmux-slash — inject a slash command into an already-running Claude pane.

cmux-slash

Run a Claude Code slash command (/context, /status, /reload-skills, …) that remote control can't open, by typing it directly into a local cmux pane via the cmux CLI. The command executes in the real TUI; view the result through cmux pane mirroring (this skill does NOT read output back into the conversation).

CMUX binary: /Applications/cmux.app/Contents/Resources/bin/cmux

Pick a mode

  • Own pane (default → Mode A) — inject into THIS session's pane. Use for commands about this session: /context, /status, /cost, /model, /compact.
  • Broadcast (Mode B) — inject into EVERY running Claude pane at once. Use when the user says "모든 claude", "전부", "all sessions", "every claude" — typically /reload-skills after editing a skill.

What command to send

Passthrough — send whatever slash command the user names, including arguments (/model opus, /config). Normalize a single leading slash (accept context or /context; send /context).

Mode A — own pane

The target is always this session's own pane, identified by $CMUX_SURFACE_ID (cmux auto-sets it as the default --surface; it points to the pane this Claude process runs in).

Note: the worktree-cmux-* skills deliberately AVOID $CMUX_SURFACE_ID because their goal is the pane the user is looking at (identify.focused), which differs from Claude's own pane. Here the goal is the opposite — Claude's own pane — so $CMUX_SURFACE_ID is exactly right. Do not import that warning.

CMUX=/Applications/cmux.app/Contents/Resources/bin/cmux

# 1. Guard: must be inside a cmux terminal.
if [ -z "$CMUX_SURFACE_ID" ]; then
  echo "ABORT: \$CMUX_SURFACE_ID is empty — not running inside a cmux pane."
  exit 1
fi

# 2. Transparency: echo the target surface + its title so the user can confirm.
title=$("$CMUX" tree --all 2>/dev/null | grep '◀ here' | grep -oE '"[^"]+"' | head -1)
echo "target surface: $CMUX_SURFACE_ID  ${title:-(title unknown)}"

# 3. Type the command, then commit it with Enter.
CMD="/context"   # <- the normalized command the user asked for
"$CMUX" send     --surface "$CMUX_SURFACE_ID" -- "$CMD"
"$CMUX" send-key --surface "$CMUX_SURFACE_ID" enter

echo "sent: $CMD"

$CMUX_SURFACE_ID is a UUID, so it resolves without --window/--workspace context.

Mode B — broadcast to every Claude pane

Detect every pane running Claude Code and fire the command into each (this pane included).

  • Detection. A Claude pane is a cmux top process row whose parent is a surface:N and whose command label is a version string (2.1.177).
  • Window context. Short surface refs (surface:5) resolve only within a --window; without it they mis-resolve against $CMUX_WORKSPACE_ID. Map each surface→window from cmux --json tree, then pass --window on every send/send-key.

Set FIRE=0 to preview the target list, then FIRE=1 to send. The block below prints the targets before sending either way. For destructive commands (/clear, /compact, /logout, /exit), run FIRE=0 and confirm with the user first — broadcast hits every running agent.

CMUX=/Applications/cmux.app/Contents/Resources/bin/cmux
CMUX="$CMUX" CMD="/reload-skills" FIRE=1 python3 <<'PY'
import os, re, subprocess, json
CMUX=os.environ["CMUX"]; CMD=os.environ["CMD"]; FIRE=os.environ["FIRE"]=="1"
def run(*a): return subprocess.run([CMUX, *a], capture_output=True, text=True)

# surface -> window / title, from structured tree
tree = json.loads(run("--json", "tree", "--all").stdout)
surf2win, surf2title = {}, {}
for win in tree.get("windows", []):
    for ws in win.get("workspaces", []):
        for pane in ws.get("panes", []):
            for s in pane.get("surfaces", []):
                surf2win[s["ref"]] = win["ref"]
                surf2title[s["ref"]] = s.get("title", "")
own = tree.get("caller", {}).get("surface_ref")

# claude panes: process rows parented to a surface, whose command is a version
VER = re.compile(r'^\d+\.\d+\.\d+')
targets = []
for line in run("top", "--all", "--processes", "--flat", "--format", "tsv").stdout.splitlines():
    f = line.split("\t")
    if len(f) >= 7 and f[3] == "process" and f[5].startswith("surface:") and VER.match(f[6].strip()):
        targets.append((f[5], surf2win.get(f[5], "window:1")))
targets.sort(key=lambda t: int(t[0].split(":")[1]))

print(f"{CMD}  own={own}  claude panes: {len(targets)}")
for ref, win in targets:
    print(f"  {ref:<11} {win:<9} {'[self]' if ref == own else '      '} {surf2title.get(ref, '')}")

if not FIRE:
    print("DRY-RUN: nothing sent.")
    raise SystemExit

print("--- sending ---")
ok = 0
for ref, win in targets:
    a = run("send",     "--window", win, "--surface", ref, "--", CMD)
    b = run("send-key", "--window", win, "--surface", ref, "enter")
    good = a.returncode == 0 and b.returncode == 0
    ok += good
    print(f"  {'OK  ' if good else 'FAIL'} {ref}")
print(f"done: {ok}/{len(targets)} sent")
PY

Behavior: queued, then runs on turn-end

This skill runs during an active turn, so the Enter does not execute the command immediately — Claude Code queues it (the pane shows ❯ /context above "Press up to edit queued messages"). The queued command runs the instant that pane's turn ends, and the result renders there. That is exactly why the "view via the pane mirror" model works — and why this skill never tries to read the result back. Don't treat the queued state as a failure. (Idle panes in a broadcast execute right away; busy panes queue and run at their own turn-end.)

Safety

  • Mode A is own pane only. Targeting is pinned to $CMUX_SURFACE_ID; there is no path to fire into another agent.
  • Mode B hits every Claude pane. Safe and intended for idempotent commands like /reload-skills. For destructive ones (/clear, /compact, /logout, /exit), preview with FIRE=0 and confirm before sending.
  • Destructive commands fire as named. If the user explicitly names /clear, /compact, etc. for their own pane (Mode A), naming it is the confirmation — send it. Don't add a guard.
  • No read-back. Results are visible only in the panes; the user views them through cmux's mirror. Don't claim to have read them.

Related

  • worktree-cmux-split / worktree-cmux-workspace — open a worktree in a cmux pane (those target the focused pane, not Claude's own).

Sponsors

Details

Marketplace
powdream/claude-plugins
Source
plugins/cmux-tools
Category
Community

More from powdream/claude-plugins

All 8