Compare commits
11 Commits
e4ab8c2136
...
v0.0.7
| Author | SHA1 | Date | |
|---|---|---|---|
| fe25fcf043 | |||
| 2fa00ad510 | |||
| 34b41be1df | |||
| de60b93bc6 | |||
| 67b994f629 | |||
| f10598601f | |||
| cadd4c8f64 | |||
| 98d1c059cf | |||
| cf65d5d707 | |||
| ef9b8e71c6 | |||
| e64060e40f |
76
CHANGELOG.md
76
CHANGELOG.md
@@ -6,6 +6,70 @@ loosely follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.0.7] - 2026-05-18
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- The top tab bar now prefixes each agent tab's label with its
|
||||||
|
idle-state glyph (✕ error, ? permission, ◐ thinking, ○ idle, ●
|
||||||
|
working), matching the sidebar's vocabulary so the state of every
|
||||||
|
open agent is visible without opening or focusing each tab.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Built-in agent presets (`claude`, `codex`, `opencode`) now live in
|
||||||
|
memory and user preset files merge over them by name instead of
|
||||||
|
patterm writing default preset files into `$XDG_CONFIG_HOME`. Add
|
||||||
|
`"disabled": true` in a matching user preset to hide a built-in.
|
||||||
|
- Generated MCP config files for agent launches now live under the
|
||||||
|
runtime agent directory instead of `$XDG_CONFIG_HOME/patterm/mcp`.
|
||||||
|
- Auto-summarization settings now save as soon as a changed row is
|
||||||
|
applied, including cadence/provider/toggle changes and model edits,
|
||||||
|
without requiring a separate save step.
|
||||||
|
- The Agents / Auto-summarization settings screen no longer shows
|
||||||
|
explicit Save, Cancel, or Back rows, and its footer copy no longer
|
||||||
|
describes a separate save/cancel flow.
|
||||||
|
- Auto-summarization setting rows now visually separate grey labels
|
||||||
|
from regular-colour values.
|
||||||
|
- The active-thread summary in the tab bar is now constrained to the
|
||||||
|
active tab's width instead of spanning the whole top row.
|
||||||
|
- Sidebar summary text now wraps from the full summary text instead of
|
||||||
|
using an ellipsized single-line value.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Claude permission prompts are now detected from the rendered pane as
|
||||||
|
well as the recent output tail, so the sidebar marks the pane as
|
||||||
|
waiting for permission even while `Calling patterm...` continues to
|
||||||
|
repaint.
|
||||||
|
- Removed the redundant "Back to Settings" row from the
|
||||||
|
Agents / Auto-summarization settings screen.
|
||||||
|
- Pending `timer_*` entries are now cancelled when their owning or
|
||||||
|
watched child is closed via `close_process`, preventing stale
|
||||||
|
timer bodies from being re-delivered to the orchestrator pane
|
||||||
|
after the work has already been handled.
|
||||||
|
|
||||||
|
## [0.0.6] - 2026-05-15
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Toast notifications now reserve three content rows and word-wrap
|
||||||
|
the message body inside the box, replacing the previous
|
||||||
|
single-line+ellipsis layout. The `Ctrl-N · N more` inline hint is
|
||||||
|
gone; instead the host status strip surfaces a `Ctrl-N · dismiss`
|
||||||
|
hint, shown only while a notification is on screen so the chord
|
||||||
|
doesn't advertise itself when it has nothing to dismiss.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Auto-summary no longer fails immediately with `codex summarizer:
|
||||||
|
error: unexpected argument '--ask-for-approval' found`. The codex
|
||||||
|
CLI dropped that flag; we now rely on `--sandbox read-only` (which
|
||||||
|
already implies no approvals) instead of passing it.
|
||||||
|
- Toast box no longer flickers / half-erases while the focused
|
||||||
|
child (claude, codex, opencode, etc.) repaints its TUI. The
|
||||||
|
overlay is now stitched onto the end of the per-chunk PTY write
|
||||||
|
under `outMu`, and wrapped in DECSET 2026 (synchronized output)
|
||||||
|
brackets so terminals that support it batch the child's redraw +
|
||||||
|
the box paint into a single frame instead of racing cell-by-cell.
|
||||||
|
|
||||||
|
## [0.0.5] - 2026-05-15
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
- Replaced the single-slot status-line "flash" with a stackable toast
|
- Replaced the single-slot status-line "flash" with a stackable toast
|
||||||
surface anchored at the top-right of the focused pane. `flashError`,
|
surface anchored at the top-right of the focused pane. `flashError`,
|
||||||
@@ -17,6 +81,18 @@ loosely follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|||||||
- `Ctrl-N` is consumed by the host only when there is a toast to
|
- `Ctrl-N` is consumed by the host only when there is a toast to
|
||||||
dismiss; an empty stack lets `Ctrl-N` pass through to the focused
|
dismiss; an empty stack lets `Ctrl-N` pass through to the focused
|
||||||
child so readline / nano / emacs / opencode keep their bindings.
|
child so readline / nano / emacs / opencode keep their bindings.
|
||||||
|
- Command palette is calmer when something is focused. Focused-section
|
||||||
|
rows now read as bare verbs (`Rename`, `Close`, `Stop`, `Restart`,
|
||||||
|
`Delete`, `Edit`) instead of repeating the focused name (`Close
|
||||||
|
agent: codex`); the title bar's `on: codex` / `pad: notes.md`
|
||||||
|
carries the subject. Fuzzy queries still match the dropped context
|
||||||
|
through the row hint (e.g. typing `close codex` still finds the
|
||||||
|
Close row).
|
||||||
|
- Dashed `── Focused ──` / `── Open ──` / `── Spawn ──` section
|
||||||
|
banners are gone. Sections are separated by a single blank spacer
|
||||||
|
row, so the action labels themselves carry the visual weight.
|
||||||
|
- The Open section no longer lists a `Switch to <current>` row for
|
||||||
|
the pane you're already focused on.
|
||||||
|
|
||||||
## [0.0.4] - 2026-05-15
|
## [0.0.4] - 2026-05-15
|
||||||
|
|
||||||
|
|||||||
23
SPEC.md
23
SPEC.md
@@ -39,7 +39,7 @@ The tool is one Go process that owns: the TUI, all PTYs, vt-emulated grids, sess
|
|||||||
|
|
||||||
## 3. Project state layout
|
## 3. Project state layout
|
||||||
|
|
||||||
Scratchpads (user data) live under `$XDG_DATA_HOME`; presets and config live under `$XDG_CONFIG_HOME`.
|
Scratchpads (user data) live under `$XDG_DATA_HOME`; user-authored preset overlays and config live under `$XDG_CONFIG_HOME`.
|
||||||
|
|
||||||
```
|
```
|
||||||
$XDG_DATA_HOME/patterm/
|
$XDG_DATA_HOME/patterm/
|
||||||
@@ -53,12 +53,12 @@ $XDG_DATA_HOME/patterm/
|
|||||||
└── <agent-written>.md
|
└── <agent-written>.md
|
||||||
|
|
||||||
$XDG_CONFIG_HOME/patterm/
|
$XDG_CONFIG_HOME/patterm/
|
||||||
├── config.json # global settings (theme, default keymap, etc.)
|
├── settings.json # global settings, written only after the user changes settings
|
||||||
└── presets/
|
└── presets/
|
||||||
├── agents/
|
├── agents/
|
||||||
│ ├── claude.json # ships as default
|
│ ├── claude.json # optional overlay for built-in claude
|
||||||
│ ├── codex.json # ships as default
|
│ ├── codex.json # optional overlay for built-in codex
|
||||||
│ ├── opencode.json # ships as default
|
│ ├── opencode.json # optional overlay for built-in opencode
|
||||||
│ └── <user-defined>.json
|
│ └── <user-defined>.json
|
||||||
└── processes/
|
└── processes/
|
||||||
├── dev.json # e.g. { "name": "bun run dev", "argv": ["bun", "run", "dev"] }
|
├── dev.json # e.g. { "name": "bun run dev", "argv": ["bun", "run", "dev"] }
|
||||||
@@ -66,7 +66,7 @@ $XDG_CONFIG_HOME/patterm/
|
|||||||
└── <user-defined>.json
|
└── <user-defined>.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Both preset directories are scanned at startup; every file found becomes a palette entry ("Spawn agent: claude", "Run process: bun run dev", …). Presets are project-agnostic in v1 — the same set is available in every project. Per-project overrides can be added later.
|
patterm always has built-in agent presets for `claude`, `codex`, and `opencode`. User preset files are scanned at startup and merged into matching built-ins by `name`, or added as standalone custom presets when the name is new. A matching file with `"disabled": true` hides a built-in. Startup does not write default preset files. Presets are project-agnostic in v1 — the same set is available in every project. Per-project overrides can be added later.
|
||||||
|
|
||||||
Project key = `sha256(realpath(project_dir))[:16]`. Used only as a scratchpad directory name — there is no daemon to look up.
|
Project key = `sha256(realpath(project_dir))[:16]`. Used only as a scratchpad directory name — there is no daemon to look up.
|
||||||
|
|
||||||
@@ -121,7 +121,7 @@ Scratchpads and command-preset trust grants persist across runs. Sessions and ch
|
|||||||
Almost all application functions are driven through a single command palette opened with `Ctrl-K`. The palette is a fuzzy-searchable list of commands, scoped to whatever makes sense for the current focus. Two kinds of entries appear:
|
Almost all application functions are driven through a single command palette opened with `Ctrl-K`. The palette is a fuzzy-searchable list of commands, scoped to whatever makes sense for the current focus. Two kinds of entries appear:
|
||||||
|
|
||||||
- **Built-in commands** — "Switch to session…", "Focus pane…", "Take input control", "Release control to orchestrator", "Open scratchpad…", "Kill child…", "Quit", etc.
|
- **Built-in commands** — "Switch to session…", "Focus pane…", "Take input control", "Release control to orchestrator", "Open scratchpad…", "Kill child…", "Quit", etc.
|
||||||
- **Preset commands** — one entry per file under `$XDG_CONFIG_HOME/patterm/presets/`. Agent presets surface as "Spawn agent: codex" / "Spawn agent: claude" / …; process presets surface as "Run process: bun run dev" / "Run process: vitest" / …. The label comes from the preset's `name` field; the action is "launch this preset into a new pane."
|
- **Preset commands** — one entry per built-in or user-defined preset. Agent presets surface as "Spawn agent: codex" / "Spawn agent: claude" / …; process presets surface as "Run process: bun run dev" / "Run process: vitest" / …. The label comes from the preset's `name` field; the action is "launch this preset into a new pane."
|
||||||
|
|
||||||
Selecting a preset either launches it immediately (no required args) or opens a sub-palette for optional args — namely an **initial prompt** (agent presets only), which patterm injects into the spawned PTY's input after the agent is ready (§8). The orchestrator equivalent of this — `spawn_agent` / `spawn_process` MCP tools — uses the exact same machinery: pick a preset by name, optionally supply an initial prompt, patterm handles the rest.
|
Selecting a preset either launches it immediately (no required args) or opens a sub-palette for optional args — namely an **initial prompt** (agent presets only), which patterm injects into the spawned PTY's input after the agent is ready (§8). The orchestrator equivalent of this — `spawn_agent` / `spawn_process` MCP tools — uses the exact same machinery: pick a preset by name, optionally supply an initial prompt, patterm handles the rest.
|
||||||
|
|
||||||
@@ -365,11 +365,11 @@ Risks acknowledged: the orchestrator's reading of the prompt is a vision/parsing
|
|||||||
|
|
||||||
## 10. Presets
|
## 10. Presets
|
||||||
|
|
||||||
Presets are user-editable JSON files that describe how to launch something. patterm itself has no hard-coded agent or process types — every spawnable thing is a preset. Two flavours:
|
Presets describe how to launch something. patterm has built-in defaults for common agent CLIs, and user-editable JSON files can override, disable, or add presets. Two flavours:
|
||||||
|
|
||||||
### Agent presets
|
### Agent presets
|
||||||
|
|
||||||
`$XDG_CONFIG_HOME/patterm/presets/agents/<name>.json`. Launches a vendor LLM CLI with MCP wired up and the conversation-protocol addendum injected.
|
Built-in agent presets launch vendor LLM CLIs with MCP wired up and the conversation-protocol addendum injected. `$XDG_CONFIG_HOME/patterm/presets/agents/<name>.json` can overlay a built-in by `name` or define a new agent preset.
|
||||||
|
|
||||||
| Field | Purpose |
|
| Field | Purpose |
|
||||||
|---|---|
|
|---|---|
|
||||||
@@ -377,17 +377,18 @@ Presets are user-editable JSON files that describe how to launch something. patt
|
|||||||
| `argv` | Full launch argv (e.g. `["claude"]`, `["codex", "--no-tui-banner"]`) |
|
| `argv` | Full launch argv (e.g. `["claude"]`, `["codex", "--no-tui-banner"]`) |
|
||||||
| `env` | Env vars to set (merged over inherited env) |
|
| `env` | Env vars to set (merged over inherited env) |
|
||||||
| `working_dir` | Defaults to the project root |
|
| `working_dir` | Defaults to the project root |
|
||||||
|
| `disabled` | If `true`, hides a built-in preset with the same `name` |
|
||||||
| `mcp_injection` | How to point this CLI at patterm's stdio proxy. One of: `{ "kind": "flag", "flag": "--mcp-config", "config_path": "..." }`, `{ "kind": "config_file", "path": "~/.codex/config.toml", "merge_key": "mcp_servers" }`, `{ "kind": "env_var", "var": "MCP_CONFIG_PATH" }` |
|
| `mcp_injection` | How to point this CLI at patterm's stdio proxy. One of: `{ "kind": "flag", "flag": "--mcp-config", "config_path": "..." }`, `{ "kind": "config_file", "path": "~/.codex/config.toml", "merge_key": "mcp_servers" }`, `{ "kind": "env_var", "var": "MCP_CONFIG_PATH" }` |
|
||||||
| `ready_signal` | How to detect the TUI is ready (default: 1s idle after launch). Override per-CLI if needed. |
|
| `ready_signal` | How to detect the TUI is ready (default: 1s idle after launch). Override per-CLI if needed. |
|
||||||
| `chrome_trim_hints` | Optional regexes / row ranges for stripping vendor chrome in grid reads |
|
| `chrome_trim_hints` | Optional regexes / row ranges for stripping vendor chrome in grid reads |
|
||||||
|
|
||||||
Default presets shipped: `claude`, `codex`, `opencode`. Authoring these is per-vendor research — each CLI has its own MCP config conventions, ready states, and TUI chrome. Users can copy and edit them, or add new ones (e.g. a second `claude` preset that launches with a specific model or system prompt file).
|
Built-in presets: `claude`, `codex`, `opencode`. Authoring these is per-vendor research — each CLI has its own MCP config conventions, ready states, idle detection, and TUI chrome. Users can add small overlay files for built-ins, disable built-ins, or add new presets (e.g. a second `claude-sonnet` preset that launches with a specific model or system prompt file).
|
||||||
|
|
||||||
MCP config flow: at startup, for each agent preset, patterm renders a small JSON pointing at its own `mcp-stdio` proxy subcommand (`patterm mcp-stdio --socket <pid-sock> --identity <token>`) into a per-preset temp file. The launch then uses the preset's `mcp_injection` strategy to hand that path to the CLI. The user's global vendor config is never mutated.
|
MCP config flow: at startup, for each agent preset, patterm renders a small JSON pointing at its own `mcp-stdio` proxy subcommand (`patterm mcp-stdio --socket <pid-sock> --identity <token>`) into a per-preset temp file. The launch then uses the preset's `mcp_injection` strategy to hand that path to the CLI. The user's global vendor config is never mutated.
|
||||||
|
|
||||||
### Process presets
|
### Process presets
|
||||||
|
|
||||||
`$XDG_CONFIG_HOME/patterm/presets/processes/<name>.json`. Launches a raw command in a PTY — no MCP, no addendum, no system prompt.
|
`$XDG_CONFIG_HOME/patterm/presets/processes/<name>.json`. Launches a raw command in a PTY — no MCP, no addendum, no system prompt. There are no built-in process presets.
|
||||||
|
|
||||||
| Field | Purpose |
|
| Field | Purpose |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
|||||||
3
TODO.md
3
TODO.md
@@ -1,3 +0,0 @@
|
|||||||
The close action in the command palette should just be "Close current agent" rather than "Close codex"
|
|
||||||
Same with the other "focused" parts. It seems a bit clunky right now. "Close current agent"
|
|
||||||
In general I think while the feature set has grown, the actual refinement of it isn't great, it feels a bit cluttered.
|
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
claude + new │ Processes
|
|
||||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━───────│ ─────────────────────────
|
|
||||||
- abc1234 if no tag exists yet
|
|
||||||
|
|
||||||
4. Wire version into the release workflow
|
|
||||||
|
|
||||||
Update .gitea/workflows/release.yml lines 31-35 to inject the pushed tag:
|
|
||||||
|
|
||||||
go build -trimpath \
|
|
||||||
-ldflags="-s -w -X main.version=${{ github.ref_name }}" \
|
|
||||||
-o dist/patterm-${{ github.ref_name }}-linux-amd64 \
|
|
||||||
./cmd/patterm
|
|
||||||
|
|
||||||
github.ref_name is the tag name (e.g. v0.0.1) because the workflow only
|
|
||||||
triggers on tags: ['v*'].
|
|
||||||
|
|
||||||
5. Update inline doc comment
|
|
||||||
|
|
||||||
cmd/patterm/main.go header comment (lines 5-11) — add the --version form
|
|
||||||
to the usage block. SPEC.md/CLAUDE.md already use --, no change needed there.
|
|
||||||
|
|
||||||
Out of scope
|
|
||||||
|
|
||||||
- Surfacing version in MCP whoami (the hardcoded "version": "0.1.0" in
|
|
||||||
internal/mcp/protocol.go:27 is the MCP protocol version, not the patterm
|
|
||||||
binary version — leave it).
|
|
||||||
- Renaming any existing flags.
|
|
||||||
- Adding short forms like -p for --project.
|
|
||||||
|
|
||||||
Critical files
|
|
||||||
|
|
||||||
- cmd/patterm/main.go — import swap, --version wiring, version var, header comment
|
|
||||||
- cmd/patterm/debug_harness.go — import swap
|
|
||||||
- Makefile lines 38-39 — VERSION var + ldflags
|
|
||||||
- .gitea/workflows/release.yml lines 31-35 — ldflags
|
|
||||||
- go.mod / go.sum — add github.com/spf13/pflag
|
|
||||||
|
|
||||||
Verification
|
|
||||||
|
|
||||||
1. go build -o ./bin/patterm ./cmd/patterm (without Makefile) → still builds, version reports dev.
|
|
||||||
2. make patterm → ./bin/patterm --version prints patterm v0.0.1 (commit <sha>, built <date>).
|
|
||||||
3. ./bin/patterm -h → help text shows --project string and --version lines.
|
|
||||||
4. ./bin/patterm -project /tmp → pflag rejects with usage error (confirms -- is enforced).
|
|
||||||
5. ./bin/patterm --project /tmp → starts normally.
|
|
||||||
6. ./bin/patterm mcp-stdio --socket /tmp/s --identity x → existing path still works (will fail to connect, but should parse flags fine).
|
|
||||||
7. ./bin/patterm debug-harness --scenario internal/harness/scenarios/spawn_process_via_palette.json → harness still runs.
|
|
||||||
8. go test ./... and go test ./internal/harness/... — both green.
|
|
||||||
9. Push a temporary tag locally and inspect git describe output; confirm release workflow's ${{ github.ref_name }} substitution matches the tag.
|
|
||||||
╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌
|
|
||||||
|
|
||||||
Claude has written up a plan and is ready to execute. Would you like to proceed?
|
|
||||||
|
|
||||||
❯ 1. Yes, and use auto mode
|
|
||||||
2. Yes, manually approve edits
|
|
||||||
3. No, refine with Ultraplan on Claude Code on the web
|
|
||||||
4. Tell Claude what to change
|
|
||||||
shift+tab to approve with this feedback
|
|
||||||
|
|
||||||
ctrl-g to edit in VS Code · ~/.claude/plans/flags-in-this-project-vectorized-gosling.md
|
|
||||||
|
|
||||||
claude · you have control Ctrl-A/D · tabs · Ctrl-W/S · tree · Ctrl-K · palette
|
|
||||||
@@ -187,9 +187,7 @@ func Run(ctx context.Context, opts Options) error {
|
|||||||
}, func(_ string, result summaryState) {
|
}, func(_ string, result summaryState) {
|
||||||
if result.Error != "" {
|
if result.Error != "" {
|
||||||
st.flashError(fmt.Sprintf("summary: %v", result.Error))
|
st.flashError(fmt.Sprintf("summary: %v", result.Error))
|
||||||
return
|
|
||||||
}
|
}
|
||||||
st.flashTransient("summary updated")
|
|
||||||
})
|
})
|
||||||
sess.SetMetrics(metrics)
|
sess.SetMetrics(metrics)
|
||||||
host.attention = st
|
host.attention = st
|
||||||
@@ -507,7 +505,18 @@ func (st *uiState) dbgf(format string, args ...any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (st *uiState) activeSummaryText(width int) string {
|
func (st *uiState) activeSummaryText(width int) string {
|
||||||
if width <= 0 || st.summaries == nil {
|
text := st.activeSummaryRaw()
|
||||||
|
if text == "" || width <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if visibleLen(text) > width {
|
||||||
|
text = clipRunes(text, width-1) + "…"
|
||||||
|
}
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
func (st *uiState) activeSummaryRaw() string {
|
||||||
|
if st.summaries == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
st.settingsMu.Lock()
|
st.settingsMu.Lock()
|
||||||
@@ -527,9 +536,6 @@ func (st *uiState) activeSummaryText(width int) string {
|
|||||||
if text == "" {
|
if text == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
if visibleLen(text) > width {
|
|
||||||
text = clipRunes(text, width-1) + "…"
|
|
||||||
}
|
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -823,14 +829,21 @@ func (st *uiState) OnChildSpawned(c *Child) {
|
|||||||
st.drawStatusLine()
|
st.drawStatusLine()
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnChildStateChanged repaints the sidebar whenever a child's
|
// OnChildStateChanged repaints the sidebar and tab bar whenever a
|
||||||
// idle-state badge flips. Cheap — the badge is the only chrome that
|
// child's idle-state badge flips. Cheap — both draws bail when the
|
||||||
// reflects state today, and drawSidebar bails when the cached frame
|
// cached frame hasn't changed.
|
||||||
// hasn't changed.
|
|
||||||
func (st *uiState) OnChildStateChanged(string, IdleState) {
|
func (st *uiState) OnChildStateChanged(string, IdleState) {
|
||||||
|
st.drawTabBar()
|
||||||
st.drawSidebar()
|
st.drawSidebar()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OnChildClosed is the explicit-removal hook (close_process or the
|
||||||
|
// terminal-corpse cleanup in reapChild). The UI already reflects
|
||||||
|
// removals via the OnChildExited path and the children-map view, so
|
||||||
|
// this is a no-op here — the timerManager is the consumer that
|
||||||
|
// cares.
|
||||||
|
func (st *uiState) OnChildClosed(string) {}
|
||||||
|
|
||||||
// OnChildExited drops focus and shows the empty state if it was the
|
// OnChildExited drops focus and shows the empty state if it was the
|
||||||
// focused child.
|
// focused child.
|
||||||
func (st *uiState) OnChildExited(c *Child) {
|
func (st *uiState) OnChildExited(c *Child) {
|
||||||
@@ -969,14 +982,19 @@ func (st *uiState) OnPTYOut(childID string, chunk []byte) {
|
|||||||
st.metrics.recordRender(time.Since(rstart))
|
st.metrics.recordRender(time.Since(rstart))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// One write covers the autowrap-disable prelude, the chunk, and the
|
// One write covers the autowrap-disable prelude, the chunk, the
|
||||||
// autowrap-restore postlude — three syscalls collapsed into one
|
// autowrap-restore postlude, and (when a toast is up) the toast
|
||||||
// under outMu. The three sequences were already emitted atomically
|
// overlay — four syscalls collapsed into one under outMu. The
|
||||||
// under the lock; coalescing just halves the syscall count.
|
// sequences were already emitted atomically under the lock;
|
||||||
wrapped := make([]byte, 0, len(out)+10)
|
// coalescing just halves the syscall count and makes claude's
|
||||||
|
// continuous redraws + our toast layer land in the same frame so
|
||||||
|
// the box doesn't flicker as the child paints over its cells.
|
||||||
|
overlay := st.toastOverlayBytes()
|
||||||
|
wrapped := make([]byte, 0, len(out)+len(overlay)+10)
|
||||||
wrapped = append(wrapped, "\x1b[?7l"...)
|
wrapped = append(wrapped, "\x1b[?7l"...)
|
||||||
wrapped = append(wrapped, out...)
|
wrapped = append(wrapped, out...)
|
||||||
wrapped = append(wrapped, "\x1b[?7h"...)
|
wrapped = append(wrapped, "\x1b[?7h"...)
|
||||||
|
wrapped = append(wrapped, overlay...)
|
||||||
var wstart time.Time
|
var wstart time.Time
|
||||||
if st.metrics != nil {
|
if st.metrics != nil {
|
||||||
wstart = time.Now()
|
wstart = time.Now()
|
||||||
@@ -1219,6 +1237,12 @@ func (st *uiState) drawStatusLine() {
|
|||||||
hints = append(hints, "Ctrl-R · restart")
|
hints = append(hints, "Ctrl-R · restart")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Surface the toast-dismiss chord only while a notification is on
|
||||||
|
// screen — the hint is noise otherwise, and Ctrl-N falls through
|
||||||
|
// to the focused PTY when the stack is empty.
|
||||||
|
if st.toasts.length() > 0 {
|
||||||
|
hints = append(hints, "Ctrl-N · dismiss")
|
||||||
|
}
|
||||||
right := strings.Join(hints, " · ")
|
right := strings.Join(hints, " · ")
|
||||||
for len(hints) > 1 && int(cols)-len(left)-len(right) < 1 {
|
for len(hints) > 1 && int(cols)-len(left)-len(right) < 1 {
|
||||||
hints = hints[1:]
|
hints = hints[1:]
|
||||||
@@ -1617,6 +1641,11 @@ func (st *uiState) processStdin(chunk []byte) {
|
|||||||
adv = 1
|
adv = 1
|
||||||
}
|
}
|
||||||
i += adv
|
i += adv
|
||||||
|
if action.kind == "settings-save" {
|
||||||
|
st.applySettingsAction(action)
|
||||||
|
st.renderPaletteLocked()
|
||||||
|
continue
|
||||||
|
}
|
||||||
if done {
|
if done {
|
||||||
a := action
|
a := action
|
||||||
pendingAction = &a
|
pendingAction = &a
|
||||||
@@ -2026,13 +2055,6 @@ func (st *uiState) closePalette(action paletteAction) {
|
|||||||
case "proc-restart":
|
case "proc-restart":
|
||||||
st.handleProcRestart(action.childID)
|
st.handleProcRestart(action.childID)
|
||||||
|
|
||||||
case "settings-close":
|
|
||||||
st.applySettingsAction(action)
|
|
||||||
restoreView()
|
|
||||||
st.drawTabBar()
|
|
||||||
st.drawSidebar()
|
|
||||||
st.drawStatusLine()
|
|
||||||
|
|
||||||
case "settings-test":
|
case "settings-test":
|
||||||
st.applySettingsAction(action)
|
st.applySettingsAction(action)
|
||||||
restoreView()
|
restoreView()
|
||||||
|
|||||||
@@ -50,8 +50,14 @@ func (s *Session) classifyOne(c *Child) {
|
|||||||
idleMS := c.IdleMS()
|
idleMS := c.IdleMS()
|
||||||
titleIdleMS := c.TitleIdleMS()
|
titleIdleMS := c.TitleIdleMS()
|
||||||
title := c.Title()
|
title := c.Title()
|
||||||
tail := c.tailBytes(classifierTailBytes)
|
tail := stripANSIBytes(nil, c.tailBytes(classifierTailBytes))
|
||||||
state, reason := classify(c.idleDetection, exited, exitNonZero, idleMS, titleIdleMS, title, tail)
|
var screen []byte
|
||||||
|
if em := c.Emulator(); em != nil {
|
||||||
|
if txt, err := em.ScreenText(); err == nil {
|
||||||
|
screen = []byte(txt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state, reason := classify(c.idleDetection, exited, exitNonZero, idleMS, titleIdleMS, title, tail, screen)
|
||||||
if c.setIdleState(state, reason) {
|
if c.setIdleState(state, reason) {
|
||||||
s.emitStateChanged(c.ID, state)
|
s.emitStateChanged(c.ID, state)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,6 +111,13 @@ func (d *debugCapture) OnChildStateChanged(id string, state IdleState) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (d *debugCapture) OnChildClosed(id string) {
|
||||||
|
d.writeEvent("child_closed", map[string]any{
|
||||||
|
"time": time.Now().Format(time.RFC3339Nano),
|
||||||
|
"id": id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (d *debugCapture) OnPTYOut(childID string, chunk []byte) {
|
func (d *debugCapture) OnPTYOut(childID string, chunk []byte) {
|
||||||
if len(chunk) == 0 {
|
if len(chunk) == 0 {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -86,10 +86,10 @@ func newToolHost(sess *Session, pads *scratchpad.Store, launcher *Launcher, pres
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
// timerListenerAdapter forwards OnChildStateChanged into the timer
|
// timerListenerAdapter forwards OnChildStateChanged and OnChildClosed
|
||||||
// manager and ignores the other ChildEventListener methods. The
|
// into the timer manager and ignores the other ChildEventListener
|
||||||
// session's listener API is by-interface, so we wrap the manager
|
// methods. The session's listener API is by-interface, so we wrap
|
||||||
// rather than make it implement the full surface.
|
// the manager rather than make it implement the full surface.
|
||||||
type timerListenerAdapter struct{ m *timerManager }
|
type timerListenerAdapter struct{ m *timerManager }
|
||||||
|
|
||||||
func (a timerListenerAdapter) OnChildSpawned(*Child) {}
|
func (a timerListenerAdapter) OnChildSpawned(*Child) {}
|
||||||
@@ -98,6 +98,9 @@ func (a timerListenerAdapter) OnPTYOut(string, []byte) {}
|
|||||||
func (a timerListenerAdapter) OnChildStateChanged(id string, st IdleState) {
|
func (a timerListenerAdapter) OnChildStateChanged(id string, st IdleState) {
|
||||||
a.m.onChildStateChanged(id, st)
|
a.m.onChildStateChanged(id, st)
|
||||||
}
|
}
|
||||||
|
func (a timerListenerAdapter) OnChildClosed(id string) {
|
||||||
|
a.m.onChildClosed(id)
|
||||||
|
}
|
||||||
|
|
||||||
func (h *toolHost) SetSize(cols, rows uint16) {
|
func (h *toolHost) SetSize(cols, rows uint16) {
|
||||||
h.sizeMu.Lock()
|
h.sizeMu.Lock()
|
||||||
@@ -553,6 +556,7 @@ func (n *chunkNotifier) OnPTYOut(id string, chunk []byte) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
func (n *chunkNotifier) OnChildStateChanged(string, IdleState) {}
|
func (n *chunkNotifier) OnChildStateChanged(string, IdleState) {}
|
||||||
|
func (n *chunkNotifier) OnChildClosed(string) {}
|
||||||
|
|
||||||
func (h *toolHost) GetProcessPorts(callerID, processID string) ([]mcp.PortSighting, error) {
|
func (h *toolHost) GetProcessPorts(callerID, processID string) ([]mcp.PortSighting, error) {
|
||||||
c := h.sess.FindChild(processID)
|
c := h.sess.FindChild(processID)
|
||||||
|
|||||||
@@ -118,7 +118,8 @@ func compilePatterns(ps []string) []*regexp.Regexp {
|
|||||||
// - titleIdleMS: ms since the last OSC title change (0 if no title yet)
|
// - titleIdleMS: ms since the last OSC title change (0 if no title yet)
|
||||||
// - title: current OSC title
|
// - title: current OSC title
|
||||||
// - tail: recent output bytes for regex matching
|
// - tail: recent output bytes for regex matching
|
||||||
func classify(cfg *resolvedIdleDetection, exited, exitNonZero bool, idleMS, titleIdleMS int64, title string, tail []byte) (IdleState, string) {
|
// - screen: current rendered screen text for persistent prompt matching
|
||||||
|
func classify(cfg *resolvedIdleDetection, exited, exitNonZero bool, idleMS, titleIdleMS int64, title string, tail, screen []byte) (IdleState, string) {
|
||||||
if exited {
|
if exited {
|
||||||
if exitNonZero {
|
if exitNonZero {
|
||||||
return StateError, "process exited non-zero"
|
return StateError, "process exited non-zero"
|
||||||
@@ -128,14 +129,14 @@ func classify(cfg *resolvedIdleDetection, exited, exitNonZero bool, idleMS, titl
|
|||||||
if cfg == nil {
|
if cfg == nil {
|
||||||
cfg = &resolvedIdleDetection{strategy: StrategyOutputActivity, idleThresholdMS: defaultIdleThresholdMS}
|
cfg = &resolvedIdleDetection{strategy: StrategyOutputActivity, idleThresholdMS: defaultIdleThresholdMS}
|
||||||
}
|
}
|
||||||
if len(tail) > 0 {
|
if len(tail) > 0 || len(screen) > 0 {
|
||||||
if matchAny(cfg.errorRegexes, tail) {
|
if matchAny(cfg.errorRegexes, tail, screen) {
|
||||||
return StateError, "error regex matched"
|
return StateError, "error regex matched"
|
||||||
}
|
}
|
||||||
if matchAny(cfg.permissionRegexes, tail) {
|
if matchAny(cfg.permissionRegexes, tail, screen) {
|
||||||
return StatePermission, "permission regex matched"
|
return StatePermission, "permission regex matched"
|
||||||
}
|
}
|
||||||
if matchAny(cfg.thinkingRegexes, tail) {
|
if matchAny(cfg.thinkingRegexes, tail, screen) {
|
||||||
return StateThinking, "thinking regex matched"
|
return StateThinking, "thinking regex matched"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -172,12 +173,14 @@ func baseStateFromIdleMS(idleMS, threshold int64) (IdleState, string) {
|
|||||||
return StateIdle, "quiet for threshold"
|
return StateIdle, "quiet for threshold"
|
||||||
}
|
}
|
||||||
|
|
||||||
func matchAny(res []*regexp.Regexp, tail []byte) bool {
|
func matchAny(res []*regexp.Regexp, texts ...[]byte) bool {
|
||||||
for _, re := range res {
|
for _, re := range res {
|
||||||
if re.Match(tail) {
|
for _, text := range texts {
|
||||||
|
if len(text) > 0 && re.Match(text) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestClassifyOutputActivity(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
got, _ := classify(cfg, false, false, tc.idleMS, 0, "", nil)
|
got, _ := classify(cfg, false, false, tc.idleMS, 0, "", nil, nil)
|
||||||
if got != tc.want {
|
if got != tc.want {
|
||||||
t.Fatalf("got %q want %q", got, tc.want)
|
t.Fatalf("got %q want %q", got, tc.want)
|
||||||
}
|
}
|
||||||
@@ -41,18 +41,18 @@ func TestClassifyOutputActivity(t *testing.T) {
|
|||||||
func TestClassifyTitleStability(t *testing.T) {
|
func TestClassifyTitleStability(t *testing.T) {
|
||||||
cfg := &resolvedIdleDetection{strategy: StrategyOSCTitleStability, idleThresholdMS: 2000}
|
cfg := &resolvedIdleDetection{strategy: StrategyOSCTitleStability, idleThresholdMS: 2000}
|
||||||
// Title change recent → working.
|
// Title change recent → working.
|
||||||
if got, _ := classify(cfg, false, false, 9999, 500, "step 3", nil); got != StateWorking {
|
if got, _ := classify(cfg, false, false, 9999, 500, "step 3", nil, nil); got != StateWorking {
|
||||||
t.Fatalf("recent title change: got %q", got)
|
t.Fatalf("recent title change: got %q", got)
|
||||||
}
|
}
|
||||||
// Title stable past threshold → idle.
|
// Title stable past threshold → idle.
|
||||||
if got, _ := classify(cfg, false, false, 9999, 5000, "step 3", nil); got != StateIdle {
|
if got, _ := classify(cfg, false, false, 9999, 5000, "step 3", nil, nil); got != StateIdle {
|
||||||
t.Fatalf("stable title: got %q", got)
|
t.Fatalf("stable title: got %q", got)
|
||||||
}
|
}
|
||||||
// No title yet: fall back to output activity.
|
// No title yet: fall back to output activity.
|
||||||
if got, _ := classify(cfg, false, false, 100, 0, "", nil); got != StateWorking {
|
if got, _ := classify(cfg, false, false, 100, 0, "", nil, nil); got != StateWorking {
|
||||||
t.Fatalf("no title yet, recent output: got %q", got)
|
t.Fatalf("no title yet, recent output: got %q", got)
|
||||||
}
|
}
|
||||||
if got, _ := classify(cfg, false, false, 5000, 0, "", nil); got != StateIdle {
|
if got, _ := classify(cfg, false, false, 5000, 0, "", nil, nil); got != StateIdle {
|
||||||
t.Fatalf("no title yet, output idle: got %q", got)
|
t.Fatalf("no title yet, output idle: got %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -67,14 +67,14 @@ func TestClassifyTitleStatus(t *testing.T) {
|
|||||||
"error": StateError,
|
"error": StateError,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if got, _ := classify(cfg, false, false, 9999, 500, "Thinking…", nil); got != StateThinking {
|
if got, _ := classify(cfg, false, false, 9999, 500, "Thinking…", nil, nil); got != StateThinking {
|
||||||
t.Fatalf("thinking title: got %q", got)
|
t.Fatalf("thinking title: got %q", got)
|
||||||
}
|
}
|
||||||
if got, _ := classify(cfg, false, false, 9999, 500, "Waiting for permission", nil); got != StatePermission {
|
if got, _ := classify(cfg, false, false, 9999, 500, "Waiting for permission", nil, nil); got != StatePermission {
|
||||||
t.Fatalf("permission title: got %q", got)
|
t.Fatalf("permission title: got %q", got)
|
||||||
}
|
}
|
||||||
// No match in map → fall back to stability.
|
// No match in map → fall back to stability.
|
||||||
if got, _ := classify(cfg, false, false, 9999, 5000, "ready", nil); got != StateIdle {
|
if got, _ := classify(cfg, false, false, 9999, 5000, "ready", nil, nil); got != StateIdle {
|
||||||
t.Fatalf("unmatched title, stable: got %q", got)
|
t.Fatalf("unmatched title, stable: got %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -88,25 +88,30 @@ func TestClassifyPromoterRegex(t *testing.T) {
|
|||||||
thinkingRegexes: []*regexp.Regexp{mustCompile(t, `Thinking`)},
|
thinkingRegexes: []*regexp.Regexp{mustCompile(t, `Thinking`)},
|
||||||
}
|
}
|
||||||
// Permission promoter beats idle.
|
// Permission promoter beats idle.
|
||||||
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("Approve? [y/n]")); got != StatePermission {
|
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("Approve? [y/n]"), nil); got != StatePermission {
|
||||||
t.Fatalf("permission promoter: got %q", got)
|
t.Fatalf("permission promoter: got %q", got)
|
||||||
}
|
}
|
||||||
// Error trumps permission.
|
// Error trumps permission.
|
||||||
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("panic: bad\nApprove?")); got != StateError {
|
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("panic: bad\nApprove?"), nil); got != StateError {
|
||||||
t.Fatalf("error promoter beats permission: got %q", got)
|
t.Fatalf("error promoter beats permission: got %q", got)
|
||||||
}
|
}
|
||||||
// Thinking promoter on idle output.
|
// Thinking promoter on idle output.
|
||||||
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("Thinking…")); got != StateThinking {
|
if got, _ := classify(cfg, false, false, 5000, 0, "", []byte("Thinking…"), nil); got != StateThinking {
|
||||||
t.Fatalf("thinking promoter: got %q", got)
|
t.Fatalf("thinking promoter: got %q", got)
|
||||||
}
|
}
|
||||||
|
// Rendered-screen prompts still promote even when the raw tail no
|
||||||
|
// longer contains the original prompt bytes.
|
||||||
|
if got, _ := classify(cfg, false, false, 100, 0, "", []byte("Calling patterm..."), []byte("Approve? [y/n]")); got != StatePermission {
|
||||||
|
t.Fatalf("screen permission promoter: got %q", got)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClassifyExitTerminal(t *testing.T) {
|
func TestClassifyExitTerminal(t *testing.T) {
|
||||||
cfg := &resolvedIdleDetection{strategy: StrategyOutputActivity, idleThresholdMS: 2000}
|
cfg := &resolvedIdleDetection{strategy: StrategyOutputActivity, idleThresholdMS: 2000}
|
||||||
if got, _ := classify(cfg, true, true, 0, 0, "", nil); got != StateError {
|
if got, _ := classify(cfg, true, true, 0, 0, "", nil, nil); got != StateError {
|
||||||
t.Fatalf("non-zero exit: got %q", got)
|
t.Fatalf("non-zero exit: got %q", got)
|
||||||
}
|
}
|
||||||
if got, _ := classify(cfg, true, false, 0, 0, "", nil); got != StateIdle {
|
if got, _ := classify(cfg, true, false, 0, 0, "", nil, nil); got != StateIdle {
|
||||||
t.Fatalf("clean exit: got %q", got)
|
t.Fatalf("clean exit: got %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -261,15 +261,11 @@ func (l *Launcher) LaunchTerminal(argv []string, displayName, parentID, workDir
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *Launcher) writeMCPConfig(identity string) (string, error) {
|
func (l *Launcher) writeMCPConfig(identity string) (string, error) {
|
||||||
dir, err := preset.ConfigDir()
|
dir, err := mcpRuntimeDir(identity)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
dir = filepath.Join(dir, "mcp")
|
path := filepath.Join(dir, "mcp.json")
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
path := filepath.Join(dir, identity+".json")
|
|
||||||
cfg := map[string]any{
|
cfg := map[string]any{
|
||||||
"mcpServers": map[string]any{
|
"mcpServers": map[string]any{
|
||||||
"patterm": map[string]any{
|
"patterm": map[string]any{
|
||||||
|
|||||||
30
internal/app/launch_test.go
Normal file
30
internal/app/launch_test.go
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWriteMCPConfigUsesRuntimeDir(t *testing.T) {
|
||||||
|
runtimeDir := t.TempDir()
|
||||||
|
configHome := filepath.Join(t.TempDir(), "config")
|
||||||
|
t.Setenv("XDG_RUNTIME_DIR", runtimeDir)
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||||
|
|
||||||
|
l := &Launcher{bin: "patterm", mcpSocket: "/tmp/patterm.sock"}
|
||||||
|
path, err := l.writeMCPConfig("abc123")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("writeMCPConfig: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(path, filepath.Join(runtimeDir, "patterm", "agents", "abc123")) {
|
||||||
|
t.Fatalf("path = %q, want under runtime dir", path)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
t.Fatalf("config file stat: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(configHome, "patterm")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("writeMCPConfig created XDG config dir or unexpected stat error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -54,14 +54,6 @@ const (
|
|||||||
groupQuit
|
groupQuit
|
||||||
)
|
)
|
||||||
|
|
||||||
var groupLabels = map[int]string{
|
|
||||||
groupFocused: "Focused",
|
|
||||||
groupOpen: "Open",
|
|
||||||
groupSpawn: "Spawn",
|
|
||||||
groupSettings: "Settings",
|
|
||||||
groupQuit: "Quit",
|
|
||||||
}
|
|
||||||
|
|
||||||
type paletteItem struct {
|
type paletteItem struct {
|
||||||
label string
|
label string
|
||||||
hint string
|
hint string
|
||||||
@@ -113,7 +105,6 @@ type settingsInputForm struct {
|
|||||||
title string
|
title string
|
||||||
field string
|
field string
|
||||||
value []rune
|
value []rune
|
||||||
subtitle string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// paletteState is the in-memory model for the overlay. SPEC §4: a
|
// paletteState is the in-memory model for the overlay. SPEC §4: a
|
||||||
@@ -205,8 +196,10 @@ func (p *paletteState) rebuild() {
|
|||||||
all := p.buildItems(macro)
|
all := p.buildItems(macro)
|
||||||
|
|
||||||
if rest == "" {
|
if rest == "" {
|
||||||
// No textual filter: render with section headers between groups.
|
// No textual filter: render with blank spacer rows between
|
||||||
p.items = itemsWithHeaders(all)
|
// groups so sections read as scannable bands without dashed
|
||||||
|
// headers stealing visual weight.
|
||||||
|
p.items = itemsWithSpacers(all)
|
||||||
p.clampCursor()
|
p.clampCursor()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -243,25 +236,28 @@ func (p *paletteState) rebuild() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// buildItems assembles every selectable row in fixed group order
|
// buildItems assembles every selectable row in fixed group order
|
||||||
// (Focused → Open → Spawn → Quit). Headers are added by
|
// (Focused → Open → Spawn → Quit). Blank spacer rows are added by
|
||||||
// itemsWithHeaders for the no-query case; scored mode drops them.
|
// itemsWithSpacers for the no-query case; scored mode drops them.
|
||||||
// When macro is non-empty the result is filtered down to the kinds
|
// When macro is non-empty the result is filtered down to the kinds
|
||||||
// that macro retains.
|
// that macro retains.
|
||||||
func (p *paletteState) buildItems(macro string) []paletteItem {
|
func (p *paletteState) buildItems(macro string) []paletteItem {
|
||||||
var out []paletteItem
|
var out []paletteItem
|
||||||
|
|
||||||
// Group 0: Focused — context-aware actions for whatever owns focus.
|
// Group 0: Focused — context-aware actions for whatever owns focus.
|
||||||
// A focused scratchpad shadows any focused child.
|
// A focused scratchpad shadows any focused child. Labels are bare
|
||||||
|
// verbs because the title bar already carries the subject ("on:
|
||||||
|
// codex" / "pad: notes.md"); the noun + name move into the hint so
|
||||||
|
// fuzzy queries like "close codex" still surface the row.
|
||||||
switch {
|
switch {
|
||||||
case p.focusedPad != "":
|
case p.focusedPad != "":
|
||||||
name := p.focusedPad
|
name := p.focusedPad
|
||||||
out = append(out,
|
out = append(out,
|
||||||
paletteItem{label: "Delete scratchpad: " + name, hint: "remove the file from disk",
|
paletteItem{label: "Edit", hint: "edit scratchpad · " + name + " (opens $EDITOR)",
|
||||||
action: paletteAction{kind: "pad-delete", padName: name}, group: groupFocused},
|
|
||||||
paletteItem{label: "Rename scratchpad: " + name, hint: "inline rename · enter to commit",
|
|
||||||
action: paletteAction{kind: "pad-rename-form", padName: name}, group: groupFocused},
|
|
||||||
paletteItem{label: "Edit scratchpad: " + name, hint: "open in external editor (zed)",
|
|
||||||
action: paletteAction{kind: "pad-edit", padName: name}, group: groupFocused},
|
action: paletteAction{kind: "pad-edit", padName: name}, group: groupFocused},
|
||||||
|
paletteItem{label: "Rename", hint: "rename scratchpad · " + name,
|
||||||
|
action: paletteAction{kind: "pad-rename-form", padName: name}, group: groupFocused},
|
||||||
|
paletteItem{label: "Delete", hint: "delete scratchpad · " + name,
|
||||||
|
action: paletteAction{kind: "pad-delete", padName: name}, group: groupFocused},
|
||||||
)
|
)
|
||||||
case p.focused != "":
|
case p.focused != "":
|
||||||
if c := findChildByID(p.children, p.focused); c != nil {
|
if c := findChildByID(p.children, p.focused); c != nil {
|
||||||
@@ -269,40 +265,39 @@ func (p *paletteState) buildItems(macro string) []paletteItem {
|
|||||||
switch c.Kind {
|
switch c.Kind {
|
||||||
case KindAgent:
|
case KindAgent:
|
||||||
out = append(out,
|
out = append(out,
|
||||||
paletteItem{label: "Rename agent: " + name, hint: "inline rename · enter to commit",
|
paletteItem{label: "Rename", hint: "rename agent · " + name,
|
||||||
action: paletteAction{kind: "agent-rename-form", childID: c.ID}, group: groupFocused},
|
action: paletteAction{kind: "agent-rename-form", childID: c.ID}, group: groupFocused},
|
||||||
paletteItem{label: "Close agent: " + name, hint: "SIGTERM " + strings.Join(c.Argv, " "),
|
paletteItem{label: "Close", hint: "close agent · " + name + " (SIGTERM)",
|
||||||
action: paletteAction{kind: "agent-close", childID: c.ID}, group: groupFocused},
|
action: paletteAction{kind: "agent-close", childID: c.ID}, group: groupFocused},
|
||||||
)
|
)
|
||||||
default:
|
default:
|
||||||
out = append(out,
|
out = append(out,
|
||||||
paletteItem{label: "Rename process: " + name, hint: "inline rename · enter to commit",
|
paletteItem{label: "Rename", hint: "rename process · " + name,
|
||||||
action: paletteAction{kind: "proc-rename-form", childID: c.ID}, group: groupFocused},
|
action: paletteAction{kind: "proc-rename-form", childID: c.ID}, group: groupFocused},
|
||||||
paletteItem{label: "Delete process: " + name, hint: "remove entry; SIGKILL if alive",
|
paletteItem{label: "Stop", hint: "stop process · " + name + " (SIGTERM, keeps entry)",
|
||||||
action: paletteAction{kind: "proc-delete", childID: c.ID}, group: groupFocused},
|
|
||||||
paletteItem{label: "Stop process: " + name, hint: "SIGTERM · keep entry for restart",
|
|
||||||
action: paletteAction{kind: "proc-stop", childID: c.ID}, group: groupFocused},
|
action: paletteAction{kind: "proc-stop", childID: c.ID}, group: groupFocused},
|
||||||
paletteItem{label: "Restart process: " + name, hint: "SIGTERM then start with same argv",
|
paletteItem{label: "Restart", hint: "restart process · " + name,
|
||||||
action: paletteAction{kind: "proc-restart", childID: c.ID}, group: groupFocused},
|
action: paletteAction{kind: "proc-restart", childID: c.ID}, group: groupFocused},
|
||||||
|
paletteItem{label: "Delete", hint: "delete process · " + name + " (SIGKILL if alive)",
|
||||||
|
action: paletteAction{kind: "proc-delete", childID: c.ID}, group: groupFocused},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Group 1: Open — switch entries for every running child. Dead
|
// Group 1: Open — switch entries for every running child *other than*
|
||||||
|
// the one already focused (no point offering a no-op switch). Dead
|
||||||
// agents are filtered out (no restart path); dead command processes
|
// agents are filtered out (no restart path); dead command processes
|
||||||
// remain so they can be restarted. The currently-focused child is
|
// remain so they can be restarted.
|
||||||
// marked with a leading ▶ instead of the older "• … (current)" suffix
|
|
||||||
// so the row reads cleaner.
|
|
||||||
for _, c := range p.children {
|
for _, c := range p.children {
|
||||||
|
if c.ID == p.focused {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if c.Kind == KindAgent && c.Status() != StatusRunning {
|
if c.Kind == KindAgent && c.Status() != StatusRunning {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
label := "Switch to " + c.DisplayName()
|
label := "Switch to " + c.DisplayName()
|
||||||
hint := strings.Join(c.Argv, " ")
|
hint := strings.Join(c.Argv, " ")
|
||||||
if c.ID == p.focused {
|
|
||||||
label = "▶ " + label
|
|
||||||
}
|
|
||||||
if c.Status() != StatusRunning {
|
if c.Status() != StatusRunning {
|
||||||
label = label + " [" + string(c.Status()) + "]"
|
label = label + " [" + string(c.Status()) + "]"
|
||||||
}
|
}
|
||||||
@@ -384,9 +379,11 @@ func (p *paletteState) buildItems(macro string) []paletteItem {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
// itemsWithHeaders splices a non-selectable header row in front of
|
// itemsWithSpacers splices a non-selectable blank row between groups
|
||||||
// each new group so the (unfiltered) list reads as scannable bands.
|
// so the (unfiltered) list reads as scannable bands without dashed
|
||||||
func itemsWithHeaders(items []paletteItem) []paletteItem {
|
// section headers stealing weight from the actions themselves. The
|
||||||
|
// first group never gets a leading spacer.
|
||||||
|
func itemsWithSpacers(items []paletteItem) []paletteItem {
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -394,17 +391,14 @@ func itemsWithHeaders(items []paletteItem) []paletteItem {
|
|||||||
currentGroup := -1
|
currentGroup := -1
|
||||||
for _, it := range items {
|
for _, it := range items {
|
||||||
if it.group != currentGroup {
|
if it.group != currentGroup {
|
||||||
currentGroup = it.group
|
if currentGroup != -1 {
|
||||||
label, ok := groupLabels[it.group]
|
|
||||||
if !ok {
|
|
||||||
label = ""
|
|
||||||
}
|
|
||||||
result = append(result, paletteItem{
|
result = append(result, paletteItem{
|
||||||
label: "── " + label + " ──",
|
|
||||||
action: paletteAction{kind: "header"},
|
action: paletteAction{kind: "header"},
|
||||||
group: it.group,
|
group: it.group,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
currentGroup = it.group
|
||||||
|
}
|
||||||
result = append(result, it)
|
result = append(result, it)
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
@@ -1282,8 +1276,11 @@ func (p *paletteState) handleSettingsTextInput(chunk []byte, i int) (paletteActi
|
|||||||
}
|
}
|
||||||
switch b {
|
switch b {
|
||||||
case '\r', '\n':
|
case '\r', '\n':
|
||||||
p.applySettingsInput()
|
changed := p.applySettingsInput()
|
||||||
p.mode = paletteModeAutoSummary
|
p.mode = paletteModeAutoSummary
|
||||||
|
if changed {
|
||||||
|
return p.settingsAction("settings-save"), false, 1
|
||||||
|
}
|
||||||
case 0x7f, 0x08:
|
case 0x7f, 0x08:
|
||||||
if len(p.settingsInput.value) > 0 {
|
if len(p.settingsInput.value) > 0 {
|
||||||
p.settingsInput.value = p.settingsInput.value[:len(p.settingsInput.value)-1]
|
p.settingsInput.value = p.settingsInput.value[:len(p.settingsInput.value)-1]
|
||||||
@@ -1313,9 +1310,6 @@ func autoSummaryRows() []autoSummaryRow {
|
|||||||
{key: "cadence", label: "Cadence"},
|
{key: "cadence", label: "Cadence"},
|
||||||
{key: "test", label: "Test summarizer"},
|
{key: "test", label: "Test summarizer"},
|
||||||
{key: "run_now", label: "Summarize current top-level agent now"},
|
{key: "run_now", label: "Summarize current top-level agent now"},
|
||||||
{key: "save", label: "Save settings"},
|
|
||||||
{key: "cancel", label: "Cancel"},
|
|
||||||
{key: "back", label: "Back to Settings"},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1327,6 +1321,8 @@ func (p *paletteState) activateAutoSummaryRow() (paletteAction, bool, int) {
|
|||||||
switch rows[p.cursor].key {
|
switch rows[p.cursor].key {
|
||||||
case "enabled":
|
case "enabled":
|
||||||
p.settings.AutoSummary.Enabled = !p.settings.AutoSummary.Enabled
|
p.settings.AutoSummary.Enabled = !p.settings.AutoSummary.Enabled
|
||||||
|
p.settings.normalize()
|
||||||
|
return p.settingsAction("settings-save"), false, 1
|
||||||
case "provider":
|
case "provider":
|
||||||
switch p.settings.AutoSummary.Provider {
|
switch p.settings.AutoSummary.Provider {
|
||||||
case "codex":
|
case "codex":
|
||||||
@@ -1336,13 +1332,14 @@ func (p *paletteState) activateAutoSummaryRow() (paletteAction, bool, int) {
|
|||||||
default:
|
default:
|
||||||
p.settings.AutoSummary.Provider = "codex"
|
p.settings.AutoSummary.Provider = "codex"
|
||||||
}
|
}
|
||||||
|
p.settings.normalize()
|
||||||
|
return p.settingsAction("settings-save"), false, 1
|
||||||
case "codex_model", "opencode_model", "claude_model":
|
case "codex_model", "opencode_model", "claude_model":
|
||||||
provider := strings.TrimSuffix(rows[p.cursor].key, "_model")
|
provider := strings.TrimSuffix(rows[p.cursor].key, "_model")
|
||||||
p.settingsInput = &settingsInputForm{
|
p.settingsInput = &settingsInputForm{
|
||||||
title: provider + " model",
|
title: provider + " model",
|
||||||
field: rows[p.cursor].key,
|
field: rows[p.cursor].key,
|
||||||
value: []rune(p.settings.AutoSummary.modelFor(provider)),
|
value: []rune(p.settings.AutoSummary.modelFor(provider)),
|
||||||
subtitle: "model flag passed to " + provider,
|
|
||||||
}
|
}
|
||||||
p.mode = paletteModeSettingsInput
|
p.mode = paletteModeSettingsInput
|
||||||
case "cadence":
|
case "cadence":
|
||||||
@@ -1354,48 +1351,42 @@ func (p *paletteState) activateAutoSummaryRow() (paletteAction, bool, int) {
|
|||||||
default:
|
default:
|
||||||
p.settings.AutoSummary.Cadence = "15s"
|
p.settings.AutoSummary.Cadence = "15s"
|
||||||
}
|
}
|
||||||
|
p.settings.normalize()
|
||||||
|
return p.settingsAction("settings-save"), false, 1
|
||||||
case "test":
|
case "test":
|
||||||
return p.settingsAction("settings-test"), true, 1
|
return p.settingsAction("settings-test"), true, 1
|
||||||
case "run_now":
|
case "run_now":
|
||||||
return p.settingsAction("settings-run-now"), true, 1
|
return p.settingsAction("settings-run-now"), true, 1
|
||||||
case "save":
|
|
||||||
return p.settingsAction("settings-close"), true, 1
|
|
||||||
case "cancel":
|
|
||||||
return paletteAction{kind: "cancel"}, true, 1
|
|
||||||
case "back":
|
|
||||||
p.mode = paletteModeSettings
|
|
||||||
p.cursor = 0
|
|
||||||
p.query = nil
|
|
||||||
p.rebuildSettings()
|
|
||||||
}
|
}
|
||||||
p.settings.normalize()
|
p.settings.normalize()
|
||||||
return paletteAction{}, false, 1
|
return paletteAction{}, false, 1
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *paletteState) applySettingsInput() {
|
func (p *paletteState) applySettingsInput() bool {
|
||||||
if p.settingsInput == nil {
|
if p.settingsInput == nil {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
val := strings.TrimSpace(string(p.settingsInput.value))
|
val := strings.TrimSpace(string(p.settingsInput.value))
|
||||||
if val == "" {
|
if val == "" {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
if p.settings.AutoSummary.Models == nil {
|
if p.settings.AutoSummary.Models == nil {
|
||||||
p.settings.AutoSummary.Models = defaultSummaryModels()
|
p.settings.AutoSummary.Models = defaultSummaryModels()
|
||||||
}
|
}
|
||||||
|
changed := false
|
||||||
switch p.settingsInput.field {
|
switch p.settingsInput.field {
|
||||||
case "codex_model":
|
case "codex_model":
|
||||||
|
changed = p.settings.AutoSummary.Models["codex"] != val
|
||||||
p.settings.AutoSummary.Models["codex"] = val
|
p.settings.AutoSummary.Models["codex"] = val
|
||||||
case "opencode_model":
|
case "opencode_model":
|
||||||
|
changed = p.settings.AutoSummary.Models["opencode"] != val
|
||||||
p.settings.AutoSummary.Models["opencode"] = val
|
p.settings.AutoSummary.Models["opencode"] = val
|
||||||
case "claude_model":
|
case "claude_model":
|
||||||
|
changed = p.settings.AutoSummary.Models["claude"] != val
|
||||||
p.settings.AutoSummary.Models["claude"] = val
|
p.settings.AutoSummary.Models["claude"] = val
|
||||||
}
|
}
|
||||||
p.settings.normalize()
|
p.settings.normalize()
|
||||||
}
|
return changed
|
||||||
|
|
||||||
func (p *paletteState) settingsCloseAction() paletteAction {
|
|
||||||
return p.settingsAction("settings-close")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *paletteState) settingsAction(kind string) paletteAction {
|
func (p *paletteState) settingsAction(kind string) paletteAction {
|
||||||
@@ -1404,7 +1395,7 @@ func (p *paletteState) settingsAction(kind string) paletteAction {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *paletteState) renderSettings(out writeFlusher, cols, rows int) {
|
func (p *paletteState) renderSettings(out writeFlusher, cols, rows int) {
|
||||||
p.renderSimplePicker(out, cols, rows, "Settings", "esc cancel", "search settings")
|
p.renderSimplePicker(out, cols, rows, "Settings", "esc close", "search settings")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *paletteState) renderSimplePicker(out writeFlusher, cols, rows int, title, hint, placeholder string) {
|
func (p *paletteState) renderSimplePicker(out writeFlusher, cols, rows int, title, hint, placeholder string) {
|
||||||
@@ -1440,7 +1431,7 @@ func (p *paletteState) renderSimplePicker(out writeFlusher, cols, rows int, titl
|
|||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
||||||
row++
|
row++
|
||||||
footer := styleHint + "↵ open · esc cancel · ↑↓ navigate" + styleReset
|
footer := styleHint + "↵ open · esc close · ↑↓ navigate" + styleReset
|
||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "│" + styleReset + " " + footer + strings.Repeat(" ", max(0, content-visibleLen(footer))) + " " + styleBorder + "│" + styleReset)
|
b.WriteString(styleBorder + "│" + styleReset + " " + footer + strings.Repeat(" ", max(0, content-visibleLen(footer))) + " " + styleBorder + "│" + styleReset)
|
||||||
row++
|
row++
|
||||||
@@ -1456,7 +1447,7 @@ func (p *paletteState) renderAutoSummary(out writeFlusher, cols, rows int) {
|
|||||||
b.WriteString("\x1b[?25l\x1b[H\x1b[2J\x1b[3J")
|
b.WriteString("\x1b[?25l\x1b[H\x1b[2J\x1b[3J")
|
||||||
row := 2
|
row := 2
|
||||||
title := "Auto-summarization"
|
title := "Auto-summarization"
|
||||||
hint := "esc cancel"
|
hint := "esc close"
|
||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "╭─ " + styleActive + title + styleReset + styleBorder + " " + strings.Repeat("─", max(2, width-visibleLen(title)-visibleLen(hint)-9)) + " " + styleHint + hint + styleReset + styleBorder + " ─╮" + styleReset)
|
b.WriteString(styleBorder + "╭─ " + styleActive + title + styleReset + styleBorder + " " + strings.Repeat("─", max(2, width-visibleLen(title)-visibleLen(hint)-9)) + " " + styleHint + hint + styleReset + styleBorder + " ─╮" + styleReset)
|
||||||
row++
|
row++
|
||||||
@@ -1478,7 +1469,7 @@ func (p *paletteState) renderAutoSummary(out writeFlusher, cols, rows int) {
|
|||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
||||||
row++
|
row++
|
||||||
footer := styleHint + "↵ edit/toggle · cadence 15s/30s/1m · save row commits · esc cancel" + styleReset
|
footer := styleHint + "↵ edit/toggle · esc close" + styleReset
|
||||||
if visibleLen(footer) > content {
|
if visibleLen(footer) > content {
|
||||||
footer = clipRunes(footer, content-1) + "…"
|
footer = clipRunes(footer, content-1) + "…"
|
||||||
}
|
}
|
||||||
@@ -1508,7 +1499,7 @@ func (p *paletteState) autoSummaryDisplayRows() []string {
|
|||||||
var out []string
|
var out []string
|
||||||
for _, row := range autoSummaryRows() {
|
for _, row := range autoSummaryRows() {
|
||||||
if v, ok := values[row.key]; ok {
|
if v, ok := values[row.key]; ok {
|
||||||
out = append(out, row.label+": "+v)
|
out = append(out, styleHint+row.label+":"+styleReset+" "+v)
|
||||||
} else {
|
} else {
|
||||||
out = append(out, row.label)
|
out = append(out, row.label)
|
||||||
}
|
}
|
||||||
@@ -1525,19 +1516,10 @@ func (p *paletteState) renderSettingsInput(out writeFlusher, cols, rows int) {
|
|||||||
b.WriteString("\x1b[?25l\x1b[H\x1b[2J\x1b[3J")
|
b.WriteString("\x1b[?25l\x1b[H\x1b[2J\x1b[3J")
|
||||||
row := 2
|
row := 2
|
||||||
title := p.settingsInput.title
|
title := p.settingsInput.title
|
||||||
hint := "esc cancel"
|
hint := "esc back"
|
||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "╭─ " + styleActive + title + styleReset + styleBorder + " " + strings.Repeat("─", max(2, width-visibleLen(title)-visibleLen(hint)-9)) + " " + styleHint + hint + styleReset + styleBorder + " ─╮" + styleReset)
|
b.WriteString(styleBorder + "╭─ " + styleActive + title + styleReset + styleBorder + " " + strings.Repeat("─", max(2, width-visibleLen(title)-visibleLen(hint)-9)) + " " + styleHint + hint + styleReset + styleBorder + " ─╮" + styleReset)
|
||||||
row++
|
row++
|
||||||
if p.settingsInput.subtitle != "" {
|
|
||||||
sub := p.settingsInput.subtitle
|
|
||||||
if visibleLen(sub) > content {
|
|
||||||
sub = clipRunes(sub, content-1) + "…"
|
|
||||||
}
|
|
||||||
moveTo(&b, row, leftPad)
|
|
||||||
b.WriteString(styleBorder + "│" + styleReset + " " + styleHint + sub + styleReset + strings.Repeat(" ", max(0, content-visibleLen(sub))) + " " + styleBorder + "│" + styleReset)
|
|
||||||
row++
|
|
||||||
}
|
|
||||||
value := string(p.settingsInput.value)
|
value := string(p.settingsInput.value)
|
||||||
if visibleLen(value) > content-2 {
|
if visibleLen(value) > content-2 {
|
||||||
value = clipRunes(value, content-3) + "…"
|
value = clipRunes(value, content-3) + "…"
|
||||||
@@ -1549,7 +1531,7 @@ func (p *paletteState) renderSettingsInput(out writeFlusher, cols, rows int) {
|
|||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
b.WriteString(styleBorder + "├" + strings.Repeat("─", width-2) + "┤" + styleReset)
|
||||||
row++
|
row++
|
||||||
footer := styleHint + "↵ save · esc cancel · ⌃u clear" + styleReset
|
footer := styleHint + "↵ apply · esc back · ⌃u clear" + styleReset
|
||||||
moveTo(&b, row, leftPad)
|
moveTo(&b, row, leftPad)
|
||||||
b.WriteString(styleBorder + "│" + styleReset + " " + footer + strings.Repeat(" ", max(0, content-visibleLen(footer))) + " " + styleBorder + "│" + styleReset)
|
b.WriteString(styleBorder + "│" + styleReset + " " + footer + strings.Repeat(" ", max(0, content-visibleLen(footer))) + " " + styleBorder + "│" + styleReset)
|
||||||
row++
|
row++
|
||||||
|
|||||||
@@ -31,16 +31,17 @@ func findItem(p *paletteState, want string) (int, *paletteItem) {
|
|||||||
|
|
||||||
func TestContextItemsScratchpad(t *testing.T) {
|
func TestContextItemsScratchpad(t *testing.T) {
|
||||||
p := newPalette(nil, "", "notes.md", preset.Set{})
|
p := newPalette(nil, "", "notes.md", preset.Set{})
|
||||||
// pad-delete is the first selectable row; the Focused section header
|
// With the dashed section header gone, pad-edit is the first row;
|
||||||
// (a non-selectable row) sits above it.
|
// pad-rename-form follows, with destructive pad-delete last in the
|
||||||
if i, _ := findItem(p, "pad-delete"); i != 1 {
|
// Focused section.
|
||||||
t.Fatalf("pad-delete at %d; want 1 (after Focused header)", i)
|
if i, _ := findItem(p, "pad-edit"); i != 0 {
|
||||||
|
t.Fatalf("pad-edit at %d; want 0", i)
|
||||||
}
|
}
|
||||||
if _, it := findItem(p, "pad-rename-form"); it == nil || it.action.padName != "notes.md" {
|
if _, it := findItem(p, "pad-rename-form"); it == nil || it.action.padName != "notes.md" {
|
||||||
t.Fatalf("pad-rename-form missing or wrong padName: %+v", it)
|
t.Fatalf("pad-rename-form missing or wrong padName: %+v", it)
|
||||||
}
|
}
|
||||||
if _, it := findItem(p, "pad-edit"); it == nil {
|
if i, _ := findItem(p, "pad-delete"); i < 0 {
|
||||||
t.Fatalf("pad-edit missing")
|
t.Fatalf("pad-delete missing")
|
||||||
}
|
}
|
||||||
// No focused child → no agent/proc context items.
|
// No focused child → no agent/proc context items.
|
||||||
if i, _ := findItem(p, "agent-rename-form"); i != -1 {
|
if i, _ := findItem(p, "agent-rename-form"); i != -1 {
|
||||||
@@ -83,8 +84,11 @@ func TestContextItemsProcess(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestContextItemsAppearAboveSwitch(t *testing.T) {
|
func TestContextItemsAppearAboveSwitch(t *testing.T) {
|
||||||
c := makeFakeChild("pid", "devserver", KindCommand)
|
// Two children so there's still a non-focused switch entry to compare
|
||||||
p := newPalette([]*Child{c}, "pid", "", preset.Set{})
|
// against (the focused child is suppressed from the Open section).
|
||||||
|
focused := makeFakeChild("pid", "devserver", KindCommand)
|
||||||
|
other := makeFakeChild("oid", "worker", KindCommand)
|
||||||
|
p := newPalette([]*Child{focused, other}, "pid", "", preset.Set{})
|
||||||
procIdx, _ := findItem(p, "proc-rename-form")
|
procIdx, _ := findItem(p, "proc-rename-form")
|
||||||
switchIdx, _ := findItem(p, "switch")
|
switchIdx, _ := findItem(p, "switch")
|
||||||
if procIdx < 0 || switchIdx < 0 {
|
if procIdx < 0 || switchIdx < 0 {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -57,21 +58,44 @@ func TestPaletteDropsGlobalCloseList(t *testing.T) {
|
|||||||
|
|
||||||
// -- Phase 2: section headers and cursor skip ------------------------
|
// -- Phase 2: section headers and cursor skip ------------------------
|
||||||
|
|
||||||
func TestPaletteSectionHeadersPresent(t *testing.T) {
|
func TestPaletteSectionsSeparatedBySpacers(t *testing.T) {
|
||||||
|
// Section-named dashed headers are gone; groups are visually
|
||||||
|
// separated by a single non-selectable blank row. Verify that the
|
||||||
|
// build emits one such spacer between every pair of adjacent groups
|
||||||
|
// and never a leading spacer.
|
||||||
c := makeFakeChild("a", "claude", KindAgent)
|
c := makeFakeChild("a", "claude", KindAgent)
|
||||||
p := newPalette([]*Child{c}, "a", "", preset.Set{Agents: []*preset.Preset{{Name: "codex"}}})
|
other := makeFakeChild("b", "worker", KindCommand)
|
||||||
wantSections := []string{"Focused", "Open", "Spawn", "Quit"}
|
p := newPalette([]*Child{c, other}, "a", "",
|
||||||
for _, w := range wantSections {
|
preset.Set{Agents: []*preset.Preset{{Name: "codex"}}})
|
||||||
found := false
|
|
||||||
for _, it := range p.items {
|
if len(p.items) == 0 {
|
||||||
if it.action.kind == "header" && strings.Contains(it.label, w) {
|
t.Fatalf("palette built no items")
|
||||||
found = true
|
}
|
||||||
break
|
if p.items[0].action.kind == "header" {
|
||||||
|
t.Fatalf("first row is a spacer; should be a selectable item")
|
||||||
|
}
|
||||||
|
transitions := 0
|
||||||
|
prevGroup := p.items[0].group
|
||||||
|
for i := 1; i < len(p.items); i++ {
|
||||||
|
it := p.items[i]
|
||||||
|
if it.group != prevGroup {
|
||||||
|
if it.action.kind != "header" || it.label != "" {
|
||||||
|
t.Fatalf("group transition at %d not a blank spacer: %+v", i, it)
|
||||||
|
}
|
||||||
|
transitions++
|
||||||
|
// The row immediately after the spacer must be selectable.
|
||||||
|
if i+1 >= len(p.items) || p.items[i+1].action.kind == "header" {
|
||||||
|
t.Fatalf("spacer at %d not followed by selectable row", i)
|
||||||
|
}
|
||||||
|
prevGroup = p.items[i+1].group
|
||||||
|
}
|
||||||
|
// No dashed banners anywhere.
|
||||||
|
if it.action.kind == "header" && strings.Contains(it.label, "──") {
|
||||||
|
t.Errorf("dashed section header still present at %d: %q", i, it.label)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !found {
|
if transitions == 0 {
|
||||||
t.Errorf("section header %q missing from items", w)
|
t.Fatalf("no section transitions found in palette items")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,20 +357,95 @@ func TestAutoSummaryCadenceCyclesSoloValues(t *testing.T) {
|
|||||||
if p.settings.AutoSummary.Cadence != "1m" {
|
if p.settings.AutoSummary.Cadence != "1m" {
|
||||||
t.Fatalf("initial cadence = %q", p.settings.AutoSummary.Cadence)
|
t.Fatalf("initial cadence = %q", p.settings.AutoSummary.Cadence)
|
||||||
}
|
}
|
||||||
p.activateAutoSummaryRow()
|
action, done, _ := p.activateAutoSummaryRow()
|
||||||
|
if done || action.kind != "settings-save" {
|
||||||
|
t.Fatalf("first cycle action = %+v done=%v, want settings-save without close", action, done)
|
||||||
|
}
|
||||||
if p.settings.AutoSummary.Cadence != "15s" {
|
if p.settings.AutoSummary.Cadence != "15s" {
|
||||||
t.Fatalf("first cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
t.Fatalf("first cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
||||||
}
|
}
|
||||||
p.activateAutoSummaryRow()
|
action, done, _ = p.activateAutoSummaryRow()
|
||||||
|
if done || action.kind != "settings-save" {
|
||||||
|
t.Fatalf("second cycle action = %+v done=%v, want settings-save without close", action, done)
|
||||||
|
}
|
||||||
if p.settings.AutoSummary.Cadence != "30s" {
|
if p.settings.AutoSummary.Cadence != "30s" {
|
||||||
t.Fatalf("second cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
t.Fatalf("second cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
||||||
}
|
}
|
||||||
p.activateAutoSummaryRow()
|
action, done, _ = p.activateAutoSummaryRow()
|
||||||
|
if done || action.kind != "settings-save" {
|
||||||
|
t.Fatalf("third cycle action = %+v done=%v, want settings-save without close", action, done)
|
||||||
|
}
|
||||||
if p.settings.AutoSummary.Cadence != "1m" {
|
if p.settings.AutoSummary.Cadence != "1m" {
|
||||||
t.Fatalf("third cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
t.Fatalf("third cycle cadence = %q", p.settings.AutoSummary.Cadence)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAutoSummaryScreenOmitsExplicitSaveCancelBackRows(t *testing.T) {
|
||||||
|
omitted := map[string]bool{
|
||||||
|
"Save settings": true,
|
||||||
|
"Cancel": true,
|
||||||
|
"Back to Settings": true,
|
||||||
|
}
|
||||||
|
for _, row := range autoSummaryRows() {
|
||||||
|
if omitted[row.label] {
|
||||||
|
t.Fatalf("auto-summary settings should not show %q", row.label)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAutoSummaryRenderOmitsStaleSettingsHelp(t *testing.T) {
|
||||||
|
p := newPalette(nil, "", "", preset.Set{}, defaultSettings())
|
||||||
|
p.mode = paletteModeAutoSummary
|
||||||
|
var b bytes.Buffer
|
||||||
|
p.renderAutoSummary(wrapWriter(&b), 100, 30)
|
||||||
|
out := b.String()
|
||||||
|
for _, text := range []string{
|
||||||
|
"Save settings",
|
||||||
|
"Cancel",
|
||||||
|
"Back to Settings",
|
||||||
|
"changes save",
|
||||||
|
"applies immediately",
|
||||||
|
} {
|
||||||
|
if strings.Contains(out, text) {
|
||||||
|
t.Fatalf("auto-summary render should not contain %q:\n%s", text, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAutoSummaryValueRowsStyleLabelAndValueSeparately(t *testing.T) {
|
||||||
|
p := newPalette(nil, "", "", preset.Set{}, defaultSettings())
|
||||||
|
rows := p.autoSummaryDisplayRows()
|
||||||
|
for _, row := range rows {
|
||||||
|
if strings.Contains(row, "Cadence:") {
|
||||||
|
if !strings.HasPrefix(row, styleHint+"Cadence:"+styleReset+" ") {
|
||||||
|
t.Fatalf("cadence row styling = %q", row)
|
||||||
|
}
|
||||||
|
if strings.Contains(strings.TrimPrefix(row, styleHint+"Cadence:"+styleReset+" "), styleHint) {
|
||||||
|
t.Fatalf("cadence value should use regular text styling: %q", row)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("missing cadence display row")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAutoSummaryTextInputSavesWhenSubmitted(t *testing.T) {
|
||||||
|
p := newPalette(nil, "", "", preset.Set{}, defaultSettings())
|
||||||
|
p.mode = paletteModeSettingsInput
|
||||||
|
p.settingsInput = &settingsInputForm{
|
||||||
|
title: "codex model",
|
||||||
|
field: "codex_model",
|
||||||
|
value: []rune("custom-model"),
|
||||||
|
}
|
||||||
|
action, done, _ := p.handleSettingsTextInput([]byte{'\r'}, 0)
|
||||||
|
if done || action.kind != "settings-save" {
|
||||||
|
t.Fatalf("submit action = %+v done=%v, want settings-save without close", action, done)
|
||||||
|
}
|
||||||
|
if got := p.settings.AutoSummary.modelFor("codex"); got != "custom-model" {
|
||||||
|
t.Fatalf("codex model = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPaletteFormCtrlRTogglesRelaunchFromCommandField(t *testing.T) {
|
func TestPaletteFormCtrlRTogglesRelaunchFromCommandField(t *testing.T) {
|
||||||
p := newPalette(nil, "", "", preset.Set{})
|
p := newPalette(nil, "", "", preset.Set{})
|
||||||
p.mode = paletteModeSpawnForm
|
p.mode = paletteModeSpawnForm
|
||||||
|
|||||||
@@ -91,6 +91,12 @@ type ChildEventListener interface {
|
|||||||
// updates a child's IdleState. Listeners use this to repaint the
|
// updates a child's IdleState. Listeners use this to repaint the
|
||||||
// sidebar badge and to evaluate idle-aware timers.
|
// sidebar badge and to evaluate idle-aware timers.
|
||||||
OnChildStateChanged(childID string, state IdleState)
|
OnChildStateChanged(childID string, state IdleState)
|
||||||
|
// OnChildClosed fires when a child is being removed from the
|
||||||
|
// session (either via close_process, or — for agent/terminal
|
||||||
|
// kinds — when the PTY exits and the entry will never be
|
||||||
|
// restarted). It signals that any pending references to childID
|
||||||
|
// (e.g. timers owned by or watching it) should be dropped.
|
||||||
|
OnChildClosed(childID string)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSession(projectDir, projectKey string) *Session {
|
func NewSession(projectDir, projectKey string) *Session {
|
||||||
@@ -167,6 +173,12 @@ func (s *Session) emitStateChanged(id string, state IdleState) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Session) emitClosed(id string) {
|
||||||
|
for _, l := range s.listenersSnapshot() {
|
||||||
|
l.OnChildClosed(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Session) ChildEnv() []string {
|
func (s *Session) ChildEnv() []string {
|
||||||
env := os.Environ()
|
env := os.Environ()
|
||||||
// Mark patterm-owned PTYs so a recursive `patterm` invocation can
|
// Mark patterm-owned PTYs so a recursive `patterm` invocation can
|
||||||
@@ -374,6 +386,11 @@ func (s *Session) Close(id string, sig syscall.Signal) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
// Notify listeners outside s.mu so they can take their own locks
|
||||||
|
// without inversion. Timer manager uses this to drop pending
|
||||||
|
// timers owned by or watching the closed child — otherwise the
|
||||||
|
// next classifier tick can deliver a stale fire to the parent.
|
||||||
|
s.emitClosed(id)
|
||||||
s.forgetPersisted(id)
|
s.forgetPersisted(id)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -486,6 +503,7 @@ func (s *Session) reapChild(c *Child, runID uint64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
s.emitClosed(c.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -331,7 +331,7 @@ func (st *uiState) drawSidebar() {
|
|||||||
write(prefix + openStyle + nameCell + styleReset + suffix)
|
write(prefix + openStyle + nameCell + styleReset + suffix)
|
||||||
}
|
}
|
||||||
|
|
||||||
if summary := st.activeSummaryText(width - 4); summary != "" && row+2 <= maxRow {
|
if summary := st.activeSummaryRaw(); summary != "" && row+2 <= maxRow {
|
||||||
write("")
|
write("")
|
||||||
for _, line := range wrapSidebarSummary(summary, width-4) {
|
for _, line := range wrapSidebarSummary(summary, width-4) {
|
||||||
if row > maxRow {
|
if row > maxRow {
|
||||||
@@ -417,7 +417,13 @@ func wrapSidebarSummary(s string, width int) []string {
|
|||||||
out = append(out, cur)
|
out = append(out, cur)
|
||||||
cur = ""
|
cur = ""
|
||||||
}
|
}
|
||||||
out = append(out, clipRunes(word, width-1)+"…")
|
for visibleLen(word) > width {
|
||||||
|
out = append(out, clipRunes(word, width))
|
||||||
|
word = string([]rune(word)[width:])
|
||||||
|
}
|
||||||
|
if word != "" {
|
||||||
|
cur = word
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if cur == "" {
|
if cur == "" {
|
||||||
|
|||||||
@@ -404,7 +404,7 @@ func runSummarizerCommand(ctx context.Context, cfg autoSummarySettings, projectD
|
|||||||
case "claude":
|
case "claude":
|
||||||
cmd = exec.CommandContext(ctx, "claude", "--print", "--model", model, prompt)
|
cmd = exec.CommandContext(ctx, "claude", "--print", "--model", model, prompt)
|
||||||
default:
|
default:
|
||||||
cmd = exec.CommandContext(ctx, "codex", "exec", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--ask-for-approval", "never", "--model", model, "-")
|
cmd = exec.CommandContext(ctx, "codex", "exec", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--model", model, "-")
|
||||||
cmd.Stdin = strings.NewReader(prompt)
|
cmd.Stdin = strings.NewReader(prompt)
|
||||||
}
|
}
|
||||||
cmd.Dir = projectDir
|
cmd.Dir = projectDir
|
||||||
|
|||||||
@@ -42,8 +42,13 @@ func TestWrapSidebarSummaryKeepsWordBoundaries(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
long := wrapSidebarSummary("supercalifragilistic short", 8)
|
long := wrapSidebarSummary("supercalifragilistic short", 8)
|
||||||
if len(long) == 0 || !strings.HasSuffix(long[0], "…") {
|
if len(long) == 0 || strings.Contains(strings.Join(long, ""), "…") {
|
||||||
t.Fatalf("long word should clip with ellipsis: %#v", long)
|
t.Fatalf("long word should wrap without ellipsis: %#v", long)
|
||||||
|
}
|
||||||
|
for _, line := range long {
|
||||||
|
if visibleLen(line) > 8 {
|
||||||
|
t.Fatalf("line %q exceeds width", line)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,8 +62,11 @@ func (st *uiState) drawTabBar() {
|
|||||||
startCol int
|
startCol int
|
||||||
width int
|
width int
|
||||||
label string
|
label string
|
||||||
|
glyph string
|
||||||
|
glyphStyle string
|
||||||
active bool
|
active bool
|
||||||
}
|
}
|
||||||
|
activeTab := -1
|
||||||
|
|
||||||
// Reserve space at the right edge for "+ new". If there are too
|
// Reserve space at the right edge for "+ new". If there are too
|
||||||
// many tabs to fit even at minTabWidth, drop tabs from the right
|
// many tabs to fit even at minTabWidth, drop tabs from the right
|
||||||
@@ -114,9 +117,16 @@ func (st *uiState) drawTabBar() {
|
|||||||
if i < extra {
|
if i < extra {
|
||||||
w++
|
w++
|
||||||
}
|
}
|
||||||
|
active := c.ID == focus
|
||||||
|
glyph, glyphStyle := tabIdleGlyph(c.IdleState(), active)
|
||||||
label := c.DisplayName()
|
label := c.DisplayName()
|
||||||
labelW := utf8.RuneCountInString(label)
|
labelW := utf8.RuneCountInString(label)
|
||||||
maxLabelW := w - 2 // one pad on each side
|
// Reserve room for the glyph + its trailing space when present
|
||||||
|
// (1 + 1 runes), on top of the one-cell pad on each side.
|
||||||
|
maxLabelW := w - 2
|
||||||
|
if glyph != "" {
|
||||||
|
maxLabelW -= 2
|
||||||
|
}
|
||||||
if maxLabelW < 1 {
|
if maxLabelW < 1 {
|
||||||
maxLabelW = 1
|
maxLabelW = 1
|
||||||
}
|
}
|
||||||
@@ -132,8 +142,13 @@ func (st *uiState) drawTabBar() {
|
|||||||
startCol: col,
|
startCol: col,
|
||||||
width: w,
|
width: w,
|
||||||
label: label,
|
label: label,
|
||||||
active: c.ID == focus,
|
glyph: glyph,
|
||||||
|
glyphStyle: glyphStyle,
|
||||||
|
active: active,
|
||||||
})
|
})
|
||||||
|
if tabs[len(tabs)-1].active {
|
||||||
|
activeTab = len(tabs) - 1
|
||||||
|
}
|
||||||
col += w
|
col += w
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,23 +166,37 @@ func (st *uiState) drawTabBar() {
|
|||||||
fmt.Fprintf(&b, "\x1b[3;1H\x1b[%dX", width)
|
fmt.Fprintf(&b, "\x1b[3;1H\x1b[%dX", width)
|
||||||
|
|
||||||
for _, t := range tabs {
|
for _, t := range tabs {
|
||||||
// Row 1: centre-ish label inside the tab cell.
|
// Row 1: centre-ish glyph+label inside the tab cell.
|
||||||
labelW := utf8.RuneCountInString(t.label)
|
labelW := utf8.RuneCountInString(t.label)
|
||||||
leftPad := (t.width - labelW) / 2
|
visibleW := labelW
|
||||||
|
if t.glyph != "" {
|
||||||
|
visibleW += 2 // glyph + separator space
|
||||||
|
}
|
||||||
|
leftPad := (t.width - visibleW) / 2
|
||||||
if leftPad < 1 {
|
if leftPad < 1 {
|
||||||
leftPad = 1
|
leftPad = 1
|
||||||
}
|
}
|
||||||
rightPad := t.width - labelW - leftPad
|
rightPad := t.width - visibleW - leftPad
|
||||||
if rightPad < 0 {
|
if rightPad < 0 {
|
||||||
rightPad = 0
|
rightPad = 0
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, "\x1b[1;%dH", t.startCol)
|
cellStyle := styleHint
|
||||||
if t.active {
|
if t.active {
|
||||||
b.WriteString(styleActive)
|
cellStyle = styleActive
|
||||||
} else {
|
|
||||||
b.WriteString(styleHint)
|
|
||||||
}
|
}
|
||||||
|
fmt.Fprintf(&b, "\x1b[1;%dH", t.startCol)
|
||||||
|
b.WriteString(cellStyle)
|
||||||
b.WriteString(strings.Repeat(" ", leftPad))
|
b.WriteString(strings.Repeat(" ", leftPad))
|
||||||
|
if t.glyph != "" {
|
||||||
|
// Glyph uses its own colour so error/permission states pop
|
||||||
|
// regardless of tab focus, matching the sidebar's vocabulary.
|
||||||
|
b.WriteString(styleReset)
|
||||||
|
b.WriteString(t.glyphStyle)
|
||||||
|
b.WriteString(t.glyph)
|
||||||
|
b.WriteString(styleReset)
|
||||||
|
b.WriteString(cellStyle)
|
||||||
|
b.WriteString(" ")
|
||||||
|
}
|
||||||
b.WriteString(t.label)
|
b.WriteString(t.label)
|
||||||
b.WriteString(strings.Repeat(" ", rightPad))
|
b.WriteString(strings.Repeat(" ", rightPad))
|
||||||
b.WriteString(styleReset)
|
b.WriteString(styleReset)
|
||||||
@@ -195,8 +224,12 @@ func (st *uiState) drawTabBar() {
|
|||||||
hintCol, styleBorder, strings.Repeat("─", newHintW), styleReset)
|
hintCol, styleBorder, strings.Repeat("─", newHintW), styleReset)
|
||||||
}
|
}
|
||||||
|
|
||||||
if summary := st.activeSummaryText(width - 2); summary != "" {
|
if activeTab >= 0 {
|
||||||
fmt.Fprintf(&b, "\x1b[2;1H %s%s%s", styleDim, summary, styleReset)
|
tab := tabs[activeTab]
|
||||||
|
summaryWidth := tab.width - 2
|
||||||
|
if summary := st.activeSummaryText(summaryWidth); summary != "" {
|
||||||
|
fmt.Fprintf(&b, "\x1b[2;%dH %s%s%s", tab.startCol, styleDim, summary, styleReset)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
frame := b.String()
|
frame := b.String()
|
||||||
@@ -218,3 +251,29 @@ func (st *uiState) drawTabBar() {
|
|||||||
defer st.outMu.Unlock()
|
defer st.outMu.Unlock()
|
||||||
fmt.Fprintf(os.Stdout, "\x1b7%s\x1b8", frame)
|
fmt.Fprintf(os.Stdout, "\x1b7%s\x1b8", frame)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tabIdleGlyph returns the one-rune state indicator (and its SGR style)
|
||||||
|
// to render before a tab's label. Mirrors the sidebar's vocabulary so
|
||||||
|
// users learn the symbols in one place: ✕ error, ? permission, ◐
|
||||||
|
// thinking, ○ idle, ● working. Returns ("", "") for StateUnknown so the
|
||||||
|
// first frame after spawn doesn't show a misleading badge.
|
||||||
|
func tabIdleGlyph(state IdleState, active bool) (string, string) {
|
||||||
|
base := styleHint
|
||||||
|
if active {
|
||||||
|
base = styleAccent
|
||||||
|
}
|
||||||
|
switch state {
|
||||||
|
case StateError:
|
||||||
|
return "✕", styleError
|
||||||
|
case StatePermission:
|
||||||
|
return "?", styleAccent
|
||||||
|
case StateThinking:
|
||||||
|
return "◐", base
|
||||||
|
case StateIdle:
|
||||||
|
return "○", base
|
||||||
|
case StateWorking:
|
||||||
|
return "●", base
|
||||||
|
default:
|
||||||
|
return "", ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -296,6 +296,65 @@ func (m *timerManager) onChildStateChanged(childID string, state IdleState) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// onChildClosed drops pending timer references to childID. Called
|
||||||
|
// from Session.Close (and the terminal-corpse cleanup in reapChild)
|
||||||
|
// via the session listener bus — a deliberate signal from the host
|
||||||
|
// that childID is gone and the parent is not waiting on it anymore.
|
||||||
|
//
|
||||||
|
// Semantics:
|
||||||
|
// - timers owned by childID are cancelled and deleted: their owner
|
||||||
|
// is gone, so even if defaultFireFn's IsLive guard would no-op
|
||||||
|
// the delivery, the entry has no business surviving a close.
|
||||||
|
// - timers watching childID have childID pruned from t.watched
|
||||||
|
// (and t.idleBaseline). If t.watched becomes empty the timer is
|
||||||
|
// cancelled and deleted; we deliberately do NOT synthesise a
|
||||||
|
// fire here. The parent already received any legitimate idle
|
||||||
|
// transition before close_process — see allWatchedIdleLocked's
|
||||||
|
// "treat as satisfied" comment, which only applies to a
|
||||||
|
// concurrent re-evaluation, not to this explicit-removal hook.
|
||||||
|
//
|
||||||
|
// The natural-exit path (reapChild → emitExit for agent/command
|
||||||
|
// kinds) is NOT routed through here: the classifier emits a final
|
||||||
|
// idle transition on exit, which fires and deletes any watching
|
||||||
|
// timers exactly once. Cancelling on exit would swallow that
|
||||||
|
// legitimate fire and leave the parent never notified.
|
||||||
|
func (m *timerManager) onChildClosed(childID string) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
for id, t := range m.timers {
|
||||||
|
if t.ownerID == childID {
|
||||||
|
if t.rt != nil {
|
||||||
|
t.rt.Stop()
|
||||||
|
t.rt = nil
|
||||||
|
}
|
||||||
|
t.status = timerStatusCanceled
|
||||||
|
delete(m.timers, id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !contains(t.watched, childID) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pruned := t.watched[:0]
|
||||||
|
for _, w := range t.watched {
|
||||||
|
if w != childID {
|
||||||
|
pruned = append(pruned, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.watched = pruned
|
||||||
|
if t.idleBaseline != nil {
|
||||||
|
delete(t.idleBaseline, childID)
|
||||||
|
}
|
||||||
|
if len(t.watched) == 0 {
|
||||||
|
if t.rt != nil {
|
||||||
|
t.rt.Stop()
|
||||||
|
t.rt = nil
|
||||||
|
}
|
||||||
|
t.status = timerStatusCanceled
|
||||||
|
delete(m.timers, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// allWatchedIdleLocked reports whether every watched child is now
|
// allWatchedIdleLocked reports whether every watched child is now
|
||||||
// idle. Called with m.mu held — uses live Child.IdleState() under the
|
// idle. Called with m.mu held — uses live Child.IdleState() under the
|
||||||
// child's own atomic, not under m.mu.
|
// child's own atomic, not under m.mu.
|
||||||
|
|||||||
@@ -411,3 +411,178 @@ func TestTimerRecordsRemovedOnIdleFire(t *testing.T) {
|
|||||||
t.Fatalf("fired idle timer %s was not removed from registry", resp.ID)
|
t.Fatalf("fired idle timer %s was not removed from registry", resp.ID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestTimerCloseChildPrunesWatched covers the happy partial-prune
|
||||||
|
// case: an idle_any timer watches two children, one is closed, the
|
||||||
|
// timer stays pending and the remaining child can still satisfy it.
|
||||||
|
func TestTimerCloseChildPrunesWatched(t *testing.T) {
|
||||||
|
sess, mgr, rec := newTestManager(t)
|
||||||
|
owner := fakeChild("p_owner")
|
||||||
|
a := fakeChild("p_a")
|
||||||
|
b := fakeChild("p_b")
|
||||||
|
addChild(sess, owner)
|
||||||
|
addChild(sess, a)
|
||||||
|
addChild(sess, b)
|
||||||
|
working := StateWorking
|
||||||
|
a.idleState.Store(&working)
|
||||||
|
b.idleState.Store(&working)
|
||||||
|
|
||||||
|
resp, err := mgr.TimerFireWhenIdleAny("p_owner", "one done", "", []string{"p_a", "p_b"}, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TimerFireWhenIdleAny: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mgr.onChildClosed("p_a")
|
||||||
|
|
||||||
|
mgr.mu.Lock()
|
||||||
|
t1, ok := mgr.timers[resp.ID]
|
||||||
|
if !ok {
|
||||||
|
mgr.mu.Unlock()
|
||||||
|
t.Fatalf("timer was removed but still has live watched")
|
||||||
|
}
|
||||||
|
watched := append([]string(nil), t1.watched...)
|
||||||
|
mgr.mu.Unlock()
|
||||||
|
if len(watched) != 1 || watched[0] != "p_b" {
|
||||||
|
t.Fatalf("watched after close: %v, want [p_b]", watched)
|
||||||
|
}
|
||||||
|
if got := rec.snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("close synthesised a fire: %+v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// p_b can still satisfy the timer.
|
||||||
|
idle := StateIdle
|
||||||
|
b.idleState.Store(&idle)
|
||||||
|
mgr.onChildStateChanged("p_b", StateIdle)
|
||||||
|
if got := rec.snapshot(); len(got) != 1 || got[0].Body != "one done" {
|
||||||
|
t.Fatalf("post-prune fire: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTimerCloseLastWatchedCancels is the regression for the
|
||||||
|
// reported stale-fire symptom: the only watched child is closed,
|
||||||
|
// so the timer must be cancelled — no synthetic fire, and the
|
||||||
|
// registry entry must be gone so a trailing classifier tick for the
|
||||||
|
// removed child cannot re-deliver later.
|
||||||
|
func TestTimerCloseLastWatchedCancels(t *testing.T) {
|
||||||
|
sess, mgr, rec := newTestManager(t)
|
||||||
|
owner := fakeChild("p_owner")
|
||||||
|
a := fakeChild("p_a")
|
||||||
|
addChild(sess, owner)
|
||||||
|
addChild(sess, a)
|
||||||
|
working := StateWorking
|
||||||
|
a.idleState.Store(&working)
|
||||||
|
|
||||||
|
resp, err := mgr.TimerFireWhenIdleAny("p_owner", "stale body", "", []string{"p_a"}, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TimerFireWhenIdleAny: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mgr.onChildClosed("p_a")
|
||||||
|
|
||||||
|
mgr.mu.Lock()
|
||||||
|
_, stillThere := mgr.timers[resp.ID]
|
||||||
|
mgr.mu.Unlock()
|
||||||
|
if stillThere {
|
||||||
|
t.Fatalf("timer with no remaining watched should be removed")
|
||||||
|
}
|
||||||
|
if got := rec.snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("close synthesised a fire: %+v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulate the trailing classifier tick for the now-closed child —
|
||||||
|
// must not fire.
|
||||||
|
mgr.onChildStateChanged("p_a", StateIdle)
|
||||||
|
if got := rec.snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("trailing state change re-fired: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTimerCloseChildIdleAllPartialPrune mirrors the idle_any
|
||||||
|
// partial-prune for idle_all: pruning a watched child shrinks the
|
||||||
|
// list; the remaining child going idle then satisfies the timer.
|
||||||
|
func TestTimerCloseChildIdleAllPartialPrune(t *testing.T) {
|
||||||
|
sess, mgr, rec := newTestManager(t)
|
||||||
|
owner := fakeChild("p_owner")
|
||||||
|
a := fakeChild("p_a")
|
||||||
|
b := fakeChild("p_b")
|
||||||
|
addChild(sess, owner)
|
||||||
|
addChild(sess, a)
|
||||||
|
addChild(sess, b)
|
||||||
|
working := StateWorking
|
||||||
|
a.idleState.Store(&working)
|
||||||
|
b.idleState.Store(&working)
|
||||||
|
|
||||||
|
resp, err := mgr.TimerFireWhenIdleAll("p_owner", "all done", "", []string{"p_a", "p_b"}, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TimerFireWhenIdleAll: %v", err)
|
||||||
|
}
|
||||||
|
if resp.Status != "pending" {
|
||||||
|
t.Fatalf("status: got %q want pending", resp.Status)
|
||||||
|
}
|
||||||
|
|
||||||
|
mgr.onChildClosed("p_a")
|
||||||
|
|
||||||
|
idle := StateIdle
|
||||||
|
b.idleState.Store(&idle)
|
||||||
|
mgr.onChildStateChanged("p_b", StateIdle)
|
||||||
|
if got := rec.snapshot(); len(got) != 1 || got[0].Body != "all done" {
|
||||||
|
t.Fatalf("idle_all after partial prune: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTimerCloseOwnerCancelsDelay ensures a delay timer is dropped
|
||||||
|
// when its owner is closed: no delivery, registry empty, the
|
||||||
|
// underlying time.Timer is stopped.
|
||||||
|
func TestTimerCloseOwnerCancelsDelay(t *testing.T) {
|
||||||
|
sess, mgr, rec := newTestManager(t)
|
||||||
|
c := fakeChild("p_owner")
|
||||||
|
addChild(sess, c)
|
||||||
|
id, err := mgr.TimerSet("p_owner", "x", "", 0.1)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("TimerSet: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mgr.onChildClosed("p_owner")
|
||||||
|
|
||||||
|
mgr.mu.Lock()
|
||||||
|
_, stillThere := mgr.timers[id]
|
||||||
|
mgr.mu.Unlock()
|
||||||
|
if stillThere {
|
||||||
|
t.Fatalf("delay timer was not removed when owner closed")
|
||||||
|
}
|
||||||
|
time.Sleep(200 * time.Millisecond) // past the original firesAt
|
||||||
|
if got := rec.snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("delay timer fired after owner close: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTimerCloseWatchedSubAgent is the exact shape of the reported
|
||||||
|
// stale-fire bug: orchestrator registers a watcher on a sub-agent,
|
||||||
|
// the sub-agent is closed, and the orchestrator must receive
|
||||||
|
// nothing (no stale body delivered after close_process).
|
||||||
|
func TestTimerCloseWatchedSubAgent(t *testing.T) {
|
||||||
|
sess, mgr, rec := newTestManager(t)
|
||||||
|
parent := fakeChild("p_owner")
|
||||||
|
sub := fakeChild("p_sub")
|
||||||
|
addChild(sess, parent)
|
||||||
|
addChild(sess, sub)
|
||||||
|
working := StateWorking
|
||||||
|
sub.idleState.Store(&working)
|
||||||
|
|
||||||
|
if _, err := mgr.TimerFireWhenIdleAny(
|
||||||
|
"p_owner",
|
||||||
|
"codex-review-591 finished. Read your own pane …",
|
||||||
|
"", []string{"p_sub"}, 0,
|
||||||
|
); err != nil {
|
||||||
|
t.Fatalf("TimerFireWhenIdleAny: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
mgr.onChildClosed("p_sub")
|
||||||
|
|
||||||
|
// Trailing classifier emission for the closed sub-agent must
|
||||||
|
// not deliver anything to the parent.
|
||||||
|
mgr.onChildStateChanged("p_sub", StateIdle)
|
||||||
|
if got := rec.snapshot(); len(got) != 0 {
|
||||||
|
t.Fatalf("stale fire delivered to parent after sub-agent close: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -40,6 +39,11 @@ const toastBoxMaxWidth = 50
|
|||||||
// any narrower and there's not enough room for borders + content.
|
// any narrower and there's not enough room for borders + content.
|
||||||
const toastBoxMinWidth = 20
|
const toastBoxMinWidth = 20
|
||||||
|
|
||||||
|
// toastContentRows is how many lines of message body each toast box
|
||||||
|
// reserves. The dismiss hint lives on the host status strip, so the
|
||||||
|
// box itself is purely the message.
|
||||||
|
const toastContentRows = 3
|
||||||
|
|
||||||
// toastStack owns the ordered list of live toasts. Oldest at
|
// toastStack owns the ordered list of live toasts. Oldest at
|
||||||
// index 0, newest (visually topmost) at the end. The stack's own
|
// index 0, newest (visually topmost) at the end. The stack's own
|
||||||
// mutex is intentionally separate from uiState.mu so push / dismiss
|
// mutex is intentionally separate from uiState.mu so push / dismiss
|
||||||
@@ -115,6 +119,10 @@ func (st *uiState) notifyToast(kind toastKind, text string) {
|
|||||||
// canvas). Each of those paths calls renderToasts at the end, so
|
// canvas). Each of those paths calls renderToasts at the end, so
|
||||||
// the toast layer is always reapplied on top of a freshly-drawn
|
// the toast layer is always reapplied on top of a freshly-drawn
|
||||||
// pane. Centralised so push / dismiss / clear share one code path.
|
// pane. Centralised so push / dismiss / clear share one code path.
|
||||||
|
//
|
||||||
|
// The status strip also gains/loses the "Ctrl-N · dismiss" hint as
|
||||||
|
// the stack toggles between empty and non-empty, so we redraw it
|
||||||
|
// here too rather than waiting for the chrome ticker.
|
||||||
func (st *uiState) refreshToastSurface() {
|
func (st *uiState) refreshToastSurface() {
|
||||||
st.mu.Lock()
|
st.mu.Lock()
|
||||||
focusedPad := st.focusedPad
|
focusedPad := st.focusedPad
|
||||||
@@ -134,6 +142,7 @@ func (st *uiState) refreshToastSurface() {
|
|||||||
default:
|
default:
|
||||||
st.renderEmptyState()
|
st.renderEmptyState()
|
||||||
}
|
}
|
||||||
|
st.drawStatusLine()
|
||||||
}
|
}
|
||||||
|
|
||||||
// renderToasts draws the toast stack over the top-right of the
|
// renderToasts draws the toast stack over the top-right of the
|
||||||
@@ -142,33 +151,62 @@ func (st *uiState) refreshToastSurface() {
|
|||||||
// freshly-redrawn pane content. Safe to call when the stack is
|
// freshly-redrawn pane content. Safe to call when the stack is
|
||||||
// empty (no-op).
|
// empty (no-op).
|
||||||
func (st *uiState) renderToasts() {
|
func (st *uiState) renderToasts() {
|
||||||
|
bytes := st.toastOverlayBytes()
|
||||||
|
if len(bytes) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
st.outMu.Lock()
|
||||||
|
defer st.outMu.Unlock()
|
||||||
|
_, _ = os.Stdout.Write(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// toastOverlayBytes builds the toast layer as a single byte buffer
|
||||||
|
// without writing to stdout. Returns nil when the stack is empty or
|
||||||
|
// the layout can't accommodate a box. Callers either write it
|
||||||
|
// directly (renderToasts) or stitch it onto the end of another
|
||||||
|
// stdout write so claude/codex/opencode redraws that paint over the
|
||||||
|
// top-right region can't leave the toast half-erased.
|
||||||
|
func (st *uiState) toastOverlayBytes() []byte {
|
||||||
items := st.toasts.snapshot()
|
items := st.toasts.snapshot()
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
st.mu.Lock()
|
st.mu.Lock()
|
||||||
palOpen := st.palette != nil
|
palOpen := st.palette != nil
|
||||||
st.mu.Unlock()
|
st.mu.Unlock()
|
||||||
if palOpen {
|
if palOpen {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
layout := st.layoutSnapshot()
|
layout := st.layoutSnapshot()
|
||||||
paneCols := int(layout.childCols())
|
paneCols := int(layout.childCols())
|
||||||
paneRows := int(layout.childRows())
|
paneRows := int(layout.childRows())
|
||||||
if paneCols < toastBoxMinWidth+2 || paneRows < 3 {
|
if paneCols < toastBoxMinWidth+2 || paneRows < toastContentRows+2 {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
boxWidth := toastBoxMaxWidth
|
boxWidth := toastBoxMaxWidth
|
||||||
if max := paneCols - 4; max < boxWidth {
|
if max := paneCols - 4; max < boxWidth {
|
||||||
boxWidth = max
|
boxWidth = max
|
||||||
}
|
}
|
||||||
if boxWidth < toastBoxMinWidth {
|
if boxWidth < toastBoxMinWidth {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
contentWidth := boxWidth - 4 // 2 border cells + 2 inner padding
|
contentWidth := boxWidth - 4 // 2 border cells + 2 inner padding
|
||||||
|
// Reserve two columns for the icon prefix on row 1 so wrapped rows
|
||||||
|
// indent under the body text rather than under the glyph.
|
||||||
|
const iconCols = 2
|
||||||
|
bodyRoom := contentWidth - iconCols
|
||||||
|
if bodyRoom < 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString("\x1b7\x1b[?25l")
|
// Wrap the whole overlay in DECSET 2026 (synchronized output)
|
||||||
|
// brackets so terminals that support BSU/ESU buffer the box paint
|
||||||
|
// into a single frame — without this, claude's continuous redraws
|
||||||
|
// and our overlay race on each cell, producing visible flicker.
|
||||||
|
// Terminals that don't recognise 2026 ignore the brackets, so the
|
||||||
|
// fallback behaviour is the same as before.
|
||||||
|
b.WriteString("\x1b[?2026h\x1b7\x1b[?25l")
|
||||||
|
|
||||||
row := int(layout.mainTop) + 1
|
row := int(layout.mainTop) + 1
|
||||||
col := int(layout.mainLeft) + paneCols - boxWidth - 1
|
col := int(layout.mainLeft) + paneCols - boxWidth - 1
|
||||||
@@ -180,20 +218,13 @@ func (st *uiState) renderToasts() {
|
|||||||
// reverse so the most recent push lands at the smallest row.
|
// reverse so the most recent push lands at the smallest row.
|
||||||
for idx := len(items) - 1; idx >= 0; idx-- {
|
for idx := len(items) - 1; idx >= 0; idx-- {
|
||||||
t := items[idx]
|
t := items[idx]
|
||||||
isTopmost := idx == len(items)-1
|
height := toastContentRows + 2
|
||||||
hintLine := ""
|
|
||||||
if isTopmost && len(items) > 1 {
|
|
||||||
hintLine = fmt.Sprintf("Ctrl-N · %d more", len(items)-1)
|
|
||||||
}
|
|
||||||
height := 3
|
|
||||||
if hintLine != "" {
|
|
||||||
height++
|
|
||||||
}
|
|
||||||
// Stop if we'd run off the bottom of the pane.
|
// Stop if we'd run off the bottom of the pane.
|
||||||
if row+height > int(layout.mainTop)+paneRows {
|
if row+height > int(layout.mainTop)+paneRows {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
border := toastBorderStyle(t.kind)
|
border := toastBorderStyle(t.kind)
|
||||||
|
wrapped := wrapToastBody(t.text, bodyRoom)
|
||||||
|
|
||||||
// Top border.
|
// Top border.
|
||||||
moveTo(&b, row, col)
|
moveTo(&b, row, col)
|
||||||
@@ -204,40 +235,22 @@ func (st *uiState) renderToasts() {
|
|||||||
b.WriteString(styleReset)
|
b.WriteString(styleReset)
|
||||||
row++
|
row++
|
||||||
|
|
||||||
// Content row.
|
// Content rows. Row 0 carries the kind glyph; rows 1..N indent
|
||||||
|
// by iconCols spaces so wrapped text lines up under the body.
|
||||||
|
for i := 0; i < toastContentRows; i++ {
|
||||||
moveTo(&b, row, col)
|
moveTo(&b, row, col)
|
||||||
b.WriteString(border)
|
b.WriteString(border)
|
||||||
b.WriteString("│")
|
b.WriteString("│")
|
||||||
b.WriteString(styleReset)
|
b.WriteString(styleReset)
|
||||||
b.WriteString(" ")
|
b.WriteString(" ")
|
||||||
|
if i == 0 {
|
||||||
b.WriteString(toastIcon(t.kind))
|
b.WriteString(toastIcon(t.kind))
|
||||||
body := t.text
|
} else {
|
||||||
bodyRoom := contentWidth - 2 // icon + space
|
b.WriteString(strings.Repeat(" ", iconCols))
|
||||||
if visibleLen(body) > bodyRoom {
|
|
||||||
body = clipRunes(body, bodyRoom-1) + "…"
|
|
||||||
}
|
}
|
||||||
b.WriteString(body)
|
line := wrapped[i]
|
||||||
b.WriteString(strings.Repeat(" ", max(0, bodyRoom-visibleLen(body))))
|
b.WriteString(line)
|
||||||
b.WriteString(" ")
|
b.WriteString(strings.Repeat(" ", max(0, bodyRoom-visibleLen(line))))
|
||||||
b.WriteString(border)
|
|
||||||
b.WriteString("│")
|
|
||||||
b.WriteString(styleReset)
|
|
||||||
row++
|
|
||||||
|
|
||||||
// Hint row (topmost only, when stack has more than one).
|
|
||||||
if hintLine != "" {
|
|
||||||
if visibleLen(hintLine) > contentWidth {
|
|
||||||
hintLine = clipRunes(hintLine, contentWidth-1) + "…"
|
|
||||||
}
|
|
||||||
moveTo(&b, row, col)
|
|
||||||
b.WriteString(border)
|
|
||||||
b.WriteString("│")
|
|
||||||
b.WriteString(styleReset)
|
|
||||||
b.WriteString(" ")
|
|
||||||
b.WriteString(styleHint)
|
|
||||||
b.WriteString(hintLine)
|
|
||||||
b.WriteString(styleReset)
|
|
||||||
b.WriteString(strings.Repeat(" ", max(0, contentWidth-visibleLen(hintLine))))
|
|
||||||
b.WriteString(" ")
|
b.WriteString(" ")
|
||||||
b.WriteString(border)
|
b.WriteString(border)
|
||||||
b.WriteString("│")
|
b.WriteString("│")
|
||||||
@@ -258,11 +271,8 @@ func (st *uiState) renderToasts() {
|
|||||||
row++
|
row++
|
||||||
}
|
}
|
||||||
|
|
||||||
b.WriteString("\x1b[?25h\x1b8")
|
b.WriteString("\x1b[?25h\x1b8\x1b[?2026l")
|
||||||
|
return []byte(b.String())
|
||||||
st.outMu.Lock()
|
|
||||||
defer st.outMu.Unlock()
|
|
||||||
_, _ = os.Stdout.WriteString(b.String())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func toastBorderStyle(kind toastKind) string {
|
func toastBorderStyle(kind toastKind) string {
|
||||||
@@ -276,6 +286,69 @@ func toastBorderStyle(kind toastKind) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// wrapToastBody word-wraps text into exactly toastContentRows lines,
|
||||||
|
// each at most width visible runes wide. Short messages are padded
|
||||||
|
// with empty trailing lines so callers can iterate a fixed-size
|
||||||
|
// slice; messages that don't fit get ellipsized on the last line.
|
||||||
|
func wrapToastBody(text string, width int) []string {
|
||||||
|
out := make([]string, toastContentRows)
|
||||||
|
if width < 1 {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
all := wrapToastWords(text, width)
|
||||||
|
if len(all) > toastContentRows {
|
||||||
|
all = all[:toastContentRows]
|
||||||
|
last := all[len(all)-1]
|
||||||
|
if visibleLen(last) >= width {
|
||||||
|
last = clipRunes(last, width-1) + "…"
|
||||||
|
} else {
|
||||||
|
last = last + "…"
|
||||||
|
}
|
||||||
|
all[len(all)-1] = last
|
||||||
|
}
|
||||||
|
for i, l := range all {
|
||||||
|
out[i] = l
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// wrapToastWords is a small word-wrapper sized for toast bodies:
|
||||||
|
// greedy, breaks overlong words on rune boundaries, drops collapsing
|
||||||
|
// whitespace via strings.Fields.
|
||||||
|
func wrapToastWords(text string, width int) []string {
|
||||||
|
var lines []string
|
||||||
|
var cur string
|
||||||
|
flush := func() {
|
||||||
|
if cur != "" {
|
||||||
|
lines = append(lines, cur)
|
||||||
|
cur = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, word := range strings.Fields(text) {
|
||||||
|
for visibleLen(word) > width {
|
||||||
|
flush()
|
||||||
|
head := clipRunes(word, width)
|
||||||
|
lines = append(lines, head)
|
||||||
|
word = word[len(head):]
|
||||||
|
}
|
||||||
|
if word == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cur == "" {
|
||||||
|
cur = word
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if visibleLen(cur)+1+visibleLen(word) <= width {
|
||||||
|
cur += " " + word
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
cur = word
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return lines
|
||||||
|
}
|
||||||
|
|
||||||
func toastIcon(kind toastKind) string {
|
func toastIcon(kind toastKind) string {
|
||||||
switch kind {
|
switch kind {
|
||||||
case toastError:
|
case toastError:
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
func TestToastStackPushAndOrder(t *testing.T) {
|
func TestToastStackPushAndOrder(t *testing.T) {
|
||||||
var s toastStack
|
var s toastStack
|
||||||
@@ -98,3 +101,64 @@ func TestToastStackSnapshotIsCopy(t *testing.T) {
|
|||||||
t.Fatalf("snapshot is not an independent copy: %#v", again)
|
t.Fatalf("snapshot is not an independent copy: %#v", again)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWrapToastBodyFixedHeight(t *testing.T) {
|
||||||
|
got := wrapToastBody("short", 20)
|
||||||
|
if len(got) != toastContentRows {
|
||||||
|
t.Fatalf("len = %d, want %d", len(got), toastContentRows)
|
||||||
|
}
|
||||||
|
if got[0] != "short" {
|
||||||
|
t.Fatalf("line 0 = %q, want \"short\"", got[0])
|
||||||
|
}
|
||||||
|
if got[1] != "" || got[2] != "" {
|
||||||
|
t.Fatalf("trailing pads not empty: %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrapToastBodyWrapsOnWordBoundary(t *testing.T) {
|
||||||
|
got := wrapToastBody("the quick brown fox jumps over", 10)
|
||||||
|
// Expect greedy fill: "the quick" (9), "brown fox" (9), "jumps over" (10).
|
||||||
|
want := []string{"the quick", "brown fox", "jumps over"}
|
||||||
|
for i, w := range want {
|
||||||
|
if got[i] != w {
|
||||||
|
t.Fatalf("line %d = %q, want %q (full=%#v)", i, got[i], w, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrapToastBodyEllipsizesOverflow(t *testing.T) {
|
||||||
|
got := wrapToastBody("alpha beta gamma delta epsilon zeta eta theta", 6)
|
||||||
|
if len(got) != toastContentRows {
|
||||||
|
t.Fatalf("len = %d, want %d", len(got), toastContentRows)
|
||||||
|
}
|
||||||
|
last := got[toastContentRows-1]
|
||||||
|
if !strings.HasSuffix(last, "…") {
|
||||||
|
t.Fatalf("overflow should ellipsize last line, got %q (full=%#v)", last, got)
|
||||||
|
}
|
||||||
|
if visibleLen(last) > 6 {
|
||||||
|
t.Fatalf("last line %q exceeds width 6", last)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrapToastBodyBreaksOverlongWord(t *testing.T) {
|
||||||
|
got := wrapToastBody("supercalifragilistic", 6)
|
||||||
|
if got[0] != "superc" {
|
||||||
|
t.Fatalf("line 0 = %q, want \"superc\"", got[0])
|
||||||
|
}
|
||||||
|
if got[1] != "alifra" {
|
||||||
|
t.Fatalf("line 1 = %q, want \"alifra\"", got[1])
|
||||||
|
}
|
||||||
|
// Third line should hold the rest (possibly ellipsized).
|
||||||
|
if got[2] == "" {
|
||||||
|
t.Fatalf("line 2 unexpectedly empty: %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrapToastBodyEmptyInput(t *testing.T) {
|
||||||
|
got := wrapToastBody("", 20)
|
||||||
|
for i, l := range got {
|
||||||
|
if l != "" {
|
||||||
|
t.Fatalf("line %d = %q, want \"\"", i, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"name": "idle_screen_permission_prompt",
|
||||||
|
"presets": {
|
||||||
|
"processes": [
|
||||||
|
{
|
||||||
|
"name": "screen-permission",
|
||||||
|
"argv": [
|
||||||
|
"sh",
|
||||||
|
"-lc",
|
||||||
|
"printf '\\033[2J\\033[HCalling patterm...\\n\\nTool use\\n\\nDo you want to proceed?\\n 1. Yes\\n'; i=0; while [ $i -lt 300 ]; do printf '\\033[HCalling patterm... %03d' $i; i=$((i+1)); done; sleep 60"
|
||||||
|
],
|
||||||
|
"idle_detection": {
|
||||||
|
"strategy": "output_activity",
|
||||||
|
"idle_threshold_ms": 500,
|
||||||
|
"permission_patterns": ["Do you want to proceed\\?"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"trust": ["screen-permission"],
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"type": "mcp_call",
|
||||||
|
"method": "spawn_process",
|
||||||
|
"params": {"kind": "command", "preset": "screen-permission", "name": "screen-permission"},
|
||||||
|
"save_as": "proc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "wait_until_mcp",
|
||||||
|
"method": "get_process_status",
|
||||||
|
"params": {"process_id": "{{proc.process_id}}"},
|
||||||
|
"path": "idle_state",
|
||||||
|
"equals": "permission",
|
||||||
|
"timeout_ms": 4000
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
package preset
|
package preset
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -35,6 +36,7 @@ type Preset struct {
|
|||||||
Argv []string `json:"argv"`
|
Argv []string `json:"argv"`
|
||||||
Env map[string]string `json:"env,omitempty"`
|
Env map[string]string `json:"env,omitempty"`
|
||||||
WorkingDir string `json:"working_dir,omitempty"`
|
WorkingDir string `json:"working_dir,omitempty"`
|
||||||
|
Disabled bool `json:"disabled,omitempty"`
|
||||||
|
|
||||||
// Process-only.
|
// Process-only.
|
||||||
Shell bool `json:"shell,omitempty"`
|
Shell bool `json:"shell,omitempty"`
|
||||||
@@ -119,28 +121,22 @@ type Set struct {
|
|||||||
Processes []*Preset
|
Processes []*Preset
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load scans the standard locations under $XDG_CONFIG_HOME/patterm/
|
// Load returns the built-in presets plus user overlays from
|
||||||
// presets/{agents,processes}/*.json. Unknown files are skipped with a
|
// $XDG_CONFIG_HOME/patterm/presets/{agents,processes}/*.json. Startup
|
||||||
// warning to stderr; the spec is forgiving here.
|
// does not write default files; user files only override or extend the
|
||||||
|
// in-memory defaults. A user overlay with {"disabled": true} hides a
|
||||||
|
// built-in preset of the same name.
|
||||||
func Load() (Set, error) {
|
func Load() (Set, error) {
|
||||||
base, err := ConfigDir()
|
base, err := ConfigDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Set{}, err
|
return Set{}, err
|
||||||
}
|
}
|
||||||
if err := os.MkdirAll(base, 0o700); err != nil {
|
|
||||||
return Set{}, fmt.Errorf("preset: mkdir %s: %w", base, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Make sure the default-preset files exist on first run. Idempotent.
|
agents, err := loadWithDefaults(filepath.Join(base, "presets", "agents"), KindAgent, defaultAgentPresets())
|
||||||
if err := ensureDefaults(base); err != nil {
|
|
||||||
return Set{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
agents, err := loadDir(filepath.Join(base, "presets", "agents"), KindAgent)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Set{}, err
|
return Set{}, err
|
||||||
}
|
}
|
||||||
procs, err := loadDir(filepath.Join(base, "presets", "processes"), KindCommand)
|
procs, err := loadWithDefaults(filepath.Join(base, "presets", "processes"), KindCommand, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Set{}, err
|
return Set{}, err
|
||||||
}
|
}
|
||||||
@@ -160,51 +156,154 @@ func ConfigDir() (string, error) {
|
|||||||
return filepath.Join(home, ".config", "patterm"), nil
|
return filepath.Join(home, ".config", "patterm"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadDir(dir string, kind Kind) ([]*Preset, error) {
|
func loadWithDefaults(dir string, kind Kind, defaults []*Preset) ([]*Preset, error) {
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
byName := make(map[string]*Preset, len(defaults))
|
||||||
return nil, fmt.Errorf("preset: mkdir %s: %w", dir, err)
|
for _, p := range defaults {
|
||||||
|
cp := clonePreset(p)
|
||||||
|
cp.Kind = kind
|
||||||
|
byName[cp.Name] = cp
|
||||||
}
|
}
|
||||||
|
|
||||||
entries, err := os.ReadDir(dir)
|
entries, err := os.ReadDir(dir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return sortedPresets(byName), nil
|
||||||
|
}
|
||||||
return nil, fmt.Errorf("preset: read %s: %w", dir, err)
|
return nil, fmt.Errorf("preset: read %s: %w", dir, err)
|
||||||
}
|
}
|
||||||
var out []*Preset
|
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
path := filepath.Join(dir, e.Name())
|
path := filepath.Join(dir, e.Name())
|
||||||
p, err := loadFile(path, kind)
|
p, err := loadFileOverlay(path, kind, byName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "patterm: preset %s: %v\n", path, err)
|
fmt.Fprintf(os.Stderr, "patterm: preset %s: %v\n", path, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if p.Disabled {
|
||||||
|
delete(byName, p.Name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
byName[p.Name] = p
|
||||||
|
}
|
||||||
|
return sortedPresets(byName), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedPresets(byName map[string]*Preset) []*Preset {
|
||||||
|
out := make([]*Preset, 0, len(byName))
|
||||||
|
for _, p := range byName {
|
||||||
out = append(out, p)
|
out = append(out, p)
|
||||||
}
|
}
|
||||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||||
return out, nil
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadFile(path string, kind Kind) (*Preset, error) {
|
func loadFileOverlay(path string, kind Kind, defaults map[string]*Preset) (*Preset, error) {
|
||||||
b, err := os.ReadFile(path)
|
b, err := os.ReadFile(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
var header struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Disabled bool `json:"disabled,omitempty"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(b, &header); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if header.Name == "" {
|
||||||
|
return nil, errors.New("missing 'name'")
|
||||||
|
}
|
||||||
|
if def := defaults[header.Name]; def != nil {
|
||||||
|
p, err := mergePreset(def, b)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
p.Path = path
|
||||||
|
p.Kind = kind
|
||||||
|
return p, validatePreset(p)
|
||||||
|
}
|
||||||
|
var p Preset
|
||||||
|
if err := json.Unmarshal(b, &p); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
p.Path = path
|
||||||
|
p.Kind = kind
|
||||||
|
return &p, validatePreset(&p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validatePreset(p *Preset) error {
|
||||||
|
if p.Name == "" {
|
||||||
|
return errors.New("missing 'name'")
|
||||||
|
}
|
||||||
|
if p.Disabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(p.Argv) == 0 && !p.Shell {
|
||||||
|
return errors.New("missing 'argv'")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mergePreset(def *Preset, overlay []byte) (*Preset, error) {
|
||||||
|
base, err := presetMap(def)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var over map[string]any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(overlay))
|
||||||
|
dec.UseNumber()
|
||||||
|
if err := dec.Decode(&over); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
deepMerge(base, over)
|
||||||
|
b, err := json.Marshal(base)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
var p Preset
|
var p Preset
|
||||||
if err := json.Unmarshal(b, &p); err != nil {
|
if err := json.Unmarshal(b, &p); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if p.Name == "" {
|
|
||||||
return nil, errors.New("missing 'name'")
|
|
||||||
}
|
|
||||||
if len(p.Argv) == 0 && !p.Shell {
|
|
||||||
return nil, errors.New("missing 'argv'")
|
|
||||||
}
|
|
||||||
p.Path = path
|
|
||||||
p.Kind = kind
|
|
||||||
return &p, nil
|
return &p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func presetMap(p *Preset) (map[string]any, error) {
|
||||||
|
b, err := json.Marshal(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var m map[string]any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(b))
|
||||||
|
dec.UseNumber()
|
||||||
|
if err := dec.Decode(&m); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func deepMerge(dst, src map[string]any) {
|
||||||
|
for k, v := range src {
|
||||||
|
if sm, ok := v.(map[string]any); ok {
|
||||||
|
if dm, ok := dst[k].(map[string]any); ok {
|
||||||
|
deepMerge(dm, sm)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dst[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func clonePreset(p *Preset) *Preset {
|
||||||
|
if p == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
b, _ := json.Marshal(p)
|
||||||
|
var out Preset
|
||||||
|
_ = json.Unmarshal(b, &out)
|
||||||
|
return &out
|
||||||
|
}
|
||||||
|
|
||||||
// ResolvedArgv returns the argv to actually exec, handling the
|
// ResolvedArgv returns the argv to actually exec, handling the
|
||||||
// process-preset "shell: true" case (SPEC §10).
|
// process-preset "shell: true" case (SPEC §10).
|
||||||
func (p *Preset) ResolvedArgv() []string {
|
func (p *Preset) ResolvedArgv() []string {
|
||||||
@@ -214,16 +313,8 @@ func (p *Preset) ResolvedArgv() []string {
|
|||||||
return p.Argv
|
return p.Argv
|
||||||
}
|
}
|
||||||
|
|
||||||
// ensureDefaults writes default agent presets (claude/codex/opencode)
|
func defaultAgentPresets() []*Preset {
|
||||||
// and a sample process preset on first run. Never overwrites existing
|
bodies := []string{
|
||||||
// user files.
|
|
||||||
func ensureDefaults(base string) error {
|
|
||||||
defaults := []struct {
|
|
||||||
rel string
|
|
||||||
body string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
"presets/agents/claude.json",
|
|
||||||
`{
|
`{
|
||||||
"name": "claude",
|
"name": "claude",
|
||||||
"argv": ["claude"],
|
"argv": ["claude"],
|
||||||
@@ -249,9 +340,6 @@ func ensureDefaults(base string) error {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
},
|
|
||||||
{
|
|
||||||
"presets/agents/codex.json",
|
|
||||||
`{
|
`{
|
||||||
"name": "codex",
|
"name": "codex",
|
||||||
"argv": ["codex"],
|
"argv": ["codex"],
|
||||||
@@ -275,9 +363,6 @@ func ensureDefaults(base string) error {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
},
|
|
||||||
{
|
|
||||||
"presets/agents/opencode.json",
|
|
||||||
`{
|
`{
|
||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"argv": ["opencode"],
|
"argv": ["opencode"],
|
||||||
@@ -301,19 +386,15 @@ func ensureDefaults(base string) error {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
},
|
|
||||||
}
|
}
|
||||||
for _, d := range defaults {
|
out := make([]*Preset, 0, len(bodies))
|
||||||
full := filepath.Join(base, d.rel)
|
for _, body := range bodies {
|
||||||
if _, err := os.Stat(full); err == nil {
|
var p Preset
|
||||||
continue
|
if err := json.Unmarshal([]byte(body), &p); err != nil {
|
||||||
|
panic(err)
|
||||||
}
|
}
|
||||||
if err := os.MkdirAll(filepath.Dir(full), 0o700); err != nil {
|
p.Kind = KindAgent
|
||||||
return err
|
out = append(out, &p)
|
||||||
}
|
}
|
||||||
if err := os.WriteFile(full, []byte(d.body), 0o600); err != nil {
|
return out
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
124
internal/preset/preset_test.go
Normal file
124
internal/preset/preset_test.go
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
package preset
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadUsesBuiltInDefaultsWithoutWritingConfig(t *testing.T) {
|
||||||
|
configHome := filepath.Join(t.TempDir(), "config")
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||||
|
|
||||||
|
set, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(configHome, "patterm")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("Load created config dir or unexpected stat error: %v", err)
|
||||||
|
}
|
||||||
|
if len(set.Agents) != 3 {
|
||||||
|
t.Fatalf("agents len = %d, want 3", len(set.Agents))
|
||||||
|
}
|
||||||
|
claude := presetByName(set.Agents, "claude")
|
||||||
|
if claude == nil {
|
||||||
|
t.Fatal("missing built-in claude preset")
|
||||||
|
}
|
||||||
|
if claude.IdleDetection == nil || len(claude.IdleDetection.PermissionPatterns) == 0 {
|
||||||
|
t.Fatalf("built-in claude missing permission patterns: %+v", claude.IdleDetection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadMergesUserOverlayIntoBuiltInPreset(t *testing.T) {
|
||||||
|
configHome := t.TempDir()
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||||
|
dir := filepath.Join(configHome, "patterm", "presets", "agents")
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(dir, "claude.json"), `{
|
||||||
|
"name": "claude",
|
||||||
|
"argv": ["claude", "--model", "sonnet"],
|
||||||
|
"idle_detection": { "idle_threshold_ms": 3500 }
|
||||||
|
}`)
|
||||||
|
|
||||||
|
set, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
claude := presetByName(set.Agents, "claude")
|
||||||
|
if claude == nil {
|
||||||
|
t.Fatal("missing claude preset")
|
||||||
|
}
|
||||||
|
if got := claude.Argv; len(got) != 3 || got[0] != "claude" || got[2] != "sonnet" {
|
||||||
|
t.Fatalf("argv = %#v", got)
|
||||||
|
}
|
||||||
|
if claude.IdleDetection.IdleThresholdMS != 3500 {
|
||||||
|
t.Fatalf("idle threshold = %d", claude.IdleDetection.IdleThresholdMS)
|
||||||
|
}
|
||||||
|
if len(claude.IdleDetection.PermissionPatterns) == 0 {
|
||||||
|
t.Fatalf("permission patterns were not inherited: %+v", claude.IdleDetection)
|
||||||
|
}
|
||||||
|
if claude.MCPInjection == nil || claude.MCPInjection.Kind != "flag" {
|
||||||
|
t.Fatalf("mcp injection was not inherited: %+v", claude.MCPInjection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadCanDisableBuiltInPreset(t *testing.T) {
|
||||||
|
configHome := t.TempDir()
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||||
|
dir := filepath.Join(configHome, "patterm", "presets", "agents")
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(dir, "opencode.json"), `{"name":"opencode","disabled":true}`)
|
||||||
|
|
||||||
|
set, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
if presetByName(set.Agents, "opencode") != nil {
|
||||||
|
t.Fatal("opencode preset was not disabled")
|
||||||
|
}
|
||||||
|
if presetByName(set.Agents, "claude") == nil || presetByName(set.Agents, "codex") == nil {
|
||||||
|
t.Fatalf("other built-ins missing: %+v", set.Agents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadAddsCustomUserPreset(t *testing.T) {
|
||||||
|
configHome := t.TempDir()
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", configHome)
|
||||||
|
dir := filepath.Join(configHome, "patterm", "presets", "processes")
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(dir, "test.json"), `{"name":"test","argv":["go","test","./..."]}`)
|
||||||
|
|
||||||
|
set, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load: %v", err)
|
||||||
|
}
|
||||||
|
proc := presetByName(set.Processes, "test")
|
||||||
|
if proc == nil {
|
||||||
|
t.Fatal("missing custom process preset")
|
||||||
|
}
|
||||||
|
if proc.Kind != KindCommand {
|
||||||
|
t.Fatalf("kind = %q", proc.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func presetByName(ps []*Preset, name string) *Preset {
|
||||||
|
for _, p := range ps {
|
||||||
|
if p.Name == name {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, path, body string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user