Add per-program restore strategies to psmux-resurrect (port of tmux-resurrect's strategies mechanism)
Scenario
psmux-resurrect restores running processes by replaying pane_current_command verbatim. That works for shells and stateless tools, but it's not enough for any program that maintains its own internal session state outside its launch command:
- Editors with session files. A pane was running
nvimin a project with aSession.vim; on restore we get a freshnvimwith no buffers, splits, or cursor positions. - AI agent CLIs. Tools like Copilot CLI keep a SQLite-backed session per project (resume with
copilot --resume <id>). Currently after restore the agent's session is lost. - REPLs and TUIs with workspace state. Same shape: the binary name is the same, but the meaningful "open this back where I left it" command is not.
In all of these the saved pane_current_command is nvim / copilot / etc., and replaying it produces a running program but not a restored workspace.
tmux-resurrect addresses with its per-program strategies mechanism (docs, implementation).
Proposed direction
Port tmux-resurrect's strategies model, including a bundled reference strategy.
Activation
# In ~/.psmux.conf
set -g @resurrect-strategy-nvim 'session'
General form: @resurrect-strategy-<program> '<strategy-name>', where <program> is the basename of pane_current_command (without .exe) and <strategy-name> selects which strategy file to use.
Only programs the user explicitly opts in get strategy-driven restore. Everything else keeps today's verbatim-replay behavior.
Strategy contract
A strategy is a PowerShell script that takes two positional arguments and writes one line to stdout (the command to send to the restored pane):
# <strategies-dir>/<program>_<strategy>.ps1
param(
[Parameter(Mandatory)] [string] $OriginalCommand,
[Parameter(Mandatory)] [string] $Directory
)
# Compute a better restore command using $Directory and / or tool-specific state.
# Echo $OriginalCommand if you cannot improve on the default.
'mytool --resume <id>'
restore.ps1 invokes the strategy as pwsh -NoProfile -ExecutionPolicy Bypass -File <strategy>.ps1 <originalCommand> <directory>, reads stdout, and sends the first non-empty line to the pane via send-keys instead of replaying pane_current_command.
Lookup order
For a pane with command <program> and an active @resurrect-strategy-<program> '<strategy>' option, restore.ps1 searches in order:
~/.psmux/strategies/<program>_<strategy>.ps1- user-owned overrides<plugin>/strategies/<program>_<strategy>.ps1- strategies bundled with the plugin
First match wins.
[!NOTE] The user-dir lookup is a small enhancement over tmux-resurrect's design, not a port of it. tmux-resurrect's
_get_strategy_file()only consults the bundledstrategies/directory; there is no user-dir override. Adding~/.psmux/strategies/lets users tweak or prototype strategies without forking the plugin, at the cost of one extraTest-Pathper resolution. Flagging the divergence so it's an intentional design choice on the table for review, not accidental drift. Happy to drop the user-dir mechanism if you'd rather stick closer to tmux-resurrect's bundled-only model.
Bundled strategies
Initial bundle: just nvim_session, mirroring tmux-resurrect's strategies/nvim_session.sh. Behavior:
- If
Session.vimexists in the pane's working directory, restore asnvim -S(loads the session). - Otherwise fall back to bare
nvim.
That's a minimal, well-precedented starting set. Adding more bundled strategies (copilot, etc.) can come incrementally as users ask for them or stay user-dir-only and let the community ship them.
Failure handling
Strategies are restore-time conveniences, not preconditions. Any of the following silently falls back to the original saved command:
- Strategy script not found
- Strategy script throws / exits non-zero
- Strategy script writes empty / whitespace-only stdout
- Strategy option is set but the value is empty or matches
unknown option | error | no server | not found | refused
A broken strategy can never block a restore. The worst case is "this one pane came back as if no strategy was configured," which matches today's behavior.
[!NOTE] The empty-stdout fallback above is also slightly stricter than tmux-resurrect, which
send-keyswhatever the strategy emits. Empty stdout in tmux-resurrect's runtime results in just-Enter being sent to the pane. I chose to fall back to the original command instead so a misbehaving strategy can't accidentally fire a no-op Enter at a TUI's prompt. The bundled tmux-resurrect strategies (nvim_session.sh,vim_session.sh) all echo$ORIGINAL_COMMANDon fallback so this divergence is invisible to most users, but the runtime contract is what matters when third-party strategies arrive. Easy to flip back to pure pass-through if you'd prefer fidelity to tmux-resurrect over the safety net.
What it looks like end-to-end
# psmux.conf
set -g @resurrect-strategy-nvim 'session'
set -g @resurrect-strategy-copilot 'project' # user-supplied strategy at ~/.psmux/strategies/copilot_project.ps1
# ~/.psmux/strategies/copilot_project.ps1
param(
[Parameter(Mandatory)] [string] $OriginalCommand,
[Parameter(Mandatory)] [string] $Directory
)
# Query Claude Code's per-project session store for the most recent session id.
$db = Join-Path $env:USERPROFILE '.copilot\sessions.db'
if (-not (Test-Path $db)) { return $OriginalCommand }
$id = sqlite3 $db "SELECT id FROM sessions WHERE cwd='$Directory' ORDER BY updated_at DESC LIMIT 1"
if ($id) { "copilot --resume $id" } else { $OriginalCommand }
After restore, the nvim pane comes back with its session loaded and the copilot pane comes back with its prior conversation.
Considered alternatives
- Save a richer "restore command" per pane at save time (instead of computing it at restore time). Rejected: it doesn't help if the meaningful session state was created after the last save, and it doubles the save-side surface. Strategies run at restore time precisely so they can consult fresh tool state.
- Hardcode special-case logic for known tools in restore.ps1. Rejected: doesn't scale (tmux-resurrect has 12+ community strategies the last time I counted) and bakes user-tool choices into the core plugin. Strategies decouple the plugin from any specific tool.
- Per-pane custom save hooks instead of restore strategies. Considered, more complex contract (when do hooks run, can they fail, do they block save). tmux-resurrect's restore-side strategies are simpler and battle-tested. Save-side hooks could be a follow-up if there's demand.
- A more elaborate plugin API (DLLs, IPC, etc.). Rejected for the same reason tmux-resurrect uses scripts: scripts are easy to write, easy to debug, easy to share, and the perf cost (one short-lived pwsh per restored pane) is negligible compared to PTY spawn time.
Prototype status
I have a working implementation on MattKotsenas/psmux-plugins@feat/resurrect-restore-strategies. Two commits, ~600 LoC across the strategy helper, the bundled nvim_session strategy, restore.ps1 wiring, README + plugin.conf docs, 15 unit tests (covering precedence, fallback paths, basename normalization, broken-strategy handling) and 1 E2E test that exercises the full save → kill → restore round trip with a sentinel strategy and asserts the strategy actually got invoked.
Happy to send it as a PR if this direction lands well with you. Wanted to check first because it adds new API surface (per-program options + a strategies/ directory in the plugin).
Question
Does this direction align with where you want psmux-resurrect to grow? Specifically:
- Are you on board with strategies as a concept (per-program restore-time extension point, opt-in via
@resurrect-strategy-<program>)? - If yes, is the file-based strategy script contract above the shape you'd accept, or would you prefer something different (e.g., powershell module + cmdlet, options-based DSL, hooks-into-restore.ps1)?
- Should bundled strategies live in
psmux-resurrect/strategies/inside the monorepo? - Initial bundle scope: just
nvim_sessionto start, or would you like specific other tools shipped (copilot, claude, …)?
If you'd prefer a different mechanism entirely (or no extension point at all) that's good to know before I open the PR. Thanks!
Quick cross-link as I work on this:
The matching key for strategies (pane_current_command) hits a related problem that I just filed as psmux/psmux#299. psmux's pane_current_command diverges from tmux for both idle shells (returns the literal "shell" placeholder instead of the shell binary name) and active programs (returns deepest descendant instead of immediate foreground, so a copilot pane reports as cmd / aspire / dotnet non-deterministically).
That's a precondition for this issue: even with strategies wired in, non-deterministic program names prevent reliable restore.
Not asking for anything here, just making the dependency visible since it materially affects whether strategies are useful end-to-end.
Hey @MattKotsenas, thank you for one of the most thorough proposals this repo has received. You did the homework on tmux resurrect parity, flagged your divergences explicitly, and even built and tested a prototype before asking. That makes this an easy review. Answers to your four questions:
-
Strategies as a concept: yes, approved. A per program extension point that runs at restore time is exactly the right shape. Your rejected alternatives section matches my own reasoning, especially the point that computing the restore command at restore time lets a strategy consult tool state created after the last save. Opt in via
@resurrect-strategy-<program>mirrors tmux resurrect, which keeps the learning curve at zero for anyone coming from Linux. -
The file based script contract is the shape I want. Two positional arguments, first non empty line of stdout wins, invoked with
pwsh -NoProfile -ExecutionPolicy Bypass. Please keep both of your flagged divergences, and keep them documented as intentional:- The
~/.psmux/strategies/user override directory stays. Being able to prototype or patch a strategy without forking the plugin is worth one extraTest-Path, and it gives the community a place to share strategies before they graduate to the bundled set. - The empty stdout fallback to the original command stays too. Sending a bare Enter at an arbitrary TUI because a strategy misbehaved is exactly the kind of surprise I do not want users debugging. Fidelity to tmux resurrect matters at the config surface, not in a runtime edge case the bundled upstream strategies never exercise anyway.
The failure handling table you wrote (missing script, non zero exit, empty output, all silently fall back) is the right invariant: a broken strategy can never block a restore.
- The
-
Yes, bundled strategies live in
psmux-resurrect/strategies/inside the monorepo. They version with the plugin and withrestore.ps1, which is the code that invokes them. -
Start with
nvim_sessiononly. It is well precedented and testable. I would rather grow the bundled set one proven strategy at a time than ship speculative ones. Community strategies can live in the user directory first, and anything that sees real adoption (copilot, claude, and friends) graduates into the bundle with tests.
On your cross link to psmux/psmux#299: agreed that pane_current_command determinism is the real precondition for strategies being reliable end to end, and thank you for filing it with that level of detail. It is on the core roadmap. Strategies do not need to wait for it though. The contract is independent of how good the matching key is, and nvim panes already report usably today. When #299 lands, every strategy gets better for free.
Please send the PR. With 15 unit tests and an E2E round trip already written, I suspect the review will be quick. One request: include the README section explaining the lookup order and the failure semantics, since that contract is what third party strategy authors will build against.
Also, a heads up for when you rebase: the restore path is about to change underneath you. PR #32 (your pane id targeting fix) and issue #29 (an overwrite option for existing sessions) are being landed on restore.ps1 as part of the current maintenance pass, so branch from latest main before wiring in the strategy invocation.
Hey @MattKotsenas, this sat waiting on a PR that never had to be opened: your feat/resurrect-restore-strategies branch was complete, so I landed it from your fork directly. Both commits are on main with your authorship intact (c81535c, 736d6f5). Thank you for doing the port properly, the contract you wrote is the one third party strategy authors will build against now.
What I changed while landing it
- The restore path moved under you, as I warned it would: panes are now targeted by their
%idinsideRestore-WindowPanes(your own #32) rather than by${winTarget}.index. TheGet-StrategyCommandcall now sits in that loop, right beforesend-keys, with the pane's saved directory passed through. Nothing else instrategy.ps1ornvim_session.ps1needed to move. - Your E2E keyed the sentinel strategy on the literal
shell, which is whatpane_current_commandreturned when you wrote it. psmux/psmux#299 has since been fixed and an idle pane reportspwsh,powershellorcmd, so the test could never match. It now registers the same strategy under every shell name and asserts on the command the pane actually reported (21c60e2). With that it runs green, sentinel hit and the marker echoed in the restored pane: 9 for 9. Your resolution test passes 15 for 15 against a live server; I added a note to its header that it needs one, since strategy names are read back throughshow-options. - The README lookup order list is unchanged in substance, only reworded.
Where things stand
set -g @resurrect-strategy-nvim 'session' in ~/.psmux.conf activates the bundled nvim_session; ~/.psmux/strategies/<program>_<strategy>.ps1 overrides the bundled set. Failure handling is exactly your table: missing script, non zero exit, empty stdout all fall back to the saved command.
One thing to know about the option surface: psmux runs one server process per session, so a set -g typed at runtime only reaches the session it targets, while ~/.psmux.conf applies to every session as it starts. Your E2E already works around that by pre seeding a config file, which is the right pattern.
If you want to send feat/resurrect-save-command-strategy as a PR too, I will review it. Closing this one as shipped.