Add task sidebar workflow
This commit is contained in:
+333
-17
@@ -21,6 +21,7 @@ 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"
|
||||
)
|
||||
@@ -81,6 +82,11 @@ 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.
|
||||
@@ -129,7 +135,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, launcher, presets, trustStore, layout.childCols(), layout.childRows())
|
||||
host := newToolHost(sess, pads, taskStore, launcher, presets, trustStore, layout.childCols(), layout.childRows())
|
||||
mcpSrv.SetHost(host)
|
||||
|
||||
var restoreState *term.State
|
||||
@@ -166,6 +172,7 @@ func Run(ctx context.Context, opts Options) error {
|
||||
presets: presets,
|
||||
launcher: launcher,
|
||||
pads: pads,
|
||||
tasks: taskStore,
|
||||
chromeWake: make(chan struct{}, 1),
|
||||
trust: trustStore,
|
||||
timers: host.timers,
|
||||
@@ -194,6 +201,7 @@ 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)
|
||||
@@ -402,6 +410,7 @@ type uiState struct {
|
||||
presets preset.Set
|
||||
launcher *Launcher
|
||||
pads *scratchpad.Store
|
||||
tasks *task.Store
|
||||
trust *trust.Store
|
||||
timers *timerManager
|
||||
|
||||
@@ -417,6 +426,11 @@ 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
|
||||
@@ -503,8 +517,10 @@ 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
|
||||
padsCacheMu sync.Mutex
|
||||
padsCache []scratchpad.Entry
|
||||
tasksCacheMu sync.Mutex
|
||||
tasksCache []task.Task
|
||||
|
||||
lastExit atomic.Int32
|
||||
}
|
||||
@@ -585,8 +601,9 @@ func (st *uiState) focusProcess(processID string) {
|
||||
layout := st.layoutSnapshot()
|
||||
onAlt := childIsOnAlt(c)
|
||||
st.mu.Lock()
|
||||
leavingPad := st.focusedPad != ""
|
||||
leavingStaticView := st.focusedPad != "" || st.focusedTaskID != ""
|
||||
st.focusedPad = ""
|
||||
st.focusedTaskID = ""
|
||||
st.focusedID = c.ID
|
||||
st.focusedName = c.DisplayName()
|
||||
st.updateActiveAgentLocked(c)
|
||||
@@ -597,7 +614,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 leavingPad {
|
||||
if leavingStaticView {
|
||||
st.clearViewportArea()
|
||||
}
|
||||
st.repaintFocused()
|
||||
@@ -656,6 +673,7 @@ func (st *uiState) focusScratchpad(name string) {
|
||||
st.padOffsetName = name
|
||||
}
|
||||
st.focusedPad = name
|
||||
st.focusedTaskID = ""
|
||||
st.focusedID = ""
|
||||
st.focusedName = name
|
||||
st.renderer = nil
|
||||
@@ -667,6 +685,29 @@ 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.
|
||||
@@ -691,8 +732,11 @@ func (st *uiState) clearViewportArea() {
|
||||
func (st *uiState) repaintFocusedWithChrome() {
|
||||
st.mu.Lock()
|
||||
padFocused := st.focusedPad != ""
|
||||
taskFocused := st.focusedTaskID != ""
|
||||
st.mu.Unlock()
|
||||
if padFocused {
|
||||
if taskFocused {
|
||||
st.repaintFocusedTask()
|
||||
} else if padFocused {
|
||||
st.repaintFocusedPad()
|
||||
} else {
|
||||
st.repaintFocused()
|
||||
@@ -786,6 +830,18 @@ 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
|
||||
@@ -795,6 +851,15 @@ 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
|
||||
@@ -810,6 +875,10 @@ 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()
|
||||
}
|
||||
@@ -823,6 +892,7 @@ func (st *uiState) OnChildSpawned(c *Child) {
|
||||
onAlt := childIsOnAlt(c)
|
||||
st.mu.Lock()
|
||||
st.focusedPad = ""
|
||||
st.focusedTaskID = ""
|
||||
st.focusedID = c.ID
|
||||
st.focusedName = c.DisplayName()
|
||||
st.updateActiveAgentLocked(c)
|
||||
@@ -833,6 +903,10 @@ 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()
|
||||
}
|
||||
@@ -915,6 +989,10 @@ func (st *uiState) OnChildExited(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()
|
||||
}
|
||||
@@ -1158,6 +1236,40 @@ 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,
|
||||
@@ -1269,6 +1381,7 @@ 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)
|
||||
@@ -1297,10 +1410,24 @@ func (st *uiState) drawStatusLine() {
|
||||
owner = "you have control"
|
||||
}
|
||||
}
|
||||
if focusTaskID != "" && focusName == "" {
|
||||
focusName = st.taskTitle(focusTaskID)
|
||||
}
|
||||
left := ""
|
||||
if focusName != "" {
|
||||
if focusTaskID != "" && focusName != "" {
|
||||
left = "task: " + focusName
|
||||
} else 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
|
||||
@@ -1369,7 +1496,7 @@ func (st *uiState) drawStatusLine() {
|
||||
// child is focused.
|
||||
func (st *uiState) renderEmptyState() {
|
||||
layout := st.layoutSnapshot()
|
||||
line := "Press Ctrl-K to spawn an agent or process"
|
||||
line := "Press Ctrl-K to create a task or spawn an agent/process"
|
||||
row := int(layout.mainTop) + (int(layout.childRows()) / 2)
|
||||
col := int(layout.mainLeft) + ((int(layout.childCols()) - len(line)) / 2)
|
||||
if row < int(layout.mainTop) {
|
||||
@@ -1790,13 +1917,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.activeAgentID, st.padsList(), -1)
|
||||
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.activeAgentID, st.tasksList(), 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.activeAgentID, st.padsList(), +1)
|
||||
pendingNav = nextNavEntry(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.activeAgentID, st.tasksList(), st.padsList(), +1)
|
||||
i += adv
|
||||
break
|
||||
}
|
||||
@@ -1884,6 +2011,8 @@ 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():
|
||||
@@ -1965,7 +2094,7 @@ func (st *uiState) openPaletteLocked() {
|
||||
st.settingsMu.Lock()
|
||||
appSettings := st.settings.clone()
|
||||
st.settingsMu.Unlock()
|
||||
st.palette = newPalette(st.sess.Children(), st.focusedID, st.focusedPad, st.presets, appSettings)
|
||||
st.palette = newPaletteWithTasks(st.sess.Children(), st.focusedID, st.focusedPad, st.focusedTaskID, st.tasksList(), 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
|
||||
@@ -2001,7 +2130,12 @@ 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
|
||||
@@ -2025,7 +2159,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, "", ""); err != nil {
|
||||
if _, err := st.launcher.LaunchAgent(action.preset, action.preset.Name, "", LaunchContext{}); err != nil {
|
||||
st.flashError(fmt.Sprintf("spawn %s: %v", action.preset.Name, err))
|
||||
}
|
||||
|
||||
@@ -2036,14 +2170,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, ""); err != nil {
|
||||
if _, err := st.launcher.LaunchCommandPreset(action.preset, action.preset.Name, LaunchContext{}); 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", "", "", nil); err != nil {
|
||||
if _, err := st.launcher.LaunchTerminal(nil, "terminal", LaunchContext{}, nil); err != nil {
|
||||
st.flashError(fmt.Sprintf("spawn terminal: %v", err))
|
||||
}
|
||||
|
||||
@@ -2061,7 +2195,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, "", "", nil, true)
|
||||
c, err := st.launcher.LaunchCommandArgv([]string{action.command}, display, LaunchContext{}, nil, true)
|
||||
if err != nil {
|
||||
st.flashError(fmt.Sprintf("spawn: %v", err))
|
||||
return
|
||||
@@ -2077,6 +2211,18 @@ 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) {
|
||||
@@ -2085,8 +2231,9 @@ func (st *uiState) closePalette(action paletteAction) {
|
||||
}
|
||||
layout := st.layoutSnapshot()
|
||||
st.mu.Lock()
|
||||
leavingPad := st.focusedPad != ""
|
||||
leavingStaticView := st.focusedPad != "" || st.focusedTaskID != ""
|
||||
st.focusedPad = ""
|
||||
st.focusedTaskID = ""
|
||||
st.focusedID = action.childID
|
||||
st.focusedName = c.DisplayName()
|
||||
st.updateActiveAgentLocked(c)
|
||||
@@ -2095,7 +2242,7 @@ func (st *uiState) closePalette(action paletteAction) {
|
||||
// Switching from a pad to a child: wipe the pad body so the
|
||||
// child's snapshot paints onto a clean canvas, mirroring
|
||||
// focusProcess.
|
||||
if leavingPad {
|
||||
if leavingStaticView {
|
||||
st.clearViewportArea()
|
||||
}
|
||||
st.repaintFocused()
|
||||
@@ -2162,6 +2309,70 @@ 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
|
||||
@@ -2459,9 +2670,14 @@ 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
|
||||
}
|
||||
@@ -2492,6 +2708,106 @@ 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
|
||||
|
||||
@@ -83,10 +83,10 @@ func TestCanonicalizeTerminalTextMaxLines(t *testing.T) {
|
||||
|
||||
func TestGetProcessOutputStreamCanonicalByDefault(t *testing.T) {
|
||||
sess := NewSession(t.TempDir(), "test")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "")
|
||||
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, preset.Set{}, nil, 80, 24)
|
||||
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 {
|
||||
@@ -105,10 +105,10 @@ func TestGetProcessOutputStreamCanonicalByDefault(t *testing.T) {
|
||||
|
||||
func TestGetProcessOutputRawReturnsStreamBytes(t *testing.T) {
|
||||
sess := NewSession(t.TempDir(), "test")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
|
||||
addChild(sess, c)
|
||||
c.recordWrite([]byte("\x1b[31mred\x1b[0m"))
|
||||
host := newToolHost(sess, nil, nil, preset.Set{}, nil, 80, 24)
|
||||
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 {
|
||||
@@ -130,10 +130,10 @@ func TestGetProcessOutputRawReturnsStreamBytes(t *testing.T) {
|
||||
|
||||
func TestGetProcessOutputCanonicalAfterRawRead(t *testing.T) {
|
||||
sess := NewSession(t.TempDir(), "test")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "")
|
||||
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, preset.Set{}, nil, 80, 24)
|
||||
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)
|
||||
@@ -149,10 +149,10 @@ func TestGetProcessOutputCanonicalAfterRawRead(t *testing.T) {
|
||||
|
||||
func TestGetProcessOutputIncludeMetaRestoresFields(t *testing.T) {
|
||||
sess := NewSession(t.TempDir(), "test")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "")
|
||||
c := newChildEntry("p1", "proc", KindCommand, nil, nil, "", "", "", "")
|
||||
addChild(sess, c)
|
||||
c.recordWrite([]byte("ok"))
|
||||
host := newToolHost(sess, nil, nil, preset.Set{}, nil, 80, 24)
|
||||
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 {
|
||||
|
||||
@@ -77,6 +77,7 @@ 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
|
||||
@@ -191,7 +192,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, workDir, presetRef string) *Child {
|
||||
func newChildEntry(id, name string, kind ChildKind, argv, env []string, parentID, taskID, workDir, presetRef string) *Child {
|
||||
c := &Child{
|
||||
ID: id,
|
||||
Name: name,
|
||||
@@ -200,6 +201,7 @@ 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),
|
||||
}
|
||||
@@ -228,7 +230,7 @@ func (c *Child) startPTY(cols, rows uint16) (uint64, error) {
|
||||
}
|
||||
starting := StatusStarting
|
||||
c.status.Store(&starting)
|
||||
p, err := pkgpty.Start(c.Argv, c.Env, cols, rows)
|
||||
p, err := pkgpty.Start(c.Argv, c.Env, c.WorkDir, cols, rows)
|
||||
if err != nil {
|
||||
em.Close()
|
||||
errored := StatusErrored
|
||||
|
||||
+132
-26
@@ -2,6 +2,7 @@ package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -12,6 +13,7 @@ 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"
|
||||
)
|
||||
@@ -41,11 +43,16 @@ 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
|
||||
@@ -61,6 +68,7 @@ type toolHost struct {
|
||||
focus focusSink
|
||||
prompter trustPrompter
|
||||
scratch scratchpadSink
|
||||
taskUI taskSink
|
||||
|
||||
timers *timerManager
|
||||
}
|
||||
@@ -76,10 +84,11 @@ const (
|
||||
maxSearchMatches = 50
|
||||
)
|
||||
|
||||
func newToolHost(sess *Session, pads *scratchpad.Store, launcher *Launcher, presets preset.Set, tr *trust.Store, cols, rows uint16) *toolHost {
|
||||
func newToolHost(sess *Session, pads *scratchpad.Store, tasks *task.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,
|
||||
@@ -157,6 +166,21 @@ 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
|
||||
// ───────────────────────────────────────────────────────────────────
|
||||
@@ -176,8 +200,14 @@ func (h *toolHost) SpawnAgent(callerID string, args mcp.SpawnAgentArgs) (mcp.Pro
|
||||
if display == "" {
|
||||
display = args.Agent
|
||||
}
|
||||
prompt := wrapSubAgentPrompt(args.AgentInstructions, h.sess.FindChild(callerID) != nil)
|
||||
c, err := h.launcher.LaunchAgent(p, display, prompt, callerID)
|
||||
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)
|
||||
if err != nil {
|
||||
return mcp.ProcessInfo{}, err
|
||||
}
|
||||
@@ -193,8 +223,12 @@ 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), callerID, args.WorkingDir, env)
|
||||
c, err := h.launcher.LaunchTerminal(args.Argv, h.terminalName(args.Name), ctx, env)
|
||||
if err != nil {
|
||||
return mcp.ProcessInfo{}, err
|
||||
}
|
||||
@@ -215,7 +249,7 @@ func (h *toolHost) SpawnProcess(callerID string, args mcp.SpawnProcessArgs) (mcp
|
||||
if display == "" {
|
||||
display = ps.Name
|
||||
}
|
||||
c, err := h.launcher.LaunchCommandPreset(ps, display, callerID)
|
||||
c, err := h.launcher.LaunchCommandPreset(ps, display, ctx)
|
||||
if err != nil {
|
||||
return mcp.ProcessInfo{}, err
|
||||
}
|
||||
@@ -229,7 +263,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, callerID, args.WorkingDir, env, args.Shell)
|
||||
c, err := h.launcher.LaunchCommandArgv(args.Argv, display, ctx, env, args.Shell)
|
||||
if err != nil {
|
||||
return mcp.ProcessInfo{}, err
|
||||
}
|
||||
@@ -368,12 +402,16 @@ func (h *toolHost) GetProjectStatus(callerID string, includeTools bool) (mcp.Pro
|
||||
caller := h.WhoAmI(callerID, includeTools)
|
||||
processes := h.ListProcesses(callerID, "")
|
||||
pads, _ := h.pads.List()
|
||||
return mcp.ProjectStatus{
|
||||
status := mcp.ProjectStatus{
|
||||
Project: caller.Project,
|
||||
Caller: caller,
|
||||
Processes: processes,
|
||||
Scratchpads: pads,
|
||||
}, nil
|
||||
}
|
||||
if caller.Task != nil {
|
||||
status.Task = caller.Task
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (h *toolHost) GetProcessOutput(callerID string, args mcp.ProcessOutputArgs) (mcp.ProcessOutput, error) {
|
||||
@@ -925,17 +963,59 @@ 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)
|
||||
w := mcp.WhoAmI{
|
||||
ProcessID: callerID,
|
||||
Role: h.CallerRole(callerID),
|
||||
Role: role,
|
||||
Project: mcp.ProjectMeta{
|
||||
Path: h.sess.projectDir,
|
||||
Key: h.sess.projectKey,
|
||||
},
|
||||
}
|
||||
if taskBound {
|
||||
w.Task = &taskInfo
|
||||
}
|
||||
if includeTools {
|
||||
w.AvailableTools = availableToolsForRole(h.CallerRole(callerID))
|
||||
w.AvailableTools = availableToolsForRole(role, taskBound)
|
||||
}
|
||||
if c := h.sess.FindChild(callerID); c != nil {
|
||||
w.Name = c.DisplayName()
|
||||
@@ -976,6 +1056,27 @@ 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
|
||||
@@ -1034,23 +1135,25 @@ func (h *toolHost) askForTrust(callerID, presetName, reason string) {
|
||||
h.prompter.promptTrust(callerID, presetName, reason)
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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').]")
|
||||
}
|
||||
if instructions == "" {
|
||||
return ""
|
||||
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)))
|
||||
}
|
||||
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
|
||||
if instructions != "" {
|
||||
parts = append(parts, instructions)
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
func sanitizePromptText(s string) string {
|
||||
return strings.NewReplacer("\r", " ", "\n", " ", `"`, "'").Replace(s)
|
||||
}
|
||||
|
||||
// applyChromeTrim deletes lines matching any of the given regexes.
|
||||
@@ -1273,7 +1376,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) []string {
|
||||
func availableToolsForRole(role mcp.CallerRole, taskBound bool) []string {
|
||||
tools := []string{
|
||||
"spawn_process", "start_process", "restart_process", "stop_process",
|
||||
"close_process", "rename_process", "select_process",
|
||||
@@ -1289,6 +1392,9 @@ func availableToolsForRole(role mcp.CallerRole) []string {
|
||||
if role == mcp.RoleOrchestrator {
|
||||
tools = append([]string{"spawn_agent"}, tools...)
|
||||
}
|
||||
if taskBound {
|
||||
tools = append(tools, "task_register_worktree")
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
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
|
||||
@@ -100,8 +103,8 @@ func TestClassifySendMessageNilCallerRejectsNonTopLevelTarget(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapSubAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
|
||||
out := wrapSubAgentPrompt("ship feature X", true)
|
||||
func TestBuildAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
|
||||
out := buildAgentPrompt("ship feature X", true, nil)
|
||||
if !strings.HasPrefix(out, "[system:") {
|
||||
t.Fatalf("expected prepended [system: …] block, got %q", out)
|
||||
}
|
||||
@@ -119,18 +122,18 @@ func TestWrapSubAgentPromptPrependsSystemBlockWhenParented(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapSubAgentPromptPassthroughWhenNoParent(t *testing.T) {
|
||||
out := wrapSubAgentPrompt("hello", false)
|
||||
func TestBuildAgentPromptPassthroughWhenNoParent(t *testing.T) {
|
||||
out := buildAgentPrompt("hello", false, nil)
|
||||
if out != "hello" {
|
||||
t.Fatalf("expected passthrough for top-level spawn, got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapSubAgentPromptEmptyStaysEmpty(t *testing.T) {
|
||||
func TestBuildAgentPromptEmptyStaysEmpty(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 := wrapSubAgentPrompt("", true); out != "" {
|
||||
if out := buildAgentPrompt("", true, nil); out != "" {
|
||||
t.Fatalf("empty instructions should stay empty, got %q", out)
|
||||
}
|
||||
}
|
||||
@@ -215,7 +218,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)
|
||||
tools := availableToolsForRole(role, false)
|
||||
for _, w := range want {
|
||||
if !containsString(tools, w) {
|
||||
t.Fatalf("role %q missing %q in available tools: %v", role, w, tools)
|
||||
@@ -224,6 +227,95 @@ 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.
|
||||
|
||||
+33
-13
@@ -24,6 +24,12 @@ 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 {
|
||||
@@ -47,7 +53,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, parentID string) (*Child, error) {
|
||||
func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt string, ctx LaunchContext) (*Child, error) {
|
||||
if p.Kind != preset.KindAgent {
|
||||
return nil, fmt.Errorf("launch: %q is not an agent preset", p.Name)
|
||||
}
|
||||
@@ -131,7 +137,9 @@ func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt, par
|
||||
Argv: argv,
|
||||
Env: env,
|
||||
Name: displayName,
|
||||
ParentID: parentID,
|
||||
ParentID: ctx.ParentID,
|
||||
TaskID: ctx.TaskID,
|
||||
WorkDir: firstNonEmpty(ctx.WorkDir, p.WorkingDir),
|
||||
PresetRef: p.Name,
|
||||
Identity: identity,
|
||||
CleanupPaths: cleanupPaths,
|
||||
@@ -163,7 +171,7 @@ func (l *Launcher) LaunchAgent(p *preset.Preset, displayName, initialPrompt, par
|
||||
// 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, parentID string) (*Child, error) {
|
||||
func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName string, ctx LaunchContext) (*Child, error) {
|
||||
if p.Kind != preset.KindCommand {
|
||||
return nil, fmt.Errorf("launch: %q is not a command preset", p.Name)
|
||||
}
|
||||
@@ -177,8 +185,9 @@ func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName, parentID s
|
||||
Argv: p.ResolvedArgv(),
|
||||
Env: env,
|
||||
Name: displayName,
|
||||
ParentID: parentID,
|
||||
WorkDir: p.WorkingDir,
|
||||
ParentID: ctx.ParentID,
|
||||
TaskID: ctx.TaskID,
|
||||
WorkDir: firstNonEmpty(ctx.WorkDir, p.WorkingDir),
|
||||
PresetRef: p.Name,
|
||||
IdleDetection: resolveIdleDetection(p.IdleDetection),
|
||||
}, cols, rows)
|
||||
@@ -191,7 +200,7 @@ func (l *Launcher) LaunchCommandPreset(p *preset.Preset, displayName, parentID s
|
||||
// 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, parentID, workDir string, env []string, shell bool) (*Child, error) {
|
||||
func (l *Launcher) LaunchCommandArgv(argv []string, displayName string, ctx LaunchContext, env []string, shell bool) (*Child, error) {
|
||||
if shell && len(argv) > 0 {
|
||||
argv = []string{"sh", "-lc", strings.Join(argv, " ")}
|
||||
}
|
||||
@@ -204,8 +213,9 @@ func (l *Launcher) LaunchCommandArgv(argv []string, displayName, parentID, workD
|
||||
Argv: argv,
|
||||
Env: env,
|
||||
Name: displayName,
|
||||
ParentID: parentID,
|
||||
WorkDir: workDir,
|
||||
ParentID: ctx.ParentID,
|
||||
TaskID: ctx.TaskID,
|
||||
WorkDir: ctx.WorkDir,
|
||||
}, cols, rows)
|
||||
}
|
||||
|
||||
@@ -223,7 +233,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, "")
|
||||
return l.LaunchCommandPreset(p, e.Name, LaunchContext{})
|
||||
}
|
||||
}
|
||||
// Preset has been deleted since the entry was saved. Fall
|
||||
@@ -233,12 +243,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, "", e.WorkDir, nil, false)
|
||||
return l.LaunchCommandArgv(e.Argv, e.Name, LaunchContext{WorkDir: 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, parentID, workDir string, env []string) (*Child, error) {
|
||||
func (l *Launcher) LaunchTerminal(argv []string, displayName string, ctx LaunchContext, env []string) (*Child, error) {
|
||||
if len(argv) == 0 {
|
||||
sh := os.Getenv("SHELL")
|
||||
if sh == "" {
|
||||
@@ -255,11 +265,21 @@ func (l *Launcher) LaunchTerminal(argv []string, displayName, parentID, workDir
|
||||
Argv: argv,
|
||||
Env: env,
|
||||
Name: displayName,
|
||||
ParentID: parentID,
|
||||
WorkDir: workDir,
|
||||
ParentID: ctx.ParentID,
|
||||
TaskID: ctx.TaskID,
|
||||
WorkDir: ctx.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 {
|
||||
|
||||
@@ -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, preset.Set{}, nil, l.childCols(), l.childRows())
|
||||
host := newToolHost(nil, 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)
|
||||
|
||||
+118
-17
@@ -7,6 +7,7 @@ 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.
|
||||
@@ -35,7 +36,10 @@ type paletteAction struct {
|
||||
// For pad-* actions, the scratchpad name to operate on.
|
||||
padName string
|
||||
|
||||
// For *-rename-submit actions, the user-typed new name.
|
||||
// For task-* actions, the task to operate on.
|
||||
taskID string
|
||||
|
||||
// For *-rename-submit and task-create-submit actions, the user-typed name.
|
||||
newName string
|
||||
|
||||
// For settings actions, the updated settings snapshot to persist.
|
||||
@@ -90,12 +94,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 or child id)
|
||||
// determines what gets renamed; the target name (pad name, task id, or child id)
|
||||
// is carried alongside so closePalette knows what to apply the new
|
||||
// name to.
|
||||
type renameForm struct {
|
||||
name []rune
|
||||
subject string // "pad" | "agent" | "proc"
|
||||
subject string // "pad" | "task" | "task-create" | "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
|
||||
@@ -110,13 +114,16 @@ 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
|
||||
presets preset.Set
|
||||
settings settings
|
||||
query []rune
|
||||
cursor int
|
||||
children []*Child
|
||||
focused string
|
||||
focusedPad string
|
||||
focusedTaskID string
|
||||
tasksEnabled bool
|
||||
tasks []task.Task
|
||||
presets preset.Set
|
||||
settings settings
|
||||
|
||||
items []paletteItem
|
||||
|
||||
@@ -135,9 +142,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"},
|
||||
"sw": {"switch", "task-switch"},
|
||||
"k": {"kill", "agent-close", "proc-stop", "proc-delete"},
|
||||
"sp": {"spawn-agent", "spawn-process", "spawn-terminal", "spawn-process-form"},
|
||||
"sp": {"spawn-agent", "spawn-process", "spawn-terminal", "spawn-process-form", "task-start-agent"},
|
||||
}
|
||||
|
||||
// chipOrder is the cycle order for Tab / Shift-Tab when the user
|
||||
@@ -179,12 +186,35 @@ 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, presets: presets, settings: st}
|
||||
p := &paletteState{children: children, focused: focused, focusedPad: focusedPad, focusedTaskID: focusedTaskID, tasksEnabled: tasks != nil || focusedTaskID != "", tasks: tasks, presets: presets, settings: st}
|
||||
p.rebuild()
|
||||
return p
|
||||
}
|
||||
@@ -259,6 +289,21 @@ 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()
|
||||
@@ -291,13 +336,46 @@ 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 — switch entries for every running child *other than*
|
||||
// Group 1: Open — tasks first, then 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
|
||||
@@ -649,6 +727,16 @@ 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
|
||||
@@ -676,12 +764,16 @@ 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: "Rename",
|
||||
title: title,
|
||||
subjectLine: subjectLine,
|
||||
}
|
||||
}
|
||||
@@ -921,6 +1013,10 @@ 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":
|
||||
@@ -1151,12 +1247,17 @@ func (p *paletteState) selectableIndex() int {
|
||||
}
|
||||
|
||||
// focusedSubject returns the short context string shown in the title
|
||||
// bar — "on: <child>" / "pad: <name>" / "" — so the user knows which
|
||||
// focus the context-section is targeting.
|
||||
// bar — "on: <child>" / "pad: <name>" / "task: <title>" / "" — 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()
|
||||
|
||||
@@ -6,6 +6,7 @@ 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
|
||||
@@ -83,6 +84,54 @@ 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{})
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -116,7 +116,7 @@ func TestToolHostScratchpadDeleteRemovesPadAndRefreshes(t *testing.T) {
|
||||
t.Fatalf("write doomed.md: %v", err)
|
||||
}
|
||||
recorder := &scratchpadChangeRecorder{}
|
||||
host := newToolHost(nil, pads, nil, preset.Set{}, nil, 120, 40)
|
||||
host := newToolHost(nil, pads, nil, nil, preset.Set{}, nil, 120, 40)
|
||||
host.scratch = recorder
|
||||
|
||||
if err := host.ScratchpadDelete("doomed.md"); err != nil {
|
||||
|
||||
@@ -201,6 +201,7 @@ 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
|
||||
@@ -235,7 +236,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.WorkDir, spec.PresetRef)
|
||||
c := newChildEntry(id, spec.Name, spec.Kind, spec.Argv, spec.Env, spec.ParentID, spec.TaskID, spec.WorkDir, spec.PresetRef)
|
||||
if spec.Identity != "" {
|
||||
c.Identity = spec.Identity
|
||||
}
|
||||
|
||||
@@ -168,6 +168,7 @@ 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 {
|
||||
@@ -262,6 +263,42 @@ 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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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
|
||||
|
||||
+23
-13
@@ -1,16 +1,21 @@
|
||||
package app
|
||||
|
||||
import "github.com/hjbdev/patterm/internal/scratchpad"
|
||||
import (
|
||||
"github.com/hjbdev/patterm/internal/scratchpad"
|
||||
"github.com/hjbdev/patterm/internal/task"
|
||||
)
|
||||
|
||||
// navEntry is one row in the unified sidebar navigation list. Exactly
|
||||
// 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".
|
||||
// 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".
|
||||
type navEntry struct {
|
||||
taskID string
|
||||
childID string
|
||||
pad string
|
||||
}
|
||||
|
||||
func (n navEntry) empty() bool { return n.childID == "" && n.pad == "" }
|
||||
func (n navEntry) empty() bool { return n.taskID == "" && n.childID == "" && n.pad == "" }
|
||||
func (n navEntry) isTask() bool { return n.taskID != "" }
|
||||
func (n navEntry) isPad() bool { return n.pad != "" }
|
||||
func (n navEntry) isChild() bool { return n.childID != "" }
|
||||
|
||||
@@ -221,12 +226,14 @@ func sidebarNavList(children []*Child, activeAgentID string) []*Child {
|
||||
return out
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// 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 {
|
||||
flat := sidebarNavList(children, activeAgentID)
|
||||
out := make([]navEntry, 0, len(flat)+len(pads))
|
||||
out := make([]navEntry, 0, len(tasks)+len(flat)+len(pads))
|
||||
for _, t := range tasks {
|
||||
out = append(out, navEntry{taskID: t.ID})
|
||||
}
|
||||
for _, c := range flat {
|
||||
out = append(out, navEntry{childID: c.ID})
|
||||
}
|
||||
@@ -237,15 +244,18 @@ func sidebarNav(children []*Child, activeAgentID string, pads []scratchpad.Entry
|
||||
}
|
||||
|
||||
// nextNavEntry returns the entry `step` positions away from the
|
||||
// current focus in the unified nav list. Either focusChildID or
|
||||
// focusPad will be set (or both empty for "nothing focused yet").
|
||||
// current focus in the unified nav list. Exactly one focus identifier is
|
||||
// usually set (or all empty for "nothing focused yet").
|
||||
// Empty when there's nothing else to land on.
|
||||
func nextNavEntry(children []*Child, focusChildID, focusPad, activeAgentID string, pads []scratchpad.Entry, step int) navEntry {
|
||||
flat := sidebarNav(children, activeAgentID, pads)
|
||||
func nextNavEntry(children []*Child, focusChildID, focusPad, focusTaskID, activeAgentID string, tasks []task.Task, pads []scratchpad.Entry, step int) navEntry {
|
||||
flat := sidebarNav(children, activeAgentID, tasks, 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,6 +1,10 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/hjbdev/patterm/internal/task"
|
||||
)
|
||||
|
||||
func TestVisibleSessionTreeScopesToFocusedRoot(t *testing.T) {
|
||||
root1 := testChild("c1", "root1", "", StatusRunning)
|
||||
@@ -125,6 +129,34 @@ 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)
|
||||
|
||||
Reference in New Issue
Block a user