4 Commits
Author SHA1 Message Date
harry ec0c148164 Update PTY start call sites 2026-05-27 13:21:18 +01:00
harry 9aecc8b7a2 Scaffold loopback daemon client split 2026-05-27 13:19:56 +01:00
harry e63bdad5e1 Add daemon client protocol frames 2026-05-27 13:19:42 +01:00
harry b72a32bbc6 Fix PTY workdir and process group teardown 2026-05-27 13:19:35 +01:00
46 changed files with 1127 additions and 2796 deletions
@@ -1,358 +0,0 @@
# Task Sidebar Simplification Plan
## User Decisions
- First pass is manual project-local tasks only. Future GitHub/Linear linking should not be built now.
- The right sidebar should put Tasks first, while keeping existing process, agent tree, and scratchpad navigation secondary.
- Generic palette-spawned top-level agents must not inherit a selected task. Only explicit task-scoped actions, such as `Start agent for task`, create task-bound agents.
- Agents should receive task context only when they are task-bound, and task-bound agents should be told to register task worktrees through MCP.
## UX Review: Missing Pieces Today
- There is no task model. The current right rail in `internal/app/sidebar.go` is `Processes`, `Agent Tree`, and `Scratchpads` only.
- There is no task list, task detail view, task-focused navigation entry, or visible way to discover existing tasks.
- Task creation is absent. Existing creation flows are process/agent palette actions in `internal/app/palette.go` and `internal/app/app.go`.
- There is no explicit task-scoped launch action, so a user cannot intentionally start an agent for a task.
- MCP has no task context and no worktree registration tool, so agents cannot tell patterm which worktrees belong to a task.
- Current process rows are not grouped by task and do not surface task membership.
- Sidebar empty states are generic process/scratchpad placeholders and do not advertise task creation.
- The sidebar has no click or row activation model. First pass should stay keyboard/palette driven rather than inventing mouse interactions.
- Cleanup/status/archive and external issue links are real task-list UX needs, but they are out of scope for this first simplification pass unless requested later.
## Recommended Scope
Implement a minimal first-class task feature:
- Persist manual tasks per project.
- Render Tasks as the first sidebar section.
- Let users create, open, and rename tasks through the palette.
- Render a focused task detail view in the main viewport.
- Add explicit `Start agent for task` actions for focused tasks and task-bound children.
- Thread `TaskID` through children spawned from task context.
- Expose task context and `task_register_worktree` only to task-bound MCP callers.
- Fix PTY working-directory propagation, because task worktree paths are otherwise misleading.
Do not add GitHub/Linear linking, task import, agent-side task creation, task list MCP tools, click handling, or broad task/project management UI in this pass.
## Implementation Steps
### 1. Add Project Task Store
Add `internal/task/task.go` and `internal/task/task_test.go`.
Persist to `$XDG_DATA_HOME/patterm/projects/<projectKey>/tasks.json`, matching the existing project-local persistence pattern in `internal/persist/persist.go`.
Minimal structs:
```go
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Worktrees []Worktree `json:"worktrees,omitempty"`
}
type Worktree struct {
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
CreatedByProcessID string `json:"created_by_process_id,omitempty"`
RegisteredAt string `json:"registered_at"`
}
```
Store API:
```go
Open(projectKey string) (*Store, error)
(*Store).List() []Task
(*Store).Get(id string) (Task, bool)
(*Store).Create(title string) (Task, error)
(*Store).Rename(id, title string) (Task, error)
(*Store).RegisterWorktree(taskID string, wt Worktree) (Task, error)
```
Keep it deliberately small:
- Generate opaque IDs like `task_<hex>`.
- Validate non-empty titles.
- Use stable list ordering.
- De-duplicate worktrees by cleaned absolute path.
- Atomic write via `tasks.json.tmp` then rename.
- No status, assignee, priority, external refs, labels, or issue links yet.
### 2. Fix PTY Working Directory
Change `internal/pty/pty.go`:
- Update `Start(argv, env, cols, rows)` to `Start(argv, env, workDir, cols, rows)`.
- Set `cmd.Dir = workDir` when non-empty.
Update call sites:
- `internal/app/child.go: startPTY` passes `c.WorkDir`.
- `internal/harness/session.go` and `internal/harness/restart_persist_test.go` pass an empty workdir or project dir as appropriate.
- `cmd/spike/main.go` passes an empty workdir.
Add a focused PTY/app test that spawns `sh -lc pwd` with a temp workdir and verifies the child runs there.
### 3. Thread Task Context Through Runtime State
Modify `internal/app/child.go`:
- Add `TaskID string` to `Child`.
- Add `taskID` to `newChildEntry`.
Modify `internal/app/session.go`:
- Add `TaskID string` to `SpawnSpec`.
- Pass it into `newChildEntry`.
- Keep persistence limited to top-level command entries. Do not persist agent/task process trees in `processes.json`.
Modify `internal/app/launch.go`:
- Avoid adding more positional string parameters. Introduce a small launch context struct, for example:
```go
type LaunchContext struct {
ParentID string
TaskID string
WorkDir string
}
```
- Update `LaunchAgent`, `LaunchCommandPreset`, `LaunchCommandArgv`, and `LaunchTerminal` to accept this context or an equivalent minimal option.
- Generic palette spawns pass empty `TaskID` even when a task is focused.
- Explicit task actions pass `TaskID`.
- MCP spawns inherit `TaskID` from the caller only when the caller is task-bound.
### 4. Wire Task Store Into App State
Modify `internal/app/app.go`:
- Open `task.Open(opts.ProjectKey)` during `Run`, near scratchpads/trust/persist stores.
- Add `tasks *task.Store` to `uiState`.
- Add `focusedTaskID string`, mutually exclusive with `focusedID` and `focusedPad`.
- Add `tasksCacheMu` / `tasksCache`, mirroring `padsList()`.
- Add `tasksList()`, `invalidateTasksCache()`, and `tasksChanged()`.
- Pass the task store to `newToolHost`.
Modify `internal/app/host.go`:
- Add `tasks *task.Store` to `toolHost`.
- Extend `newToolHost` to accept it.
- Add a small `taskSink` interface like `tasksChanged()` so MCP worktree registration can refresh the sidebar/detail view.
### 5. Make Tasks First In The Sidebar
Modify `internal/app/sidebar.go:drawSidebar`:
- Render `Tasks` before `Processes`.
- Show empty state as something actionable, for example `(Ctrl-K create task)`.
- Show task rows with focus marker, title, and a compact suffix such as `2 worktrees` or `2w`.
- Keep current `Processes`, `Agent Tree`, and `Scratchpads` sections after Tasks.
- Do not add mouse or click behavior in this pass.
Modify `internal/app/tree.go`:
- Extend `navEntry` with `taskID string` and `isTask()`.
- Change `empty()` to include task entries.
- Change `sidebarNav` and `nextNavEntry` to accept tasks and order entries as `tasks -> processes -> active agent tree -> scratchpads`.
- Keep `nextChildID` compatibility tests working for process-only behavior.
Modify `internal/app/app.go`:
- Add `focusTask(taskID string)`.
- Add `renderTaskView(taskID string)` and `repaintFocusedTask()`.
- Update `focusProcess` and `focusScratchpad` to clear `focusedTaskID`.
- Update `repaintFocused`, `repaintFocusedWithChrome`, `restoreView` inside `closePalette`, and Ctrl-W/S pending nav handling to route task entries correctly.
- Update `drawStatusLine` to show `task: <title>` when a task is focused, and optionally `task: <title>` when a focused child is task-bound.
- Update `renderEmptyState` copy to mention tasks, for example `Press Ctrl-K to create a task or spawn an agent/process`.
Focused task detail view should be read-only and compact:
- Title and task ID.
- Registered worktrees.
- Task-bound running children if cheap to derive from `Session.Children()`.
- Hints: `Ctrl-K task actions`, `Ctrl-W/S navigate`.
### 6. Add Palette Task Actions
Modify `internal/app/palette.go`:
- Add task list and focused task fields to `paletteState`.
- Add `taskID string` to `paletteAction`.
- Add task action kinds:
- `task-create-form`
- `task-create-submit`
- `task-switch`
- `task-rename-form`
- `task-rename-submit`
- `task-start-agent`
- Add a task macro if useful, but do not make it required for the first patch.
- Reuse `renameForm` for create/rename by allowing subject `task` and different submit kinds.
Palette item behavior:
- Global/Open group includes `Create task...` and `Open task: <title>`.
- When a task is focused, show `Rename task` and `Start agent for task: <preset>` rows.
- When a task-bound child is focused, show `Open task: <title>` and `Start another agent for task: <preset>` rows.
- Normal `Spawn agent: <preset>` remains unscoped and passes empty `TaskID`.
Modify `internal/app/app.go:openPaletteLocked`:
- Pass `tasksList()`, `focusedTaskID`, and current focused child task information into `newPalette`.
Modify `internal/app/app.go:closePalette`:
- `task-create-submit`: create task, invalidate cache, focus the new task.
- `task-switch`: focus task.
- `task-rename-submit`: rename task, invalidate cache, redraw/focus task.
- `task-start-agent`: launch selected agent preset with the task ID and a task initial prompt.
Task initial prompt should be injected only for task-bound agents. Keep it single-line because agent input submission is line-sensitive:
```text
[system: you are working on patterm task "<title>" (<task_id>). If you create or use git worktrees for this task, call task_register_worktree with the path and branch.]
```
Include known registered worktrees in the prompt only if the list is short; otherwise rely on `whoami`.
### 7. Add Conditional MCP Task Context And Worktree Registration
Modify `internal/mcp/tools.go`:
- Add MCP structs `TaskInfo`, `TaskWorktree`, and `TaskRegisterWorktreeArgs`.
- Add optional `Task *TaskInfo `json:"task,omitempty"`` to `WhoAmI` and `ProjectStatus`.
- Do not add task fields to `ProcessInfo` in this pass, so unbound agents cannot discover task assignments through `list_processes`.
- Extend `ToolHost` with:
```go
CallerTask(processID string) (TaskInfo, bool)
RegisterTaskWorktree(callerID string, args TaskRegisterWorktreeArgs) (TaskInfo, error)
```
`TaskRegisterWorktreeArgs` should contain only `path` and optional `branch`. Do not accept a task ID from the caller; the host infers the task from `callerID`.
Modify `internal/mcp/protocol.go`:
- Replace the constant-only `serverInstructions` path with a helper that can append task-bound instructions only when `host.CallerTask(callerID)` is present.
- Change `toolCatalog(role)` to `toolCatalog(role, taskBound bool)`.
- Advertise `task_register_worktree` only when `taskBound` is true.
- Keep `spawn_agent` hidden from sub-agents as today.
Modify `internal/mcp/tools.go:callTool`:
- Add case `task_register_worktree`.
- Reject unbound callers with `role_forbidden`.
- Call `h.RegisterTaskWorktree(callerID, args)` and return the updated task.
Modify `internal/app/host.go`:
- Add helper `callerTaskID(callerID string) string` based on `Child.TaskID`.
- Implement `CallerTask` by resolving the caller child and task store entry.
- `WhoAmI` includes `Task` only when the caller child has a valid task ID.
- `GetProjectStatus` includes the same optional task only for task-bound callers.
- `SpawnAgent` and `SpawnProcess` inherit `TaskID` from the caller.
- Replace `wrapSubAgentPrompt` with a small prompt builder that can include sub-agent instructions, task instructions, or both. Task instructions should be added whenever the spawned agent is task-bound, even when caller `agent_instructions` is empty.
- `RegisterTaskWorktree` resolves relative paths against the caller child `WorkDir`, falling back to the project dir, cleans/absolutizes the path, stores it, and triggers `tasksChanged()`.
Important security/UX rule:
- Unbound MCP callers should not receive task context, task tool availability, task worktree data, or task IDs.
### 8. Tests
Add or update focused unit tests before broad harness work.
Task store:
- `internal/task/task_test.go`: create/list persists across reopen.
- Validate empty title errors.
- Rename updates title and `updated_at`.
- Register worktree de-duplicates cleaned absolute paths.
Runtime/spawn:
- `internal/app/session_test.go` or focused launch tests: `TaskID` lands on spawned child.
- MCP spawn from task-bound caller propagates `TaskID` to child.
- Generic palette spawn while `focusedTaskID` is set keeps `TaskID == ""`.
- Explicit `task-start-agent` sets `TaskID` and injects task prompt.
Sidebar/navigation/palette:
- `internal/app/tree_test.go`: task nav entries precede processes, agent tree, and scratchpads.
- `internal/app/palette_context_test.go`: focused task shows task actions; generic spawn remains unscoped.
- Add render-level tests only where existing helpers make that cheap; avoid brittle full-frame snapshots.
MCP:
- `internal/mcp/protocol_test.go`: unbound tools/list omits `task_register_worktree`; task-bound tools/list includes it.
- `internal/mcp/tools.go` tests or app host tests: unbound registration is rejected.
- `internal/app/host_test.go`: task-bound `whoami` includes task; unbound `whoami` omits task.
- `internal/app/host_test.go`: registration stores an absolute path and returns updated task info.
PTY working dir:
- Add the smallest test proving a PTY child honors configured `WorkDir`.
Harness:
- Add one lightweight scenario under `internal/harness/scenarios/`:
- Open palette.
- Create a task.
- Assert sidebar shows `Tasks` and the task title.
- Start a fake agent through `Start agent for task`.
- Use MCP `whoami` from that fake agent if feasible, or assert the prompt/context path indirectly through captured output.
### 9. Changelog
Update `CHANGELOG.md` under `[Unreleased]`.
Suggested bullets:
```md
### Added
- Added project-local manual tasks in the right sidebar, with palette actions to create tasks, open tasks, rename tasks, and start task-scoped agents.
- Added task-bound MCP context and `task_register_worktree` so agents launched for a task can register git worktrees they create.
### Fixed
- Child PTYs now honor their configured working directory when launched.
```
## Verification Commands
Run focused checks first:
```sh
go test ./internal/task/...
go test ./internal/pty/...
go test ./internal/app/...
go test ./internal/mcp/...
```
Then run broader checks:
```sh
go test ./internal/harness/...
go test ./...
go build -o ./bin/patterm ./cmd/patterm
```
Manual TUI smoke test:
```sh
./bin/patterm --project /home/harry/Dev/patterm
```
Manual flow to verify:
- Press `Ctrl-K`, create a task, and confirm it appears first in the sidebar.
- Focus the task from the sidebar navigation with `Ctrl-W/S`.
- Press `Ctrl-K`, start an agent for that task, and confirm the task remains visible and the agent is task-bound.
- Start a normal agent through `Spawn agent` while the task is selected and confirm it is not task-bound.
- From a task-bound fake/test agent, call `whoami` and confirm task context appears.
- From an unbound agent, call `whoami` and confirm no task context appears.
- From a task-bound agent, call `task_register_worktree` and confirm the task detail view/sidebar suffix updates.
If harness tests fail with Unix socket or PTY permission errors, rerun them in an environment that permits sockets and PTYs, as documented in `AGENTS.md`.
+3 -16
View File
@@ -7,30 +7,17 @@ loosely follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- Project-local manual tasks now appear first in the right sidebar,
with palette actions to create tasks, open tasks, rename tasks, and
start task-scoped agents.
- Task-bound agents now receive task MCP context and can call
`task_register_worktree` to register git worktrees they create or
use for the task.
- MCP clients can now call `scratchpad_delete` with a scratchpad name
to remove a shared project scratchpad.
### Changed
- The tab bar now shows each visible agent tab's own summary instead
of only rendering the focused tab's summary.
- `get_process_output` now returns aggressively canonical terminal text
by default, removing ANSI/control noise, decorative borders, duplicate
status churn, and volatile progress/timer fragments; raw PTY bytes are
opt-in with `raw:true`.
- MCP responses now use slimmer defaults: tool-call JSON is no longer
duplicated into text content, large output and scratchpad reads are
capped with truncation metadata, and `whoami` / `get_project_status`
only include full tool lists when `include_tools` is requested.
- Grid-mode `get_process_output` now returns whitespace-normalized
text to avoid sending padded terminal rows and repeated blank lines
over MCP.
### Fixed
- Child PTYs now honor their configured working directory when
launched.
- Injected agent input now sends the submit Enter as a separated,
settled keystroke so messages reliably submit instead of sometimes
sitting unsent in the composer.
-1
View File
@@ -1 +0,0 @@
- [ ] Pasting into codex is no longer clean, it sends loads of messages rather than one clean paste.
+89 -369
View File
@@ -21,7 +21,6 @@ import (
"github.com/hjbdev/patterm/internal/persist"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/scratchpad"
"github.com/hjbdev/patterm/internal/task"
"github.com/hjbdev/patterm/internal/trust"
"github.com/hjbdev/patterm/internal/vt"
)
@@ -82,11 +81,6 @@ func Run(ctx context.Context, opts Options) error {
return fmt.Errorf("app: persist init: %w", err)
}
taskStore, err := task.Open(opts.ProjectKey)
if err != nil {
return fmt.Errorf("app: task init: %w", err)
}
// In-process MCP server bound to the per-PID socket. Children that
// support MCP get pointed at `patterm mcp-stdio --socket=... --identity=...`.
// SPEC §10.
@@ -135,7 +129,7 @@ func Run(ctx context.Context, opts Options) error {
// Wire the tool host into MCP. Spawns through MCP use the host
// terminal's viewport grid for their initial PTY size; SIGWINCH paths
// resize them later.
host := newToolHost(sess, pads, taskStore, launcher, presets, trustStore, layout.childCols(), layout.childRows())
host := newToolHost(sess, pads, launcher, presets, trustStore, layout.childCols(), layout.childRows())
mcpSrv.SetHost(host)
var restoreState *term.State
@@ -167,17 +161,37 @@ func Run(ctx context.Context, opts Options) error {
// ctx is cancelled.
go sess.runClassifier(ctx)
st := &uiState{
sess: sess,
core := &headlessCore{
projectDir: opts.ProjectDir,
projectKey: opts.ProjectKey,
presets: presets,
launcher: launcher,
settings: appSettings,
pads: pads,
tasks: taskStore,
chromeWake: make(chan struct{}, 1),
trust: trustStore,
timers: host.timers,
hostCols: cols,
hostRows: rows,
trustStore: trustStore,
persistStore: persistStore,
mcpSrv: mcpSrv,
sess: sess,
launcher: launcher,
host: host,
}
_ = core
st := &uiState{
sess: sess,
presets: presets,
launcher: launcher,
pads: pads,
chromeWake: make(chan struct{}, 1),
trust: trustStore,
timers: host.timers,
hostCols: cols,
hostRows: rows,
view: ClientView{
ID: "loopback",
ProjectKey: opts.ProjectKey,
Cols: cols,
Rows: rows,
},
stdinTTY: term.IsTerminal(int(os.Stdin.Fd())),
metrics: metrics,
settings: appSettings,
@@ -201,7 +215,6 @@ func Run(ctx context.Context, opts Options) error {
host.focus = st
host.prompter = st
host.scratch = st
host.taskUI = st
st.lastExit.Store(-1)
sess.Subscribe(st)
go st.summaries.run(ctx)
@@ -260,6 +273,7 @@ func Run(ctx context.Context, opts Options) error {
}
st.dimsMu.Lock()
st.hostCols, st.hostRows = c, r
st.view.Resize(c, r)
l := st.layoutLocked()
st.dimsMu.Unlock()
st.mu.Lock()
@@ -410,13 +424,13 @@ type uiState struct {
presets preset.Set
launcher *Launcher
pads *scratchpad.Store
tasks *task.Store
trust *trust.Store
timers *timerManager
outMu sync.Mutex
mu sync.Mutex
view ClientView
palette *paletteState
focusedID string
focusedName string
@@ -426,11 +440,6 @@ type uiState struct {
// exclusive with focusedID. The palette also reads this to surface
// scratchpad-specific actions at the top of the command list.
focusedPad string
// focusedTaskID names the task currently rendered in the main viewport.
// It is mutually exclusive with focusedID and focusedPad. Task selection
// is not ambient spawn context; only explicit task actions launch
// task-bound agents/processes.
focusedTaskID string
// padOffset is the index of the top-most rendered row in the
// markdown-formatted view of focusedPad. Reset when focus moves to
// a different pad; preserved across content changes for the same
@@ -517,10 +526,8 @@ type uiState struct {
// repaint; the cache invalidates in scratchpadsChanged() which is
// the canonical "pads mutated" signal from MCP write/append. nil
// means "never read yet" — next caller refreshes.
padsCacheMu sync.Mutex
padsCache []scratchpad.Entry
tasksCacheMu sync.Mutex
tasksCache []task.Task
padsCacheMu sync.Mutex
padsCache []scratchpad.Entry
lastExit atomic.Int32
}
@@ -590,6 +597,21 @@ func (st *uiState) promptTrust(processID, presetName, reason string) {
st.drawStatusLine()
}
func (st *uiState) focusChildLocked(c *Child) {
st.focusedPad = ""
st.focusedID = c.ID
st.focusedName = c.DisplayName()
st.view.FocusChild(c.ID)
}
func (st *uiState) focusPadLocked(name string) {
st.view.FocusPad(name)
st.focusedPad = st.view.FocusedPad
st.focusedID = st.view.FocusedID
st.padOffset = st.view.PadOffset
st.padOffsetName = st.view.PadOffsetName
}
// focusProcess is the SPEC §7 select_process hook. Routes through the
// normal focus-change path; only takes effect if the process exists.
func (st *uiState) focusProcess(processID string) {
@@ -601,11 +623,8 @@ func (st *uiState) focusProcess(processID string) {
layout := st.layoutSnapshot()
onAlt := childIsOnAlt(c)
st.mu.Lock()
leavingStaticView := st.focusedPad != "" || st.focusedTaskID != ""
st.focusedPad = ""
st.focusedTaskID = ""
st.focusedID = c.ID
st.focusedName = c.DisplayName()
leavingPad := st.focusedPad != ""
st.focusChildLocked(c)
st.updateActiveAgentLocked(c)
r := newViewportRenderer(layout)
r.SetChildOnAlt(onAlt)
@@ -614,7 +633,7 @@ func (st *uiState) focusProcess(processID string) {
st.syncHostMouseForChild(onAlt)
// Wipe whatever the previous focus (PTY child or pad view) left in
// the viewport before painting the new child's snapshot.
if leavingStaticView {
if leavingPad {
st.clearViewportArea()
}
st.repaintFocused()
@@ -668,13 +687,7 @@ func (st *uiState) focusScratchpad(name string) {
}
st.marquee.reset()
st.mu.Lock()
if st.padOffsetName != name {
st.padOffset = 0
st.padOffsetName = name
}
st.focusedPad = name
st.focusedTaskID = ""
st.focusedID = ""
st.focusPadLocked(name)
st.focusedName = name
st.renderer = nil
st.mu.Unlock()
@@ -685,29 +698,6 @@ func (st *uiState) focusScratchpad(name string) {
st.drawStatusLine()
}
func (st *uiState) focusTask(taskID string) {
if taskID == "" || st.tasks == nil {
return
}
t, ok := st.tasks.Get(taskID)
if !ok {
return
}
st.marquee.reset()
st.mu.Lock()
st.focusedTaskID = t.ID
st.focusedPad = ""
st.focusedID = ""
st.focusedName = t.Title
st.renderer = nil
st.mu.Unlock()
st.clearViewportArea()
st.repaintFocusedTask()
st.drawTabBar()
st.drawSidebar()
st.drawStatusLine()
}
// clearViewportArea wipes the rectangle the focused-child PTY (or pad
// view) paints into so the next paint starts on a clean canvas. Used
// when transitioning between pad and child focus.
@@ -732,11 +722,8 @@ func (st *uiState) clearViewportArea() {
func (st *uiState) repaintFocusedWithChrome() {
st.mu.Lock()
padFocused := st.focusedPad != ""
taskFocused := st.focusedTaskID != ""
st.mu.Unlock()
if taskFocused {
st.repaintFocusedTask()
} else if padFocused {
if padFocused {
st.repaintFocusedPad()
} else {
st.repaintFocused()
@@ -755,8 +742,7 @@ func (st *uiState) restartFocusedCommand(processID string) {
layout := st.layoutSnapshot()
renderer := newViewportRenderer(layout)
st.mu.Lock()
st.focusedID = c.ID
st.focusedName = c.DisplayName()
st.focusChildLocked(c)
st.renderer = renderer
st.repaintNextPTY = c.ID
st.repaintNextPTYBudget = 2
@@ -791,6 +777,7 @@ func (st *uiState) updateActiveAgentLocked(c *Child) {
}
if c.ParentID == "" {
st.activeAgentID = c.ID
st.view.ActiveAgentID = c.ID
return
}
// Walk up to the top-level agent.
@@ -804,6 +791,7 @@ func (st *uiState) updateActiveAgentLocked(c *Child) {
}
if root.Kind == KindAgent && root.ParentID == "" {
st.activeAgentID = root.ID
st.view.ActiveAgentID = root.ID
}
}
@@ -830,18 +818,6 @@ func (st *uiState) scratchpadsChanged() {
}
}
func (st *uiState) tasksChanged() {
st.invalidateTasksCache()
st.drawSidebar()
st.mu.Lock()
focusedTask := st.focusedTaskID
st.mu.Unlock()
if focusedTask != "" {
st.repaintFocusedTask()
st.drawStatusLine()
}
}
func (st *uiState) invalidateScratchpadsCache() {
st.padsCacheMu.Lock()
st.padsCache = nil
@@ -851,15 +827,6 @@ func (st *uiState) invalidateScratchpadsCache() {
st.chromeCacheMu.Unlock()
}
func (st *uiState) invalidateTasksCache() {
st.tasksCacheMu.Lock()
st.tasksCache = nil
st.tasksCacheMu.Unlock()
st.chromeCacheMu.Lock()
st.sidebarCache = ""
st.chromeCacheMu.Unlock()
}
// OnChildSpawned auto-focuses the new child when the spawn came from
// the user (palette, persistence restore, or an external MCP client with
// no resolved identity). When ParentID is set — meaning a patterm-managed
@@ -875,10 +842,6 @@ func (st *uiState) OnChildSpawned(c *Child) {
if st.palette != nil {
st.palette.children = st.sess.Children()
st.palette.focused = st.focusedID
st.palette.focusedPad = st.focusedPad
st.palette.focusedTaskID = st.focusedTaskID
st.palette.tasksEnabled = st.tasks != nil
st.palette.tasks = st.tasksList()
st.palette.rebuild()
st.renderPaletteLocked()
}
@@ -891,10 +854,7 @@ func (st *uiState) OnChildSpawned(c *Child) {
layout := st.layoutSnapshot()
onAlt := childIsOnAlt(c)
st.mu.Lock()
st.focusedPad = ""
st.focusedTaskID = ""
st.focusedID = c.ID
st.focusedName = c.DisplayName()
st.focusChildLocked(c)
st.updateActiveAgentLocked(c)
renderer := newViewportRenderer(layout)
renderer.SetChildOnAlt(onAlt)
@@ -903,10 +863,6 @@ func (st *uiState) OnChildSpawned(c *Child) {
if palOpen {
st.palette.children = st.sess.Children()
st.palette.focused = st.focusedID
st.palette.focusedPad = st.focusedPad
st.palette.focusedTaskID = st.focusedTaskID
st.palette.tasksEnabled = st.tasks != nil
st.palette.tasks = st.tasksList()
st.palette.rebuild()
st.renderPaletteLocked()
}
@@ -973,10 +929,10 @@ func (st *uiState) OnChildExited(c *Child) {
if next == nil {
st.focusedID = ""
st.focusedName = ""
st.view.FocusedID = ""
renderEmpty = true
} else {
st.focusedID = next.ID
st.focusedName = next.DisplayName()
st.focusChildLocked(next)
st.updateActiveAgentLocked(next)
st.renderer = newViewportRenderer(layout)
}
@@ -985,14 +941,11 @@ func (st *uiState) OnChildExited(c *Child) {
// The active agent died; pin the agent tree to whatever agent
// root is still running, or clear it if none remain.
st.activeAgentID = firstRunningAgentID(st.sess.Children())
st.view.ActiveAgentID = st.activeAgentID
}
if st.palette != nil {
st.palette.children = st.sess.Children()
st.palette.focused = st.focusedID
st.palette.focusedPad = st.focusedPad
st.palette.focusedTaskID = st.focusedTaskID
st.palette.tasksEnabled = st.tasks != nil
st.palette.tasks = st.tasksList()
st.palette.rebuild()
st.renderPaletteLocked()
}
@@ -1236,40 +1189,6 @@ func (st *uiState) padsList() []scratchpad.Entry {
return entries
}
// tasksList returns the cached task listing. Callers must not mutate the
// returned slice — it is shared until invalidateTasksCache runs.
func (st *uiState) tasksList() []task.Task {
if st.tasks == nil {
return nil
}
st.tasksCacheMu.Lock()
if st.tasksCache != nil {
out := st.tasksCache
st.tasksCacheMu.Unlock()
return out
}
st.tasksCacheMu.Unlock()
entries := st.tasks.List()
st.tasksCacheMu.Lock()
st.tasksCache = entries
st.tasksCacheMu.Unlock()
return entries
}
func (st *uiState) taskByID(id string) (task.Task, bool) {
if id == "" || st.tasks == nil {
return task.Task{}, false
}
return st.tasks.Get(id)
}
func (st *uiState) taskTitle(id string) string {
if t, ok := st.taskByID(id); ok {
return t.Title
}
return ""
}
// markChromeDirty schedules a chrome (tab bar + status line) repaint
// on the next ticker frame. Cheap to call from the per-PTY-chunk hot
// path. Latency-sensitive sites (focus change, owner flip, attention,
@@ -1381,7 +1300,6 @@ func (st *uiState) drawStatusLine() {
palOpen := st.palette != nil
focusID := st.focusedID
focusName := st.focusedName
focusTaskID := st.focusedTaskID
var trustMsg string
if st.pendingTrust != nil {
trustMsg = fmt.Sprintf("trust preset %q? [y]es / [n]o", st.pendingTrust.presetName)
@@ -1410,24 +1328,10 @@ func (st *uiState) drawStatusLine() {
owner = "you have control"
}
}
if focusTaskID != "" && focusName == "" {
focusName = st.taskTitle(focusTaskID)
}
left := ""
if focusTaskID != "" && focusName != "" {
left = "task: " + focusName
} else if focusName != "" {
if focusName != "" {
left = focusName
}
if focusedChild != nil && focusedChild.TaskID != "" {
if title := st.taskTitle(focusedChild.TaskID); title != "" {
if left != "" {
left = left + " · task: " + title
} else {
left = "task: " + title
}
}
}
if owner != "" {
if left != "" {
left = left + " · " + owner
@@ -1496,7 +1400,7 @@ func (st *uiState) drawStatusLine() {
// child is focused.
func (st *uiState) renderEmptyState() {
layout := st.layoutSnapshot()
line := "Press Ctrl-K to create a task or spawn an agent/process"
line := "Press Ctrl-K to spawn an agent or process"
row := int(layout.mainTop) + (int(layout.childRows()) / 2)
col := int(layout.mainLeft) + ((int(layout.childCols()) - len(line)) / 2)
if row < int(layout.mainTop) {
@@ -1514,7 +1418,10 @@ func (st *uiState) renderEmptyState() {
func (st *uiState) hostSizeSnapshot() (uint16, uint16) {
st.dimsMu.Lock()
defer st.dimsMu.Unlock()
return st.hostCols, st.hostRows
if st.view.Cols == 0 || st.view.Rows == 0 {
return st.hostCols, st.hostRows
}
return st.view.Cols, st.view.Rows
}
func (st *uiState) layoutSnapshot() terminalLayout {
@@ -1524,7 +1431,10 @@ func (st *uiState) layoutSnapshot() terminalLayout {
}
func (st *uiState) layoutLocked() terminalLayout {
return newTerminalLayout(st.hostCols, st.hostRows)
if st.view.Cols == 0 || st.view.Rows == 0 {
return newTerminalLayout(st.hostCols, st.hostRows)
}
return newTerminalLayout(st.view.Cols, st.view.Rows)
}
// splitOnEnter walks input and returns each Enter byte (CR or LF) as
@@ -1917,13 +1827,13 @@ func (st *uiState) processStdin(chunk []byte) {
}
if hit, adv := matchCtrlChar(chunk, i, 'w'); hit {
flushForward()
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.activeAgentID, st.tasksList(), st.padsList(), -1)
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.activeAgentID, st.padsList(), -1)
i += adv
break
}
if hit, adv := matchCtrlChar(chunk, i, 's'); hit {
flushForward()
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.activeAgentID, st.tasksList(), st.padsList(), +1)
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.activeAgentID, st.padsList(), +1)
i += adv
break
}
@@ -2011,8 +1921,6 @@ func (st *uiState) processStdin(chunk []byte) {
}
if !pendingNav.empty() {
switch {
case pendingNav.isTask():
st.focusTask(pendingNav.taskID)
case pendingNav.isPad():
st.focusScratchpad(pendingNav.pad)
case pendingNav.isChild():
@@ -2094,7 +2002,7 @@ func (st *uiState) openPaletteLocked() {
st.settingsMu.Lock()
appSettings := st.settings.clone()
st.settingsMu.Unlock()
st.palette = newPaletteWithTasks(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.tasksList(), st.presets, appSettings)
st.palette = newPalette(st.sess.Children(), st.focusedID, st.focusedPad, st.presets, appSettings)
// Push a "no kitty flags" entry onto the host terminal's keyboard
// stack so palette input arrives in plain legacy form regardless of
// what the focused child pushed. Codex/ratatui enables kitty mode
@@ -2130,12 +2038,7 @@ func (st *uiState) closePalette(action paletteAction) {
restoreView := func() {
st.mu.Lock()
padFocused := st.focusedPad != ""
taskFocused := st.focusedTaskID != ""
st.mu.Unlock()
if taskFocused {
st.repaintFocusedTask()
return
}
if padFocused {
st.repaintFocusedPad()
return
@@ -2159,7 +2062,7 @@ func (st *uiState) closePalette(action paletteAction) {
st.launcher.SetSize(l.childCols(), l.childRows())
// LaunchAgent fires OnChildSpawned synchronously; it will draw
// chrome and set focus.
if _, err := st.launcher.LaunchAgent(action.preset, action.preset.Name, "", LaunchContext{}); err != nil {
if _, err := st.launcher.LaunchAgent(action.preset, action.preset.Name, "", ""); err != nil {
st.flashError(fmt.Sprintf("spawn %s: %v", action.preset.Name, err))
}
@@ -2170,14 +2073,14 @@ func (st *uiState) closePalette(action paletteAction) {
}
l := st.layoutSnapshot()
st.launcher.SetSize(l.childCols(), l.childRows())
if _, err := st.launcher.LaunchCommandPreset(action.preset, action.preset.Name, LaunchContext{}); err != nil {
if _, err := st.launcher.LaunchCommandPreset(action.preset, action.preset.Name, ""); err != nil {
st.flashError(fmt.Sprintf("spawn %s: %v", action.preset.Name, err))
}
case "spawn-terminal":
l := st.layoutSnapshot()
st.launcher.SetSize(l.childCols(), l.childRows())
if _, err := st.launcher.LaunchTerminal(nil, "terminal", LaunchContext{}, nil); err != nil {
if _, err := st.launcher.LaunchTerminal(nil, "terminal", "", "", nil); err != nil {
st.flashError(fmt.Sprintf("spawn terminal: %v", err))
}
@@ -2195,7 +2098,7 @@ func (st *uiState) closePalette(action paletteAction) {
// shell=true so multi-word commands like "bun run dev" pass
// through `sh -lc` and the user's PATH resolves binaries the
// way they expect from an interactive shell.
c, err := st.launcher.LaunchCommandArgv([]string{action.command}, display, LaunchContext{}, nil, true)
c, err := st.launcher.LaunchCommandArgv([]string{action.command}, display, "", "", nil, true)
if err != nil {
st.flashError(fmt.Sprintf("spawn: %v", err))
return
@@ -2211,18 +2114,6 @@ func (st *uiState) closePalette(action paletteAction) {
st.drawSidebar()
}
case "task-create-submit":
st.handleTaskCreate(action.newName)
case "task-switch":
st.focusTask(action.taskID)
case "task-rename-submit":
st.handleTaskRename(action.taskID, action.newName)
case "task-start-agent":
st.handleTaskStartAgent(action.taskID, action.preset)
case "switch":
c := st.sess.FindChild(action.childID)
if c == nil || (c.Kind == KindAgent && c.Status() != StatusRunning) {
@@ -2231,18 +2122,15 @@ func (st *uiState) closePalette(action paletteAction) {
}
layout := st.layoutSnapshot()
st.mu.Lock()
leavingStaticView := st.focusedPad != "" || st.focusedTaskID != ""
st.focusedPad = ""
st.focusedTaskID = ""
st.focusedID = action.childID
st.focusedName = c.DisplayName()
leavingPad := st.focusedPad != ""
st.focusChildLocked(c)
st.updateActiveAgentLocked(c)
st.renderer = newViewportRenderer(layout)
st.mu.Unlock()
// Switching from a pad to a child: wipe the pad body so the
// child's snapshot paints onto a clean canvas, mirroring
// focusProcess.
if leavingStaticView {
if leavingPad {
st.clearViewportArea()
}
st.repaintFocused()
@@ -2309,70 +2197,6 @@ func (st *uiState) closePalette(action paletteAction) {
}
}
func (st *uiState) handleTaskCreate(title string) {
if st.tasks == nil {
st.flashError("tasks unavailable")
return
}
t, err := st.tasks.Create(title)
if err != nil {
st.flashError(fmt.Sprintf("create task: %v", err))
return
}
st.invalidateTasksCache()
st.focusTask(t.ID)
}
func (st *uiState) handleTaskRename(taskID, title string) {
if st.tasks == nil || taskID == "" {
st.repaintFocused()
return
}
t, err := st.tasks.Rename(taskID, title)
if err != nil {
st.flashError(fmt.Sprintf("rename task: %v", err))
return
}
st.invalidateTasksCache()
st.mu.Lock()
wasFocused := st.focusedTaskID == taskID
if wasFocused {
st.focusedName = t.Title
}
st.mu.Unlock()
if wasFocused {
st.focusTask(taskID)
return
}
st.drawSidebar()
st.drawStatusLine()
}
func (st *uiState) handleTaskStartAgent(taskID string, p *preset.Preset) {
if p == nil {
st.repaintFocused()
return
}
t, ok := st.taskByID(taskID)
if !ok {
st.flashError("start task agent: task not found")
return
}
l := st.layoutSnapshot()
st.launcher.SetSize(l.childCols(), l.childRows())
display := p.Name + " · " + t.Title
ctx := LaunchContext{TaskID: t.ID, WorkDir: st.sess.projectDir}
if _, err := st.launcher.LaunchAgent(p, display, taskAgentPrompt(t), ctx); err != nil {
st.flashError(fmt.Sprintf("start task agent: %v", err))
}
}
func taskAgentPrompt(t task.Task) string {
title := strings.NewReplacer("\r", " ", "\n", " ", `"`, "'").Replace(t.Title)
id := strings.NewReplacer("\r", " ", "\n", " ").Replace(t.ID)
return fmt.Sprintf("[system: you are working on patterm task %q (%s). If you create or use git worktrees for this task, call task_register_worktree with the path and branch.]", title, id)
}
func (st *uiState) applySettingsAction(action paletteAction) {
if action.settings == nil {
return
@@ -2443,13 +2267,8 @@ func (st *uiState) handlePadDelete(name string) {
if entries := st.padsList(); len(entries) > 0 {
next := entries[0].Name
st.mu.Lock()
st.focusedPad = next
st.focusedID = ""
st.focusPadLocked(next)
st.focusedName = next
if st.padOffsetName != next {
st.padOffset = 0
st.padOffsetName = next
}
st.mu.Unlock()
st.repaintFocusedWithChrome()
return
@@ -2460,9 +2279,12 @@ func (st *uiState) handlePadDelete(name string) {
}
st.mu.Lock()
st.focusedPad = ""
st.view.FocusedPad = ""
st.focusedName = ""
st.padOffset = 0
st.padOffsetName = ""
st.view.PadOffset = 0
st.view.PadOffsetName = ""
st.mu.Unlock()
st.renderEmptyState()
st.drawTabBar()
@@ -2489,7 +2311,7 @@ func (st *uiState) handlePadRename(oldName, newName string) {
}
st.mu.Lock()
if st.focusedPad == oldName {
st.focusedPad = newName
st.focusPadLocked(newName)
}
st.mu.Unlock()
st.scratchpadsChanged()
@@ -2670,14 +2492,9 @@ func (st *uiState) repaintFocused() {
layout := st.layoutSnapshot()
st.mu.Lock()
id := st.focusedID
taskID := st.focusedTaskID
renderer := st.renderer
st.mu.Unlock()
if id == "" {
if taskID != "" {
st.repaintFocusedTask()
return
}
st.renderEmptyState()
return
}
@@ -2708,106 +2525,6 @@ func (st *uiState) repaintFocused() {
st.renderToasts()
}
func (st *uiState) repaintFocusedTask() {
st.mu.Lock()
taskID := st.focusedTaskID
st.mu.Unlock()
if taskID == "" {
return
}
t, ok := st.taskByID(taskID)
if !ok {
st.renderEmptyState()
return
}
out := st.renderTaskView(t, st.sess.Children(), st.layoutSnapshot())
if len(out) == 0 {
return
}
st.outMu.Lock()
_, _ = os.Stdout.Write(out)
st.outMu.Unlock()
st.renderToasts()
}
func (st *uiState) renderTaskView(t task.Task, children []*Child, layout terminalLayout) []byte {
mainBottom := int(layout.statusRow) - statusRows
width := int(layout.childCols())
if mainBottom < int(layout.mainTop) || width < 1 {
return nil
}
contentWidth := width - 2
if contentWidth < 1 {
contentWidth = 1
}
var b strings.Builder
fmt.Fprintf(&b, "\x1b[0m\x1b[?6l\x1b[%d;%dr\x1b[?25l\x1b[%d;%dH",
int(layout.mainTop), mainBottom,
int(layout.mainTop), int(layout.mainLeft))
row := int(layout.mainTop)
writeRow := func(text, style string) {
if row > mainBottom {
return
}
if visibleLen(text) > contentWidth {
text = clampVisible(text, contentWidth)
}
fmt.Fprintf(&b, "\x1b[%d;%dH\x1b[%dX", row, int(layout.mainLeft), width)
fmt.Fprintf(&b, "\x1b[%d;%dH%s %s%s", row, int(layout.mainLeft), style, text, styleReset)
row++
}
writeRow("task: "+t.Title, styleActive+styleBold)
writeRow("id: "+t.ID, styleDim)
if width > 2 {
writeRow(strings.Repeat("─", contentWidth), styleBorder)
}
writeRow("worktrees", styleHint)
if len(t.Worktrees) == 0 {
writeRow("(none registered yet)", styleDim)
} else {
for _, wt := range t.Worktrees {
line := wt.Path
if wt.Branch != "" {
line += " [" + wt.Branch + "]"
}
writeRow(line, "")
}
}
bound := taskBoundChildren(children, t.ID)
if row+1 <= mainBottom {
writeRow("", "")
writeRow("processes", styleHint)
if len(bound) == 0 {
writeRow("(none running for this task)", styleDim)
} else {
for _, c := range bound {
writeRow(fmt.Sprintf("%s %s %s", c.ID, c.Kind, c.DisplayName()), "")
}
}
}
if row+1 <= mainBottom {
writeRow("", "")
writeRow("Ctrl-K task actions · Ctrl-W/S navigate", styleDim)
}
for row <= mainBottom {
writeRow("", "")
}
return []byte(b.String())
}
func taskBoundChildren(children []*Child, taskID string) []*Child {
out := make([]*Child, 0, 4)
for _, c := range children {
if c.TaskID == taskID {
out = append(out, c)
}
}
return out
}
// repaintFocusedPad paints the focused scratchpad's content into the
// main viewport, honouring the per-pad scroll offset and clamping it
// to the rendered body size so a shrunk pad doesn't leave the view
@@ -2865,6 +2582,7 @@ func (st *uiState) renderPadView(name, content string, layout terminalLayout) []
st.padOffset = 0
}
offset := st.padOffset
st.view.PadOffset = offset
st.mu.Unlock()
var b strings.Builder
@@ -2922,6 +2640,7 @@ func (st *uiState) exitPadView() {
return
}
st.focusedPad = ""
st.view.FocusedPad = ""
st.focusedName = ""
st.mu.Unlock()
st.clearViewportArea()
@@ -2948,6 +2667,7 @@ func (st *uiState) padScroll(delta int) {
if st.padOffset < 0 {
st.padOffset = 0
}
st.view.PadOffset = st.padOffset
st.mu.Unlock()
st.repaintFocusedPad()
}
-143
View File
@@ -1,143 +0,0 @@
package app
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var (
statusVolatileRE = regexp.MustCompile(`\b(?:\d+h\s*)?\d+m\s*\d+s\b|\b\d{1,2}:\d{2}(?::\d{2})?\b|\b\d+(?:\.\d+)?s\b`)
counterRE = regexp.MustCompile(`\b\d+\s*/\s*\d+\b|\b\d{1,3}%`)
spinnerGlyphRE = regexp.MustCompile(`^[\s⠁⠂⠄⡀⢀⠠⠐⠈⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏•·∙◐◓◑◒]+`)
)
func canonicalizeTerminalText(s string, maxLines int) (string, bool, int) {
s = string(stripANSIBytes(nil, []byte(s)))
s = strings.ReplaceAll(s, "\r\n", "\n")
s = carriageReturnToLines(s)
s = strings.ReplaceAll(s, "\r", "\n")
lines := strings.Split(s, "\n")
out := make([]string, 0, len(lines))
pendingBlank := false
for _, raw := range lines {
line := strings.TrimRightFunc(stripControlRunes(raw), unicode.IsSpace)
if strings.TrimSpace(line) == "" {
if len(out) > 0 {
pendingBlank = true
}
continue
}
if isBorderOnlyLine(line) {
continue
}
line = canonicalStatusLine(line)
if len(out) > 0 && out[len(out)-1] == line {
pendingBlank = false
continue
}
if pendingBlank {
out = append(out, "")
pendingBlank = false
}
out = append(out, line)
}
if maxLines > 0 && len(out) > maxLines {
dropped := strings.Join(out[:len(out)-maxLines], "\n")
out = out[len(out)-maxLines:]
return strings.Join(out, "\n"), true, len(dropped)
}
return strings.Join(out, "\n"), false, 0
}
func carriageReturnToLines(s string) string {
var out []string
var current strings.Builder
flush := func() {
out = append(out, current.String())
current.Reset()
}
for len(s) > 0 {
r, size := utf8.DecodeRuneInString(s)
s = s[size:]
switch r {
case '\r':
current.Reset()
case '\n':
flush()
default:
current.WriteRune(r)
}
}
if current.Len() > 0 || len(out) == 0 {
flush()
}
return strings.Join(out, "\n")
}
func stripControlRunes(s string) string {
return strings.Map(func(r rune) rune {
if r == '\t' || r == '\n' {
return r
}
if unicode.IsControl(r) {
return -1
}
return r
}, s)
}
func isBorderOnlyLine(s string) bool {
trimmed := strings.TrimSpace(s)
if trimmed == "" {
return false
}
seenBox := false
for _, r := range trimmed {
if r >= 0x2500 && r <= 0x257f {
seenBox = true
continue
}
switch r {
case ' ', '\t', '-', '_', '=', '+', '|', ':', '.', '\'', '"', '`', '*':
continue
default:
return false
}
}
return seenBox
}
func canonicalStatusLine(s string) string {
if !looksStatusLike(s) {
return s
}
leading := len(s) - len(strings.TrimLeftFunc(s, unicode.IsSpace))
prefix := s[:leading]
body := s[leading:]
body = spinnerGlyphRE.ReplaceAllString(body, "")
body = statusVolatileRE.ReplaceAllString(body, "[time]")
body = counterRE.ReplaceAllString(body, "[count]")
return prefix + strings.TrimRightFunc(body, unicode.IsSpace)
}
func looksStatusLike(s string) bool {
lower := strings.ToLower(s)
for _, token := range []string{
"status", "running", "remaining", "progress", "loading",
"building", "installing", "downloading", "waiting", "working",
} {
if strings.Contains(lower, token) {
return true
}
}
trimmed := strings.TrimSpace(s)
if trimmed == "" {
return false
}
r, _ := utf8.DecodeRuneInString(trimmed)
return strings.ContainsRune("⠁⠂⠄⡀⢀⠠⠐⠈⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏•·∙◐◓◑◒", r)
}
-167
View File
@@ -1,167 +0,0 @@
package app
import (
"strings"
"testing"
"github.com/hjbdev/patterm/internal/mcp"
"github.com/hjbdev/patterm/internal/preset"
)
func TestCanonicalizeTerminalText(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{
name: "ansi osc and controls",
in: "\x1b]0;title\x07\x1b[31mred\x1b[0m\x00\nok",
want: "red\nok",
},
{
name: "noisy harness stream",
in: "\x1b]0;noise\x07\x1b[31mStatus: running 12s\x1b[0m\nStatus: running 13s\n╭────╮\n│ │\nDownloading 10%\rDownloading 100%\nFINAL: deploy ready\n",
want: "Status: running [time]\nDownloading [count]\nFINAL: deploy ready",
},
{
name: "repeated blank collapse",
in: "one\n\n\n two\n \n\t\nthree",
want: "one\n\n two\n\nthree",
},
{
name: "border only box drawing removal",
in: "╭────────╮\n│ │\nimportant\n╰────────╯",
want: "important",
},
{
name: "carriage return progress coalesces final frame",
in: "Downloading 10%\rDownloading 20%\rDownloading 100%\nDone",
want: "Downloading [count]\nDone",
},
{
name: "volatile timer duplicate collapse",
in: "Status: running 12s\nStatus: running 13s\nStatus: running 01:23",
want: "Status: running [time]",
},
{
name: "duplicate status row collapse",
in: "⠋ Building 1/4\n⠙ Building 2/4\n⠹ Building 3/4\nready",
want: "Building [count]\nready",
},
{
name: "preserve meaningful indented code and tables",
in: " if elapsed == 12s {\n return value\n }\n| name | value |\n| a | 1 |",
want: " if elapsed == 12s {\n return value\n }\n| name | value |\n| a | 1 |",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, truncated, _ := canonicalizeTerminalText(tc.in, 120)
if truncated {
t.Fatalf("unexpected truncation")
}
if got != tc.want {
t.Fatalf("got %q want %q", got, tc.want)
}
})
}
}
func TestCanonicalizeTerminalTextMaxLines(t *testing.T) {
got, truncated, dropped := canonicalizeTerminalText("one\ntwo\nthree", 2)
if !truncated {
t.Fatalf("expected truncation")
}
if dropped == 0 {
t.Fatalf("expected dropped bytes")
}
if got != "two\nthree" {
t.Fatalf("got %q", got)
}
}
func TestGetProcessOutputStreamCanonicalByDefault(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
addChild(sess, c)
c.recordWrite([]byte("\x1b[31mStatus: running 12s\x1b[0m\nStatus: running 13s\nresult\n"))
host := newToolHost(sess, nil, nil, nil, preset.Set{}, nil, 80, 24)
out, err := host.GetProcessOutput("", mcp.ProcessOutputArgs{ProcessID: c.ID, Mode: "stream"})
if err != nil {
t.Fatal(err)
}
if !out.Canonicalized {
t.Fatalf("expected canonicalized output")
}
if out.Content != "Status: running [time]\nresult" {
t.Fatalf("content = %q", out.Content)
}
if out.Cursor != nil || out.Rows != 0 || out.Cols != 0 || out.ScreenVersion != 0 || out.IdleMS != 0 {
t.Fatalf("default output should be metadata-light: %#v", out)
}
}
func TestGetProcessOutputRawReturnsStreamBytes(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
addChild(sess, c)
c.recordWrite([]byte("\x1b[31mred\x1b[0m"))
host := newToolHost(sess, nil, nil, nil, preset.Set{}, nil, 80, 24)
out, err := host.GetProcessOutput("", mcp.ProcessOutputArgs{ProcessID: c.ID, Mode: "grid", Raw: true})
if err != nil {
t.Fatal(err)
}
if out.Mode != "stream" {
t.Fatalf("raw grid mode should report stream semantics, got %q", out.Mode)
}
if out.Canonicalized {
t.Fatalf("raw output should not be canonicalized")
}
if out.Content != "\x1b[31mred\x1b[0m" {
t.Fatalf("content = %q", out.Content)
}
if out.NewOffset != int64(len(out.Content)) {
t.Fatalf("new_offset=%d want %d", out.NewOffset, len(out.Content))
}
}
func TestGetProcessOutputCanonicalAfterRawRead(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
addChild(sess, c)
c.recordWrite([]byte("\x1b[31mStatus: running 12s\x1b[0m\nStatus: running 13s\nDownloading 10%\rDownloading 100%\nFINAL: deploy ready\n"))
host := newToolHost(sess, nil, nil, nil, preset.Set{}, nil, 80, 24)
if _, err := host.GetProcessOutput("", mcp.ProcessOutputArgs{ProcessID: c.ID, Mode: "stream", Raw: true}); err != nil {
t.Fatal(err)
}
out, err := host.GetProcessOutput("", mcp.ProcessOutputArgs{ProcessID: c.ID, Mode: "stream", MaxLines: 20})
if err != nil {
t.Fatal(err)
}
if out.Content != "Status: running [time]\nDownloading [count]\nFINAL: deploy ready" {
t.Fatalf("content = %q", out.Content)
}
}
func TestGetProcessOutputIncludeMetaRestoresFields(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
addChild(sess, c)
c.recordWrite([]byte("ok"))
host := newToolHost(sess, nil, nil, nil, preset.Set{}, nil, 80, 24)
out, err := host.GetProcessOutput("", mcp.ProcessOutputArgs{ProcessID: c.ID, Mode: "stream", IncludeMeta: true})
if err != nil {
t.Fatal(err)
}
if out.ScreenVersion == 0 {
t.Fatalf("screen_version missing with include_meta: %#v", out)
}
if !strings.Contains(out.Content, "ok") {
t.Fatalf("content = %q", out.Content)
}
}
+1 -9
View File
@@ -77,7 +77,6 @@ type Child struct {
WorkDir string
Kind ChildKind
ParentID string // empty for top-level sessions
TaskID string // empty unless launched from an explicit task context
// PresetRef names the source preset (when known). Used by trust
// gating to re-check on restart_process. Empty for freeform-argv
@@ -192,7 +191,7 @@ type PortSighting struct {
const ringCap = 1 << 20 // 1 MiB per SPEC §5
// newChildEntry builds the in-memory Child record but does NOT start a PTY.
func newChildEntry(id, name string, kind ChildKind, argv, env []string, parentID, taskID, workDir, presetRef string) *Child {
func newChildEntry(id, name string, kind ChildKind, argv, env []string, parentID, workDir, presetRef string) *Child {
c := &Child{
ID: id,
Name: name,
@@ -201,7 +200,6 @@ func newChildEntry(id, name string, kind ChildKind, argv, env []string, parentID
WorkDir: workDir,
Kind: kind,
ParentID: parentID,
TaskID: taskID,
PresetRef: presetRef,
ring: make([]byte, ringCap),
}
@@ -534,12 +532,6 @@ func (c *Child) StreamRead(since int64) ([]byte, int64) {
return out, end
}
func (c *Child) StreamOffset() int64 {
c.ringMu.Lock()
defer c.ringMu.Unlock()
return c.ringWrites
}
func (c *Child) signal(sig syscall.Signal) error {
pty := c.PTY()
if pty == nil {
+78
View File
@@ -0,0 +1,78 @@
package app
import "github.com/hjbdev/patterm/internal/scratchpad"
// chromeModel is the semantic host chrome state. Renderers continue to own
// ANSI output; this model is the serializable shape a client can draw locally.
type chromeModel struct {
ProjectKey string `json:"project_key"`
FocusedID string `json:"focused_id,omitempty"`
FocusedPad string `json:"focused_pad,omitempty"`
ActiveAgentID string `json:"active_agent_id,omitempty"`
Tabs []childModel `json:"tabs"`
Processes []childModel `json:"processes"`
AgentTree []childModel `json:"agent_tree"`
Sidebar []navEntryModel `json:"sidebar"`
Scratchpads []scratchpadModel `json:"scratchpads"`
}
type childModel struct {
ID string `json:"id"`
Name string `json:"name"`
Kind string `json:"kind"`
ParentID string `json:"parent_id,omitempty"`
Status string `json:"status"`
Owner string `json:"owner"`
}
type navEntryModel struct {
ChildID string `json:"child_id,omitempty"`
Pad string `json:"pad,omitempty"`
}
type scratchpadModel struct {
Name string `json:"name"`
}
func buildChromeModel(projectKey string, view ClientView, children []*Child, pads []scratchpad.Entry) chromeModel {
active := view.ActiveAgentID
if active == "" {
active = activeRootID(children, view.FocusedID)
}
model := chromeModel{
ProjectKey: projectKey,
FocusedID: view.FocusedID,
FocusedPad: view.FocusedPad,
ActiveAgentID: active,
}
for _, c := range runningTopLevels(children) {
model.Tabs = append(model.Tabs, serializeChildModel(c))
}
for _, c := range processList(children) {
model.Processes = append(model.Processes, serializeChildModel(c))
}
for _, c := range visibleAgentTree(children, active) {
model.AgentTree = append(model.AgentTree, serializeChildModel(c))
}
for _, n := range sidebarNav(children, active, pads) {
model.Sidebar = append(model.Sidebar, navEntryModel{ChildID: n.childID, Pad: n.pad})
}
for _, p := range pads {
model.Scratchpads = append(model.Scratchpads, scratchpadModel{Name: p.Name})
}
return model
}
func serializeChildModel(c *Child) childModel {
if c == nil {
return childModel{}
}
return childModel{
ID: c.ID,
Name: c.DisplayName(),
Kind: string(c.Kind),
ParentID: c.ParentID,
Status: string(c.Status()),
Owner: string(c.Owner()),
}
}
+24
View File
@@ -0,0 +1,24 @@
package app
import "testing"
func TestBuildChromeModelSeparatesProcessesTabsAndSidebar(t *testing.T) {
running := StatusRunning
proc := testProcess("p1", "server", running)
agent := testAgent("a1", "codex", "", running)
sub := testAgent("a2", "worker", "a1", running)
model := buildChromeModel("project", ClientView{FocusedID: "p1", ActiveAgentID: "a1"}, []*Child{proc, agent, sub}, nil)
if len(model.Tabs) != 1 || model.Tabs[0].ID != "a1" {
t.Fatalf("tabs = %#v, want only top-level agent", model.Tabs)
}
if len(model.Processes) != 1 || model.Processes[0].ID != "p1" {
t.Fatalf("processes = %#v, want process section", model.Processes)
}
if len(model.AgentTree) != 2 || model.AgentTree[0].ID != "a1" || model.AgentTree[1].ID != "a2" {
t.Fatalf("agent tree = %#v", model.AgentTree)
}
if len(model.Sidebar) != 3 || model.Sidebar[0].ChildID != "p1" || model.Sidebar[1].ChildID != "a1" {
t.Fatalf("sidebar = %#v", model.Sidebar)
}
}
+122
View File
@@ -0,0 +1,122 @@
package app
import (
"encoding/json"
"sync"
"github.com/hjbdev/patterm/internal/protocol"
)
const defaultClientSubscriberQueue = 256
// clientSubscriber is the daemon-to-client event bridge. Unlike daemon-local
// listeners such as timers, debug capture, and waiters, it never blocks the PTY
// pump: PTY chunks are copied before enqueue, and overflow marks the pane as
// needing a fresh snapshot.
type clientSubscriber struct {
projectKey string
frames chan protocol.Frame
mu sync.Mutex
snapshotRequired map[string]bool
lifecycleDirty bool
}
func newClientSubscriber(projectKey string, size int) *clientSubscriber {
if size <= 0 {
size = defaultClientSubscriberQueue
}
return &clientSubscriber{
projectKey: projectKey,
frames: make(chan protocol.Frame, size),
snapshotRequired: make(map[string]bool),
lifecycleDirty: false,
}
}
func (s *clientSubscriber) Recv() (protocol.Frame, bool) {
f, ok := <-s.frames
return f, ok
}
func (s *clientSubscriber) SnapshotRequired(childID string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.snapshotRequired[childID]
}
func (s *clientSubscriber) OnChildSpawned(c *Child) {
s.sendLifecycle(protocol.LifecycleSpawned, c, "")
}
func (s *clientSubscriber) OnChildExited(c *Child) {
s.sendLifecycle(protocol.LifecycleExited, c, "")
}
func (s *clientSubscriber) OnChildClosed(id string) {
s.sendFrame(protocol.Frame{Type: protocol.FrameLifecycle, Payload: mustJSON(protocol.Lifecycle{
Kind: protocol.LifecycleClosed,
ProjectKey: s.projectKey,
ChildID: id,
})})
}
func (s *clientSubscriber) OnChildStateChanged(id string, state IdleState) {
s.sendFrame(protocol.Frame{Type: protocol.FrameLifecycle, Payload: mustJSON(protocol.Lifecycle{
Kind: protocol.LifecycleStateChanged,
ProjectKey: s.projectKey,
ChildID: id,
State: string(state),
})})
}
func (s *clientSubscriber) OnPTYOut(childID string, chunk []byte) {
cp := append([]byte(nil), chunk...)
f, err := protocol.NewFrame(protocol.FramePaneChunk, protocol.PaneChunk{PaneID: childID, Bytes: cp})
if err != nil {
return
}
select {
case s.frames <- f:
default:
s.mu.Lock()
s.snapshotRequired[childID] = true
s.mu.Unlock()
}
}
func (s *clientSubscriber) sendLifecycle(kind protocol.LifecycleKind, c *Child, state string) {
var child json.RawMessage
if c != nil {
child = mustJSON(serializeChildModel(c))
}
childID := ""
if c != nil {
childID = c.ID
}
s.sendFrame(protocol.Frame{Type: protocol.FrameLifecycle, Payload: mustJSON(protocol.Lifecycle{
Kind: kind,
ProjectKey: s.projectKey,
ChildID: childID,
Child: child,
State: state,
})})
}
func (s *clientSubscriber) sendFrame(f protocol.Frame) {
select {
case s.frames <- f:
default:
s.mu.Lock()
s.lifecycleDirty = true
s.mu.Unlock()
}
}
func mustJSON(v any) json.RawMessage {
b, err := json.Marshal(v)
if err != nil {
return nil
}
return b
}
+32
View File
@@ -0,0 +1,32 @@
package app
import (
"testing"
"github.com/hjbdev/patterm/internal/protocol"
)
func TestClientSubscriberCopiesChunksAndMarksSnapshotOnOverflow(t *testing.T) {
sub := newClientSubscriber("project", 1)
chunk := []byte("first")
sub.OnPTYOut("p_123456", chunk)
chunk[0] = 'X'
f, ok := sub.Recv()
if !ok {
t.Fatalf("Recv closed")
}
payload, err := protocol.Decode[protocol.PaneChunk](f)
if err != nil {
t.Fatalf("Decode: %v", err)
}
if string(payload.Bytes) != "first" {
t.Fatalf("payload retained pump buffer: %q", string(payload.Bytes))
}
sub.OnPTYOut("p_123456", []byte("queued"))
sub.OnPTYOut("p_123456", []byte("dropped"))
if !sub.SnapshotRequired("p_123456") {
t.Fatalf("overflow did not mark pane snapshot required")
}
}
+39
View File
@@ -0,0 +1,39 @@
package app
// ClientView is the per-client UI cursor over daemon-owned project/process
// state. In loopback mode there is one view, owned by uiState; future network
// clients will each get their own copy.
type ClientView struct {
ID string
ProjectKey string
FocusedID string
FocusedPad string
ActiveAgentID string
PadOffset int
PadOffsetName string
Cols uint16
Rows uint16
}
func (v *ClientView) FocusChild(id string) {
v.FocusedID = id
v.FocusedPad = ""
}
func (v *ClientView) FocusPad(name string) {
v.FocusedID = ""
v.FocusedPad = name
if v.PadOffsetName != name {
v.PadOffset = 0
v.PadOffsetName = name
}
}
func (v *ClientView) ClearPadFocus() {
v.FocusedPad = ""
}
func (v *ClientView) Resize(cols, rows uint16) {
v.Cols = cols
v.Rows = rows
}
+29
View File
@@ -0,0 +1,29 @@
package app
import (
"github.com/hjbdev/patterm/internal/mcp"
"github.com/hjbdev/patterm/internal/persist"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/scratchpad"
"github.com/hjbdev/patterm/internal/trust"
)
// headlessCore is the daemon-owned half of today's single-process app. It is
// intentionally small for the foundation phase: it groups process/project
// state while the existing loopback client still renders in-process.
type headlessCore struct {
projectDir string
projectKey string
presets preset.Set
settings settings
pads *scratchpad.Store
trustStore *trust.Store
persistStore *persist.Store
mcpSrv *mcp.Server
sess *Session
launcher *Launcher
host *toolHost
}
+63 -328
View File
@@ -2,7 +2,6 @@ package app
import (
"fmt"
"path/filepath"
"regexp"
"strings"
"sync"
@@ -13,7 +12,6 @@ import (
"github.com/hjbdev/patterm/internal/mcp"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/scratchpad"
"github.com/hjbdev/patterm/internal/task"
"github.com/hjbdev/patterm/internal/trust"
pkgvt "github.com/hjbdev/patterm/internal/vt"
)
@@ -43,16 +41,11 @@ type scratchpadSink interface {
scratchpadsChanged()
}
type taskSink interface {
tasksChanged()
}
// toolHost adapts the running session + scratchpad store + trust store
// to the MCP ToolHost interface. SPEC §7 tools route through here.
type toolHost struct {
sess *Session
pads *scratchpad.Store
tasks *task.Store
launcher *Launcher
presets preset.Set
trust *trust.Store
@@ -68,27 +61,14 @@ type toolHost struct {
focus focusSink
prompter trustPrompter
scratch scratchpadSink
taskUI taskSink
timers *timerManager
}
const (
defaultMCPContentBytes = 12_000
maxMCPContentBytes = 65_536
defaultMCPCanonicalLines = 120
maxMCPCanonicalLines = 500
defaultMCPTailBytes = 8_000
defaultScratchpadReadBytes = 12_000
defaultSearchLineBytes = 2_000
maxSearchMatches = 50
)
func newToolHost(sess *Session, pads *scratchpad.Store, tasks *task.Store, launcher *Launcher, presets preset.Set, tr *trust.Store, cols, rows uint16) *toolHost {
func newToolHost(sess *Session, pads *scratchpad.Store, launcher *Launcher, presets preset.Set, tr *trust.Store, cols, rows uint16) *toolHost {
h := &toolHost{
sess: sess,
pads: pads,
tasks: tasks,
launcher: launcher,
presets: presets,
trust: tr,
@@ -166,21 +146,6 @@ func (h *toolHost) CallerRole(processID string) mcp.CallerRole {
return mcp.RoleSubAgent
}
func (h *toolHost) CallerTask(processID string) (mcp.TaskInfo, bool) {
if h == nil || h.sess == nil || h.tasks == nil || processID == "" {
return mcp.TaskInfo{}, false
}
c := h.sess.FindChild(processID)
if c == nil || c.TaskID == "" {
return mcp.TaskInfo{}, false
}
t, ok := h.tasks.Get(c.TaskID)
if !ok {
return mcp.TaskInfo{}, false
}
return taskInfoOf(t), true
}
// ───────────────────────────────────────────────────────────────────
// Lifecycle
// ───────────────────────────────────────────────────────────────────
@@ -200,14 +165,8 @@ func (h *toolHost) SpawnAgent(callerID string, args mcp.SpawnAgentArgs) (mcp.Pro
if display == "" {
display = args.Agent
}
var taskInfo *mcp.TaskInfo
ctx := LaunchContext{ParentID: callerID}
if ti, ok := h.CallerTask(callerID); ok {
ctx.TaskID = ti.ID
taskInfo = &ti
}
prompt := buildAgentPrompt(args.AgentInstructions, h.sess.FindChild(callerID) != nil, taskInfo)
c, err := h.launcher.LaunchAgent(p, display, prompt, ctx)
prompt := wrapSubAgentPrompt(args.AgentInstructions, h.sess.FindChild(callerID) != nil)
c, err := h.launcher.LaunchAgent(p, display, prompt, callerID)
if err != nil {
return mcp.ProcessInfo{}, err
}
@@ -223,12 +182,8 @@ func (h *toolHost) SpawnProcess(callerID string, args mcp.SpawnProcessArgs) (mcp
return mcp.ProcessInfo{}, mcp.Errorf(mcp.ErrorKindInvalidKind, "spawn_process: kind must be 'command' or 'terminal'")
}
env := h.mergeEnv(args.Env)
ctx := LaunchContext{ParentID: callerID, WorkDir: args.WorkingDir}
if ti, ok := h.CallerTask(callerID); ok {
ctx.TaskID = ti.ID
}
if args.Kind == "terminal" {
c, err := h.launcher.LaunchTerminal(args.Argv, h.terminalName(args.Name), ctx, env)
c, err := h.launcher.LaunchTerminal(args.Argv, h.terminalName(args.Name), callerID, args.WorkingDir, env)
if err != nil {
return mcp.ProcessInfo{}, err
}
@@ -249,7 +204,7 @@ func (h *toolHost) SpawnProcess(callerID string, args mcp.SpawnProcessArgs) (mcp
if display == "" {
display = ps.Name
}
c, err := h.launcher.LaunchCommandPreset(ps, display, ctx)
c, err := h.launcher.LaunchCommandPreset(ps, display, callerID)
if err != nil {
return mcp.ProcessInfo{}, err
}
@@ -263,7 +218,7 @@ func (h *toolHost) SpawnProcess(callerID string, args mcp.SpawnProcessArgs) (mcp
if display == "" {
display = args.Argv[0]
}
c, err := h.launcher.LaunchCommandArgv(args.Argv, display, ctx, env, args.Shell)
c, err := h.launcher.LaunchCommandArgv(args.Argv, display, callerID, args.WorkingDir, env, args.Shell)
if err != nil {
return mcp.ProcessInfo{}, err
}
@@ -398,64 +353,39 @@ func (h *toolHost) GetProcessStatus(callerID, processID string) (mcp.ProcessStat
return st, nil
}
func (h *toolHost) GetProjectStatus(callerID string, includeTools bool) (mcp.ProjectStatus, error) {
caller := h.WhoAmI(callerID, includeTools)
func (h *toolHost) GetProjectStatus(callerID string) (mcp.ProjectStatus, error) {
caller := h.WhoAmI(callerID)
processes := h.ListProcesses(callerID, "")
pads, _ := h.pads.List()
status := mcp.ProjectStatus{
return mcp.ProjectStatus{
Project: caller.Project,
Caller: caller,
Processes: processes,
Scratchpads: pads,
}
if caller.Task != nil {
status.Task = caller.Task
}
return status, nil
}, nil
}
func (h *toolHost) GetProcessOutput(callerID string, args mcp.ProcessOutputArgs) (mcp.ProcessOutput, error) {
processID, mode, sinceOffset := args.ProcessID, args.Mode, args.SinceOffset
func (h *toolHost) GetProcessOutput(callerID, processID, mode string, sinceOffset int64) (mcp.ProcessOutput, error) {
c := h.sess.FindChild(processID)
if c == nil {
return mcp.ProcessOutput{}, mcp.Errorf(mcp.ErrorKindNotFound, "no such process %q", processID)
}
if mode == "" {
mode = "grid"
}
if args.Raw {
b, end := c.StreamRead(sinceOffset)
content, contentBytes, truncated, truncatedBytes := capBytesTail(b, capLimit(args.MaxBytes, defaultMCPContentBytes))
return mcp.ProcessOutput{
Content: content,
Mode: "stream",
NewOffset: end,
Status: string(c.Status()),
ContentBytes: contentBytes,
Truncated: truncated,
TruncatedBytes: truncatedBytes,
}, nil
}
out := mcp.ProcessOutput{
Mode: mode,
IdleMS: c.IdleMS(),
Status: string(c.Status()),
Canonicalized: true,
ScreenVersion: c.ScreenVersion(),
}
if args.IncludeMeta {
out.IdleMS = c.IdleMS()
out.ScreenVersion = c.ScreenVersion()
if em := c.Emulator(); em != nil {
if sc, err := em.ActiveScreen(); err == nil {
out.ActiveScreen = activeScreenName(sc)
}
if cur, err := em.Cursor(); err == nil {
out.Cursor = &mcp.Cursor{X: int(cur.Col), Y: int(cur.Row)}
}
cols, rows := em.Size()
out.Cols, out.Rows = int(cols), int(rows)
if em := c.Emulator(); em != nil {
if sc, err := em.ActiveScreen(); err == nil {
out.ActiveScreen = activeScreenName(sc)
}
if cur, err := em.Cursor(); err == nil {
out.Cursor = mcp.Cursor{X: int(cur.Col), Y: int(cur.Row)}
}
cols, rows := em.Size()
out.Cols, out.Rows = int(cols), int(rows)
}
maxLines := canonicalLineLimit(args.MaxLines)
switch mode {
case "grid":
em := c.Emulator()
@@ -469,21 +399,11 @@ func (h *toolHost) GetProcessOutput(callerID string, args mcp.ProcessOutputArgs)
if c.Kind == KindAgent {
txt = applyChromeTrim(txt, h.chromeHintsFor(c.PresetRef))
}
content, lineTruncated, lineDroppedBytes := canonicalizeTerminalText(txt, maxLines)
out.Content, out.ContentBytes, out.Truncated, out.TruncatedBytes = capTextMiddle(content, capLimit(args.MaxBytes, defaultMCPContentBytes))
if lineTruncated {
out.Truncated = true
out.TruncatedBytes += lineDroppedBytes
}
out.Content = normalizeGridText(txt)
return out, nil
case "stream":
b, end := c.StreamRead(sinceOffset)
content, lineTruncated, lineDroppedBytes := canonicalizeTerminalText(string(b), maxLines)
out.Content, out.ContentBytes, out.Truncated, out.TruncatedBytes = capTextTail(content, capLimit(args.MaxBytes, defaultMCPContentBytes))
if lineTruncated {
out.Truncated = true
out.TruncatedBytes += lineDroppedBytes
}
out.Content = string(stripANSIBytes(nil, b))
out.NewOffset = end
return out, nil
default:
@@ -491,46 +411,34 @@ func (h *toolHost) GetProcessOutput(callerID string, args mcp.ProcessOutputArgs)
}
}
func (h *toolHost) GetProcessRawOutput(callerID string, args mcp.RawOutputArgs) (mcp.RawOutput, error) {
c := h.sess.FindChild(args.ProcessID)
func (h *toolHost) GetProcessRawOutput(callerID, processID string, sinceOffset int64) (mcp.RawOutput, error) {
c := h.sess.FindChild(processID)
if c == nil {
return mcp.RawOutput{}, mcp.Errorf(mcp.ErrorKindNotFound, "no such process %q", args.ProcessID)
return mcp.RawOutput{}, mcp.Errorf(mcp.ErrorKindNotFound, "no such process %q", processID)
}
b, end := c.StreamRead(args.SinceOffset)
content, contentBytes, truncated, truncatedBytes := capBytesTail(b, capLimit(args.MaxBytes, defaultMCPContentBytes))
b, end := c.StreamRead(sinceOffset)
return mcp.RawOutput{
Content: content,
NewOffset: end,
Status: string(c.Status()),
ContentBytes: contentBytes,
Truncated: truncated,
TruncatedBytes: truncatedBytes,
Content: string(b),
NewOffset: end,
Status: string(c.Status()),
}, nil
}
func (h *toolHost) SearchOutput(callerID string, args mcp.SearchOutputArgs) (mcp.SearchResult, error) {
c := h.sess.FindChild(args.ProcessID)
func (h *toolHost) SearchOutput(callerID, processID, pattern, kind string, limit int) (mcp.SearchResult, error) {
c := h.sess.FindChild(processID)
if c == nil {
return mcp.SearchResult{}, mcp.Errorf(mcp.ErrorKindNotFound, "no such process %q", args.ProcessID)
return mcp.SearchResult{}, mcp.Errorf(mcp.ErrorKindNotFound, "no such process %q", processID)
}
re, err := regexp.Compile(args.Pattern)
re, err := regexp.Compile(pattern)
if err != nil {
return mcp.SearchResult{}, mcp.Errorf(mcp.ErrorKindInvalidArgs, "regex: %v", err)
}
b, _ := c.StreamRead(0)
if args.Kind == "rendered" {
if kind == "rendered" {
b = stripANSIBytes(nil, b)
}
text := string(b)
lines := strings.Split(text, "\n")
limit := args.Limit
if limit <= 0 {
limit = 10
}
if limit > maxSearchMatches {
limit = maxSearchMatches
}
lineLimit := capLimit(args.MaxBytes, defaultSearchLineBytes)
matches := make([]mcp.SearchMatch, 0, limit)
truncated := false
for i, line := range lines {
@@ -539,8 +447,6 @@ func (h *toolHost) SearchOutput(callerID string, args mcp.SearchOutputArgs) (mcp
truncated = true
break
}
line, _, lineTruncated, _ := capTextTail(line, lineLimit)
truncated = truncated || lineTruncated
matches = append(matches, mcp.SearchMatch{LineNo: i + 1, Text: line})
}
}
@@ -682,7 +588,6 @@ func (h *toolHost) SendInput(callerID string, args mcp.SendInputArgs) (mcp.SendI
if err != nil {
return mcp.SendInputResult{}, err
}
tailSince := c.StreamOffset()
if err := c.InjectAsOrchestrator(payload); err != nil {
return mcp.SendInputResult{}, err
}
@@ -694,12 +599,7 @@ func (h *toolHost) SendInput(callerID string, args mcp.SendInputArgs) (mcp.SendI
}
if mode != "none" {
time.Sleep(time.Duration(args.WaitMS) * time.Millisecond)
tail, err := h.GetProcessOutput(callerID, mcp.ProcessOutputArgs{
ProcessID: args.ProcessID,
Mode: mode,
SinceOffset: tailSince,
MaxBytes: capLimit(args.TailMaxBytes, defaultMCPTailBytes),
})
tail, err := h.GetProcessOutput(callerID, args.ProcessID, mode, 0)
if err == nil {
res.Tail = &tail
}
@@ -913,30 +813,8 @@ func (h *toolHost) TimerList(callerID string) ([]mcp.TimerInfo, error) {
func (h *toolHost) ScratchpadList() ([]scratchpad.Entry, error) { return h.pads.List() }
func (h *toolHost) ScratchpadRead(args mcp.ScratchpadReadArgs) (mcp.ScratchpadReadResult, error) {
content, rev, err := h.pads.Read(args.Name)
if err != nil {
return mcp.ScratchpadReadResult{}, err
}
offset := args.Offset
if offset < 0 {
offset = 0
}
if offset > len(content) {
offset = len(content)
}
limited, contentBytes, truncated, truncatedBytes := capTextHead(content[offset:], capLimit(args.MaxBytes, defaultScratchpadReadBytes))
next := offset + contentBytes
return mcp.ScratchpadReadResult{
Content: limited,
Revision: rev,
Offset: offset,
NextOffset: next,
ContentBytes: contentBytes,
TotalBytes: len(content),
Truncated: truncated,
TruncatedBytes: truncatedBytes,
}, nil
func (h *toolHost) ScratchpadRead(name string) (string, string, error) {
return h.pads.Read(name)
}
func (h *toolHost) ScratchpadWrite(name, content, expectedRevision string) (string, error) {
@@ -963,59 +841,15 @@ func (h *toolHost) ScratchpadDelete(name string) error {
return err
}
func (h *toolHost) RegisterTaskWorktree(callerID string, args mcp.TaskRegisterWorktreeArgs) (mcp.TaskInfo, error) {
current, ok := h.CallerTask(callerID)
if !ok {
return mcp.TaskInfo{}, mcp.Errorf(mcp.ErrorKindRoleForbidden, "task_register_worktree: caller is not attached to a task")
}
if h.tasks == nil {
return mcp.TaskInfo{}, mcp.Errorf(mcp.ErrorKindNotFound, "task_register_worktree: task store unavailable")
}
path := strings.TrimSpace(args.Path)
if path == "" {
return mcp.TaskInfo{}, mcp.Errorf(mcp.ErrorKindInvalidArgs, "task_register_worktree: path required")
}
if !filepath.IsAbs(path) {
base := h.sess.projectDir
if c := h.sess.FindChild(callerID); c != nil && c.WorkDir != "" {
base = c.WorkDir
}
path = filepath.Join(base, path)
}
abs, err := filepath.Abs(path)
if err != nil {
return mcp.TaskInfo{}, err
}
updated, err := h.tasks.RegisterWorktree(current.ID, task.Worktree{
Path: abs,
Branch: args.Branch,
CreatedByProcessID: callerID,
})
if err != nil {
return mcp.TaskInfo{}, err
}
if h.taskUI != nil {
h.taskUI.tasksChanged()
}
return taskInfoOf(updated), nil
}
func (h *toolHost) WhoAmI(callerID string, includeTools bool) mcp.WhoAmI {
role := h.CallerRole(callerID)
taskInfo, taskBound := h.CallerTask(callerID)
func (h *toolHost) WhoAmI(callerID string) mcp.WhoAmI {
w := mcp.WhoAmI{
ProcessID: callerID,
Role: role,
Role: h.CallerRole(callerID),
Project: mcp.ProjectMeta{
Path: h.sess.projectDir,
Key: h.sess.projectKey,
},
}
if taskBound {
w.Task = &taskInfo
}
if includeTools {
w.AvailableTools = availableToolsForRole(role, taskBound)
AvailableTools: availableToolsForRole(h.CallerRole(callerID)),
}
if c := h.sess.FindChild(callerID); c != nil {
w.Name = c.DisplayName()
@@ -1056,27 +890,6 @@ func (h *toolHost) processInfoOf(c *Child) mcp.ProcessInfo {
return info
}
func taskInfoOf(t task.Task) mcp.TaskInfo {
out := mcp.TaskInfo{
ID: t.ID,
Title: t.Title,
CreatedAt: t.CreatedAt,
UpdatedAt: t.UpdatedAt,
}
if len(t.Worktrees) > 0 {
out.Worktrees = make([]mcp.TaskWorktree, 0, len(t.Worktrees))
for _, wt := range t.Worktrees {
out.Worktrees = append(out.Worktrees, mcp.TaskWorktree{
Path: wt.Path,
Branch: wt.Branch,
CreatedByProcessID: wt.CreatedByProcessID,
RegisteredAt: wt.RegisteredAt,
})
}
}
return out
}
func (h *toolHost) chromeHintsFor(presetName string) []string {
if presetName == "" {
return nil
@@ -1135,25 +948,23 @@ func (h *toolHost) askForTrust(callerID, presetName, reason string) {
h.prompter.promptTrust(callerID, presetName, reason)
}
// buildAgentPrompt prepends one-line orientation blocks to the initial
// prompt. The blocks are single-line on purpose: writeInput splits on
// CR/LF, so any embedded newline would submit prematurely.
func buildAgentPrompt(instructions string, hasParent bool, taskInfo *mcp.TaskInfo) string {
var parts []string
if hasParent && (instructions != "" || taskInfo != nil) {
parts = append(parts, "[system: you are a patterm sub-agent. When your work is done, call send_message to your parent (use whoami to get parent_process_id) with a summary, and close_process / scratchpad cleanup anything you created. See help('conventions').]")
// wrapSubAgentPrompt prepends a one-line orientation block to the
// caller-supplied agent_instructions. patterm injects nothing on its
// own (SPEC §7), but vendor TUIs that learn their role purely from
// their first turn need to be told they're a sub-agent — otherwise
// they finish without reporting back to the parent or cleaning up
// processes/scratchpads they spawned. The block is single-line on
// purpose: writeInput splits on CR/LF, so any embedded newline would
// submit prematurely.
func wrapSubAgentPrompt(instructions string, hasParent bool) string {
if !hasParent {
return instructions
}
if taskInfo != nil {
parts = append(parts, fmt.Sprintf("[system: you are working on patterm task %q (%s). If you create or use git worktrees for this task, call task_register_worktree with the path and branch.]", sanitizePromptText(taskInfo.Title), sanitizePromptText(taskInfo.ID)))
if instructions == "" {
return ""
}
if instructions != "" {
parts = append(parts, instructions)
}
return strings.Join(parts, " ")
}
func sanitizePromptText(s string) string {
return strings.NewReplacer("\r", " ", "\n", " ", `"`, "'").Replace(s)
const preface = "[system: you are a patterm sub-agent. When your work is done, call send_message to your parent (use whoami to get parent_process_id) with a summary, and close_process / scratchpad cleanup anything you created. See help('conventions').] "
return preface + instructions
}
// applyChromeTrim deletes lines matching any of the given regexes.
@@ -1198,10 +1009,11 @@ func activeScreenName(s pkgvt.Screen) string {
}
}
// ansiRegexp strips CSI/OSC escape sequences and common single-character
// controls from the stream. The vt emulator already handles full
// rendering for grid mode; this is only for stream-mode text output.
var ansiRegexp = regexp.MustCompile(`\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\x40-\x5f]|\x07`)
// ansiRegexp strips CSI escape sequences and common single-character
// controls (BEL, OSC terminators) from the stream. The vt emulator
// already handles full rendering for grid mode; this is only for
// stream-mode ANSI-stripped output.
var ansiRegexp = regexp.MustCompile(`\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\x40-\x5f]|\x07`)
func stripANSI(s string) string {
return ansiRegexp.ReplaceAllString(s, "")
@@ -1231,68 +1043,12 @@ func normalizeGridText(s string) string {
return strings.Join(out, "\n")
}
func capLimit(requested, def int) int {
if requested <= 0 {
requested = def
}
if requested > maxMCPContentBytes {
requested = maxMCPContentBytes
}
if requested < 0 {
return 0
}
return requested
}
func canonicalLineLimit(requested int) int {
if requested <= 0 {
return defaultMCPCanonicalLines
}
if requested > maxMCPCanonicalLines {
return maxMCPCanonicalLines
}
return requested
}
func capBytesTail(b []byte, limit int) (string, int, bool, int) {
if limit <= 0 || len(b) <= limit {
return string(b), len(b), false, 0
}
dropped := len(b) - limit
return string(b[dropped:]), limit, true, dropped
}
func capTextTail(s string, limit int) (string, int, bool, int) {
return capBytesTail([]byte(s), limit)
}
func capTextHead(s string, limit int) (string, int, bool, int) {
if limit <= 0 || len(s) <= limit {
return s, len(s), false, 0
}
return s[:limit], limit, true, len(s) - limit
}
func capTextMiddle(s string, limit int) (string, int, bool, int) {
if limit <= 0 || len(s) <= limit {
return s, len(s), false, 0
}
const marker = "\n...[truncated]...\n"
if limit <= len(marker)+2 {
return s[len(s)-limit:], limit, true, len(s) - limit
}
head := (limit - len(marker)) / 2
tail := limit - len(marker) - head
return s[:head] + marker + s[len(s)-tail:], limit, true, len(s) - limit
}
// stripANSIBytes is the byte-slice form of stripANSI. Skips the
// string conversion and the regex DFA — useful when the caller will
// itself walk the result line-by-line (SearchOutput) or feed it to a
// pattern match (WaitForPattern scrollback). Recognises the same
// shapes the regex did:
// - `\x1b[ <params> <intermediate> <final-byte>` (CSI / SGR)
// - `\x1b] ... (BEL|ST)` (OSC)
// - `\x1b<final-byte>` for `@..._` (one-byte escapes)
// - `\x07` (BEL)
//
@@ -1322,24 +1078,6 @@ func stripANSIBytes(dst, src []byte) []byte {
continue
}
next := src[i+1]
if next == ']' {
j := i + 2
for j < len(src) {
if src[j] == 0x07 {
i = j + 1
break
}
if src[j] == 0x1b && j+1 < len(src) && src[j+1] == '\\' {
i = j + 2
break
}
j++
}
if j >= len(src) {
i = len(src)
}
continue
}
if next != '[' {
// One-byte ESC sequence (`\x1b<final>` where final is
// `@..._` per the regex; we drop anything that follows).
@@ -1376,7 +1114,7 @@ func stripANSIBytes(dst, src []byte) []byte {
// availableToolsForRole — SPEC §7 whoami exposes the list a caller can
// invoke from its current role. Sub-agents lose `spawn_agent` (§8
// two-level-tree rule).
func availableToolsForRole(role mcp.CallerRole, taskBound bool) []string {
func availableToolsForRole(role mcp.CallerRole) []string {
tools := []string{
"spawn_process", "start_process", "restart_process", "stop_process",
"close_process", "rename_process", "select_process",
@@ -1392,9 +1130,6 @@ func availableToolsForRole(role mcp.CallerRole, taskBound bool) []string {
if role == mcp.RoleOrchestrator {
tools = append([]string{"spawn_agent"}, tools...)
}
if taskBound {
tools = append(tools, "task_register_worktree")
}
return tools
}
@@ -1425,7 +1160,7 @@ func helpFor(topic string) mcp.HelpResponse {
case "inspection":
return mcp.HelpResponse{
Topic: "inspection",
Content: "get_process_output gives you canonical terminal text by default: the visible pane (grid mode) or recent stream text from since_offset (stream mode), with ANSI/control noise, borders, duplicate status churn, and volatile timers removed. Use raw:true only when you need diagnostic PTY bytes; include_meta:true restores cursor, geometry, and screen-version fields. list_processes is for the whole session. get_project_status batches everything you need to orient yourself.",
Content: "get_process_output gives you the visible pane (grid mode) or a byte slice from since_offset (stream mode). list_processes is for the whole session. get_project_status batches everything you need to orient yourself.",
RelatedTools: []string{"list_processes", "get_process_status", "get_process_output", "search_output", "wait_for_pattern", "get_project_status"},
}
case "io":
+7 -136
View File
@@ -1,14 +1,10 @@
package app
import (
"path/filepath"
"strings"
"testing"
"github.com/hjbdev/patterm/internal/mcp"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/scratchpad"
taskstore "github.com/hjbdev/patterm/internal/task"
)
// mkChild builds a Child without starting a PTY. Use sparingly — the
@@ -103,8 +99,8 @@ func TestClassifySendMessageNilCallerRejectsNonTopLevelTarget(t *testing.T) {
}
}
func TestBuildAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
out := buildAgentPrompt("ship feature X", true, nil)
func TestWrapSubAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
out := wrapSubAgentPrompt("ship feature X", true)
if !strings.HasPrefix(out, "[system:") {
t.Fatalf("expected prepended [system: …] block, got %q", out)
}
@@ -122,58 +118,22 @@ func TestBuildAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
}
}
func TestBuildAgentPromptPassthroughWhenNoParent(t *testing.T) {
out := buildAgentPrompt("hello", false, nil)
func TestWrapSubAgentPromptPassthroughWhenNoParent(t *testing.T) {
out := wrapSubAgentPrompt("hello", false)
if out != "hello" {
t.Fatalf("expected passthrough for top-level spawn, got %q", out)
}
}
func TestBuildAgentPromptEmptyStaysEmpty(t *testing.T) {
func TestWrapSubAgentPromptEmptyStaysEmpty(t *testing.T) {
// Empty instructions mean "no inject" upstream; we must not synthesize
// content here or LaunchAgent would type the system block into an
// otherwise-idle agent.
if out := buildAgentPrompt("", true, nil); out != "" {
if out := wrapSubAgentPrompt("", true); out != "" {
t.Fatalf("empty instructions should stay empty, got %q", out)
}
}
func TestMCPContentCapsPreferRecentStreamBytes(t *testing.T) {
got, gotBytes, truncated, dropped := capBytesTail([]byte("abcdefghijklmnop"), 6)
if got != "klmnop" || gotBytes != 6 || !truncated || dropped != 10 {
t.Fatalf("capBytesTail = (%q, %d, %v, %d)", got, gotBytes, truncated, dropped)
}
}
func TestMCPGridCapKeepsHeadAndTail(t *testing.T) {
got, gotBytes, truncated, dropped := capTextMiddle("abcdefghijklmnopqrstuvwxyz", 24)
if gotBytes != 24 || !truncated || dropped != 2 {
t.Fatalf("capTextMiddle metadata = (%d, %v, %d), content %q", gotBytes, truncated, dropped, got)
}
if !strings.Contains(got, "...[truncated]...") {
t.Fatalf("capTextMiddle missing marker: %q", got)
}
}
func TestScratchpadReadPagesLargeContent(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
store, err := scratchpad.Open("test-project")
if err != nil {
t.Fatalf("scratchpad open: %v", err)
}
if _, err := store.Write("notes.md", "abcdefghijklmnopqrstuvwxyz", ""); err != nil {
t.Fatalf("scratchpad write: %v", err)
}
h := &toolHost{pads: store}
res, err := h.ScratchpadRead(mcp.ScratchpadReadArgs{Name: "notes.md", Offset: 5, MaxBytes: 7})
if err != nil {
t.Fatalf("ScratchpadRead: %v", err)
}
if res.Content != "fghijkl" || !res.Truncated || res.NextOffset != 12 || res.TotalBytes != 26 {
t.Fatalf("ScratchpadRead result = %+v", res)
}
}
func TestHelpLifecycleTopicCoversCleanup(t *testing.T) {
resp := helpFor("lifecycle")
if resp.Topic != "lifecycle" {
@@ -218,7 +178,7 @@ func TestAvailableToolsAdvertisesAllTimerTools(t *testing.T) {
"timer_cancel", "timer_pause", "timer_resume", "timer_list",
}
for _, role := range []mcp.CallerRole{mcp.RoleOrchestrator, mcp.RoleSubAgent} {
tools := availableToolsForRole(role, false)
tools := availableToolsForRole(role)
for _, w := range want {
if !containsString(tools, w) {
t.Fatalf("role %q missing %q in available tools: %v", role, w, tools)
@@ -227,95 +187,6 @@ func TestAvailableToolsAdvertisesAllTimerTools(t *testing.T) {
}
}
func TestWhoAmITaskContextIsConditional(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
tasks, err := taskstore.Open("projkey")
if err != nil {
t.Fatalf("task open: %v", err)
}
task, err := tasks.Create("Fix sidebar")
if err != nil {
t.Fatalf("task create: %v", err)
}
sess := NewSession(t.TempDir(), "projkey")
unbound := newChildEntry("p_unbound", "agent", KindAgent, []string{"sh"}, nil, "", "", "", "")
bound := newChildEntry("p_bound", "agent", KindAgent, []string{"sh"}, nil, "", task.ID, "", "")
addTestChild(sess, unbound)
addTestChild(sess, bound)
h := newToolHost(sess, nil, tasks, nil, preset.Set{}, nil, 80, 24)
if got := h.WhoAmI(unbound.ID, true); got.Task != nil || containsString(got.AvailableTools, "task_register_worktree") {
t.Fatalf("unbound whoami leaked task context/tools: %+v", got)
}
got := h.WhoAmI(bound.ID, true)
if got.Task == nil || got.Task.ID != task.ID || got.Task.Title != task.Title {
t.Fatalf("bound whoami missing task: %+v", got)
}
if !containsString(got.AvailableTools, "task_register_worktree") {
t.Fatalf("bound whoami missing task_register_worktree: %+v", got.AvailableTools)
}
}
func TestRegisterTaskWorktreeResolvesAgainstCallerWorkDir(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
tasks, err := taskstore.Open("projkey")
if err != nil {
t.Fatalf("task open: %v", err)
}
task, err := tasks.Create("Fix sidebar")
if err != nil {
t.Fatalf("task create: %v", err)
}
workDir := t.TempDir()
sess := NewSession(t.TempDir(), "projkey")
caller := newChildEntry("p_bound", "agent", KindAgent, []string{"sh"}, nil, "", task.ID, workDir, "")
addTestChild(sess, caller)
h := newToolHost(sess, nil, tasks, nil, preset.Set{}, nil, 80, 24)
info, err := h.RegisterTaskWorktree(caller.ID, mcp.TaskRegisterWorktreeArgs{Path: "../worktree", Branch: "task-branch"})
if err != nil {
t.Fatalf("register: %v", err)
}
wantPath := filepath.Clean(filepath.Join(workDir, "../worktree"))
if len(info.Worktrees) != 1 || info.Worktrees[0].Path != wantPath || info.Worktrees[0].Branch != "task-branch" || info.Worktrees[0].CreatedByProcessID != caller.ID {
t.Fatalf("registered worktree = %+v, want path %q branch/task", info.Worktrees, wantPath)
}
}
func TestSpawnProcessInheritsCallerTask(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
tasks, err := taskstore.Open("projkey")
if err != nil {
t.Fatalf("task open: %v", err)
}
task, err := tasks.Create("Fix sidebar")
if err != nil {
t.Fatalf("task create: %v", err)
}
sess := NewSession(t.TempDir(), "projkey")
defer sess.Shutdown()
caller := newChildEntry("p_bound", "agent", KindAgent, []string{"sh"}, nil, "", task.ID, "", "")
addTestChild(sess, caller)
launcher := NewLauncher(sess, "", 80, 24)
h := newToolHost(sess, nil, tasks, launcher, preset.Set{}, nil, 80, 24)
info, err := h.SpawnProcess(caller.ID, mcp.SpawnProcessArgs{Argv: []string{"sh", "-lc", "exit 0"}})
if err != nil {
t.Fatalf("spawn process: %v", err)
}
spawned := sess.FindChild(info.ID)
if spawned == nil || spawned.TaskID != task.ID {
t.Fatalf("spawned child task = %+v, want %q", spawned, task.ID)
}
}
func addTestChild(sess *Session, c *Child) {
sess.mu.Lock()
defer sess.mu.Unlock()
sess.children[c.ID] = c
sess.order = append(sess.order, c.ID)
}
// TestHelpTimersDocumentsAllTools mirrors the whoami check for the
// help("timers") topic — the related-tools list must enumerate every
// timer_* tool so callers reading help can dispatch them.
+13 -33
View File
@@ -24,12 +24,6 @@ type Launcher struct {
cols, rows uint16
}
type LaunchContext struct {
ParentID string
TaskID string
WorkDir string
}
func NewLauncher(sess *Session, mcpSocket string, cols, rows uint16) *Launcher {
bin, err := os.Executable()
if err != nil {
@@ -53,7 +47,7 @@ func (l *Launcher) size() (uint16, uint16) {
// LaunchAgent spawns the agent preset, applies the preset's MCP
// injection, waits for the ready signal, and types initial_prompt into
// the PTY. SPEC §7 spawn_agent, §8 conversation protocol.
func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt string, ctx LaunchContext) (*Child, error) {
func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt, parentID string) (*Child, error) {
if p.Kind != preset.KindAgent {
return nil, fmt.Errorf("launch: %q is not an agent preset", p.Name)
}
@@ -137,9 +131,7 @@ func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt stri
Argv: argv,
Env: env,
Name: displayName,
ParentID: ctx.ParentID,
TaskID: ctx.TaskID,
WorkDir: firstNonEmpty(ctx.WorkDir, p.WorkingDir),
ParentID: parentID,
PresetRef: p.Name,
Identity: identity,
CleanupPaths: cleanupPaths,
@@ -171,7 +163,7 @@ func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt stri
// LaunchCommandPreset spawns a process preset as a SPEC §7 command
// entry. No MCP injection; just argv. The entry is session-persistent
// (survives PTY exit so it can be Restart'd).
func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName string, ctx LaunchContext) (*Child, error) {
func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName, parentID string) (*Child, error) {
if p.Kind != preset.KindCommand {
return nil, fmt.Errorf("launch: %q is not a command preset", p.Name)
}
@@ -185,9 +177,8 @@ func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName string, ctx
Argv: p.ResolvedArgv(),
Env: env,
Name: displayName,
ParentID: ctx.ParentID,
TaskID: ctx.TaskID,
WorkDir: firstNonEmpty(ctx.WorkDir, p.WorkingDir),
ParentID: parentID,
WorkDir: p.WorkingDir,
PresetRef: p.Name,
IdleDetection: resolveIdleDetection(p.IdleDetection),
}, cols, rows)
@@ -200,7 +191,7 @@ func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName string, ctx
// LaunchCommandArgv spawns a freeform-argv command entry. Trust gating
// (SPEC §7) lives one level up in toolHost — by the time we get here
// trust is settled (freeform argv is implicitly trusted).
func (l *Launcher) LaunchCommandArgv(argv []string, displayName string, ctx LaunchContext, env []string, shell bool) (*Child, error) {
func (l *Launcher) LaunchCommandArgv(argv []string, displayName, parentID, workDir string, env []string, shell bool) (*Child, error) {
if shell && len(argv) > 0 {
argv = []string{"sh", "-lc", strings.Join(argv, " ")}
}
@@ -213,9 +204,8 @@ func (l *Launcher) LaunchCommandArgv(argv []string, displayName string, ctx Laun
Argv: argv,
Env: env,
Name: displayName,
ParentID: ctx.ParentID,
TaskID: ctx.TaskID,
WorkDir: ctx.WorkDir,
ParentID: parentID,
WorkDir: workDir,
}, cols, rows)
}
@@ -233,7 +223,7 @@ func (l *Launcher) RestoreCommand(e persist.Entry, presets preset.Set) (*Child,
if e.PresetRef != "" {
for _, p := range presets.Processes {
if p.Name == e.PresetRef {
return l.LaunchCommandPreset(p, e.Name, LaunchContext{})
return l.LaunchCommandPreset(p, e.Name, "")
}
}
// Preset has been deleted since the entry was saved. Fall
@@ -243,12 +233,12 @@ func (l *Launcher) RestoreCommand(e persist.Entry, presets preset.Set) (*Child,
if len(e.Argv) == 0 {
return nil, fmt.Errorf("restore: entry %s has no argv", e.ID)
}
return l.LaunchCommandArgv(e.Argv, e.Name, LaunchContext{WorkDir: e.WorkDir}, nil, false)
return l.LaunchCommandArgv(e.Argv, e.Name, "", e.WorkDir, nil, false)
}
// LaunchTerminal spawns a bare interactive shell. SPEC §7 kind=terminal.
// argv defaults to $SHELL -i when empty.
func (l *Launcher) LaunchTerminal(argv []string, displayName string, ctx LaunchContext, env []string) (*Child, error) {
func (l *Launcher) LaunchTerminal(argv []string, displayName, parentID, workDir string, env []string) (*Child, error) {
if len(argv) == 0 {
sh := os.Getenv("SHELL")
if sh == "" {
@@ -265,21 +255,11 @@ func (l *Launcher) LaunchTerminal(argv []string, displayName string, ctx LaunchC
Argv: argv,
Env: env,
Name: displayName,
ParentID: ctx.ParentID,
TaskID: ctx.TaskID,
WorkDir: ctx.WorkDir,
ParentID: parentID,
WorkDir: workDir,
}, cols, rows)
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if v != "" {
return v
}
}
return ""
}
func (l *Launcher) writeMCPConfig(identity string) (string, error) {
dir, err := mcpRuntimeDir(identity)
if err != nil {
+1 -1
View File
@@ -50,7 +50,7 @@ func TestSpawnSizingUsesViewportDimensions(t *testing.T) {
t.Fatalf("launcher size: got %dx%d want 91x36", cols, rows)
}
host := newToolHost(nil, nil, nil, nil, preset.Set{}, nil, l.childCols(), l.childRows())
host := newToolHost(nil, nil, nil, preset.Set{}, nil, l.childCols(), l.childRows())
cols, rows = host.size()
if cols != 91 || rows != 36 {
t.Fatalf("tool host size: got %dx%d want 91x36", cols, rows)
+17 -118
View File
@@ -7,7 +7,6 @@ import (
"unicode/utf8"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/task"
)
// paletteAction is what the palette returns when the user picks an item.
@@ -36,10 +35,7 @@ type paletteAction struct {
// For pad-* actions, the scratchpad name to operate on.
padName string
// For task-* actions, the task to operate on.
taskID string
// For *-rename-submit and task-create-submit actions, the user-typed name.
// For *-rename-submit actions, the user-typed new name.
newName string
// For settings actions, the updated settings snapshot to persist.
@@ -94,12 +90,12 @@ type spawnProcessForm struct {
// renameForm is a one-field inline form used by the "Rename scratchpad /
// agent / process" context palette entries. The submit action kind
// determines what gets renamed; the target name (pad name, task id, or child id)
// determines what gets renamed; the target name (pad name or child id)
// is carried alongside so closePalette knows what to apply the new
// name to.
type renameForm struct {
name []rune
subject string // "pad" | "task" | "task-create" | "agent" | "proc"
subject string // "pad" | "agent" | "proc"
target string // padName for "pad"; childID for "agent"/"proc"
title string // e.g. "Rename"
subjectLine string // e.g. "scratchpad: notes.md" rendered above the input
@@ -114,16 +110,13 @@ type settingsInputForm struct {
// paletteState is the in-memory model for the overlay. SPEC §4: a
// single fuzzy-searchable list of commands scoped to the current focus.
type paletteState struct {
query []rune
cursor int
children []*Child
focused string
focusedPad string
focusedTaskID string
tasksEnabled bool
tasks []task.Task
presets preset.Set
settings settings
query []rune
cursor int
children []*Child
focused string
focusedPad string
presets preset.Set
settings settings
items []paletteItem
@@ -142,9 +135,9 @@ type paletteState struct {
// macro is active. Typing `sw <query>` filters to switch entries only,
// `k <query>` to close entries, `sp <query>` to spawn entries.
var macroPrefixes = map[string][]string{
"sw": {"switch", "task-switch"},
"sw": {"switch"},
"k": {"kill", "agent-close", "proc-stop", "proc-delete"},
"sp": {"spawn-agent", "spawn-process", "spawn-terminal", "spawn-process-form", "task-start-agent"},
"sp": {"spawn-agent", "spawn-process", "spawn-terminal", "spawn-process-form"},
}
// chipOrder is the cycle order for Tab / Shift-Tab when the user
@@ -186,35 +179,12 @@ func findChildByID(children []*Child, id string) *Child {
return nil
}
func (p *paletteState) taskByID(id string) (task.Task, bool) {
if id == "" {
return task.Task{}, false
}
for _, t := range p.tasks {
if t.ID == id {
return t, true
}
}
return task.Task{}, false
}
func taskHint(t task.Task) string {
if len(t.Worktrees) == 0 {
return t.ID
}
return fmt.Sprintf("%s · %d worktrees", t.ID, len(t.Worktrees))
}
func newPalette(children []*Child, focused, focusedPad string, presets preset.Set, appSettings ...settings) *paletteState {
return newPaletteWithTasks(children, focused, focusedPad, "", nil, presets, appSettings...)
}
func newPaletteWithTasks(children []*Child, focused, focusedPad, focusedTaskID string, tasks []task.Task, presets preset.Set, appSettings ...settings) *paletteState {
st := defaultSettings()
if len(appSettings) > 0 {
st = appSettings[0].clone()
}
p := &paletteState{children: children, focused: focused, focusedPad: focusedPad, focusedTaskID: focusedTaskID, tasksEnabled: tasks != nil || focusedTaskID != "", tasks: tasks, presets: presets, settings: st}
p := &paletteState{children: children, focused: focused, focusedPad: focusedPad, presets: presets, settings: st}
p.rebuild()
return p
}
@@ -289,21 +259,6 @@ func (p *paletteState) buildItems(macro string) []paletteItem {
paletteItem{label: "Delete", hint: "delete scratchpad · " + name,
action: paletteAction{kind: "pad-delete", padName: name}, group: groupFocused},
)
case p.focusedTaskID != "":
if t, ok := p.taskByID(p.focusedTaskID); ok {
out = append(out,
paletteItem{label: "Rename task", hint: "rename task · " + t.Title,
action: paletteAction{kind: "task-rename-form", taskID: t.ID}, group: groupFocused},
)
for _, pr := range p.presets.Agents {
out = append(out, paletteItem{
label: "Start agent for task: " + pr.Name,
hint: t.Title + " · task-scoped",
action: paletteAction{kind: "task-start-agent", taskID: t.ID, preset: pr},
group: groupFocused,
})
}
}
case p.focused != "":
if c := findChildByID(p.children, p.focused); c != nil {
name := c.DisplayName()
@@ -336,46 +291,13 @@ func (p *paletteState) buildItems(macro string) []paletteItem {
action: paletteAction{kind: "proc-delete", childID: c.ID}, group: groupFocused},
)
}
if c.TaskID != "" {
if t, ok := p.taskByID(c.TaskID); ok {
out = append(out, paletteItem{label: "Open task", hint: "open task · " + t.Title,
action: paletteAction{kind: "task-switch", taskID: t.ID}, group: groupFocused})
for _, pr := range p.presets.Agents {
out = append(out, paletteItem{
label: "Start another agent for task: " + pr.Name,
hint: t.Title + " · task-scoped",
action: paletteAction{kind: "task-start-agent", taskID: t.ID, preset: pr},
group: groupFocused,
})
}
}
}
}
}
// Group 1: Open — tasks first, then switch entries for every running child *other than*
// 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
// remain so they can be restarted.
if p.tasksEnabled {
out = append(out, paletteItem{
label: "Create task...",
hint: "manual project task",
action: paletteAction{kind: "task-create-form"},
group: groupOpen,
})
for _, t := range p.tasks {
if t.ID == p.focusedTaskID {
continue
}
out = append(out, paletteItem{
label: "Open task: " + t.Title,
hint: taskHint(t),
action: paletteAction{kind: "task-switch", taskID: t.ID},
group: groupOpen,
})
}
}
for _, c := range p.children {
if c.ID == p.focused {
continue
@@ -727,16 +649,6 @@ func (p *paletteState) acceptOrEnterForm(adv int) (paletteAction, bool, int) {
p.mode = paletteModeSpawnForm
p.form = &spawnProcessForm{}
return paletteAction{}, false, adv
case "task-create-form":
p.enterNameForm("task-create", "", "", "new task", "Create task")
return paletteAction{}, false, adv
case "task-rename-form":
current := ""
if t, ok := p.taskByID(a.taskID); ok {
current = t.Title
}
p.enterNameForm("task", a.taskID, current, "task: "+current, "Rename task")
return paletteAction{}, false, adv
case "settings-open":
p.mode = paletteModeSettings
p.query = nil
@@ -764,16 +676,12 @@ func (p *paletteState) acceptOrEnterForm(adv int) (paletteAction, bool, int) {
}
func (p *paletteState) enterRenameForm(subject, target, current, subjectLine string) {
p.enterNameForm(subject, target, current, subjectLine, "Rename")
}
func (p *paletteState) enterNameForm(subject, target, current, subjectLine, title string) {
p.mode = paletteModeRenameForm
p.renameForm = &renameForm{
name: []rune(current),
subject: subject,
target: target,
title: title,
title: "Rename",
subjectLine: subjectLine,
}
}
@@ -1013,10 +921,6 @@ func (p *paletteState) submitRename() paletteAction {
case "pad":
kind = "pad-rename-submit"
return paletteAction{kind: kind, padName: p.renameForm.target, newName: newName}
case "task-create":
return paletteAction{kind: "task-create-submit", newName: newName}
case "task":
return paletteAction{kind: "task-rename-submit", taskID: p.renameForm.target, newName: newName}
case "agent":
kind = "agent-rename-submit"
case "proc":
@@ -1247,17 +1151,12 @@ func (p *paletteState) selectableIndex() int {
}
// focusedSubject returns the short context string shown in the title
// bar — "on: <child>" / "pad: <name>" / "task: <title>" / "" — so the
// user knows which focus the context-section is targeting.
// bar — "on: <child>" / "pad: <name>" / "" — so the user knows which
// focus the context-section is targeting.
func (p *paletteState) focusedSubject() string {
if p.focusedPad != "" {
return "pad: " + p.focusedPad
}
if p.focusedTaskID != "" {
if t, ok := p.taskByID(p.focusedTaskID); ok {
return "task: " + t.Title
}
}
if p.focused != "" {
if c := findChildByID(p.children, p.focused); c != nil {
return "on: " + c.DisplayName()
-49
View File
@@ -6,7 +6,6 @@ import (
"time"
"github.com/hjbdev/patterm/internal/preset"
"github.com/hjbdev/patterm/internal/task"
)
// makeFakeChild builds a Child with just enough state for the palette
@@ -84,54 +83,6 @@ func TestContextItemsProcess(t *testing.T) {
}
}
func TestFocusedTaskShowsTaskActions(t *testing.T) {
agent := &preset.Preset{Name: "codex", Kind: preset.KindAgent, Argv: []string{"codex"}}
taskList := []task.Task{{ID: "task_1", Title: "Fix sidebar"}}
p := newPaletteWithTasks(nil, "", "", "task_1", taskList, preset.Set{Agents: []*preset.Preset{agent}})
if got := p.focusedSubject(); got != "task: Fix sidebar" {
t.Fatalf("focused subject = %q", got)
}
if _, it := findItem(p, "task-rename-form"); it == nil || it.action.taskID != "task_1" {
t.Fatalf("task rename missing or wrong: %+v", it)
}
if _, it := findItem(p, "task-start-agent"); it == nil || it.action.taskID != "task_1" || it.action.preset != agent {
t.Fatalf("task start-agent missing or wrong: %+v", it)
}
if i, _ := findItem(p, "spawn-agent"); i < 0 {
t.Fatalf("normal unscoped spawn-agent row should remain available")
}
}
func TestTaskCreateFormSubmitsTitle(t *testing.T) {
p := newPaletteWithTasks(nil, "", "", "", []task.Task{}, preset.Set{})
idx, _ := findItem(p, "task-create-form")
if idx < 0 {
t.Fatalf("task-create-form missing")
}
p.cursor = idx
_, done, _ := p.handleInput([]byte("\r"), 0)
if done || p.mode != paletteModeRenameForm || p.renameForm == nil || p.renameForm.subject != "task-create" {
t.Fatalf("create task did not open name form: done=%v form=%+v", done, p.renameForm)
}
for _, b := range []byte("New task") {
_, _, _ = p.handleInput([]byte{b}, 0)
}
action, done, _ := p.handleInput([]byte("\r"), 0)
if !done || action.kind != "task-create-submit" || action.newName != "New task" {
t.Fatalf("submit = %+v done=%v", action, done)
}
}
func TestTaskBoundChildShowsOpenTask(t *testing.T) {
c := makeFakeChild("aid", "codex", KindAgent)
c.TaskID = "task_1"
taskList := []task.Task{{ID: "task_1", Title: "Fix sidebar"}}
p := newPaletteWithTasks([]*Child{c}, "aid", "", "", taskList, preset.Set{})
if _, it := findItem(p, "task-switch"); it == nil || it.action.taskID != "task_1" {
t.Fatalf("task-switch missing for task-bound child: %+v", it)
}
}
func TestContextItemsTerminalUsesCloseNotStop(t *testing.T) {
c := makeFakeChild("tid", "terminal", KindTerminal)
p := newPalette([]*Child{c}, "tid", "", preset.Set{})
+1 -3
View File
@@ -6,7 +6,7 @@ import (
)
func newRingChild() *Child {
return newChildEntry("id", "name", KindCommand, nil, nil, "", "", "", "")
return newChildEntry("id", "name", KindCommand, nil, nil, "", "", "")
}
func TestRingShortWrite(t *testing.T) {
@@ -90,8 +90,6 @@ func TestStripANSIBytesEquivalence(t *testing.T) {
cases := []string{
"hello world",
"\x1b[31mred\x1b[0m text",
"\x1b]0;title\x07after osc",
"\x1b]2;title\x1b\\after st",
"line1\nline2\r\nline3",
"bell\x07ish",
"weird \x1bA escape",
+1 -1
View File
@@ -116,7 +116,7 @@ func TestToolHostScratchpadDeleteRemovesPadAndRefreshes(t *testing.T) {
t.Fatalf("write doomed.md: %v", err)
}
recorder := &scratchpadChangeRecorder{}
host := newToolHost(nil, pads, nil, nil, preset.Set{}, nil, 120, 40)
host := newToolHost(nil, pads, nil, preset.Set{}, nil, 120, 40)
host.scratch = recorder
if err := host.ScratchpadDelete("doomed.md"); err != nil {
+41 -2
View File
@@ -46,6 +46,13 @@ type Session struct {
listenersMu sync.Mutex
listeners atomic.Pointer[[]ChildEventListener]
// clientListeners is the network-client subscriber path. These
// listeners must be non-blocking and copy PTY chunks before enqueueing;
// daemon-internal observers (timers, debug capture, waiters) stay on
// listeners above so backpressure policy is isolated to clients.
clientListenersMu sync.Mutex
clientListeners atomic.Pointer[[]ChildEventListener]
// persistStore records top-level command entries to a per-project
// JSON file so they can be re-spawned after patterm restarts.
// Optional; nil means "no persistence" (used by unit tests).
@@ -118,6 +125,16 @@ func (s *Session) Subscribe(l ChildEventListener) {
s.listeners.Store(&next)
}
func (s *Session) SubscribeClient(l ChildEventListener) {
s.clientListenersMu.Lock()
defer s.clientListenersMu.Unlock()
prev := s.clientListenersSnapshot()
next := make([]ChildEventListener, 0, len(prev)+1)
next = append(next, prev...)
next = append(next, l)
s.clientListeners.Store(&next)
}
// Unsubscribe removes a previously-registered listener. Safe to call
// with a listener that wasn't registered (no-op).
func (s *Session) Unsubscribe(l ChildEventListener) {
@@ -146,16 +163,30 @@ func (s *Session) listenersSnapshot() []ChildEventListener {
return *p
}
func (s *Session) clientListenersSnapshot() []ChildEventListener {
p := s.clientListeners.Load()
if p == nil {
return nil
}
return *p
}
func (s *Session) emitSpawn(c *Child) {
for _, l := range s.listenersSnapshot() {
l.OnChildSpawned(c)
}
for _, l := range s.clientListenersSnapshot() {
l.OnChildSpawned(c)
}
}
func (s *Session) emitExit(c *Child) {
for _, l := range s.listenersSnapshot() {
l.OnChildExited(c)
}
for _, l := range s.clientListenersSnapshot() {
l.OnChildExited(c)
}
}
// emitPTYOut dispatches a fresh PTY chunk to every listener. Listeners
@@ -165,18 +196,27 @@ func (s *Session) emitPTYOut(id string, chunk []byte) {
for _, l := range s.listenersSnapshot() {
l.OnPTYOut(id, chunk)
}
for _, l := range s.clientListenersSnapshot() {
l.OnPTYOut(id, chunk)
}
}
func (s *Session) emitStateChanged(id string, state IdleState) {
for _, l := range s.listenersSnapshot() {
l.OnChildStateChanged(id, state)
}
for _, l := range s.clientListenersSnapshot() {
l.OnChildStateChanged(id, state)
}
}
func (s *Session) emitClosed(id string) {
for _, l := range s.listenersSnapshot() {
l.OnChildClosed(id)
}
for _, l := range s.clientListenersSnapshot() {
l.OnChildClosed(id)
}
}
func (s *Session) ChildEnv() []string {
@@ -201,7 +241,6 @@ type SpawnSpec struct {
WorkDir string
Name string
ParentID string
TaskID string
PresetRef string
Identity string // pre-minted; otherwise the constructor mints one for agents
// CleanupPaths are owned runtime files/dirs removed when the child exits
@@ -236,7 +275,7 @@ func (s *Session) Spawn(spec SpawnSpec, cols, rows uint16) (*Child, error) {
}
s.mu.Unlock()
c := newChildEntry(id, spec.Name, spec.Kind, spec.Argv, spec.Env, spec.ParentID, spec.TaskID, spec.WorkDir, spec.PresetRef)
c := newChildEntry(id, spec.Name, spec.Kind, spec.Argv, spec.Env, spec.ParentID, spec.WorkDir, spec.PresetRef)
if spec.Identity != "" {
c.Identity = spec.Identity
}
-37
View File
@@ -168,7 +168,6 @@ func (st *uiState) drawSidebar() {
palOpen := st.palette != nil
focus := st.focusedID
focusPad := st.focusedPad
focusTask := st.focusedTaskID
activeAgent := st.activeAgentID
st.mu.Unlock()
if palOpen {
@@ -263,42 +262,6 @@ func (st *uiState) drawSidebar() {
}
}
// Tasks section — manual project-local tasks. Task selection is a real
// focus target, but it does not implicitly scope generic spawns.
writeHeader("Tasks")
tasks := st.tasksList()
if len(tasks) == 0 {
write(" " + styleDim + "(Ctrl-K create task)" + styleReset)
}
for _, t := range tasks {
if row > maxRow {
break
}
focused := t.ID == focusTask
var prefix, openStyle string
if focused {
prefix = " " + styleAccent + "▎" + styleReset + " "
openStyle = styleBold
} else {
prefix = " "
openStyle = styleHint
}
suffix := ""
if n := len(t.Worktrees); n > 0 {
suffix = " " + styleDim + fmt.Sprintf("%dw", n) + styleReset
}
budget := width - visibleLen(prefix) - visibleLen(suffix)
if budget < 1 {
budget = 1
}
nameCell := st.rowNameSlot("task:"+t.ID, t.Title, budget, focused)
write(prefix + openStyle + nameCell + styleReset + suffix)
}
if row+2 <= maxRow {
write("")
}
// Processes section — top-level command/terminal processes,
// session-wide (does not change when the user switches agent tabs).
writeHeader("Processes")
+3 -3
View File
@@ -12,11 +12,11 @@ func TestOnChildSpawnedAgentChildKeepsFocus(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
st := &uiState{sess: sess}
parent := newChildEntry("p_parent", "parent", KindAgent, nil, nil, "", "", "", "")
parent := newChildEntry("p_parent", "parent", KindAgent, nil, nil, "", "", "")
st.focusedID = parent.ID
st.focusedName = parent.Name
subAgent := newChildEntry("p_sub", "sub", KindAgent, nil, nil, parent.ID, "", "", "")
subAgent := newChildEntry("p_sub", "sub", KindAgent, nil, nil, parent.ID, "", "")
st.OnChildSpawned(subAgent)
@@ -36,7 +36,7 @@ func TestOnChildSpawnedPaletteChildTakesFocus(t *testing.T) {
st := &uiState{sess: sess}
st.lastExit.Store(-1)
c := newChildEntry("p_new", "newchild", KindAgent, nil, nil, "", "", "", "")
c := newChildEntry("p_new", "newchild", KindAgent, nil, nil, "", "", "")
st.OnChildSpawned(c)
+2 -2
View File
@@ -89,7 +89,7 @@ func TestSummaryTextForSelectsChildAndClips(t *testing.T) {
func TestSummaryManagerArmsOnlyTrackedTopLevelAgents(t *testing.T) {
sess := NewSession(t.TempDir(), "test")
c := newChildEntry("a1", "agent", KindAgent, []string{"fake"}, nil, "", "", "", "")
c := newChildEntry("a1", "agent", KindAgent, []string{"fake"}, nil, "", "", "")
running := StatusRunning
c.status.Store(&running)
sess.children[c.ID] = c
@@ -112,7 +112,7 @@ func TestSummaryManagerArmsOnlyTrackedTopLevelAgents(t *testing.T) {
t.Fatalf("tracked top-level agent not armed/dirty: %+v", e)
}
sub := newChildEntry("a2", "sub", KindAgent, []string{"fake"}, nil, c.ID, "", "", "")
sub := newChildEntry("a2", "sub", KindAgent, []string{"fake"}, nil, c.ID, "", "")
sub.status.Store(&running)
m.RegisterChild(sub)
m.ObserveHumanInput(sub.ID, []byte("please summarize"))
+7 -17
View File
@@ -561,16 +561,14 @@ func (m *timerManager) TimerList(ownerID string) []mcp.TimerInfo {
if t.status != timerStatusPending && t.status != timerStatusPaused {
continue
}
body, bodyTruncated := timerBodyPreview(t.body)
info := mcp.TimerInfo{
ID: t.id,
Label: t.label,
Body: body,
BodyTruncated: bodyTruncated,
Kind: string(t.kind),
Status: t.status,
OwnerID: t.ownerID,
WatchedIDs: append([]string(nil), t.watched...),
ID: t.id,
Label: t.label,
Body: t.body,
Kind: string(t.kind),
Status: t.status,
OwnerID: t.ownerID,
WatchedIDs: append([]string(nil), t.watched...),
}
if t.status == timerStatusPending && !t.firesAt.IsZero() {
info.FiresAtUnixMS = t.firesAt.UnixMilli()
@@ -583,14 +581,6 @@ func (m *timerManager) TimerList(ownerID string) []mcp.TimerInfo {
return out
}
func timerBodyPreview(body string) (string, bool) {
const max = 500
if len(body) <= max {
return body, false
}
return body[:max], true
}
// activeForChild returns the nearest pending or paused timer attached
// to child id (either owned by it or watching it). Used by the sidebar
// for the "⏱ 12s" indicator. nil when none.
+1 -1
View File
@@ -41,7 +41,7 @@ func (r *recorderFire) snapshot() []recordedFire {
// Doesn't open a PTY — fireFn is overridden so InjectAsOrchestrator is
// never reached.
func fakeChild(id string) *Child {
c := newChildEntry(id, id, KindAgent, []string{"echo"}, nil, "", "", "", "")
c := newChildEntry(id, id, KindAgent, []string{"echo"}, nil, "", "", "")
running := StatusRunning
c.status.Store(&running)
return c
+13 -23
View File
@@ -1,21 +1,16 @@
package app
import (
"github.com/hjbdev/patterm/internal/scratchpad"
"github.com/hjbdev/patterm/internal/task"
)
import "github.com/hjbdev/patterm/internal/scratchpad"
// navEntry is one row in the unified sidebar navigation list. Exactly
// one of taskID, childID, or pad is set. childID points at a Child by ID;
// pad names a scratchpad entry. Empty zero-value means "no target".
// one of childID or pad is set. childID points at a Child by ID; pad
// names a scratchpad entry. Empty zero-value means "no target".
type navEntry struct {
taskID string
childID string
pad string
}
func (n navEntry) empty() bool { return n.taskID == "" && n.childID == "" && n.pad == "" }
func (n navEntry) isTask() bool { return n.taskID != "" }
func (n navEntry) empty() bool { return n.childID == "" && n.pad == "" }
func (n navEntry) isPad() bool { return n.pad != "" }
func (n navEntry) isChild() bool { return n.childID != "" }
@@ -226,14 +221,12 @@ func sidebarNavList(children []*Child, activeAgentID string) []*Child {
return out
}
// sidebarNav returns the combined Tasks + Processes + Agent Tree + Scratchpads
// navigation list. Order matches the right rail top-to-bottom.
func sidebarNav(children []*Child, activeAgentID string, tasks []task.Task, pads []scratchpad.Entry) []navEntry {
// sidebarNav returns the combined Processes + Agent Tree + Scratchpads
// navigation list. Scratchpads always appear after children so the
// existing "step past the tree" expectation still holds.
func sidebarNav(children []*Child, activeAgentID string, pads []scratchpad.Entry) []navEntry {
flat := sidebarNavList(children, activeAgentID)
out := make([]navEntry, 0, len(tasks)+len(flat)+len(pads))
for _, t := range tasks {
out = append(out, navEntry{taskID: t.ID})
}
out := make([]navEntry, 0, len(flat)+len(pads))
for _, c := range flat {
out = append(out, navEntry{childID: c.ID})
}
@@ -244,18 +237,15 @@ func sidebarNav(children []*Child, activeAgentID string, tasks []task.Task, pads
}
// nextNavEntry returns the entry `step` positions away from the
// current focus in the unified nav list. Exactly one focus identifier is
// usually set (or all empty for "nothing focused yet").
// current focus in the unified nav list. Either focusChildID or
// focusPad will be set (or both empty for "nothing focused yet").
// Empty when there's nothing else to land on.
func nextNavEntry(children []*Child, focusChildID, focusPad, focusTaskID, activeAgentID string, tasks []task.Task, pads []scratchpad.Entry, step int) navEntry {
flat := sidebarNav(children, activeAgentID, tasks, pads)
func nextNavEntry(children []*Child, focusChildID, focusPad, activeAgentID string, pads []scratchpad.Entry, step int) navEntry {
flat := sidebarNav(children, activeAgentID, pads)
if len(flat) == 0 {
return navEntry{}
}
matches := func(e navEntry) bool {
if focusTaskID != "" && e.taskID != "" {
return e.taskID == focusTaskID
}
if focusPad != "" && e.pad != "" {
return e.pad == focusPad
}
+1 -33
View File
@@ -1,10 +1,6 @@
package app
import (
"testing"
"github.com/hjbdev/patterm/internal/task"
)
import "testing"
func TestVisibleSessionTreeScopesToFocusedRoot(t *testing.T) {
root1 := testChild("c1", "root1", "", StatusRunning)
@@ -129,34 +125,6 @@ func TestSidebarNavListIncludesProcessesAboveAgentTree(t *testing.T) {
}
}
func TestSidebarNavOrdersTasksBeforeProcessesAndPads(t *testing.T) {
p := testProcess("p1", "bun", StatusRunning)
r := testAgent("a1", "claude", "", StatusRunning)
tasks := []task.Task{{ID: "t1", Title: "Fix sidebar"}}
nav := sidebarNav([]*Child{p, r}, "a1", tasks, nil)
if len(nav) != 3 {
t.Fatalf("nav len = %d, want 3 (%+v)", len(nav), nav)
}
if !nav[0].isTask() || nav[0].taskID != "t1" {
t.Fatalf("first nav entry = %+v, want task t1", nav[0])
}
if !nav[1].isChild() || nav[1].childID != "p1" {
t.Fatalf("second nav entry = %+v, want process p1", nav[1])
}
if !nav[2].isChild() || nav[2].childID != "a1" {
t.Fatalf("third nav entry = %+v, want agent a1", nav[2])
}
}
func TestNextNavEntryWalksFromTaskToProcess(t *testing.T) {
p := testProcess("p1", "bun", StatusRunning)
tasks := []task.Task{{ID: "t1", Title: "Fix sidebar"}}
next := nextNavEntry([]*Child{p}, "", "", "t1", "", tasks, nil, +1)
if !next.isChild() || next.childID != "p1" {
t.Fatalf("task -> next = %+v, want process p1", next)
}
}
func TestSidebarNavListIncludesExitedProcesses(t *testing.T) {
p := testProcess("p1", "shell", StatusExited)
r := testAgent("a1", "claude", "", StatusRunning)
+1 -1
View File
@@ -143,7 +143,7 @@ func openSession(t *testing.T, env *testEnv, childEnv []string) *Session {
if err != nil {
t.Fatalf("vt emulator: %v", err)
}
p, err := pkgpty.Start([]string{env.PattermBin, "--project", env.ProjectDir}, childEnv, env.ProjectDir, env.Cols, env.Rows)
p, err := pkgpty.Start([]string{env.PattermBin, "--project", env.ProjectDir}, childEnv, "", env.Cols, env.Rows)
if err != nil {
_ = em.Close()
t.Fatalf("pty start: %v", err)
@@ -1,62 +0,0 @@
{
"name": "canonical_output_noise",
"steps": [
{
"type": "mcp_call",
"method": "spawn_process",
"params": {
"kind": "command",
"argv": [
"sh",
"-lc",
"printf '\\033[31mStatus: running 12s\\033[0m\\nStatus: running 13s\\n╭────╮\\n│ │\\nDownloading 10%%\\rDownloading 100%%\\nFINAL: deploy ready\\n'; sleep 5"
],
"name": "noisy"
},
"save_as": "proc"
},
{
"type": "wait_until_mcp",
"method": "get_process_output",
"params": {
"process_id": "{{proc.process_id}}",
"mode": "stream",
"raw": true,
"max_lines": 20
},
"path": "content",
"contains": "FINAL: deploy ready",
"timeout_ms": 5000,
"save_as": "raw"
},
{
"type": "assert_saved",
"from": "raw",
"path": "content",
"contains": "FINAL: deploy ready"
},
{
"type": "mcp_call",
"method": "get_process_output",
"params": {
"process_id": "{{proc.process_id}}",
"mode": "stream",
"since_offset": 0,
"max_lines": 20
},
"save_as": "canonical"
},
{
"type": "assert_saved",
"from": "canonical",
"path": "content",
"equals": "Status: running [time]\nDownloading [count]\nFINAL: deploy ready"
},
{
"type": "assert_saved",
"from": "canonical",
"path": "canonicalized",
"equals": true
}
]
}
@@ -22,7 +22,7 @@
{ "type": "assert_contains", "contains": "Scratchpads" },
{
"type": "assert_regex",
"regex": "(?m)^[^\\n]*\\+ new[^\\n]*Tasks[^\\n]*$"
"regex": "(?m)^[^\\n]*\\+ new[^\\n]*Processes[^\\n]*$"
},
{
"type": "assert_regex",
@@ -1,42 +0,0 @@
{
"name": "create_task_and_start_agent",
"presets": {
"agents": [
{
"name": "fake-agent",
"argv": ["fake-agent"]
}
]
},
"scripts": [
{
"name": "fake-agent",
"body": "#!/bin/sh\necho FAKE READY\ncat\n"
}
],
"steps": [
{ "type": "wait_stable", "timeout_ms": 3000 },
{ "type": "assert_contains", "contains": "Tasks" },
{ "type": "assert_contains", "contains": "Ctrl-K create task" },
{ "type": "send_chord", "chord": "ctrl-k" },
{ "type": "send_text", "text": "Create task" },
{ "type": "send_chord", "chord": "enter" },
{ "type": "wait_text", "contains": "Create task", "timeout_ms": 3000 },
{ "type": "send_text", "text": "Harness task" },
{ "type": "send_chord", "chord": "enter" },
{ "type": "wait_text", "contains": "task: Harness task", "timeout_ms": 5000 },
{ "type": "assert_contains", "contains": "Harness task" },
{ "type": "send_chord", "chord": "ctrl-k" },
{ "type": "send_text", "text": "fake-agent" },
{ "type": "send_chord", "chord": "enter" },
{ "type": "wait_text", "contains": "task_register_worktree", "timeout_ms": 8000 },
{
"type": "assert_mcp",
"method": "list_processes",
"path": "0.name",
"contains": "Harness task"
}
]
}
+1 -1
View File
@@ -55,7 +55,7 @@ func NewCLI(opts Options) (*Session, error) {
if err != nil {
return nil, err
}
p, err := pkgpty.Start([]string{env.PattermBin, "--project", env.ProjectDir}, childEnv, env.ProjectDir, env.Cols, env.Rows)
p, err := pkgpty.Start([]string{env.PattermBin, "--project", env.ProjectDir}, childEnv, "", env.Cols, env.Rows)
if err != nil {
_ = em.Close()
return nil, err
+8 -18
View File
@@ -108,17 +108,10 @@ type blockingToolHost struct {
waitEntered chan struct{}
waitRelease chan struct{}
waitOnce sync.Once
task TaskInfo
}
func (h *blockingToolHost) ResolveCallerIdentity(identity string) string { return "caller-" + identity }
func (h *blockingToolHost) CallerRole(string) CallerRole { return RoleOrchestrator }
func (h *blockingToolHost) CallerTask(string) (TaskInfo, bool) {
if h.task.ID == "" {
return TaskInfo{}, false
}
return h.task, true
}
func (h *blockingToolHost) SpawnAgent(string, SpawnAgentArgs) (ProcessInfo, error) {
return ProcessInfo{}, nil
}
@@ -141,16 +134,16 @@ func (h *blockingToolHost) ListProcesses(string, string) []ProcessInfo { return
func (h *blockingToolHost) GetProcessStatus(string, string) (ProcessStatus, error) {
return ProcessStatus{ProcessInfo: ProcessInfo{ID: "p_fast", Status: "running"}}, nil
}
func (h *blockingToolHost) GetProjectStatus(string, bool) (ProjectStatus, error) {
func (h *blockingToolHost) GetProjectStatus(string) (ProjectStatus, error) {
return ProjectStatus{}, nil
}
func (h *blockingToolHost) GetProcessOutput(string, ProcessOutputArgs) (ProcessOutput, error) {
func (h *blockingToolHost) GetProcessOutput(string, string, string, int64) (ProcessOutput, error) {
return ProcessOutput{}, nil
}
func (h *blockingToolHost) GetProcessRawOutput(string, RawOutputArgs) (RawOutput, error) {
func (h *blockingToolHost) GetProcessRawOutput(string, string, int64) (RawOutput, error) {
return RawOutput{}, nil
}
func (h *blockingToolHost) SearchOutput(string, SearchOutputArgs) (SearchResult, error) {
func (h *blockingToolHost) SearchOutput(string, string, string, string, int) (SearchResult, error) {
return SearchResult{}, nil
}
func (h *blockingToolHost) WaitForPattern(string, string, string, float64, string) (bool, string, error) {
@@ -185,16 +178,13 @@ func (h *blockingToolHost) TimerList(string) ([]TimerInfo, error) {
return nil, nil
}
func (h *blockingToolHost) ScratchpadList() ([]scratchpad.Entry, error) { return nil, nil }
func (h *blockingToolHost) ScratchpadRead(ScratchpadReadArgs) (ScratchpadReadResult, error) {
return ScratchpadReadResult{}, nil
func (h *blockingToolHost) ScratchpadRead(string) (string, string, error) {
return "", "", nil
}
func (h *blockingToolHost) ScratchpadWrite(string, string, string) (string, error) {
return "", nil
}
func (h *blockingToolHost) ScratchpadAppend(string, string) error { return nil }
func (h *blockingToolHost) ScratchpadDelete(string) error { return nil }
func (h *blockingToolHost) RegisterTaskWorktree(string, TaskRegisterWorktreeArgs) (TaskInfo, error) {
return TaskInfo{}, nil
}
func (h *blockingToolHost) WhoAmI(string, bool) WhoAmI { return WhoAmI{} }
func (h *blockingToolHost) Help(string, string) HelpResponse { return HelpResponse{} }
func (h *blockingToolHost) WhoAmI(string) WhoAmI { return WhoAmI{} }
func (h *blockingToolHost) Help(string, string) HelpResponse { return HelpResponse{} }
+53 -168
View File
@@ -3,8 +3,6 @@ package mcp
import (
"encoding/json"
"fmt"
"github.com/hjbdev/patterm/internal/scratchpad"
)
// MCP protocol surface. The patterm server originally exposed each
@@ -29,7 +27,7 @@ var serverInfo = map[string]any{
"version": "0.1.0",
}
// baseServerInstructions is returned in the MCP `initialize` response. MCP
// serverInstructions is returned in the MCP `initialize` response. MCP
// clients show this to the underlying LLM as context for how to use
// the server. Failure modes we've seen and want to head off:
// - The agent assumes patterm is something it has to launch (running
@@ -45,14 +43,7 @@ var serverInfo = map[string]any{
// up as sub-agents and won't be tied into the patterm lifecycle.
//
// Keep this short — clients vary in how much they surface to the LLM.
const baseServerInstructions = "You are inside patterm. Use these MCP tools; do not launch patterm or poke its Unix socket yourself. Use spawn_agent for sub-agents, close spawned panes when done, and use timer_fire_when_idle_* instead of wait_for_pattern to wait for send_message replies."
func serverInstructions(taskBound bool) string {
if !taskBound {
return baseServerInstructions
}
return baseServerInstructions + " This MCP connection is task-bound; call whoami for the task, and register git worktrees you create or use with task_register_worktree."
}
const serverInstructions = "You are already running INSIDE patterm; the `patterm` MCP server is connected over the same stdio MCP transport you use for any other MCP server. Use the MCP tools you see in tools/list — do NOT (a) try to launch `patterm` or `patterm mcp-stdio` yourself, (b) poke the Unix socket through perl / nc / socat / curl, or (c) shell out to `claude` / `codex` / `opencode` to start a peer. Any of those bypasses caller-identity and the new agent will land as a stray top-level tab instead of a child under you. Start with `whoami` for your role and the full tool list, then `help('topics')` for orientation. `spawn_agent` is the only correct way to start a sub-agent; `spawn_process` is for non-LLM commands; `list_processes` / `get_process_output` inspect them; `send_input` / `send_message` drive them. Whatever you spawn is yours to `close_process` when done. When you `send_message` a sub-agent, its reply comes back into YOUR pane as `[sub-agent:<name>] …`, not into the sub-agent's output — to wait for it, use `timer_fire_when_idle_any([sub_agent])` and then read your own pane; do NOT `wait_for_pattern` on the sub-agent, that will deadlock until timeout."
// toolDescriptor is the shape returned by `tools/list`. inputSchema is
// a JSON Schema object — we provide a minimal `{type: "object"}` schema
@@ -85,41 +76,37 @@ func objectSchema(properties map[string]any, required []string) map[string]any {
}
func stringProp(desc string) map[string]any {
_ = desc
return map[string]any{"type": "string"}
return map[string]any{"type": "string", "description": desc}
}
func numberProp(desc string) map[string]any {
_ = desc
return map[string]any{"type": "number"}
return map[string]any{"type": "number", "description": desc}
}
func integerProp(desc string) map[string]any {
_ = desc
return map[string]any{"type": "integer"}
return map[string]any{"type": "integer", "description": desc}
}
func booleanProp(desc string) map[string]any {
_ = desc
return map[string]any{"type": "boolean"}
return map[string]any{"type": "boolean", "description": desc}
}
func arrayOfStringsProp(desc string) map[string]any {
_ = desc
return map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
"type": "array",
"description": desc,
"items": map[string]any{"type": "string"},
}
}
// toolCatalog is the full list advertised via tools/list. Descriptions
// are intentionally short — clients are expected to fetch help() for
// detail. Schemas mirror the param structs in tools.go.
func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
tools := []toolDescriptor{
func toolCatalog() []toolDescriptor {
return []toolDescriptor{
{
Name: "spawn_agent",
Description: "Spawn a sub-agent from an agent preset.",
Description: "Spawn a sub-agent from an agent preset and optionally seed it with initial instructions. This is the ONLY correct way to start a sub-agent under you — do not shell out to `claude` / `codex` / `opencode` and do not poke patterm's Unix socket via perl / nc / socat. Either bypasses caller identity and the new agent lands as a stray top-level tab instead of your child. Caller owns lifecycle: when the sub-agent's work is done (it reports back via send_message, or you no longer need it), call close_process on its process_id to free the pane and tear down the PTY. See help('spawning') and help('lifecycle').",
InputSchema: objectSchema(map[string]any{
"agent": stringProp("Preset name (e.g. \"claude\", \"codex\")."),
"agent_instructions": stringProp("Initial prompt typed into the agent after it's ready."),
@@ -128,14 +115,14 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
},
{
Name: "spawn_process",
Description: "Spawn a terminal, process preset, or argv command.",
Description: "Spawn a process: a terminal, a process preset, or a freeform argv command. Caller owns lifecycle: when the process is no longer needed, call close_process to remove its entry (live children are SIGKILL'd first). See help('lifecycle').",
InputSchema: objectSchema(map[string]any{
"kind": stringProp("\"terminal\" or \"command\"."),
"preset": stringProp("Process preset name (mutually exclusive with argv)."),
"argv": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
"argv": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "Argv vector for freeform commands."},
"name": stringProp("Display name for the pane."),
"working_dir": stringProp("Working directory for the spawned process."),
"env": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}},
"env": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}, "description": "Extra environment variables."},
"shell": booleanProp("Run argv through sh -lc."),
}, nil),
},
@@ -201,30 +188,23 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
{
Name: "get_project_status",
Description: "One-shot orientation: project, caller, processes, scratchpads.",
InputSchema: objectSchema(map[string]any{
"include_tools": booleanProp("Include available_tools in caller metadata."),
}, nil),
InputSchema: objectSchema(nil, nil),
},
{
Name: "get_process_output",
Description: "Read canonical terminal text by default: visible grid (\"grid\") or recent stream (\"stream\") with ANSI/control noise, borders, duplicate status churn, and volatile timers removed. Set raw=true only for diagnostic ANSI-preserved PTY bytes.",
Description: "Read rendered grid (\"grid\") or ANSI-stripped stream (\"stream\") output, with screen-version watermark.",
InputSchema: objectSchema(map[string]any{
"process_id": stringProp("Target process id."),
"mode": stringProp("\"grid\" (default) or \"stream\"."),
"since_offset": integerProp("Watermark offset from a previous call."),
"max_bytes": integerProp("Maximum content bytes to return."),
"max_lines": integerProp("Maximum canonical lines to return (default 120, max 500)."),
"raw": booleanProp("Return raw ANSI-preserved stream bytes instead of canonical text."),
"include_meta": booleanProp("Include verbose cursor, geometry, active screen, idle, and screen-version metadata."),
}, []string{"process_id"}),
},
{
Name: "get_process_raw_output",
Description: "Compatibility alias for raw=true get_process_output: read the raw ANSI byte stream since since_offset.",
Description: "Read the raw ANSI byte stream since since_offset.",
InputSchema: objectSchema(map[string]any{
"process_id": stringProp("Target process id."),
"since_offset": integerProp("Byte offset from a previous call."),
"max_bytes": integerProp("Maximum content bytes to return."),
}, []string{"process_id"}),
},
{
@@ -234,13 +214,12 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
"process_id": stringProp("Target process id."),
"pattern": stringProp("Regex pattern."),
"kind": stringProp("\"rendered\" (default) or \"raw\"."),
"limit": integerProp("Max matches (default 10)."),
"max_bytes": integerProp("Max bytes per returned match line."),
"limit": integerProp("Max matches (default 20)."),
}, []string{"process_id", "pattern"}),
},
{
Name: "wait_for_pattern",
Description: "Block until pattern appears in the target process output.",
Description: "Block until pattern appears in the TARGET process's own output, or timeout elapses. Use this for waiting on text the target itself will emit (a shell prompt, a build's \"tests passed\" line, etc.). Anti-pattern: do NOT use this to wait for a sub-agent's reply to send_message — replies are routed into the CALLER's pane tagged `[sub-agent:<name>]`, not into the sub-agent's output, so this call will spin to timeout. For sub-agent coordination use `timer_fire_when_idle_any` and then read your own pane.",
InputSchema: objectSchema(map[string]any{
"process_id": stringProp("Target process id."),
"pattern": stringProp("Regex pattern."),
@@ -259,19 +238,18 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
Name: "send_input",
Description: "Type text, paste a block, or fire a named key into a process. Optional tail-after-send.",
InputSchema: objectSchema(map[string]any{
"process_id": stringProp("Target process id."),
"kind": stringProp("\"text\", \"paste\", or \"key\"."),
"text": stringProp("Text payload for kind=text/paste."),
"key": stringProp("Named key for kind=key (e.g. \"enter\", \"escape\")."),
"submit": booleanProp("Whether to append a submit keystroke."),
"wait_ms": integerProp("After sending, wait this many ms before tailing."),
"tail_mode": stringProp("\"none\" (default), \"stream\", or \"grid\"."),
"tail_max_bytes": integerProp("Maximum bytes in returned tail."),
"process_id": stringProp("Target process id."),
"kind": stringProp("\"text\", \"paste\", or \"key\"."),
"text": stringProp("Text payload for kind=text/paste."),
"key": stringProp("Named key for kind=key (e.g. \"enter\", \"escape\")."),
"submit": booleanProp("Whether to append a submit keystroke."),
"wait_ms": integerProp("After sending, wait this many ms before tailing."),
"tail_mode": stringProp("\"none\" (default), \"stream\", or \"grid\"."),
}, []string{"process_id", "kind"}),
},
{
Name: "send_message",
Description: "Send a tagged message to a parent or child process.",
Description: "Deliver a text message to another process as orchestrator-owned input. Fire-and-forget: returns immediately, without waiting for the recipient to read or act. If the recipient replies via send_message, that reply arrives in YOUR pane tagged `[sub-agent:<name>]` (child→parent) or `[orchestrator]` (parent→child) — NOT in the recipient's output. To wait for a sub-agent's reply, schedule `timer_fire_when_idle_any([sub_agent_id], body=…)` and then read your own pane when the timer fires. Do not `wait_for_pattern` on the recipient for a reply; it will deadlock.",
InputSchema: objectSchema(map[string]any{
"target_process_id": stringProp("Recipient process id."),
"message": stringProp("Message body."),
@@ -305,7 +283,7 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
},
{
Name: "timer_fire_when_idle_any",
Description: "Fire when any watched process becomes idle.",
Description: "Canonical way to wait for a sub-agent to finish working: send_message the sub-agent, then schedule this with watched=[sub_agent_id]; when it fires, the reply is already sitting in your own pane tagged `[sub-agent:<name>]`. Schedules a timer that fires when any watched process enters idle (already-idle entries excluded), or when max_wait_seconds elapses.",
InputSchema: objectSchema(map[string]any{
"watched": arrayOfStringsProp("Process ids to watch."),
"body": stringProp("Message delivered verbatim to the owning agent when the timer fires."),
@@ -316,7 +294,7 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
},
{
Name: "timer_fire_when_idle_all",
Description: "Fire when all watched processes are idle.",
Description: "Canonical way to wait for several sub-agents to finish working in parallel: send_message each one, then schedule this with watched=[…ids]; when it fires, each reply is in your own pane tagged `[sub-agent:<name>]`. Schedules a timer that fires when all watched processes are idle (already-idle entries count as satisfied), or when max_wait_seconds elapses.",
InputSchema: objectSchema(map[string]any{
"watched": arrayOfStringsProp("Process ids to watch."),
"body": stringProp("Message delivered verbatim to the owning agent when the timer fires."),
@@ -360,9 +338,7 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
Name: "scratchpad_read",
Description: "Read a scratchpad entry, returning content and revision.",
InputSchema: objectSchema(map[string]any{
"name": stringProp("Scratchpad name."),
"offset": integerProp("Byte offset to start reading."),
"max_bytes": integerProp("Maximum content bytes to return."),
"name": stringProp("Scratchpad name."),
}, []string{"name"}),
},
{
@@ -389,20 +365,10 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
"name": stringProp("Scratchpad name."),
}, []string{"name"}),
},
{
Name: "task_register_worktree",
Description: "Register a git worktree path for the current task.",
InputSchema: objectSchema(map[string]any{
"path": stringProp("Absolute path, or path relative to this process working directory."),
"branch": stringProp("Git branch name, if known."),
}, []string{"path"}),
},
{
Name: "whoami",
Description: "Return caller identity, role, parent, and project metadata.",
InputSchema: objectSchema(map[string]any{
"include_tools": booleanProp("Include full available tool list."),
}, nil),
Description: "Return the caller's identity, role, parent, project metadata, and available tools.",
InputSchema: objectSchema(nil, nil),
},
{
Name: "help",
@@ -412,17 +378,6 @@ func toolCatalog(role CallerRole, taskBound bool) []toolDescriptor {
}, nil),
},
}
filtered := tools[:0]
for _, tool := range tools {
if role == RoleSubAgent && tool.Name == "spawn_agent" {
continue
}
if !taskBound && tool.Name == "task_register_worktree" {
continue
}
filtered = append(filtered, tool)
}
return filtered
}
// handleProtocolMethod handles MCP protocol-level methods. Returns
@@ -442,20 +397,13 @@ func (s *Server) handleProtocolMethod(callerID, method string, params json.RawMe
if protoVersion == "" {
protoVersion = supportedProtocolVersion
}
taskBound := false
s.mu.Lock()
host := s.host
s.mu.Unlock()
if host != nil {
_, taskBound = host.CallerTask(callerID)
}
result := map[string]any{
"protocolVersion": protoVersion,
"capabilities": map[string]any{
"tools": map[string]any{"listChanged": false},
},
"serverInfo": serverInfo,
"instructions": serverInstructions(taskBound),
"instructions": serverInstructions,
}
return result, true, 0, "", nil
@@ -468,16 +416,7 @@ func (s *Server) handleProtocolMethod(callerID, method string, params json.RawMe
return map[string]any{}, true, 0, "", nil
case "tools/list":
role := RoleOrchestrator
taskBound := false
s.mu.Lock()
host := s.host
s.mu.Unlock()
if host != nil {
role = host.CallerRole(callerID)
_, taskBound = host.CallerTask(callerID)
}
return map[string]any{"tools": toolCatalog(role, taskBound)}, true, 0, "", nil
return map[string]any{"tools": toolCatalog()}, true, 0, "", nil
case "tools/call":
var p struct {
@@ -533,12 +472,25 @@ func (s *Server) handleProtocolMethod(callerID, method string, params json.RawMe
return nil, false, 0, "", nil
}
// wrapToolResult turns a tool result into an MCP tools/call response.
// Structured values are exposed once under structuredContent; content
// carries only a short model-readable summary to avoid duplicating
// large JSON payloads into the transcript.
// wrapToolResult turns a structured tool result into an MCP tools/call
// response. Plain strings (e.g. "ok") become text content; structured
// values are JSON-encoded into a single text block and also exposed
// under structuredContent so capable clients can read the shape.
func wrapToolResult(result any) map[string]any {
text := summarizeToolResult(result)
var text string
switch v := result.(type) {
case nil:
text = "ok"
case string:
text = v
default:
b, err := json.Marshal(v)
if err != nil {
text = fmt.Sprintf("%v", v)
} else {
text = string(b)
}
}
out := map[string]any{
"content": []map[string]any{{"type": "text", "text": text}},
"isError": false,
@@ -553,70 +505,3 @@ func wrapToolResult(result any) map[string]any {
}
return out
}
func summarizeToolResult(result any) string {
switch v := result.(type) {
case nil:
return "ok"
case string:
return v
case ProcessInfo:
return fmt.Sprintf("%s %s %s", v.ID, v.Kind, v.Status)
case []ProcessInfo:
return fmt.Sprintf("%d processes", len(v))
case ProcessStatus:
return fmt.Sprintf("%s %s %s", v.ID, v.Kind, v.Status)
case ProjectStatus:
return fmt.Sprintf("%d processes, %d scratchpads", len(v.Processes), len(v.Scratchpads))
case ProcessOutput:
return outputSummary(v.Mode, v.ContentBytes, v.Truncated, v.NewOffset)
case RawOutput:
return outputSummary("raw", v.ContentBytes, v.Truncated, v.NewOffset)
case SearchResult:
if v.Truncated {
return fmt.Sprintf("%d matches (truncated)", len(v.Matches))
}
return fmt.Sprintf("%d matches", len(v.Matches))
case SendInputResult:
if v.Tail != nil {
return "ok; tail included"
}
return "ok"
case TimerHandle:
return "timer " + v.ID
case TimerFireWhenIdleResponse:
if v.ID != "" {
return fmt.Sprintf("%s timer %s", v.Status, v.ID)
}
return v.Status
case []TimerInfo:
return fmt.Sprintf("%d timers", len(v))
case []scratchpad.Entry:
return fmt.Sprintf("%d scratchpads", len(v))
case ScratchpadReadResult:
if v.Truncated {
return fmt.Sprintf("%d/%d bytes from offset %d", v.ContentBytes, v.TotalBytes, v.Offset)
}
return fmt.Sprintf("%d bytes", v.ContentBytes)
case WhoAmI:
if v.ProcessID == "" {
return string(v.Role)
}
return fmt.Sprintf("%s %s", v.ProcessID, v.Role)
case HelpResponse:
return fmt.Sprintf("help: %s", v.Topic)
default:
return "ok"
}
}
func outputSummary(mode string, bytes int, truncated bool, offset int64) string {
s := fmt.Sprintf("%s output: %d bytes", mode, bytes)
if offset > 0 {
s += fmt.Sprintf(", offset %d", offset)
}
if truncated {
s += " (truncated)"
}
return s
}
-117
View File
@@ -2,7 +2,6 @@ package mcp
import (
"encoding/json"
"strings"
"testing"
)
@@ -44,9 +43,6 @@ func TestInitializeReturnsCapabilities(t *testing.T) {
if !ok || instructions == "" {
t.Fatalf("instructions missing or wrong type: %+v", parsed.Result)
}
if len(instructions) > 320 {
t.Fatalf("instructions too verbose: %d chars", len(instructions))
}
}
func TestInitializedNotificationSuppressesResponse(t *testing.T) {
@@ -78,9 +74,6 @@ func TestToolsListReturnsConcreteSchemas(t *testing.T) {
if parsed.Error != nil {
t.Fatalf("tools/list returned error: %+v", parsed.Error)
}
if len(resp) > 12000 {
t.Fatalf("tools/list response too large: %d bytes", len(resp))
}
tools, ok := parsed.Result["tools"].([]interface{})
if !ok {
t.Fatalf("tools not array: %+v", parsed.Result)
@@ -119,53 +112,6 @@ func TestToolsListReturnsConcreteSchemas(t *testing.T) {
}
}
func TestToolsListTaskRegisterWorktreeIsTaskBound(t *testing.T) {
unbound := toolsListNames(t, &Server{})
if containsString(unbound, "task_register_worktree") {
t.Fatalf("unbound tools leaked task_register_worktree: %v", unbound)
}
s := &Server{}
s.SetHost(&blockingToolHost{task: TaskInfo{ID: "task_1", Title: "Fix sidebar"}})
bound := toolsListNames(t, s)
if !containsString(bound, "task_register_worktree") {
t.Fatalf("task-bound tools missing task_register_worktree: %v", bound)
}
}
func TestInitializeTaskInstructionsAreTaskBound(t *testing.T) {
unbound := initializeInstructions(t, &Server{})
if strings.Contains(unbound, "task_register_worktree") {
t.Fatalf("unbound initialize leaked task instruction: %q", unbound)
}
s := &Server{}
s.SetHost(&blockingToolHost{task: TaskInfo{ID: "task_1", Title: "Fix sidebar"}})
bound := initializeInstructions(t, s)
if !strings.Contains(bound, "task_register_worktree") {
t.Fatalf("task-bound initialize missing worktree instruction: %q", bound)
}
}
func TestWrapToolResultDoesNotDuplicateStructuredJSON(t *testing.T) {
result := ProcessOutput{
Content: strings.Repeat("x", 1024),
Mode: "stream",
NewOffset: 2048,
ContentBytes: 1024,
}
wrapped := wrapToolResult(result)
if wrapped["structuredContent"] == nil {
t.Fatalf("structuredContent missing: %#v", wrapped)
}
content := wrapped["content"].([]map[string]any)
text := content[0]["text"].(string)
if strings.Contains(text, result.Content) {
t.Fatalf("content duplicated structured payload: %q", text)
}
if !strings.Contains(text, "stream output") {
t.Fatalf("summary text should identify output, got %q", text)
}
}
func TestPingReturnsEmptyObject(t *testing.T) {
s := &Server{}
req := []byte(`{"jsonrpc":"2.0","id":3,"method":"ping"}`)
@@ -188,69 +134,6 @@ func TestPingReturnsEmptyObject(t *testing.T) {
}
}
func toolsListNames(t *testing.T, s *Server) []string {
t.Helper()
req := []byte(`{"jsonrpc":"2.0","id":2,"method":"tools/list"}`)
resp := s.dispatch("caller", req)
if resp == nil {
t.Fatal("expected response for tools/list")
}
var parsed struct {
Result struct {
Tools []struct {
Name string `json:"name"`
} `json:"tools"`
} `json:"result"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(resp, &parsed); err != nil {
t.Fatalf("parse tools/list: %v\n%s", err, resp)
}
if parsed.Error != nil {
t.Fatalf("tools/list error: %+v", parsed.Error)
}
out := make([]string, 0, len(parsed.Result.Tools))
for _, tool := range parsed.Result.Tools {
out = append(out, tool.Name)
}
return out
}
func initializeInstructions(t *testing.T, s *Server) string {
t.Helper()
req := []byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}`)
resp := s.dispatch("caller", req)
if resp == nil {
t.Fatal("expected response for initialize")
}
var parsed struct {
Result struct {
Instructions string `json:"instructions"`
} `json:"result"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(resp, &parsed); err != nil {
t.Fatalf("parse initialize: %v\n%s", err, resp)
}
if parsed.Error != nil {
t.Fatalf("initialize error: %+v", parsed.Error)
}
return parsed.Result.Instructions
}
func containsString(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
func TestTypedInvalidArgsMapToInvalidParams(t *testing.T) {
for _, errKind := range []string{ErrorKindInvalidArgs, ErrorKindInvalidKind} {
_, code, msg, data := mapToolError(Errorf(errKind, "bad args"))
+54 -141
View File
@@ -60,7 +60,6 @@ type ToolHost interface {
// callers default to RoleOrchestrator (treated as a top-level peer)
// so they don't get silently denied.
CallerRole(processID string) CallerRole
CallerTask(processID string) (TaskInfo, bool)
// Lifecycle (SPEC §7).
SpawnAgent(callerID string, args SpawnAgentArgs) (ProcessInfo, error)
@@ -75,10 +74,10 @@ type ToolHost interface {
// Inspection.
ListProcesses(callerID, kindFilter string) []ProcessInfo
GetProcessStatus(callerID, processID string) (ProcessStatus, error)
GetProjectStatus(callerID string, includeTools bool) (ProjectStatus, error)
GetProcessOutput(callerID string, args ProcessOutputArgs) (ProcessOutput, error)
GetProcessRawOutput(callerID string, args RawOutputArgs) (RawOutput, error)
SearchOutput(callerID string, args SearchOutputArgs) (SearchResult, error)
GetProjectStatus(callerID string) (ProjectStatus, error)
GetProcessOutput(callerID, processID, mode string, sinceOffset int64) (ProcessOutput, error)
GetProcessRawOutput(callerID, processID string, sinceOffset int64) (RawOutput, error)
SearchOutput(callerID, processID, pattern, kind string, limit int) (SearchResult, error)
WaitForPattern(callerID, processID, pattern string, timeoutSeconds float64, scope string) (matched bool, snippet string, err error)
GetProcessPorts(callerID, processID string) ([]PortSighting, error)
@@ -99,14 +98,13 @@ type ToolHost interface {
// Scratchpads.
ScratchpadList() ([]scratchpad.Entry, error)
ScratchpadRead(args ScratchpadReadArgs) (ScratchpadReadResult, error)
ScratchpadRead(name string) (content string, revision string, err error)
ScratchpadWrite(name, content, expectedRevision string) (revision string, err error)
ScratchpadAppend(name, content string) error
ScratchpadDelete(name string) error
RegisterTaskWorktree(callerID string, args TaskRegisterWorktreeArgs) (TaskInfo, error)
// Meta.
WhoAmI(callerID string, includeTools bool) WhoAmI
WhoAmI(callerID string) WhoAmI
Help(callerID, topic string) HelpResponse
}
@@ -155,85 +153,36 @@ type Cursor struct {
type ProjectStatus struct {
Project ProjectMeta `json:"project"`
Caller WhoAmI `json:"caller"`
Task *TaskInfo `json:"task,omitempty"`
Processes []ProcessInfo `json:"processes"`
Scratchpads []scratchpad.Entry `json:"scratchpads"`
}
type ProjectStatusArgs struct {
IncludeTools bool `json:"include_tools"`
}
// ProjectMeta is the project root info echoed in many payloads.
type ProjectMeta struct {
Path string `json:"path"`
Key string `json:"key"`
}
type TaskInfo struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt string `json:"created_at,omitempty"`
UpdatedAt string `json:"updated_at,omitempty"`
Worktrees []TaskWorktree `json:"worktrees,omitempty"`
}
type TaskWorktree struct {
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
CreatedByProcessID string `json:"created_by_process_id,omitempty"`
RegisteredAt string `json:"registered_at,omitempty"`
}
type TaskRegisterWorktreeArgs struct {
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
}
// ProcessOutput is the get_process_output payload. By default it is
// canonical text with light metadata; include_meta restores screen
// geometry + version, and raw requests return stream bytes.
// ProcessOutput is the get_process_output payload. SPEC §7 enriches
// the old read_output result with screen geometry + version.
type ProcessOutput struct {
Content string `json:"content"`
Mode string `json:"mode"`
NewOffset int64 `json:"new_offset,omitempty"`
ActiveScreen string `json:"active_screen,omitempty"`
Rows int `json:"rows,omitempty"`
Cols int `json:"cols,omitempty"`
Cursor *Cursor `json:"cursor,omitempty"`
IdleMS int64 `json:"idle_ms,omitempty"`
Status string `json:"status,omitempty"`
ScreenVersion int64 `json:"screen_version,omitempty"`
ContentBytes int `json:"content_bytes,omitempty"`
Truncated bool `json:"truncated,omitempty"`
TruncatedBytes int `json:"truncated_bytes,omitempty"`
Canonicalized bool `json:"canonicalized,omitempty"`
}
type ProcessOutputArgs struct {
ProcessID string `json:"process_id"`
Mode string `json:"mode"`
SinceOffset int64 `json:"since_offset"`
MaxBytes int `json:"max_bytes"`
MaxLines int `json:"max_lines"`
Raw bool `json:"raw"`
IncludeMeta bool `json:"include_meta"`
Content string `json:"content"`
Mode string `json:"mode"`
NewOffset int64 `json:"new_offset,omitempty"`
ActiveScreen string `json:"active_screen,omitempty"`
Rows int `json:"rows,omitempty"`
Cols int `json:"cols,omitempty"`
Cursor Cursor `json:"cursor"`
IdleMS int64 `json:"idle_ms,omitempty"`
Status string `json:"status,omitempty"`
ScreenVersion int64 `json:"screen_version,omitempty"`
}
// RawOutput is the get_process_raw_output payload — ANSI preserved.
type RawOutput struct {
Content string `json:"content"`
NewOffset int64 `json:"new_offset"`
Status string `json:"status,omitempty"`
ContentBytes int `json:"content_bytes,omitempty"`
Truncated bool `json:"truncated,omitempty"`
TruncatedBytes int `json:"truncated_bytes,omitempty"`
}
type RawOutputArgs struct {
ProcessID string `json:"process_id"`
SinceOffset int64 `json:"since_offset"`
MaxBytes int `json:"max_bytes"`
Content string `json:"content"`
NewOffset int64 `json:"new_offset"`
Status string `json:"status,omitempty"`
}
// SearchResult is search_output's payload.
@@ -242,14 +191,6 @@ type SearchResult struct {
Truncated bool `json:"truncated"`
}
type SearchOutputArgs struct {
ProcessID string `json:"process_id"`
Pattern string `json:"pattern"`
Kind string `json:"kind"`
Limit int `json:"limit"`
MaxBytes int `json:"max_bytes"`
}
type SearchMatch struct {
LineNo int `json:"line_no"`
Text string `json:"text"`
@@ -304,7 +245,6 @@ type TimerInfo struct {
ID string `json:"timer_id"`
Label string `json:"label,omitempty"`
Body string `json:"body,omitempty"`
BodyTruncated bool `json:"body_truncated,omitempty"`
Kind string `json:"kind"` // "delay" | "idle_any" | "idle_all"
Status string `json:"status"` // "pending" | "paused"
OwnerID string `json:"owner_process_id"`
@@ -341,14 +281,13 @@ type SpawnProcessArgs struct {
// SendInputArgs is the input shape for send_input — covers text /
// paste / key with the optional wait+tail tail-after-send.
type SendInputArgs struct {
ProcessID string `json:"process_id"`
Kind string `json:"kind"` // "text" | "paste" | "key"
Text string `json:"text"`
Key string `json:"key"`
Submit *bool `json:"submit"`
WaitMS int `json:"wait_ms"`
TailMode string `json:"tail_mode"` // "none" | "stream" | "grid"
TailMaxBytes int `json:"tail_max_bytes"`
ProcessID string `json:"process_id"`
Kind string `json:"kind"` // "text" | "paste" | "key"
Text string `json:"text"`
Key string `json:"key"`
Submit *bool `json:"submit"`
WaitMS int `json:"wait_ms"`
TailMode string `json:"tail_mode"` // "none" | "stream" | "grid"
}
// SendInputResult is the return shape of send_input.
@@ -364,31 +303,9 @@ type WhoAmI struct {
Role CallerRole `json:"role"`
ParentProcessID string `json:"parent_process_id,omitempty"`
Project ProjectMeta `json:"project"`
Task *TaskInfo `json:"task,omitempty"`
AvailableTools []string `json:"available_tools"`
}
type WhoAmIArgs struct {
IncludeTools bool `json:"include_tools"`
}
type ScratchpadReadArgs struct {
Name string `json:"name"`
Offset int `json:"offset"`
MaxBytes int `json:"max_bytes"`
}
type ScratchpadReadResult struct {
Content string `json:"content"`
Revision string `json:"revision"`
Offset int `json:"offset,omitempty"`
NextOffset int `json:"next_offset,omitempty"`
ContentBytes int `json:"content_bytes,omitempty"`
TotalBytes int `json:"total_bytes,omitempty"`
Truncated bool `json:"truncated,omitempty"`
TruncatedBytes int `json:"truncated_bytes,omitempty"`
}
// HelpResponse is the help return shape.
type HelpResponse struct {
Topic string `json:"topic"`
@@ -590,51 +507,61 @@ func callTool(h ToolHost, callerID, method string, params json.RawMessage) (any,
return st, 0, "", nil
case "get_project_status":
var p ProjectStatusArgs
_ = unmarshalParamsOptional(params, &p)
ps, err := h.GetProjectStatus(callerID, p.IncludeTools)
ps, err := h.GetProjectStatus(callerID)
if err != nil {
return mapToolError(err)
}
return ps, 0, "", nil
case "get_process_output":
var p ProcessOutputArgs
var p struct {
ProcessID string `json:"process_id"`
Mode string `json:"mode"`
SinceOffset int64 `json:"since_offset"`
}
if err := unmarshalParams(params, &p); err != nil {
return nil, codeInvalidParams, err.Error(), nil
}
if p.Mode == "" {
p.Mode = "grid"
}
out, err := h.GetProcessOutput(callerID, p)
out, err := h.GetProcessOutput(callerID, p.ProcessID, p.Mode, p.SinceOffset)
if err != nil {
return mapToolError(err)
}
return out, 0, "", nil
case "get_process_raw_output":
var p RawOutputArgs
var p struct {
ProcessID string `json:"process_id"`
SinceOffset int64 `json:"since_offset"`
}
if err := unmarshalParams(params, &p); err != nil {
return nil, codeInvalidParams, err.Error(), nil
}
out, err := h.GetProcessRawOutput(callerID, p)
out, err := h.GetProcessRawOutput(callerID, p.ProcessID, p.SinceOffset)
if err != nil {
return mapToolError(err)
}
return out, 0, "", nil
case "search_output":
var p SearchOutputArgs
var p struct {
ProcessID string `json:"process_id"`
Pattern string `json:"pattern"`
Kind string `json:"kind"`
Limit int `json:"limit"`
}
if err := unmarshalParams(params, &p); err != nil {
return nil, codeInvalidParams, err.Error(), nil
}
if p.Limit <= 0 {
p.Limit = 10
p.Limit = 20
}
if p.Kind == "" {
p.Kind = "rendered"
}
res, err := h.SearchOutput(callerID, p)
res, err := h.SearchOutput(callerID, p.ProcessID, p.Pattern, p.Kind, p.Limit)
if err != nil {
return mapToolError(err)
}
@@ -804,15 +731,17 @@ func callTool(h ToolHost, callerID, method string, params json.RawMessage) (any,
return entries, 0, "", nil
case "scratchpad_read":
var p ScratchpadReadArgs
var p struct {
Name string `json:"name"`
}
if err := unmarshalParams(params, &p); err != nil {
return nil, codeInvalidParams, err.Error(), nil
}
res, err := h.ScratchpadRead(p)
content, rev, err := h.ScratchpadRead(p.Name)
if err != nil {
return nil, codeInternal, err.Error(), nil
}
return res, 0, "", nil
return map[string]any{"content": content, "revision": rev}, 0, "", nil
case "scratchpad_write":
var p struct {
@@ -860,24 +789,8 @@ func callTool(h ToolHost, callerID, method string, params json.RawMessage) (any,
}
return map[string]any{"ok": true}, 0, "", nil
case "task_register_worktree":
if _, ok := h.CallerTask(callerID); !ok {
return nil, codeRoleForbidden, "task_register_worktree: caller is not attached to a task", structuredKind(ErrorKindRoleForbidden)
}
var p TaskRegisterWorktreeArgs
if err := unmarshalParams(params, &p); err != nil {
return nil, codeInvalidParams, err.Error(), nil
}
if p.Path == "" {
return nil, codeInvalidParams, "task_register_worktree: path required", nil
}
info, err := h.RegisterTaskWorktree(callerID, p)
return mapToolResult(info, err)
case "whoami":
var p WhoAmIArgs
_ = unmarshalParamsOptional(params, &p)
return h.WhoAmI(callerID, p.IncludeTools), 0, "", nil
return h.WhoAmI(callerID), 0, "", nil
case "help":
var p struct {
+164
View File
@@ -0,0 +1,164 @@
// Package protocol defines the daemon/client control frames shared by
// transports. It intentionally contains data shapes only; app behavior stays
// in internal/app until the headless daemon split is complete.
package protocol
import (
"encoding/json"
"fmt"
"time"
)
// FrameType identifies one protocol message kind.
type FrameType string
const (
FrameHello FrameType = "hello"
FrameAuthChallenge FrameType = "auth_challenge"
FrameAuthOK FrameType = "auth_ok"
FrameAttach FrameType = "attach"
FrameDetach FrameType = "detach"
FrameProjectList FrameType = "project_list"
FrameChrome FrameType = "chrome"
FramePaneSnapshot FrameType = "pane_snapshot"
FramePaneChunk FrameType = "pane_chunk"
FrameLifecycle FrameType = "lifecycle"
FrameAttention FrameType = "attention"
FrameTrustPrompt FrameType = "trust_prompt"
FrameInput FrameType = "input"
FrameFocus FrameType = "focus"
FrameSwitchProject FrameType = "switch_project"
FrameOpenProject FrameType = "open_project"
FramePaletteCommand FrameType = "palette_command"
FrameTrustResponse FrameType = "trust_response"
FrameResize FrameType = "resize"
)
// Frame is the transport envelope. Payload is deliberately raw JSON so
// network transports can frame without knowing every message type; loopback
// transports may pass the same bytes without JSON re-encoding.
type Frame struct {
Type FrameType `json:"type"`
RequestID string `json:"request_id,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
}
// NewFrame marshals payload into a protocol frame.
func NewFrame[T any](typ FrameType, payload T) (Frame, error) {
b, err := json.Marshal(payload)
if err != nil {
return Frame{}, fmt.Errorf("protocol: marshal %s: %w", typ, err)
}
return Frame{Type: typ, Payload: b}, nil
}
// Decode unmarshals f.Payload into v.
func Decode[T any](f Frame) (T, error) {
var v T
if len(f.Payload) == 0 {
return v, nil
}
if err := json.Unmarshal(f.Payload, &v); err != nil {
return v, fmt.Errorf("protocol: decode %s: %w", f.Type, err)
}
return v, nil
}
type Hello struct {
Version int `json:"version"`
DaemonID string `json:"daemon_id,omitempty"`
ClientID string `json:"client_id,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
}
type Attach struct {
Token string `json:"token,omitempty"`
ProjectKey string `json:"project_key,omitempty"`
TermSize Size `json:"term_size"`
}
type Detach struct {
ClientID string `json:"client_id,omitempty"`
}
type Size struct {
Cols uint16 `json:"cols"`
Rows uint16 `json:"rows"`
}
type Project struct {
Key string `json:"key"`
Path string `json:"path"`
Name string `json:"name"`
LastActive time.Time `json:"last_active,omitempty"`
TabCount int `json:"tab_count"`
}
type ProjectList struct {
Projects []Project `json:"projects"`
}
type Chrome struct {
ProjectKey string `json:"project_key"`
Model json.RawMessage `json:"model"`
}
type PaneSnapshot struct {
PaneID string `json:"pane_id"`
Bytes []byte `json:"bytes"`
}
type PaneChunk struct {
PaneID string `json:"pane_id"`
Bytes []byte `json:"bytes"`
}
type LifecycleKind string
const (
LifecycleSpawned LifecycleKind = "spawned"
LifecycleExited LifecycleKind = "exited"
LifecycleClosed LifecycleKind = "closed"
LifecycleStateChanged LifecycleKind = "state_changed"
)
type Lifecycle struct {
Kind LifecycleKind `json:"kind"`
ProjectKey string `json:"project_key,omitempty"`
ChildID string `json:"child_id,omitempty"`
Child json.RawMessage `json:"child,omitempty"`
State string `json:"state,omitempty"`
}
type Input struct {
PaneID string `json:"pane_id"`
Bytes []byte `json:"bytes"`
}
type Focus struct {
PaneID string `json:"pane_id,omitempty"`
Pad string `json:"pad,omitempty"`
}
type SwitchProject struct {
Key string `json:"key"`
}
type OpenProject struct {
Path string `json:"path"`
}
type PaletteCommand struct {
Kind string `json:"kind"`
Data json.RawMessage `json:"data,omitempty"`
}
type TrustResponse struct {
ProcessID string `json:"process_id"`
Preset string `json:"preset"`
Allow bool `json:"allow"`
}
type Resize struct {
Size Size `json:"size"`
}
+67
View File
@@ -0,0 +1,67 @@
package protocol
import (
"sync"
)
const defaultLoopbackBuffer = 64
// NewLoopbackPair returns connected in-process transports. Frames cross the
// same Send/Recv boundary as network transports, but payload bytes are passed
// directly without JSON re-encoding.
func NewLoopbackPair() (client Transport, daemon Transport) {
c2d := make(chan Frame, defaultLoopbackBuffer)
d2c := make(chan Frame, defaultLoopbackBuffer)
return &loopbackTransport{send: c2d, recv: d2c}, &loopbackTransport{send: d2c, recv: c2d}
}
type loopbackTransport struct {
send chan<- Frame
recv <-chan Frame
once sync.Once
done chan struct{}
}
func (t *loopbackTransport) init() {
if t.done == nil {
t.done = make(chan struct{})
}
}
func (t *loopbackTransport) Send(f Frame) error {
t.init()
select {
case <-t.done:
return ErrTransportClosed
case t.send <- cloneFrame(f):
return nil
}
}
func (t *loopbackTransport) Recv() (Frame, error) {
t.init()
select {
case <-t.done:
return Frame{}, ErrTransportClosed
case f, ok := <-t.recv:
if !ok {
return Frame{}, ErrTransportClosed
}
return f, nil
}
}
func (t *loopbackTransport) Close() error {
t.init()
t.once.Do(func() {
close(t.done)
})
return nil
}
func cloneFrame(f Frame) Frame {
if len(f.Payload) > 0 {
f.Payload = append([]byte(nil), f.Payload...)
}
return f
}
+51
View File
@@ -0,0 +1,51 @@
package protocol
import "testing"
func TestLoopbackUsesFramePayload(t *testing.T) {
client, daemon := NewLoopbackPair()
defer client.Close()
defer daemon.Close()
sent, err := NewFrame(FrameInput, Input{PaneID: "p_123456", Bytes: []byte("hello")})
if err != nil {
t.Fatalf("NewFrame: %v", err)
}
if err := client.Send(sent); err != nil {
t.Fatalf("Send: %v", err)
}
got, err := daemon.Recv()
if err != nil {
t.Fatalf("Recv: %v", err)
}
if got.Type != FrameInput {
t.Fatalf("type = %q, want %q", got.Type, FrameInput)
}
payload, err := Decode[Input](got)
if err != nil {
t.Fatalf("Decode: %v", err)
}
if payload.PaneID != "p_123456" || string(payload.Bytes) != "hello" {
t.Fatalf("payload = %#v", payload)
}
}
func TestLoopbackCopiesPayloadOnSend(t *testing.T) {
client, daemon := NewLoopbackPair()
defer client.Close()
defer daemon.Close()
f := Frame{Type: FramePaneChunk, Payload: []byte(`{"pane_id":"p","bytes":"aGVsbG8="}`)}
if err := client.Send(f); err != nil {
t.Fatalf("Send: %v", err)
}
f.Payload[0] = 'x'
got, err := daemon.Recv()
if err != nil {
t.Fatalf("Recv: %v", err)
}
if got.Payload[0] != '{' {
t.Fatalf("payload was retained instead of copied: %q", string(got.Payload))
}
}
+73
View File
@@ -0,0 +1,73 @@
package protocol
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net"
)
var ErrTransportClosed = errors.New("protocol: transport closed")
// Transport carries framed daemon/client protocol messages.
type Transport interface {
Send(Frame) error
Recv() (Frame, error)
Close() error
}
// ConnTransport is a JSON-lines implementation over a stream connection.
type ConnTransport struct {
conn net.Conn
r *bufio.Reader
w *bufio.Writer
}
func NewConnTransport(conn net.Conn) *ConnTransport {
return &ConnTransport{
conn: conn,
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
}
}
func (t *ConnTransport) Send(f Frame) error {
if t == nil || t.conn == nil {
return ErrTransportClosed
}
b, err := json.Marshal(f)
if err != nil {
return fmt.Errorf("protocol: encode frame: %w", err)
}
if _, err := t.w.Write(append(b, '\n')); err != nil {
return err
}
return t.w.Flush()
}
func (t *ConnTransport) Recv() (Frame, error) {
if t == nil || t.conn == nil {
return Frame{}, ErrTransportClosed
}
line, err := t.r.ReadBytes('\n')
if err != nil {
if errors.Is(err, io.EOF) {
return Frame{}, ErrTransportClosed
}
return Frame{}, err
}
var f Frame
if err := json.Unmarshal(line, &f); err != nil {
return Frame{}, fmt.Errorf("protocol: decode frame: %w", err)
}
return f, nil
}
func (t *ConnTransport) Close() error {
if t == nil || t.conn == nil {
return nil
}
return t.conn.Close()
}
+7 -3
View File
@@ -6,6 +6,7 @@ import (
"io"
"os"
"os/exec"
"syscall"
cpty "github.com/creack/pty"
)
@@ -24,9 +25,8 @@ func Start(argv []string, env []string, workDir string, cols, rows uint16) (*PTY
return nil, fmt.Errorf("pty: empty argv")
}
cmd := exec.Command(argv[0], argv[1:]...)
if workDir != "" {
cmd.Dir = workDir
}
cmd.Dir = workDir
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true}
if env != nil {
cmd.Env = ensureTerm(env)
} else {
@@ -91,6 +91,10 @@ func (p *PTY) Close() error {
p.master = nil
}
if p.cmd != nil && p.cmd.Process != nil {
pid := p.cmd.Process.Pid
if pid > 0 {
_ = syscall.Kill(-pid, syscall.SIGKILL)
}
_ = p.cmd.Process.Kill()
}
return firstErr
+59 -15
View File
@@ -1,22 +1,29 @@
package pty
import (
"io"
"bytes"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
func TestStartHonorsWorkDir(t *testing.T) {
func TestStartUsesWorkDir(t *testing.T) {
dir := t.TempDir()
p, err := Start([]string{"sh", "-lc", "pwd"}, nil, dir, 80, 24)
p, err := Start([]string{"sh", "-c", "pwd"}, nil, dir, 80, 24)
if err != nil {
t.Fatalf("start: %v", err)
t.Fatalf("Start: %v", err)
}
defer p.Close()
var out strings.Builder
var out bytes.Buffer
buf := make([]byte, 256)
for {
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
n, err := p.Read(buf)
if n > 0 {
out.Write(buf[:n])
@@ -25,16 +32,53 @@ func TestStartHonorsWorkDir(t *testing.T) {
}
}
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "input/output error") {
break
}
t.Fatalf("read: %v", err)
break
}
}
if err := p.Wait(); err != nil {
t.Fatalf("wait: %v", err)
}
if got := out.String(); !strings.Contains(got, dir) {
t.Fatalf("pwd output %q does not contain %q", got, dir)
_ = p.Wait()
if got := strings.TrimSpace(out.String()); got != dir {
t.Fatalf("pwd output = %q, want %q", got, dir)
}
}
func TestCloseKillsProcessGroup(t *testing.T) {
dir := t.TempDir()
pidFile := filepath.Join(dir, "sleep.pid")
env := append(os.Environ(), "PIDFILE="+pidFile)
p, err := Start([]string{"sh", "-c", "sleep 30 & echo $! > \"$PIDFILE\"; wait"}, env, "", 80, 24)
if err != nil {
t.Fatalf("Start: %v", err)
}
deadline := time.Now().Add(5 * time.Second)
var childPID int
for time.Now().Before(deadline) {
b, err := os.ReadFile(pidFile)
if err == nil {
childPID, _ = strconv.Atoi(strings.TrimSpace(string(b)))
if childPID > 0 {
break
}
}
time.Sleep(20 * time.Millisecond)
}
if childPID <= 0 {
_ = p.Close()
t.Fatalf("background child pid was not written")
}
if err := p.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
_ = p.Wait()
deadline = time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
err := syscall.Kill(childPID, 0)
if errors.Is(err, syscall.ESRCH) {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("background child pid %d still exists after PTY.Close", childPID)
}
-264
View File
@@ -1,264 +0,0 @@
// Package task stores manual project-local tasks and the worktrees agents
// register while working on those tasks.
package task
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// Task is one manual project-local task.
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Worktrees []Worktree `json:"worktrees,omitempty"`
}
// Worktree is a git worktree path registered by a task-bound agent.
type Worktree struct {
Path string `json:"path"`
Branch string `json:"branch,omitempty"`
CreatedByProcessID string `json:"created_by_process_id,omitempty"`
RegisteredAt string `json:"registered_at"`
}
// Store is one project's tasks file. Safe for concurrent use.
type Store struct {
path string
mu sync.Mutex
tasks map[string]Task
order []string
}
// Open loads or creates the task store for projectKey.
func Open(projectKey string) (*Store, error) {
if projectKey == "" {
return nil, errors.New("task.Open: empty project key")
}
base, err := dataDir()
if err != nil {
return nil, err
}
dir := filepath.Join(base, "projects", projectKey)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, fmt.Errorf("task: mkdir %s: %w", dir, err)
}
path := filepath.Join(dir, "tasks.json")
s := &Store{path: path, tasks: make(map[string]Task)}
if err := s.loadLocked(); err != nil {
return nil, err
}
return s, nil
}
func dataDir() (string, error) {
if h := os.Getenv("XDG_DATA_HOME"); h != "" {
return filepath.Join(h, "patterm"), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".local", "share", "patterm"), nil
}
// Path returns the on-disk file path. Used by tests and diagnostics.
func (s *Store) Path() string { return s.path }
// List returns tasks in creation order.
func (s *Store) List() []Task {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Task, 0, len(s.order))
for _, id := range s.order {
if t, ok := s.tasks[id]; ok {
out = append(out, cloneTask(t))
}
}
return out
}
// Get returns one task by id.
func (s *Store) Get(id string) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[id]
if !ok {
return Task{}, false
}
return cloneTask(t), true
}
// Create inserts a new task with title.
func (s *Store) Create(title string) (Task, error) {
title = strings.TrimSpace(title)
if title == "" {
return Task{}, errors.New("task.Create: empty title")
}
s.mu.Lock()
defer s.mu.Unlock()
now := timestamp()
t := Task{ID: s.mintIDLocked(), Title: title, CreatedAt: now, UpdatedAt: now}
s.tasks[t.ID] = t
s.order = append(s.order, t.ID)
if err := s.saveLocked(); err != nil {
return Task{}, err
}
return cloneTask(t), nil
}
// Rename updates a task title.
func (s *Store) Rename(id, title string) (Task, error) {
title = strings.TrimSpace(title)
if title == "" {
return Task{}, errors.New("task.Rename: empty title")
}
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[id]
if !ok {
return Task{}, fmt.Errorf("task.Rename: no such task %q", id)
}
t.Title = title
t.UpdatedAt = timestamp()
s.tasks[id] = t
if err := s.saveLocked(); err != nil {
return Task{}, err
}
return cloneTask(t), nil
}
// RegisterWorktree records or updates a worktree for a task. Paths are
// de-duplicated by cleaned absolute path.
func (s *Store) RegisterWorktree(taskID string, wt Worktree) (Task, error) {
path := strings.TrimSpace(wt.Path)
if path == "" {
return Task{}, errors.New("task.RegisterWorktree: empty path")
}
if !filepath.IsAbs(path) {
abs, err := filepath.Abs(path)
if err != nil {
return Task{}, err
}
path = abs
}
wt.Path = filepath.Clean(path)
wt.Branch = strings.TrimSpace(wt.Branch)
if wt.RegisteredAt == "" {
wt.RegisteredAt = timestamp()
}
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[taskID]
if !ok {
return Task{}, fmt.Errorf("task.RegisterWorktree: no such task %q", taskID)
}
replaced := false
for i, existing := range t.Worktrees {
if filepath.Clean(existing.Path) == wt.Path {
if wt.CreatedByProcessID == "" {
wt.CreatedByProcessID = existing.CreatedByProcessID
}
t.Worktrees[i] = wt
replaced = true
break
}
}
if !replaced {
t.Worktrees = append(t.Worktrees, wt)
}
t.UpdatedAt = timestamp()
s.tasks[taskID] = t
if err := s.saveLocked(); err != nil {
return Task{}, err
}
return cloneTask(t), nil
}
type fileShape struct {
Tasks []Task `json:"tasks"`
}
func (s *Store) loadLocked() error {
b, err := os.ReadFile(s.path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("task: read %s: %w", s.path, err)
}
if len(b) == 0 {
return nil
}
var f fileShape
if err := json.Unmarshal(b, &f); err != nil {
return fmt.Errorf("task: parse %s: %w", s.path, err)
}
for _, t := range f.Tasks {
if t.ID == "" || strings.TrimSpace(t.Title) == "" {
continue
}
t.Title = strings.TrimSpace(t.Title)
if _, exists := s.tasks[t.ID]; !exists {
s.order = append(s.order, t.ID)
}
s.tasks[t.ID] = cloneTask(t)
}
return nil
}
func (s *Store) saveLocked() error {
out := make([]Task, 0, len(s.tasks))
for _, id := range s.order {
if t, ok := s.tasks[id]; ok {
out = append(out, cloneTask(t))
}
}
body, err := json.MarshalIndent(fileShape{Tasks: out}, "", " ")
if err != nil {
return err
}
body = append(body, '\n')
tmp := s.path + ".tmp"
if err := os.WriteFile(tmp, body, 0o600); err != nil {
return fmt.Errorf("task: write %s: %w", tmp, err)
}
if err := os.Rename(tmp, s.path); err != nil {
return fmt.Errorf("task: rename %s: %w", s.path, err)
}
return nil
}
func (s *Store) mintIDLocked() string {
for {
var b [4]byte
if _, err := rand.Read(b[:]); err != nil {
return fmt.Sprintf("task_%d", time.Now().UnixNano())
}
id := "task_" + hex.EncodeToString(b[:])
if _, exists := s.tasks[id]; !exists {
return id
}
}
}
func cloneTask(t Task) Task {
if t.Worktrees != nil {
t.Worktrees = append([]Worktree(nil), t.Worktrees...)
}
return t
}
func timestamp() string { return time.Now().UTC().Format(time.RFC3339) }
-113
View File
@@ -1,113 +0,0 @@
package task
import (
"os"
"path/filepath"
"testing"
)
func TestCreateListAndReload(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_DATA_HOME", dir)
s1, err := Open("projkey")
if err != nil {
t.Fatalf("open: %v", err)
}
created, err := s1.Create(" Ship task sidebar ")
if err != nil {
t.Fatalf("create: %v", err)
}
if created.ID == "" || created.Title != "Ship task sidebar" || created.CreatedAt == "" || created.UpdatedAt == "" {
t.Fatalf("created task incomplete: %+v", created)
}
s2, err := Open("projkey")
if err != nil {
t.Fatalf("reopen: %v", err)
}
got := s2.List()
if len(got) != 1 {
t.Fatalf("tasks len = %d, want 1 (%v)", len(got), got)
}
if got[0].ID != created.ID || got[0].Title != "Ship task sidebar" {
t.Fatalf("reload mismatch: got %+v want %+v", got[0], created)
}
if _, err := os.Stat(s2.Path()); err != nil {
t.Fatalf("stat tasks.json: %v", err)
}
}
func TestCreateRequiresTitle(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
s, err := Open("projkey")
if err != nil {
t.Fatalf("open: %v", err)
}
if _, err := s.Create(" "); err == nil {
t.Fatalf("create with empty title should fail")
}
}
func TestRenameTask(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
s, err := Open("projkey")
if err != nil {
t.Fatalf("open: %v", err)
}
created, err := s.Create("Old")
if err != nil {
t.Fatalf("create: %v", err)
}
renamed, err := s.Rename(created.ID, "New")
if err != nil {
t.Fatalf("rename: %v", err)
}
if renamed.Title != "New" {
t.Fatalf("title = %q, want New", renamed.Title)
}
got, ok := s.Get(created.ID)
if !ok || got.Title != "New" {
t.Fatalf("get after rename = %+v, %v", got, ok)
}
}
func TestRegisterWorktreeDedupesByPath(t *testing.T) {
t.Setenv("XDG_DATA_HOME", t.TempDir())
s, err := Open("projkey")
if err != nil {
t.Fatalf("open: %v", err)
}
task, err := s.Create("Worktree task")
if err != nil {
t.Fatalf("create: %v", err)
}
path := filepath.Join(t.TempDir(), "repo", "..", "repo")
updated, err := s.RegisterWorktree(task.ID, Worktree{Path: path, Branch: "one", CreatedByProcessID: "p1"})
if err != nil {
t.Fatalf("register: %v", err)
}
if len(updated.Worktrees) != 1 {
t.Fatalf("worktrees len = %d, want 1", len(updated.Worktrees))
}
clean := filepath.Clean(path)
if updated.Worktrees[0].Path != clean {
t.Fatalf("path = %q, want %q", updated.Worktrees[0].Path, clean)
}
updated, err = s.RegisterWorktree(task.ID, Worktree{Path: clean, Branch: "two"})
if err != nil {
t.Fatalf("register duplicate: %v", err)
}
if len(updated.Worktrees) != 1 {
t.Fatalf("duplicate should replace, got %+v", updated.Worktrees)
}
if got := updated.Worktrees[0]; got.Branch != "two" || got.CreatedByProcessID != "p1" {
t.Fatalf("duplicate replace mismatch: %+v", got)
}
}
func TestOpenRequiresProjectKey(t *testing.T) {
if _, err := Open(""); err == nil {
t.Fatalf("open with empty project key should fail")
}
}