diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a0ec8b9..59e1568 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,11 +1,11 @@ name: Report a problem -description: Something in cc-sessions is not working as it should. +description: Something in Paddock is not working as it should. labels: [bug] body: - type: markdown attributes: value: | - Thanks for taking the time. **Report a problem** in Settings › General (or `cc-sessions report`) fills in the version and system for you. + Thanks for taking the time. **Report a problem** in Settings › General (or `paddock report`) fills in the version and system for you. Please leave out anything private: folder names, session names, prompts, emails. - type: textarea id: what @@ -29,8 +29,8 @@ body: - type: input id: version attributes: - label: cc-sessions version - description: "`cc-sessions --version`, or Settings › General › Updates." + label: Paddock version + description: "`paddock --version`, or Settings › General › Updates." placeholder: "2.6.0" validations: required: true @@ -42,6 +42,6 @@ body: - type: textarea id: diagnostics attributes: - label: Details from cc-sessions + label: Details from Paddock description: Filled in by Report a problem. Nothing personal is included. render: text diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 18264f1..f3cf574 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,5 +1,5 @@ blank_issues_enabled: true contact_links: - name: Install or update instructions - url: https://github.com/barath-dev/cc-sessions#install - about: How to install cc-sessions, and how updates work. + url: https://github.com/barath-dev/paddock#install + about: How to install Paddock, and how updates work. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 7d29ef4..c2fcebe 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,5 +1,5 @@ name: Suggest a feature -description: An idea that would make cc-sessions more useful. +description: An idea that would make Paddock more useful. labels: [enhancement] body: - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 837bc62..e78c4e6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: - name: Unit and end-to-end tests run: cargo test - name: Build - run: cargo build --release --bin cc-sessions + run: cargo build --release --bin paddock # Install from a locally served build with the real installer, then start, # use and stop the program the way a person would. @@ -34,13 +34,13 @@ jobs: case "$(uname -s)" in Darwin) os=macos ;; *) os=linux ;; esac case "$(uname -m)" in arm64|aarch64) arch=arm64 ;; *) arch=x86_64 ;; esac mkdir dist - cp target/release/cc-sessions "dist/cc-sessions-$os-$arch" + cp target/release/paddock "dist/paddock-$os-$arch" (cd dist && (sha256sum * 2>/dev/null || shasum -a 256 *) > checksums.txt) python3 -m http.server 8765 --directory dist >/dev/null 2>&1 & sleep 1 export HOME="$RUNNER_TEMP/home" SHELL=/bin/bash mkdir -p "$HOME/.claude/projects" - CC_SESSIONS_INSTALL_BASE=http://127.0.0.1:8765 sh install.sh --yes --command cs-ci --port 47900 + PADDOCK_INSTALL_BASE=http://127.0.0.1:8765 sh install.sh --yes --command cs-ci --port 47900 export PATH="$HOME/.local/bin:$PATH" cs-ci --version cs-ci account list @@ -48,7 +48,7 @@ jobs: curl -fsS -o /dev/null http://127.0.0.1:47900/ cs-ci stop # A second install keeps the settings and adds nothing twice. - CC_SESSIONS_INSTALL_BASE=http://127.0.0.1:8765 sh install.sh --yes + PADDOCK_INSTALL_BASE=http://127.0.0.1:8765 sh install.sh --yes test "$(grep -c 'aliases.sh' "$HOME/.bashrc" "$HOME/.bash_profile" 2>/dev/null | awk -F: '{ n += $2 } END { print n }')" = 1 cs-ci --version @@ -58,18 +58,18 @@ jobs: run: | $arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'x86_64' } New-Item -ItemType Directory -Force dist | Out-Null - Copy-Item target\release\cc-sessions.exe "dist\cc-sessions-windows-$arch.exe" - $hash = (Get-FileHash -Algorithm SHA256 "dist\cc-sessions-windows-$arch.exe").Hash.ToLower() - Set-Content dist\checksums.txt "$hash cc-sessions-windows-$arch.exe" + Copy-Item target\release\paddock.exe "dist\paddock-windows-$arch.exe" + $hash = (Get-FileHash -Algorithm SHA256 "dist\paddock-windows-$arch.exe").Hash.ToLower() + Set-Content dist\checksums.txt "$hash paddock-windows-$arch.exe" $server = Start-Process python -ArgumentList '-m', 'http.server', '8765', '--directory', 'dist' -PassThru -WindowStyle Hidden Start-Sleep 2 $env:LOCALAPPDATA = Join-Path $env:RUNNER_TEMP 'localappdata' $env:APPDATA = Join-Path $env:RUNNER_TEMP 'appdata' - $env:CC_SESSIONS_SKIP_PATH = '1' - $env:CC_SESSIONS_INSTALL_BASE = 'http://127.0.0.1:8765' + $env:PADDOCK_SKIP_PATH = '1' + $env:PADDOCK_INSTALL_BASE = 'http://127.0.0.1:8765' New-Item -ItemType Directory -Force $env:LOCALAPPDATA, $env:APPDATA | Out-Null & ([scriptblock]::Create((Get-Content -Raw install.ps1))) --yes --command cs-ci --port 47900 - $cs = Join-Path $env:LOCALAPPDATA 'cc-sessions\bin\cs-ci.cmd' + $cs = Join-Path $env:LOCALAPPDATA 'paddock\bin\cs-ci.cmd' & $cs --version & $cs account list & $cs --no-open @@ -96,7 +96,7 @@ jobs: with: node-version: 22 - run: npm install -g @anthropic-ai/claude-code - - name: What cc-sessions relies on + - name: What Paddock relies on shell: bash run: | set +e diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 14e3d96..9114e08 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,13 +17,13 @@ jobs: fail-fast: false matrix: include: - - { os: macos-latest, target: aarch64-apple-darwin, asset: cc-sessions-macos-arm64 } - - { os: macos-latest, target: x86_64-apple-darwin, asset: cc-sessions-macos-x86_64 } + - { os: macos-latest, target: aarch64-apple-darwin, asset: paddock-macos-arm64 } + - { os: macos-latest, target: x86_64-apple-darwin, asset: paddock-macos-x86_64 } # Linux builds are statically linked (musl), so they run on any distribution. - - { os: ubuntu-latest, target: x86_64-unknown-linux-musl, asset: cc-sessions-linux-x86_64 } - - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-musl, asset: cc-sessions-linux-arm64 } - - { os: windows-latest, target: x86_64-pc-windows-msvc, asset: cc-sessions-windows-x86_64.exe } - - { os: windows-latest, target: aarch64-pc-windows-msvc, asset: cc-sessions-windows-arm64.exe } + - { os: ubuntu-latest, target: x86_64-unknown-linux-musl, asset: paddock-linux-x86_64 } + - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-musl, asset: paddock-linux-arm64 } + - { os: windows-latest, target: x86_64-pc-windows-msvc, asset: paddock-windows-x86_64.exe } + - { os: windows-latest, target: aarch64-pc-windows-msvc, asset: paddock-windows-arm64.exe } steps: - uses: actions/checkout@v4 - run: rustup target add ${{ matrix.target }} @@ -35,10 +35,10 @@ jobs: # No Visual C++ runtime needed on the PC that installs it. RUSTFLAGS: ${{ runner.os == 'Windows' && '-C target-feature=+crt-static' || '' }} run: | - cargo build --release --bin cc-sessions --target ${{ matrix.target }} + cargo build --release --bin paddock --target ${{ matrix.target }} mkdir out ext=""; [ "${{ runner.os }}" = "Windows" ] && ext=".exe" - cp "target/${{ matrix.target }}/release/cc-sessions$ext" "out/${{ matrix.asset }}" + cp "target/${{ matrix.target }}/release/paddock$ext" "out/${{ matrix.asset }}" - uses: actions/upload-artifact@v4 with: name: ${{ matrix.asset }} @@ -54,8 +54,12 @@ jobs: with: path: dist merge-multiple: true + # Installs from before the rename (cc-sessions 2.7 and older) update themselves by + # downloading cc-sessions-, so each file is also published under that name. + - name: Copies under the old names + run: cd dist && for f in paddock-*; do cp "$f" "cc-sessions-${f#paddock-}"; done - name: Checksums - run: cd dist && sha256sum cc-sessions-* > checksums.txt && cat checksums.txt + run: cd dist && sha256sum paddock-* cc-sessions-* > checksums.txt && cat checksums.txt - name: Create release env: GH_TOKEN: ${{ github.token }} diff --git a/Cargo.lock b/Cargo.lock index 7980d75..247f22c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,19 +8,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" -[[package]] -name = "cc-sessions" -version = "2.7.2" -dependencies = [ - "getrandom", - "libc", - "memchr", - "serde", - "serde_json", - "tiny_http", - "windows-sys", -] - [[package]] name = "cfg-if" version = "1.0.5" @@ -75,6 +62,20 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "paddock" +version = "2.8.0" +dependencies = [ + "getrandom", + "libc", + "memchr", + "ruzstd", + "serde", + "serde_json", + "tiny_http", + "windows-sys", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -99,6 +100,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" + [[package]] name = "serde" version = "1.0.229" diff --git a/Cargo.toml b/Cargo.toml index 6030f93..9b276ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,13 @@ [package] -name = "cc-sessions" -version = "2.7.2" +name = "paddock" +version = "2.8.0" edition = "2021" license = "MIT" -description = "See, close and resume Claude Code sessions across every account on one machine." -repository = "https://github.com/barath-dev/cc-sessions" +description = "Paddock: every Claude Code and Codex session on your machine, in one place. See, close and resume them across every account." +repository = "https://github.com/barath-dev/paddock" [[bin]] -name = "cc-sessions" +name = "paddock" path = "src/main.rs" # Stand-in for the real `claude` command, used only by the tests. @@ -22,6 +22,7 @@ serde_json = "1" memchr = "2" tiny_http = "0.12" getrandom = "0.3" +ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/README.md b/README.md index e23d2fa..1f042d2 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,22 @@ -# cc-sessions +# Paddock -One place to see, close and resume [Claude Code](https://claude.com/claude-code) sessions -across every account on a machine, from a local web page or the command line. It also -adds, renames, re-logs-in, removes and restores the accounts themselves. +**Every Claude Code and Codex session on your machine, in one place.** -An account is a Claude Code config folder (`~/.claude`, `~/.claude-work`, ...) with a name -and a shortcut command. `claude agents` only sees one account at a time; cc-sessions asks -each account in turn and shows the result together, grouped by project folder. +Paddock was called cc-sessions until 2.8. An install from before moves over by itself the +first time the new version runs, and the `cc-sessions` command keeps working. + +One place to see, close and resume [Claude Code](https://claude.com/claude-code) and +[Codex](https://github.com/openai/codex) sessions across every account on a machine, from +a local web page or the command line. It also adds, renames, re-logs-in, removes and +restores the accounts themselves. + +An account is a config folder of one of the two tools (`~/.claude`, `~/.claude-work`, +`~/.codex`, `~/.codex-work`, ...) with a name and a shortcut command. Each tool only sees +one account at a time; Paddock reads every account and shows the result together, +grouped by project folder, with the Usage view counting both. It is a single small program with nothing else to install, for macOS, Linux and Windows. -It is an unofficial tool and is not affiliated with Anthropic. +It is an unofficial tool and is not affiliated with Anthropic or OpenAI. ## See it @@ -24,20 +31,20 @@ accounts. Both use made-up demo data. macOS and Linux: ```sh -curl -fsSL https://raw.githubusercontent.com/barath-dev/cc-sessions/main/install.sh | sh +curl -fsSL https://raw.githubusercontent.com/barath-dev/paddock/main/install.sh | sh ``` Windows (PowerShell): ```powershell -irm https://raw.githubusercontent.com/barath-dev/cc-sessions/main/install.ps1 | iex +irm https://raw.githubusercontent.com/barath-dev/paddock/main/install.ps1 | iex ``` The installer downloads the program for your system, checks it against the release's SHA-256 list, and asks a few setup questions. Each has a default, so pressing Enter through them works: -1. **Command name** — what you type to start it (default `cc-sessions`). +1. **Command name** — what you type to start it (default `paddock`). 2. **Port** for the page (default `4777`). 3. **Clickable shortcut** in Applications or the Start menu (default yes). 4. **Register the Claude Code folders it finds** as accounts (default yes). @@ -45,11 +52,27 @@ them works: the one line it would add to your shell's startup file, and keeps a backup. 6. **Keep it up to date automatically** (default yes). See [Updates](#updates). -Run `cc-sessions setup` to change any answer later. +Run `paddock setup` to change any answer later. + +### Coming from cc-sessions + +Nothing to do: an install of cc-sessions updates itself to Paddock, and the first time it +runs it moves over by itself. + +- The settings folder moves from `~/.config/cc-sessions` to `~/.config/paddock`. A link is + left at the old path, so the line your shell's startup file already has keeps loading + the shortcuts. On Windows, `%APPDATA%\cc-sessions` becomes `%APPDATA%\paddock`. +- `paddock` is added beside `cc-sessions`; both start the same program, which stays where + it was installed. +- The app shortcut becomes Paddock, and fish's shortcut file `paddock.fish`. +- `PADDOCK_HOME`, `PADDOCK_PORT` and the rest are read, and so are their old names, + `CC_SESSIONS_HOME` and so on. + +The install line still works with the old address, which GitHub sends on to the new one. ## Updates -From 2.6.0 on, cc-sessions keeps itself up to date. Once a day the server asks GitHub for +From 2.6.0 on, Paddock keeps itself up to date. Once a day the server asks GitHub for the latest release. When there is a newer one it downloads the program for your system, checks it against the release's SHA-256 list, puts it in place and restarts on it. Settings and sessions are not touched, and a close in progress finishes first. @@ -58,8 +81,8 @@ After an update the page reloads and opens a **What's new** window (from 2.7.2): changes in every version since the one you had, newest first, with a link to all the release notes. It shows once per update; **Got it** or Esc closes it. -- Turn it off in **Settings › General › Updates**, or answer no in `cc-sessions setup`. - With it off, the same place has **Update now**, and `cc-sessions update` installs the +- Turn it off in **Settings › General › Updates**, or answer no in `paddock setup`. + With it off, the same place has **Update now**, and `paddock update` installs the latest version from a terminal (`--check` only looks). - **What's new** in the same place shows the last few versions' changes at any time. - Only the copy the installer put in place updates itself. A build from source is told @@ -71,7 +94,7 @@ release notes. It shows once per update; **Got it** or Esc closes it. ## Reporting problems **Settings › General › Report a problem** (or the **Report** button on any error message, -or `cc-sessions report`) opens a new GitHub issue filled in with the version, system, +or `paddock report`) opens a new GitHub issue filled in with the version, system, Claude Code version, number of accounts and the last few error messages. It shows you all of it first, and leaves out folder paths, session names, prompts and emails. You describe what happened on GitHub before anything is sent. **Suggest a feature** is next to it. @@ -79,8 +102,8 @@ what happened on GitHub before anything is sent. **Suggest a feature** is next t ## Start and stop ``` -cc-sessions # start the server if needed and open the page -cc-sessions stop # stop the server (same as Disconnect in the page) +paddock # start the server if needed and open the page +paddock stop # stop the server (same as Disconnect in the page) ``` The server runs in the background on `http://127.0.0.1:4777`, so the terminal can be @@ -149,14 +172,14 @@ files in them, accounts as tags in the sidebar. ### Both layouts - **Rename** a session with the pencil on its row, by double-clicking its name, or with - Enter in the Finder layout. The name is kept by cc-sessions and shown in the page and on - the command line; Claude Code keeps its own title. Clear the name to go back to that title. + Enter in the Finder layout. The name is kept by Paddock and shown in the page and on + the command line; Claude Code and Codex keep their own titles. Clear the name to go back to that title. - **Settings**, from the classic header or the Finder sidebar: - **Appearance**: the layout; Light, Dark or Match system; a template (Mac, Classic, Graphite or Paper, or each layout's own look); and a primary colour for buttons, links and what is selected. These are kept in the browser. - - **Accounts**: login, plan, shortcut and folder of each account. Add, rename, change - login, remove and restore. **Edit…** opens one dialog for an account's name, alias, + - **Accounts**: tool, login, plan, shortcut and folder of each account. Add (as a Claude + Code or a Codex account), rename, change login, remove and restore. **Edit…** opens one dialog for an account's name, alias, colour (which marks it everywhere), login and removal. - **General**: **updates** (version, check now, automatic or not), **report a problem** and **suggest a feature**, the **code editor** that folders open in, picked from the ones found on @@ -166,9 +189,12 @@ files in them, accounts as tags in the sidebar. - **From the keyboard** in the classic layout, **Skip to sessions** is the first stop, the arrow keys move through the list and the folder tree, and Esc closes the details. -Statuses: `Working` (Claude is busy), `Blocked` (waiting for your input), `Idle` (open in +Statuses: `Working` (busy on a task), `Blocked` (waiting for your input), `Idle` (open in a terminal, doing nothing), `Done` (background task finished, not closed), `Closed` -(stopped through this tool, or stopped in Claude Code). +(stopped through this tool, or stopped in Claude Code or Codex). + +A Codex account's name is shown with a small **Codex** mark where the name does not +already say so. ## What it never does @@ -183,47 +209,58 @@ a terminal, doing nothing), `Done` (background task finished, not closed), `Clos - Its own records are rewritten in place with the previous version kept as `.bak`. The only files it removes are its own launchers: its pid file, a command link it created -when you change the command name, and on Windows the `claude-.cmd` launcher of an -account you renamed or removed. None of them hold data. +when you change the command name, and on Windows the `claude-.cmd` or +`codex-.cmd` launcher of an account you renamed or removed. None of them hold data. Claude Code itself deletes conversations after `cleanupPeriodDays` (30 by default) without activity. Settings › Accounts shows that number per account. To keep history longer, set -`cleanupPeriodDays` in that account's `settings.json`. +`cleanupPeriodDays` in that account's `settings.json`. Codex keeps its conversations until +they are deleted. ## Command line ``` -cc-sessions list [--folder PATH] [--account NAME] [--open | --closed | --all] [--json] -cc-sessions history [--folder PATH] [--account NAME] [--by-date] [--json] -cc-sessions close ... | --folder PATH | --account NAME [--yes] -cc-sessions rename NEW NAME | --reset -cc-sessions account list [--removed] -cc-sessions account add NAME [--alias A] [--dir PATH] [--no-login] -cc-sessions account rename NAME NEW-NAME [--alias A] -cc-sessions account login NAME -cc-sessions account remove NAME [--yes] -cc-sessions account restore NAME [--alias A] -cc-sessions setup [--yes] [--command NAME] [--port N] [--shortcut | --no-shortcut] [--no-import] [--no-aliases] [--no-auto-update] -cc-sessions update [--check] -cc-sessions report +paddock list [--folder PATH] [--account NAME] [--open | --closed | --all] [--json] +paddock history [--folder PATH] [--account NAME] [--by-date] [--json] +paddock close ... | --folder PATH | --account NAME [--yes] +paddock rename NEW NAME | --reset +paddock account list [--removed] +paddock account add NAME [--tool claude|codex] [--alias A] [--dir PATH] [--no-login] +paddock account rename NAME NEW-NAME [--alias A] +paddock account login NAME +paddock account remove NAME [--yes] +paddock account restore NAME [--alias A] +paddock setup [--yes] [--command NAME] [--port N] [--shortcut | --no-shortcut] [--no-import] [--no-aliases] [--no-auto-update] +paddock update [--check] +paddock report ``` Session ids are shown as `account:id`. `close` asks before closing, asks separately for each interactive session, and skips the session it is run from. `--yes` only skips the question for background sessions. `history` groups by folder; `--by-date` prints one list, newest first. `rename` takes the id `history` shows, and `--reset` gives a session its own -title back. +title back. `account add` makes a Claude Code account unless `--tool codex` says otherwise; +a Codex account's folder defaults to `~/.codex-NAME` and its shortcut to `codex-NAME`. + +A Codex session's short id is the end of its id, not the start: Codex ids begin with the +time they were made, so conversations started together share their first characters. ## Differences between systems | | macOS / Linux | Windows | |---|---|---| -| Settings and records | `~/.config/cc-sessions` | `%APPDATA%\cc-sessions` | -| Program | `~/.local/share/cc-sessions/cc-sessions` | `%LOCALAPPDATA%\cc-sessions\cc-sessions.exe` | -| Account shortcuts | aliases loaded by one line in `~/.zshrc` or `~/.bashrc` (fish: a `conf.d` file) | `claude-.cmd` launchers on your PATH | +| Settings and records | `~/.config/paddock` | `%APPDATA%\paddock` | +| Program | `~/.local/share/paddock/paddock` (an install from before 2.8 keeps `~/.local/share/cc-sessions/cc-sessions`) | `%LOCALAPPDATA%\paddock\paddock.exe` (from before 2.8: `%LOCALAPPDATA%\cc-sessions\cc-sessions.exe`) | +| Account shortcuts | aliases loaded by one line in `~/.zshrc` or `~/.bashrc` (fish: a `conf.d` file) | `claude-.cmd` and `codex-.cmd` launchers on your PATH | | Closing an interactive session | asks it to exit, and leaves it if it has not within 5 seconds | ends it immediately; Windows offers no gentler way | +| Running Codex sessions | found from the running processes (`ps`, and `lsof` on macOS) | not found yet; saved Codex conversations are listed and can be resumed | | Resume opens | iTerm or Terminal; on Linux the first terminal program found | Windows Terminal, else Command Prompt | +On macOS, Resume and Log in type their command into the new iTerm or Terminal window, as +`env CLAUDE_CONFIG_DIR= claude …` (or `CODEX_HOME` and `codex`), after clearing +the line. A key pressed while the window comes to the front cannot change which account +the command runs as; at worst the command is not found. + On a Linux machine with no desktop (for example over SSH), Resume cannot open a terminal window; the Copy button still gives the command. Claude Code running inside WSL is covered by installing the Linux version inside WSL. @@ -237,7 +274,7 @@ In the settings folder above: | File | Purpose | |---|---| | `config.json` | Answers from setup: command name, port, shortcut, idle limit, automatic updates. | -| `accounts.json` | Account registry: name, folder, shortcut, colour, removed flag. | +| `accounts.json` | Account registry: name, tool, folder, shortcut, colour, removed flag. | | `aliases.sh` | Generated account shortcuts (macOS, Linux). | | `icon.png`, `icon.ico` | Icon of the clickable shortcut (Linux, Windows). | | `closed.json` | Sessions closed through the tool. | @@ -262,6 +299,8 @@ from `ui-token` on every API call, rejects requests whose `Host` is not ## How sessions are read and closed +### Claude Code + - Sessions come from `claude agents --json --all`, run once per account. The default account runs with `CLAUDE_CONFIG_DIR` unset; the others with it set to their folder. - Background sessions are closed with `claude stop `. For an interactive one, the tool @@ -277,16 +316,62 @@ from `ui-token` on every API call, rejects requests whose `Host` is not own, which are not counted, and days older than an account's `cleanupPeriodDays` are empty because Claude Code has deleted them. +### Codex + +- Codex has no command that lists its running sessions. Paddock looks for running + `codex` programs, leaving out its background service (`codex app-server`), its helpers + (`codex-code-mode-host`, `codex-exec-server`) and commands like `codex login`. Since + Codex 0.160 a session's turns run in that background service, which writes the + conversation file, so a session is matched by the conversation `codex resume` was given, + or by its folder (`-C`, else its own) and the newest conversation there since it + started. Several windows in one folder are matched newest first, each to a conversation + of its own. One run with `--no-daemon` writes the file itself and is matched by it. +- Two limits follow from that. Two windows in one folder that get their first prompts in + the opposite order to the one they were opened in may be shown the wrong way round: + nothing tells them apart. And a window started with a prompt whose first word is a + Codex command (`codex "update the docs"`) looks like that command (`codex update`), and + is not listed. +- The end of the conversation file says whether a session is working or idle. Codex does + not write approval requests there, so for a session the file says is working, the + background service is asked (`thread/read`) whether it is waiting for an approval or an + answer. +- The background service carries on with a turn after its window is closed. Such a turn is + listed as working, without a window, once the service confirms it is still running. So + is a conversation whose last turn left a command running ("Process running with session + ID" in its output): Codex keeps those in background terminals after the turn ends. +- Closing checks the process is still that Codex session, stops the turn it is in the + middle of through the background service (`turn/interrupt`, by way of + `codex app-server proxy`) and ends the commands it left running + (`thread/backgroundTerminals/clean`, as Codex's `/stop` does), then asks the window to + exit, as for Claude Code. A window run + with `--no-daemon` runs each command in a process group of its own, which would outlive + it, so those are ended with it. +- History is read from `/sessions/YYYY/MM/DD/rollout-*.jsonl`, and from the + `.jsonl.zst` files Codex compresses finished ones into, read-only. Conversations archived + in Codex are left out, as are sub-agents' threads and side conversations left empty. + Titles are the names Codex keeps in `session_index.jsonl`, else the first prompt; a + `codex review` has none, and is named after what it reviews. +- The loop check reads Codex's patches and the commands that failed, also when Codex runs + them from a script of its own (code mode), where each command's own output is taken + without the script's timings. +- Token counts come from the running totals Codex records after each reply. A forked + conversation's first total includes its parent's, so only its own reply counts there. +- Who is signed in is read from the email and plan in the identity token in the account's + `auth.json` (nothing else in it is read), or from `codex login status` when Codex keeps + the login in the system keychain. The default account runs with `CODEX_HOME` unset; the + others with it set to their folder. Resume runs `codex resume ` in the session's + folder. + ## Building from source ```sh -cargo build --release # target/release/cc-sessions -cargo test # unit tests, and end-to-end tests against a fake claude +cargo build --release # target/release/paddock +cargo test # unit tests, and end-to-end tests against a fake claude (and codex) ``` Everything that differs between systems is in `src/os/`. The page is in `ui/` and is built -into the program; set `CC_SESSIONS_UI_DIR=ui` to serve it from disk while working on it. -`CC_SESSIONS_HOME` and `CC_SESSIONS_PORT` point a run at a different settings folder and +into the program; set `PADDOCK_UI_DIR=ui` to serve it from disk while working on it. +`PADDOCK_HOME` and `PADDOCK_PORT` (or their old names, `CC_SESSIONS_…`) point a run at a different settings folder and port. Each release adds its notes to the top of `ui/changes.json` (version, date, title, notes), diff --git a/install.ps1 b/install.ps1 index 1986e30..e4760d1 100644 --- a/install.ps1 +++ b/install.ps1 @@ -1,23 +1,24 @@ -# cc-sessions installer for Windows. +# Paddock installer for Windows. # -# irm https://raw.githubusercontent.com/barath-dev/cc-sessions/main/install.ps1 | iex +# irm https://raw.githubusercontent.com/barath-dev/paddock/main/install.ps1 | iex # # Downloads the one program for this PC, checks it against the release's -# SHA-256 list, puts it in %LOCALAPPDATA%\cc-sessions, and runs its setup. -# Running it again later updates the program and keeps all settings. +# SHA-256 list, puts it in %LOCALAPPDATA%\paddock, and runs its setup. +# Running it again later updates the program and keeps all settings. An install +# from before the rename (cc-sessions) is updated where it is. # To pass setup options: -# & ([scriptblock]::Create((irm https://raw.githubusercontent.com/barath-dev/cc-sessions/main/install.ps1))) --yes --command cs +# & ([scriptblock]::Create((irm https://raw.githubusercontent.com/barath-dev/paddock/main/install.ps1))) --yes --command cs $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$repo = 'barath-dev/cc-sessions' -$base = if ($env:CC_SESSIONS_INSTALL_BASE) { $env:CC_SESSIONS_INSTALL_BASE } else { "https://github.com/$repo/releases/latest/download" } +$repo = 'barath-dev/paddock' +$base = if ($env:PADDOCK_INSTALL_BASE) { $env:PADDOCK_INSTALL_BASE } elseif ($env:CC_SESSIONS_INSTALL_BASE) { $env:CC_SESSIONS_INSTALL_BASE } else { "https://github.com/$repo/releases/latest/download" } $arch = if ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') { 'arm64' } else { 'x86_64' } -$asset = "cc-sessions-windows-$arch.exe" +$asset = "paddock-windows-$arch.exe" -$tmp = Join-Path ([IO.Path]::GetTempPath()) "cc-sessions-install-$PID" +$tmp = Join-Path ([IO.Path]::GetTempPath()) "paddock-install-$PID" New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { Write-Host "Downloading $asset..." @@ -32,12 +33,18 @@ try { Select-Object -First 1 $actual = (Get-FileHash -Algorithm SHA256 $download).Hash.ToLower() if (-not $expected -or $expected.ToLower() -ne $actual) { - throw 'cc-sessions: the download does not match the release checksum. Nothing was installed.' + throw 'paddock: the download does not match the release checksum. Nothing was installed.' } - $dir = Join-Path $env:LOCALAPPDATA 'cc-sessions' + $dir = Join-Path $env:LOCALAPPDATA 'paddock' + $exe = Join-Path $dir 'paddock.exe' + $old = Join-Path $env:LOCALAPPDATA 'cc-sessions\cc-sessions.exe' + if (-not (Test-Path $exe) -and (Test-Path $old)) { + # Installed before the rename: update it in place, where its launchers and PATH point. + $dir = Split-Path $old + $exe = $old + } New-Item -ItemType Directory -Force -Path $dir | Out-Null - $exe = Join-Path $dir 'cc-sessions.exe' if (Test-Path $exe) { # Windows keeps a running program's file locked, so stop the server before replacing it. & $exe stop | Out-Null @@ -47,7 +54,7 @@ try { Write-Host '' & $exe setup @args - if ($LASTEXITCODE -ne 0) { throw 'cc-sessions: setup did not finish.' } + if ($LASTEXITCODE -ne 0) { throw 'paddock: setup did not finish.' } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue diff --git a/install.sh b/install.sh index b083fdf..7f9ae53 100755 --- a/install.sh +++ b/install.sh @@ -1,28 +1,29 @@ #!/bin/sh -# cc-sessions installer for macOS and Linux. +# Paddock installer for macOS and Linux. # -# curl -fsSL https://raw.githubusercontent.com/barath-dev/cc-sessions/main/install.sh | sh +# curl -fsSL https://raw.githubusercontent.com/barath-dev/paddock/main/install.sh | sh # # Downloads the one program for this system, checks it against the release's -# SHA-256 list, puts it in ~/.local/share/cc-sessions, and runs its setup. -# Running it again later updates the program and keeps all settings. +# SHA-256 list, puts it in ~/.local/share/paddock, and runs its setup. +# Running it again later updates the program and keeps all settings. An install +# from before the rename (cc-sessions) is updated where it is. # To pass setup options: curl ... | sh -s -- --yes --command cs set -eu -REPO="barath-dev/cc-sessions" -BASE="${CC_SESSIONS_INSTALL_BASE:-https://github.com/$REPO/releases/latest/download}" +REPO="barath-dev/paddock" +BASE="${PADDOCK_INSTALL_BASE:-${CC_SESSIONS_INSTALL_BASE:-https://github.com/$REPO/releases/latest/download}}" case "$(uname -s)" in Darwin) os=macos ;; Linux) os=linux ;; - *) echo "cc-sessions: this installer is for macOS and Linux. On Windows use install.ps1." >&2; exit 1 ;; + *) echo "paddock: this installer is for macOS and Linux. On Windows use install.ps1." >&2; exit 1 ;; esac case "$(uname -m)" in arm64 | aarch64) arch=arm64 ;; x86_64 | amd64) arch=x86_64 ;; - *) echo "cc-sessions: no build for processor type $(uname -m)." >&2; exit 1 ;; + *) echo "paddock: no build for processor type $(uname -m)." >&2; exit 1 ;; esac -asset="cc-sessions-$os-$arch" +asset="paddock-$os-$arch" fetch() { if command -v curl >/dev/null 2>&1; then @@ -30,7 +31,7 @@ fetch() { elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1" else - echo "cc-sessions: curl or wget is needed to download." >&2 + echo "paddock: curl or wget is needed to download." >&2 exit 1 fi } @@ -49,26 +50,32 @@ else actual=$(shasum -a 256 "$tmp/$asset" | awk '{ print $1 }') fi if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then - echo "cc-sessions: the download does not match the release checksum. Nothing was installed." >&2 + echo "paddock: the download does not match the release checksum. Nothing was installed." >&2 exit 1 fi -dir="$HOME/.local/share/cc-sessions" +dir="$HOME/.local/share/paddock" +program="$dir/paddock" +if [ ! -e "$program" ] && [ -e "$HOME/.local/share/cc-sessions/cc-sessions" ]; then + # Installed before the rename: update it in place, where its commands point. + dir="$HOME/.local/share/cc-sessions" + program="$dir/cc-sessions" +fi mkdir -p "$dir" chmod +x "$tmp/$asset" -mv "$tmp/$asset" "$dir/cc-sessions" -echo "Installed $("$dir/cc-sessions" --version) in $dir" +mv "$tmp/$asset" "$program" +echo "Installed $("$program" --version) in $dir" echo # Ask the setup questions on the terminal even when this script was piped in. if [ -t 0 ]; then - "$dir/cc-sessions" setup "$@" + "$program" setup "$@" elif (exec /dev/null; then - "$dir/cc-sessions" setup "$@" General > Updates to change that)." diff --git a/src/accounts.rs b/src/accounts.rs index efe23b0..6903737 100644 --- a/src/accounts.rs +++ b/src/accounts.rs @@ -1,7 +1,8 @@ -//! The account registry and the tool's settings. +//! The account registry and the program's settings. //! -//! An account is a Claude Code config folder with a name and an alias. Removing -//! one only sets a flag here: its folder, login and history are never touched. +//! An account is a config folder of one tool (Claude Code's `~/.claude-work`, +//! Codex's `~/.codex`) with a name and an alias. Removing one only sets a flag +//! here: its folder, login and history are never touched. use std::fs; use std::path::{Path, PathBuf}; @@ -10,12 +11,17 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::os; +use crate::shell::Shortcut; use crate::store::{self, state_file}; +use crate::tools::{self, Tool}; use crate::util::{err, expand_tilde, home, now_iso, path_str, tilde, Error, Result}; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Account { pub name: String, + /// Which tool the folder belongs to; Claude Code for accounts registered before there was a choice. + #[serde(default)] + pub tool: Tool, pub dir: String, #[serde(default)] pub alias: Option, @@ -31,20 +37,23 @@ pub struct Account { } impl Account { + /// True for the tool's own folder, `~/.claude` or `~/.codex`. pub fn is_default(&self) -> bool { - Path::new(&self.dir) == default_dir() + Path::new(&self.dir) == self.tool.default_dir() } - /// The folder to export as `CLAUDE_CONFIG_DIR`. `None` for the default - /// account: setting the variable to `~/.claude` changes where Claude Code - /// looks for that account's login, so it must stay unset. + /// The folder to export as the tool's variable (`CLAUDE_CONFIG_DIR`, + /// `CODEX_HOME`). `None` for the default folder: setting the variable to + /// `~/.claude` changes where Claude Code looks for that account's login, so + /// it must stay unset. pub fn config_dir(&self) -> Option { (!self.is_default()).then(|| self.dir.clone()) } -} -pub fn default_dir() -> PathBuf { - home().join(".claude") + /// The shortcut that starts it, or the plain command for a default folder without one. + pub fn start_command(&self) -> Option { + self.alias.clone().or_else(|| self.is_default().then(|| self.tool.program().to_string())) + } } // --------------------------------------------------------------------- settings @@ -68,7 +77,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { - Config { command: "cc-sessions".into(), port: 4777, shortcut: true, manage_aliases: true, idle_minutes: 30, auto_update: true } + Config { command: crate::util::NAME.into(), port: 4777, shortcut: true, manage_aliases: true, idle_minutes: 30, auto_update: true } } } @@ -97,18 +106,15 @@ pub fn valid_alias(alias: &str) -> bool { && chars.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') } -fn looks_like_config_dir(path: &Path) -> bool { - ["projects", "sessions", ".claude.json", "settings.json"].iter().any(|child| path.join(child).exists()) -} - -/// `~/.claude-*` folders, sorted. -fn dash_folders() -> Vec { +/// A tool's `~/.claude-*` or `~/.codex-*` folders, sorted. +fn dash_folders(tool: Tool) -> Vec { + let prefix = tool.folder_prefix(); let mut found: Vec = fs::read_dir(home()) .map(|entries| { entries .flatten() .map(|e| e.path()) - .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with(".claude-"))) + .filter(|p| p.is_dir() && p.file_name().is_some_and(|n| n.to_string_lossy().starts_with(&prefix))) .collect() }) .unwrap_or_default(); @@ -116,51 +122,59 @@ fn dash_folders() -> Vec { found } -fn suffix_name(path: &Path) -> String { +/// Every folder that holds a tool's data: its default folder and its dash folders. +fn tool_folders(tool: Tool) -> Vec { + let mut found: Vec = Some(tool.default_dir()).filter(|d| d.is_dir()).into_iter().collect(); + found.extend(dash_folders(tool).into_iter().filter(|p| tool.looks_like_config_dir(p))); + found +} + +/// The account name a folder suggests: `work` for `~/.claude-work`, `codex-work` +/// for `~/.codex-work` (so it cannot clash with a Claude Code account). +fn suffix_name(path: &Path, tool: Tool) -> String { let raw = path.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default(); let cleaned: String = raw - .trim_start_matches(".claude-") + .trim_start_matches(&tool.folder_prefix()) .chars() .map(|c| if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' { c } else { '-' }) .collect(); - cleaned.trim_matches('-').to_string() + let name = cleaned.trim_matches('-').to_string(); + match tool { + Tool::Claude => name, + _ => format!("{}-{name}", tool.id()), + } } -/// The accounts a first run would register: the folders that already exist. +/// The account a folder of a tool would be registered as. +fn found_account(tool: Tool, path: &Path, alias: Option, stamp: &str) -> Account { + let is_default = path == tool.default_dir(); + let name = if is_default { tool.default_name().to_string() } else { suffix_name(path, tool) }; + let alias = alias.or_else(|| (!is_default).then(|| tool.alias_for(&name))); + Account { + name, + tool, + dir: path_str(path), + alias, + removed: false, + added_at: Some(stamp.to_string()), + removed_at: None, + color: None, + } +} + +/// The accounts a first run would register: the folders of every tool that already exist. /// `known_aliases` maps a folder to an alias the person already uses for it. pub fn discover(known_aliases: &[(PathBuf, String)]) -> Vec { let stamp = now_iso(); let alias_for = |dir: &Path| known_aliases.iter().find(|(d, _)| d == dir).map(|(_, a)| a.clone()); - let mut accounts = Vec::new(); - if default_dir().is_dir() { - accounts.push(Account { - name: "default".into(), - dir: path_str(&default_dir()), - alias: alias_for(&default_dir()), - removed: false, - added_at: Some(stamp.clone()), - removed_at: None, - color: None, - }); - } - for path in dash_folders() { - if !looks_like_config_dir(&path) { - continue; - } - let name = suffix_name(&path); - if !valid_name(&name) || accounts.iter().any(|a| a.name == name) { - continue; + let mut accounts: Vec = Vec::new(); + for tool in tools::ALL { + for path in tool_folders(tool) { + let acc = found_account(tool, &path, alias_for(&path), &stamp); + if valid_name(&acc.name) && !accounts.iter().any(|a| a.name == acc.name) { + accounts.push(acc); + } } - let alias = alias_for(&path).unwrap_or_else(|| format!("claude-{name}")); - accounts.push(Account { - name, - dir: path_str(&path), - alias: Some(alias), - removed: false, - added_at: Some(stamp.clone()), - removed_at: None, - color: None, - }); } accounts } @@ -180,20 +194,17 @@ pub fn save_all(accounts: &[Account]) -> Result<()> { } pub fn write_shortcuts(accounts: &[Account]) -> Result<()> { - let entries: Vec<(String, Option)> = accounts + let entries: Vec = accounts .iter() .filter(|a| !a.removed) - .filter_map(|a| a.alias.clone().map(|alias| (alias, a.config_dir()))) + .filter_map(|a| a.alias.clone().map(|alias| Shortcut { alias, tool: a.tool, config_dir: a.config_dir() })) .collect(); os::write_account_shortcuts(&entries, load_config().manage_aliases) } fn load_all() -> Result> { match store::read_json(®istry_file())? { - Some(data) => { - let list = data.get("accounts").cloned().unwrap_or(Value::Array(vec![])); - serde_json::from_value(list).map_err(|e| Error(format!("accounts.json is not in the expected form: {e}"))) - } + Some(data) => parse_accounts(data.get("accounts").cloned().unwrap_or(Value::Array(vec![]))), None => { // First run: register the folders that already exist. let accounts = discover(&[]); @@ -203,6 +214,19 @@ fn load_all() -> Result> { } } +/// An account saved without a tool is Claude Code's, unless its folder says Codex: a version +/// from before Codex (2.7 and older) drops the tool when it saves the registry again. +fn parse_accounts(list: Value) -> Result> { + let mut accounts: Vec = serde_json::from_value(list.clone()).map_err(|e| Error(format!("accounts.json is not in the expected form: {e}")))?; + for (acc, saved) in accounts.iter_mut().zip(list.as_array().into_iter().flatten()) { + let folder = Path::new(&acc.dir).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if saved.get("tool").is_none() && (folder == ".codex" || folder.starts_with(&Tool::Codex.folder_prefix())) { + acc.tool = Tool::Codex; + } + } + Ok(accounts) +} + pub fn load_accounts(include_removed: bool) -> Result> { let all = store::locked(load_all)?; Ok(if include_removed { all } else { all.into_iter().filter(|a| !a.removed).collect() }) @@ -237,8 +261,8 @@ fn check_alias(alias: &str, accounts: &[Account], ignore: Option) -> Resu if !valid_alias(alias) { return err("Alias must be letters, digits, dashes or underscores, with no spaces."); } - if alias == "claude" { - return err("Alias cannot be 'claude': that would hide the claude command itself."); + if let Some(tool) = tools::ALL.into_iter().find(|t| t.program() == alias) { + return err(format!("Alias cannot be '{alias}': that would hide the {} command itself.", tool.program())); } for (i, acc) in accounts.iter().enumerate() { if Some(i) != ignore && !acc.removed && acc.alias.as_deref() == Some(alias) { @@ -257,15 +281,15 @@ fn find(accounts: &[Account], name: &str) -> Result { accounts.iter().position(|a| a.name == name).ok_or_else(|| Error(format!("No account named '{name}'."))) } -/// Register an account. Returns (account, folder_was_created). -pub fn add_account(name: &str, alias: Option<&str>, folder: Option<&str>) -> Result<(Account, bool)> { +/// Register an account of a tool. Returns (account, folder_was_created). +pub fn add_account(name: &str, alias: Option<&str>, folder: Option<&str>, tool: Tool) -> Result<(Account, bool)> { store::locked(|| { let mut accounts = load_all()?; check_name(name, &accounts, None)?; let path = match folder.map(str::trim).filter(|f| !f.is_empty()) { Some(f) => expand_tilde(f), - None => home().join(format!(".claude-{name}")), + None => home().join(format!("{}{}", tool.folder_prefix(), name.strip_prefix("codex-").filter(|_| tool == Tool::Codex).unwrap_or(name))), }; if !path.is_absolute() { return err("Folder must be an absolute path, or start with ~."); @@ -281,11 +305,14 @@ pub fn add_account(name: &str, alias: Option<&str>, folder: Option<&str>) -> Res return err(format!("{} belongs to account '{}', which is {state}.", tilde(&path_str(&path)), acc.name)); } - let is_default = path == default_dir(); + if let Some(other) = tools::ALL.into_iter().find(|t| *t != tool && (path == t.default_dir() || is_dash_folder(&path, *t))) { + return err(format!("{} is a {} folder. Add it as a {} account.", tilde(&path_str(&path)), other.label(), other.label())); + } + let is_default = path == tool.default_dir(); let alias = match alias.map(str::trim).filter(|a| !a.is_empty()) { Some(a) => Some(a.to_string()), None if is_default => None, - None => Some(format!("claude-{name}")), + None => Some(tool.alias_for(name)), }; if let Some(a) = &alias { check_alias(a, &accounts, None)?; @@ -297,6 +324,7 @@ pub fn add_account(name: &str, alias: Option<&str>, folder: Option<&str>) -> Res } let acc = Account { name: name.to_string(), + tool, dir: path_str(&path), alias, removed: false, @@ -312,8 +340,8 @@ pub fn add_account(name: &str, alias: Option<&str>, folder: Option<&str>) -> Res /// Change an account's name and/or alias. The folder is never touched. /// -/// `alias`: `None` keeps a custom alias and lets the `claude-NAME` pattern -/// follow the name; `Some("")` clears it (default account only). +/// `alias`: `None` keeps a custom alias and lets the `claude-NAME` (or +/// `codex-NAME`) pattern follow the name; `Some("")` clears it (default folder only). pub fn rename_account(name: &str, new_name: Option<&str>, alias: Option<&str>) -> Result { store::locked(|| { let mut accounts = load_all()?; @@ -326,8 +354,9 @@ pub fn rename_account(name: &str, new_name: Option<&str>, alias: Option<&str>) - check_name(&new_name, &accounts, Some(i))?; } let current = accounts[i].alias.clone(); + let tool = accounts[i].tool; let new_alias = match alias.map(str::trim) { - None if current.as_deref() == Some(format!("claude-{name}").as_str()) => Some(format!("claude-{new_name}")), + None if current.as_deref() == Some(tool.alias_for(name).as_str()) => Some(tool.alias_for(&new_name)), None => current.clone(), Some("") if accounts[i].is_default() => None, Some("") => return err("This account needs an alias, otherwise it cannot be started."), @@ -399,22 +428,51 @@ pub fn restore_account(name: &str, alias: Option<&str>) -> Result { }) } -/// `~/.claude-*` folders the registry has never seen. -pub fn unregistered_folders() -> Result> { +fn is_dash_folder(path: &Path, tool: Tool) -> bool { + path.parent() == Some(home().as_path()) && path.file_name().is_some_and(|n| n.to_string_lossy().starts_with(&tool.folder_prefix())) +} + +/// A folder of a tool that the registry has never seen. +#[derive(Debug, Clone, Serialize)] +pub struct Unregistered { + pub dir: String, + pub tool: Tool, + /// The account name it would get. + pub name: String, +} + +/// Folders of every tool that the registry has never seen: `~/.claude-*`, and +/// `~/.codex` and `~/.codex-*` (which a registry from before Codex never looked for). +pub fn unregistered_folders() -> Result> { let known: Vec = load_accounts(true)?.iter().map(|a| PathBuf::from(&a.dir)).collect(); - Ok(dash_folders().into_iter().filter(|p| !known.contains(p)).map(|p| path_str(&p)).collect()) + let mut found = Vec::new(); + for tool in tools::ALL { + let mut folders = if tool == Tool::Claude { dash_folders(tool) } else { tool_folders(tool) }; + folders.retain(|p| !known.contains(p)); + for path in folders { + let name = if path == tool.default_dir() { tool.default_name().to_string() } else { suffix_name(&path, tool) }; + found.push(Unregistered { dir: path_str(&path), tool, name }); + } + } + Ok(found) } pub const DEFAULT_RETENTION_DAYS: i64 = 30; -/// How long Claude Code itself keeps this account's conversations (its -/// `cleanupPeriodDays`). Reported only; this tool never changes settings. -pub fn retention_days(acc: &Account) -> i64 { - store::read_json_or_null(&Path::new(&acc.dir).join("settings.json")) - .get("cleanupPeriodDays") - .and_then(Value::as_i64) - .filter(|days| *days > 0) - .unwrap_or(DEFAULT_RETENTION_DAYS) +/// How long the tool itself keeps this account's conversations: Claude Code's +/// `cleanupPeriodDays`. `None` when it keeps them until they are deleted by hand, +/// as Codex does. Reported only; this program never changes settings. +pub fn retention_days(acc: &Account) -> Option { + match acc.tool { + Tool::Claude => Some( + store::read_json_or_null(&Path::new(&acc.dir).join("settings.json")) + .get("cleanupPeriodDays") + .and_then(Value::as_i64) + .filter(|days| *days > 0) + .unwrap_or(DEFAULT_RETENTION_DAYS), + ), + Tool::Codex => None, + } } #[cfg(test)] @@ -437,7 +495,26 @@ mod tests { #[test] fn names_come_from_folder_suffixes() { - assert_eq!(suffix_name(Path::new("/home/me/.claude-work")), "work"); - assert_eq!(suffix_name(Path::new("/home/me/.claude-My Team")), "my-team"); + assert_eq!(suffix_name(Path::new("/home/me/.claude-work"), Tool::Claude), "work"); + assert_eq!(suffix_name(Path::new("/home/me/.claude-My Team"), Tool::Claude), "my-team"); + assert_eq!(suffix_name(Path::new("/home/me/.codex-work"), Tool::Codex), "codex-work"); + } + + #[test] + fn registries_from_before_codex_are_claude_code() { + let acc: Account = serde_json::from_value(serde_json::json!({ "name": "work", "dir": "/h/.claude-work" })).unwrap(); + assert_eq!(acc.tool, Tool::Claude); + let acc: Account = serde_json::from_value(serde_json::json!({ "name": "codex", "tool": "codex", "dir": "/h/.codex" })).unwrap(); + assert_eq!(acc.tool, Tool::Codex); + // Saved again by 2.7, which drops the tool: the folder still tells. + let saved = parse_accounts(serde_json::json!([ + { "name": "work", "dir": "/h/.claude-work" }, + { "name": "codex", "dir": "/h/.codex" }, + { "name": "codex-work", "dir": "/h/.codex-work" }, + { "name": "odd", "tool": "claude", "dir": "/h/.codex-odd" }, + ])) + .unwrap(); + let tools: Vec = saved.iter().map(|a| a.tool).collect(); + assert_eq!(tools, [Tool::Claude, Tool::Codex, Tool::Codex, Tool::Claude]); } } diff --git a/src/claude.rs b/src/claude.rs index 9286c87..ae94078 100644 --- a/src/claude.rs +++ b/src/claude.rs @@ -1,66 +1,14 @@ -//! Running the `claude` command as one account. +//! What only Claude Code has: its own report of who is signed in. -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::OnceLock; -use std::time::Duration; - -use serde::Serialize; use serde_json::Value; use crate::accounts::Account; -use crate::os; -use crate::proc::{self, Output}; -use crate::util::{home, Error, Result}; - -static CLAUDE: OnceLock> = OnceLock::new(); - -pub fn claude_bin() -> Result { - CLAUDE - .get_or_init(|| os::which("claude").or_else(|| os::claude_fallbacks().into_iter().find(|p| p.is_file()))) - .clone() - .ok_or_else(|| Error("The claude command was not found on PATH.".into())) -} - -/// A `claude` command for one account, free of any parent session's variables. -pub fn command(acc: &Account) -> Result { - let mut cmd = Command::new(claude_bin()?); - for (key, _) in std::env::vars_os() { - if key.to_string_lossy().to_uppercase().starts_with("CLAUDE") { - cmd.env_remove(key); - } - } - if let Some(dir) = acc.config_dir() { - cmd.env("CLAUDE_CONFIG_DIR", dir); - } - cmd.current_dir(home()); - Ok(cmd) -} - -pub fn run(acc: &Account, args: &[&str], seconds: u64) -> Result { - let mut cmd = command(acc)?; - cmd.args(args); - proc::run(&mut cmd, Duration::from_secs(seconds)) -} - -#[derive(Debug, Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct AuthInfo { - pub logged_in: bool, - pub email: Option, - pub org: Option, - pub plan: Option, - pub error: Option, -} +use crate::tools::{self, AuthInfo}; /// Which login an account folder holds, from `claude auth status`. pub fn auth_status(acc: &Account) -> AuthInfo { let mut info = AuthInfo::default(); - if !Path::new(&acc.dir).is_dir() { - info.error = Some("folder is missing".into()); - return info; - } - let data: Value = match run(acc, &["auth", "status"], 20) { + let data: Value = match tools::run(acc, &["auth", "status"], 20) { Ok(out) => match serde_json::from_str(&out.stdout) { Ok(data) => data, Err(_) => { diff --git a/src/cli.rs b/src/cli.rs index 541259c..9e01394 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -9,7 +9,6 @@ use std::time::{Duration, Instant}; use serde_json::Value; use crate::accounts::{self, Account}; -use crate::claude; use crate::closing; use crate::history; use crate::os; @@ -18,39 +17,43 @@ use crate::server::{self, HOST, VERSION}; use crate::sessions::{self, Session}; use crate::setup; use crate::titles; +use crate::tools::{self, Tool}; use crate::update; -use crate::util::{age, err, ms_to_date, path_str, tilde, Error, Result}; +use crate::util::{age, err, ms_to_date, path_str, tilde, Error, Result, NAME, OLD_NAME}; const HELP: &str = "\ -cc-sessions: see, close and resume Claude Code sessions across every account. - - cc-sessions start the web app if needed and open it - cc-sessions stop stop the web app (same as Disconnect in the page) - cc-sessions setup change the command name, port, shortcuts and updates - cc-sessions update [--check] install the latest version now (--check: only look) - cc-sessions report report a problem: opens a filled-in GitHub issue - - cc-sessions list [--folder PATH] [--account NAME] [--open | --closed | --all] [--json] - cc-sessions history [--folder PATH] [--account NAME] [--by-date] [--json] - cc-sessions close ... | --folder PATH | --account NAME [--yes] - cc-sessions rename NEW NAME | --reset - - cc-sessions account list [--removed] - cc-sessions account add NAME [--alias A] [--dir PATH] [--no-login] - cc-sessions account rename NAME NEW-NAME [--alias A] - cc-sessions account login NAME - cc-sessions account remove NAME [--yes] - cc-sessions account restore NAME [--alias A] - +Paddock: every Claude Code and Codex session on your machine, in one place. +See, close and resume them across every account. + + paddock start the web app if needed and open it + paddock stop stop the web app (same as Disconnect in the page) + paddock setup change the command name, port, shortcuts and updates + paddock update [--check] install the latest version now (--check: only look) + paddock report report a problem: opens a filled-in GitHub issue + + paddock list [--folder PATH] [--account NAME] [--open | --closed | --all] [--json] + paddock history [--folder PATH] [--account NAME] [--by-date] [--json] + paddock close ... | --folder PATH | --account NAME [--yes] + paddock rename NEW NAME | --reset + + paddock account list [--removed] + paddock account add NAME [--tool claude|codex] [--alias A] [--dir PATH] [--no-login] + paddock account rename NAME NEW-NAME [--alias A] + paddock account login NAME + paddock account remove NAME [--yes] + paddock account restore NAME [--alias A] + +An account is one Claude Code or Codex folder (~/.claude, ~/.codex-work, ...). Session ids are shown as account:id. Closing stops a session and keeps its -conversation. A new name is kept by cc-sessions; Claude Code keeps its own +conversation. A new name is kept by Paddock; the tool keeps its own title. Nothing under an account folder is ever deleted or changed. Options: --no-open (start without opening the browser), --version, --help +Paddock was called cc-sessions before 2.8; that command still works. "; /// Flags that take a value; every other `--flag` is a switch. -const VALUE_FLAGS: &[&str] = &["folder", "account", "alias", "dir", "command", "port"]; +const VALUE_FLAGS: &[&str] = &["folder", "account", "alias", "dir", "command", "port", "tool"]; const SWITCHES: &[&str] = &[ "json", "open", "closed", "all", "yes", "no-login", "removed", "no-open", "shortcut", "no-shortcut", "no-import", "no-aliases", "help", "version", "by-date", "reset", "check", "no-auto-update", @@ -85,7 +88,7 @@ impl Args { } else if SWITCHES.contains(&name) && inline.is_none() { args.switches.push(name.to_string()); } else { - return err(format!("Unknown option --{name}. Try: cc-sessions --help")); + return err(format!("Unknown option --{name}. Try: paddock --help")); } } Ok(args) @@ -100,7 +103,7 @@ impl Args { } fn word(&self, index: usize, what: &str) -> Result<&str> { - self.words.get(index).map(String::as_str).ok_or_else(|| Error(format!("Missing {what}. Try: cc-sessions --help"))) + self.words.get(index).map(String::as_str).ok_or_else(|| Error(format!("Missing {what}. Try: paddock --help"))) } } @@ -116,31 +119,40 @@ pub fn main() -> i32 { let quiet = matches!(args.words.first().map(String::as_str), Some("serve" | "update" | "setup" | "report")) || args.has("json"); if !quiet && !accounts::load_config().auto_update { if let Some(tag) = update::known_newer() { - eprintln!("\ncc-sessions {} is out. Install it with: {} update", tag.trim_start_matches('v'), me()); + eprintln!("\nPaddock {} is out. Install it with: {} update", tag.trim_start_matches('v'), me()); } } code } +/// The name for the version line and errors. A 2.7 updater runs the download it saved +/// as `cc-sessions-` and takes it only if its version line starts so. +fn invoked_as() -> &'static str { + let called = std::env::args_os().next().map(std::path::PathBuf::from); + let called = called.as_deref().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + if called.starts_with(&format!("{OLD_NAME}-")) { OLD_NAME } else { NAME } +} + /// What the person types to run this tool; setup lets them rename it. fn me() -> String { accounts::load_config().command } fn fail(e: &Error) -> i32 { - eprintln!("cc-sessions: {e}"); + eprintln!("{}: {e}", invoked_as()); 1 } fn run(args: &Args) -> Result { if args.has("version") { - println!("cc-sessions {VERSION}"); + println!("{} {VERSION}", invoked_as()); return Ok(0); } if args.has("help") { print!("{HELP}"); return Ok(0); } + crate::migrate::run(); match args.words.first().map(String::as_str) { None | Some("ui") => cmd_open(args), Some("stop") => cmd_stop(), @@ -161,7 +173,7 @@ fn run(args: &Args) -> Result { Some("restore") => account_restore(args), _ => err("Say what to do with accounts: list, add, rename, login, remove or restore."), }, - Some(other) => err(format!("Unknown command '{other}'. Try: cc-sessions --help")), + Some(other) => err(format!("Unknown command '{other}'. Try: paddock --help")), } } @@ -243,7 +255,9 @@ fn http(method: &str, path: &str, body: Option<&str>, timeout: Duration) -> Opti fn ping() -> Option { let (status, body) = http("GET", "/api/ping", None, Duration::from_secs(2))?; let data: Value = serde_json::from_str(&body).ok()?; - (status == 200 && data.get("app").and_then(Value::as_str) == Some("cc-sessions")).then_some(data) + // The server answers to its old name (see server.rs); a later one may answer to the new. + let app = data.get("app").and_then(Value::as_str); + (status == 200 && (app == Some(NAME) || app == Some(OLD_NAME))).then_some(data) } fn port_busy() -> bool { @@ -255,14 +269,14 @@ fn port_busy() -> bool { fn cmd_open(args: &Args) -> Result { let port = server::port(); if ping().is_some() { - println!("Claude Sessions is already running."); + println!("Paddock is already running."); } else { if port_busy() { return err(format!("Port {port} is in use by another program. Stop it, or pick another port with: {} setup", me())); } server::start_detached(&std::env::current_exe()?)?; wait_for_server()?; - println!("Claude Sessions started."); + println!("Paddock started."); } let base = format!("http://{HOST}:{port}"); if !args.has("no-open") { @@ -289,10 +303,10 @@ fn wait_for_server() -> Result<()> { fn cmd_update(args: &Args) -> Result { println!("Looking for a new version..."); let Some(release) = update::check()? else { - println!("cc-sessions {VERSION} is the latest version."); + println!("Paddock {VERSION} is the latest version."); return Ok(0); }; - println!("cc-sessions {} is out (this is {VERSION}).", release.tag.trim_start_matches('v')); + println!("Paddock {} is out (this is {VERSION}).", release.tag.trim_start_matches('v')); if !release.url.is_empty() { println!(" What's new: {}", release.url); } @@ -308,7 +322,7 @@ fn cmd_update(args: &Args) -> Result { cmd_stop()?; server::start_detached(&os::installed_program())?; wait_for_server()?; - println!("Claude Sessions restarted on the new version."); + println!("Paddock restarted on the new version."); } Ok(0) } @@ -338,7 +352,7 @@ fn cmd_report() -> Result { fn cmd_stop() -> Result { let Some(info) = ping() else { - println!("Claude Sessions is not running."); + println!("Paddock is not running."); return Ok(0); }; let pid = info.get("pid").and_then(Value::as_u64).unwrap_or(0) as u32; @@ -351,7 +365,7 @@ fn cmd_stop() -> Result { if os::pid_alive(pid) { return err(format!("The server (pid {pid}) has not stopped yet.")); } - println!("Claude Sessions stopped. Your Claude sessions are untouched."); + println!("Paddock stopped. Your Claude Code and Codex sessions are untouched."); Ok(0) } @@ -385,7 +399,7 @@ fn cmd_list(args: &Args) -> Result { println!("{}", tilde(&folder)); let rows: Vec> = group .iter() - .map(|s| vec![s.key.clone(), s.kind.clone(), s.status.clone(), age(s.updated_at), s.name.clone()]) + .map(|s| vec![s.key.clone(), s.tool.id().to_string(), s.kind.clone(), s.status.clone(), age(s.updated_at), s.name.clone()]) .collect(); table(&rows, " "); } @@ -440,7 +454,7 @@ fn cmd_rename(args: &Args) -> Result { let token = args.word(1, "the session id")?; let title = args.words[2..].join(" "); if title.trim().is_empty() != args.has("reset") { - return err("Give the new name, or --reset to go back to Claude Code's own title."); + return err("Give the new name, or --reset to go back to the tool's own title."); } let (account, ident) = match token.rsplit_once(':') { Some((account, ident)) => (Some(account), ident.to_lowercase()), @@ -454,7 +468,9 @@ fn cmd_rename(args: &Args) -> Result { .map(|s| (s.account.clone(), s.account_dir.clone(), s.session_id.clone())) .collect(); for item in history::history_items()? { - let matches = account.is_none_or(|a| a == item.account) && !ident.is_empty() && item.session_id.to_lowercase().starts_with(&ident); + let matches = account.is_none_or(|a| a == item.account) + && !ident.is_empty() + && (item.id.to_lowercase() == ident || item.session_id.to_lowercase().starts_with(&ident)); let entry = (item.account, item.account_dir, item.session_id); if matches && !found.contains(&entry) { found.push(entry); @@ -465,8 +481,8 @@ fn cmd_rename(args: &Args) -> Result { [(account, dir, session_id)] => { let short: String = session_id.chars().take(8).collect(); match titles::set(dir, session_id, &title)? { - Some(title) => println!("Renamed {account}:{short} to \"{title}\". Claude Code keeps its own title."), - None => println!("{account}:{short} goes by Claude Code's title again."), + Some(title) => println!("Renamed {account}:{short} to \"{title}\". The tool keeps its own title."), + None => println!("{account}:{short} goes by the tool's own title again."), } Ok(0) } @@ -528,11 +544,12 @@ fn cmd_close(args: &Args) -> Result { } // Never close the session this command was run from. - let own_id = std::env::var("CLAUDE_CODE_SESSION_ID").unwrap_or_default(); + // Codex runs a session's commands in its background service, not under the window: they carry its id. + let own_ids: Vec = ["CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID"].iter().filter_map(|v| std::env::var(v).ok()).filter(|id| !id.is_empty()).collect(); let parents = ancestors(); let mut kept = Vec::new(); for sess in targets { - if (!own_id.is_empty() && sess.session_id == own_id) || sess.pid.is_some_and(|pid| parents.contains(&pid)) { + if own_ids.contains(&sess.session_id) || sess.pid.is_some_and(|pid| parents.contains(&pid)) { println!("Skipped {} ({}): this command is running inside it.", sess.key, sess.name); } else if !sess.open { println!("Skipped {} ({}): already closed.", sess.key, sess.name); @@ -545,7 +562,8 @@ fn cmd_close(args: &Args) -> Result { return Ok(failed as i32); } - let (background, interactive): (Vec<&Session>, Vec<&Session>) = kept.into_iter().partition(|s| s.is_background()); + // A Codex turn whose window was closed has no terminal to ask about. + let (background, interactive): (Vec<&Session>, Vec<&Session>) = kept.into_iter().partition(|s| s.is_background() || s.pid.is_none()); let mut chosen = Vec::new(); if !background.is_empty() { println!("Background sessions to close ({}):", background.len()); @@ -573,9 +591,9 @@ fn cmd_close(args: &Args) -> Result { // --------------------------------------------------------------------- accounts -/// Run claude for an account in this terminal, so sign-in prompts work. -fn claude_here(acc: &Account, args: &[&str]) -> Result<()> { - claude::command(acc)?.args(args).status()?; +/// Run the account's tool in this terminal, so sign-in prompts work. +fn tool_here(acc: &Account, args: &[String]) -> Result<()> { + tools::command(acc)?.args(args).status()?; Ok(()) } @@ -584,7 +602,7 @@ fn alias_note() { } fn shown_alias(acc: &Account) -> String { - acc.alias.clone().unwrap_or_else(|| if acc.is_default() { "claude".into() } else { "-".into() }) + acc.start_command().unwrap_or_else(|| "-".into()) } fn account_list(args: &Args) -> Result { @@ -600,23 +618,25 @@ fn account_list(args: &Args) -> Result { return Ok(0); } if removed { - let mut rows = vec![vec!["NAME".to_string(), "ALIAS".into(), "FOLDER".into()]]; - rows.extend(accounts.iter().map(|a| vec![a.name.clone(), a.alias.clone().unwrap_or("-".into()), tilde(&a.dir)])); + let mut rows = vec![vec!["NAME".to_string(), "TOOL".into(), "ALIAS".into(), "FOLDER".into()]]; + rows.extend(accounts.iter().map(|a| vec![a.name.clone(), a.tool.label().into(), a.alias.clone().unwrap_or("-".into()), tilde(&a.dir)])); table(&rows, ""); println!("Their folders and logins are untouched. Bring one back with: {} account restore NAME", me()); return Ok(0); } - let infos: Vec = thread::scope(|scope| { - let handles: Vec<_> = accounts.iter().map(|acc| scope.spawn(move || claude::auth_status(acc))).collect(); + let infos: Vec = thread::scope(|scope| { + let handles: Vec<_> = accounts.iter().map(|acc| scope.spawn(move || tools::auth_status(acc))).collect(); handles.into_iter().map(|h| h.join().unwrap_or_default()).collect() }); let (sessions, _) = sessions::all_sessions(&accounts)?; - let mut rows = vec![["NAME", "ALIAS", "LOGIN", "ORG", "PLAN", "OPEN", "FOLDER"].map(String::from).to_vec()]; + let mut rows = vec![["NAME", "TOOL", "ALIAS", "LOGIN", "ORG", "PLAN", "OPEN", "FOLDER"].map(String::from).to_vec()]; for (acc, info) in accounts.iter().zip(infos) { + let login = if info.logged_in { info.email.unwrap_or_else(|| "logged in".into()) } else { "not logged in".into() }; rows.push(vec![ acc.name.clone(), + acc.tool.label().into(), shown_alias(acc), - info.email.unwrap_or_else(|| "not logged in".into()), + login, info.org.unwrap_or_else(|| "-".into()), info.plan.unwrap_or_else(|| "-".into()), sessions.iter().filter(|s| s.open && s.account == acc.name).count().to_string(), @@ -627,22 +647,35 @@ fn account_list(args: &Args) -> Result { let extra = accounts::unregistered_folders()?; if !extra.is_empty() { println!("\nFolders not registered as accounts:"); - for path in extra { - println!(" {0} (add with: {1} account add NAME --dir {0})", tilde(&path), me()); + for found in extra { + let dir = tilde(&found.dir); + println!(" {dir} (add with: {} account add {} --tool {} --dir {dir})", me(), found.name, found.tool.id()); } } Ok(0) } +fn login_line(info: &tools::AuthInfo) -> String { + match (&info.email, info.logged_in) { + (Some(email), true) => email.clone(), + (None, true) => info.plan.clone().map_or("logged in".into(), |plan| format!("logged in ({plan})")), + _ => "not logged in".into(), + } +} + fn account_add(args: &Args) -> Result { - let (acc, created) = accounts::add_account(args.word(2, "the account name")?, args.value("alias"), args.value("dir"))?; + let tool = match args.value("tool") { + None => Tool::Claude, + Some(id) => Tool::from_id(id).ok_or_else(|| Error(format!("--tool is claude or codex, not '{id}'.")))?, + }; + let (acc, created) = accounts::add_account(args.word(2, "the account name")?, args.value("alias"), args.value("dir"), tool)?; let how = if created { "created" } else { "already existed and was adopted as is" }; - println!("Added account '{}': folder {} {how}, alias {}.", acc.name, tilde(&acc.dir), shown_alias(&acc)); - if !args.has("no-login") && !claude::auth_status(&acc).logged_in { + println!("Added {} account '{}': folder {} {how}, alias {}.", tool.label(), acc.name, tilde(&acc.dir), shown_alias(&acc)); + if !args.has("no-login") && !tools::auth_status(&acc).logged_in { println!("Signing in..."); - claude_here(&acc, &["auth", "login"])?; + tool_here(&acc, &tool.login_args())?; } - println!("Login: {}", claude::auth_status(&acc).email.unwrap_or_else(|| "not logged in".into())); + println!("Login: {}", login_line(&tools::auth_status(&acc))); alias_note(); Ok(0) } @@ -656,10 +689,10 @@ fn account_rename(args: &Args) -> Result { fn account_login(args: &Args) -> Result { let acc = accounts::get_account(args.word(2, "the account name")?)?; - let info = claude::auth_status(&acc); + let info = tools::auth_status(&acc); if info.logged_in { let (sessions, _) = sessions::all_sessions(std::slice::from_ref(&acc))?; - println!("'{}' is logged in as {}.", acc.name, info.email.unwrap_or_default()); + println!("'{}' is {}.", acc.name, info.email.map_or("logged in".into(), |e| format!("logged in as {e}"))); let live: Vec<&Session> = sessions.iter().filter(|s| s.live).collect(); if !live.is_empty() { println!("These running sessions will lose their login:"); @@ -670,11 +703,11 @@ fn account_login(args: &Args) -> Result { if !confirm("Log out and sign in again? History and settings are kept.") { return Ok(1); } - claude_here(&acc, &["auth", "logout"])?; + tool_here(&acc, &acc.tool.logout_args())?; } - claude_here(&acc, &["auth", "login"])?; - let info = claude::auth_status(&acc); - println!("Login: {}", info.email.clone().unwrap_or_else(|| "not logged in".into())); + tool_here(&acc, &acc.tool.login_args())?; + let info = tools::auth_status(&acc); + println!("Login: {}", login_line(&info)); Ok(!info.logged_in as i32) } @@ -688,7 +721,7 @@ fn account_remove(args: &Args) -> Result { println!(" {}", describe(sess)); } } - if !args.has("yes") && !confirm(&format!("Remove account '{}' from Claude Sessions? Nothing on disk is deleted.", acc.name)) { + if !args.has("yes") && !confirm(&format!("Remove account '{}' from Paddock? Nothing on disk is deleted.", acc.name)) { return Ok(1); } accounts::remove_account(&acc.name)?; diff --git a/src/closing.rs b/src/closing.rs index e52ab49..a8665a1 100644 --- a/src/closing.rs +++ b/src/closing.rs @@ -8,10 +8,11 @@ use serde::Serialize; use serde_json::Value; use crate::accounts::{self, Account}; -use crate::claude; +use crate::codex; use crate::os; use crate::sessions::{self, Session}; use crate::store; +use crate::tools::{self, Tool}; use crate::util::{err, Result}; pub const CLOSE_WAIT_SECONDS: u64 = 5; @@ -37,7 +38,9 @@ fn wait_gone(pid: u32, seconds: u64) -> bool { /// the session really is stopped afterwards. pub fn close_session(sess: &Session) -> Closed { let result = accounts::get_account(&sess.account).and_then(|acc| { - if sess.is_background() { + if acc.tool == Tool::Codex { + close_codex(&acc, sess) + } else if sess.is_background() { close_background(&acc, sess) } else { close_interactive(&acc, sess) @@ -50,7 +53,7 @@ pub fn close_session(sess: &Session) -> Closed { } fn close_background(acc: &Account, sess: &Session) -> Result { - let out = claude::run(acc, &["stop", &sess.id], 45)?; + let out = tools::run(acc, &["stop", &sess.id], 45)?; if let Some(pid) = sess.pid.filter(|_| sess.live) { if !wait_gone(pid, CLOSE_WAIT_SECONDS) { return err(format!("claude stop did not stop it: {}", out.last_line())); @@ -60,6 +63,33 @@ fn close_background(acc: &Account, sess: &Session) -> Result { Ok(if sess.live { "Stopped." } else { "Already finished; marked closed." }.into()) } +/// A Codex session runs its turns in Codex's background service, which carries +/// on with a turn after the window is gone: the turn is stopped there first, +/// then the window. Run with `--no-daemon`, the window holds the turn itself, and +/// runs each command in a process group of its own that outlives the window. +fn close_codex(acc: &Account, sess: &Session) -> Result { + let Some(rollout) = &sess.rollout else { return err("Refresh and try again.") }; + let pid = sess.pid.filter(|pid| os::pid_alive(*pid)); + if let Some(pid) = pid { + if codex::verify(pid, &sess.session_id, rollout, &sess.cwd)? { + let commands = os::child_groups(pid); + let stopped = stop(pid)?; + for group in commands { + let _ = os::terminate_group(group); + } + return Ok(stopped); + } + } + let turn = codex::interrupt(acc, &sess.session_id, rollout); + match (pid, turn) { + (Some(pid), Ok(_)) => stop(pid), + (Some(pid), Err(e)) => stop(pid).map(|_| format!("Closed its window. {e} Its turn may still finish in the background.")), + (None, Ok(true)) => Ok("Stopped.".into()), + (None, Ok(false)) => Ok(if sess.pid.is_some() { "Its process had already ended; marked closed." } else { "Already finished; marked closed." }.into()), + (None, Err(e)) => Err(e), + } +} + fn close_interactive(acc: &Account, sess: &Session) -> Result { let Some(pid) = sess.pid.filter(|pid| os::pid_alive(*pid)) else { return Ok("Its process had already ended; marked closed.".into()); @@ -73,7 +103,10 @@ fn close_interactive(acc: &Account, sess: &Session) -> Result { } } os::verify_session_process(pid, &record)?; + stop(pid) +} +fn stop(pid: u32) -> Result { os::terminate(pid)?; if !wait_gone(pid, CLOSE_WAIT_SECONDS) { return err(format!("It did not exit within {CLOSE_WAIT_SECONDS} seconds and was left running.")); diff --git a/src/codex.rs b/src/codex.rs new file mode 100644 index 0000000..f431d20 --- /dev/null +++ b/src/codex.rs @@ -0,0 +1,1313 @@ +//! What only Codex has: its saved conversations ("rollouts"), the names it gives +//! them, its running sessions, and who is signed in. Everything under an +//! account's folder is only ever read. + +use std::collections::HashMap; +use std::fs::{self, File}; +use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::{mpsc, Mutex}; +use std::thread; +use std::time::{Duration, Instant, SystemTime}; + +use memchr::memmem; +use ruzstd::decoding::StreamingDecoder; +use serde_json::{json, Value}; + +use crate::accounts::Account; +use crate::history::{self, Entry, Tokens}; +use crate::loops::Gatherer; +use crate::os; +use crate::tools::{self, AuthInfo}; +use crate::util::{err, iso_to_ms, squash, Error, Result}; + +// ------------------------------------------------------------------- rollouts + +/// `/sessions/YYYY/MM/DD/rollout-