Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ _Avoid_: feature flag

**Adopted workstream**:
A workstream HomeShell did not create, made up on the fly for sessions a provider reports in a
directory that no workstream claims.
directory that no workstream claims. A folder that is an untracked worktree is never adopted.

### Working directory

Expand All @@ -90,6 +90,11 @@ _Avoid_: isolation mode
A workstream's working directory when it is a **worktree** or a **folder** (copy), not the project
directory itself.

**Untracked worktree**:
A linked git worktree of a project's repository that no workstream works in. HomeShell suggests
adding it; it never adds one on its own.
_Avoid_: orphan worktree, discovered worktree

**Note**:
A Markdown file a workstream keeps in its working directory, readable by the user and by the
agents working there.
Expand Down
4 changes: 3 additions & 1 deletion daemon/internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ func writeProviderError(w http.ResponseWriter, err error) {
errors.Is(err, provider.ErrSessionNeverStarted),
errors.Is(err, provider.ErrSessionNotRestartable),
errors.Is(err, provider.ErrCannotContinue),
errors.Is(err, provider.ErrOptionNotOffered):
errors.Is(err, provider.ErrOptionNotOffered),
// The folder is no suggestion of the project now: added, removed, or never one.
errors.Is(err, provider.ErrNotUntrackedWorktree):
jsonError(w, err.Error(), http.StatusConflict)
case errors.Is(err, provider.ErrConcurrencyLimit), errors.Is(err, provider.ErrSessionStopped),
errors.Is(err, provider.ErrSessionGone),
Expand Down
32 changes: 32 additions & 0 deletions daemon/internal/api/workstreams.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ func init() {
register("POST /api/projects/{projectId}/default-workstream", func(deps Deps) http.HandlerFunc {
return addDefaultWorkstreamHandler(deps)
})
register("POST /api/projects/{projectId}/worktree-workstreams", func(deps Deps) http.HandlerFunc {
return addUntrackedWorktreeHandler(deps)
})
register("POST /api/projects/{projectId}/workstream-draft", func(deps Deps) http.HandlerFunc {
return workstreamDraftHandler(deps)
})
Expand Down Expand Up @@ -76,6 +79,35 @@ func addDefaultWorkstreamHandler(deps Deps) http.HandlerFunc {
}
}

// addUntrackedWorktreeHandler makes a workstream of one of a project's
// untracked worktrees, the one at the body's path.
func addUntrackedWorktreeHandler(deps Deps) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
if deps.Providers == nil {
jsonError(writer, "no providers are available", http.StatusServiceUnavailable)
return
}
var body struct {
Path string `json:"path"`
}
if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
jsonError(writer, "invalid JSON", http.StatusBadRequest)
return
}
path := strings.TrimSpace(body.Path)
if path == "" {
jsonError(writer, "path must not be empty", http.StatusBadRequest)
return
}
added, err := deps.Providers.AddUntrackedWorktree(request.Context(), request.PathValue("projectId"), path)
if err != nil {
writeProviderError(writer, err)
return
}
writeJSON(writer, http.StatusCreated, added)
}
}

// workstreamDraftHandler answers a create's body with what the create would
// derive for the values it leaves blank (name, branch, path), creating nothing.
func workstreamDraftHandler(deps Deps) http.HandlerFunc {
Expand Down
74 changes: 74 additions & 0 deletions daemon/internal/api/workstreams_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -381,3 +384,74 @@ func TestCreatedWorkstreamAppearsOnEventStream(t *testing.T) {
t.Errorf("pushed state lacks the new workstream: %s", update.Data)
}
}

// worktreeHandler builds a handler over a git project proj-git with one linked
// worktree on branch wt-a, and returns the worktree's path.
func worktreeHandler(t *testing.T) (http.Handler, string) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not installed")
}
repo, dir := t.TempDir(), filepath.Join(t.TempDir(), "wt")
for _, args := range [][]string{
{"init", "-q", "-b", "main"},
{"commit", "-q", "--allow-empty", "-m", "initial"},
{"worktree", "add", "-q", "-b", "wt-a", dir},
} {
cmd := exec.Command("git", append([]string{"-C", repo}, args...)...)
cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_SYSTEM=/dev/null",
"GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.com",
"GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.com")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
projectStore := store.NewTestStore(t, []domain.Project{{
ID: "proj-git", Name: "git", Path: repo, GitBacked: true, Workstreams: []domain.Workstream{},
}})
service := provider.NewService(projectStore, provider.NewRegistry(), 0)
service.Reconcile(context.Background())
return handlerForTest(Deps{Version: "test", Store: projectStore, Heartbeat: time.Minute, Providers: service,
Notifications: notify.NewHub()}), dir
}

func TestAddUntrackedWorktree(t *testing.T) {
handler, dir := worktreeHandler(t)
body, _ := json.Marshal(map[string]string{"path": dir})

recorder := do(t, handler, http.MethodPost, "/api/projects/proj-git/worktree-workstreams", string(body))
if recorder.Code != http.StatusCreated {
t.Fatalf("status = %d (%s), want 201", recorder.Code, recorder.Body.String())
}
var added domain.Workstream
if err := json.Unmarshal(recorder.Body.Bytes(), &added); err != nil {
t.Fatal(err)
}
if added.ID == "" || added.Name != "wt-a" || added.WorkingDir != dir {
t.Errorf("workstream = %+v, want wt-a in %s", added, dir)
}
}

func TestAddUntrackedWorktreeRefusals(t *testing.T) {
handler, _ := worktreeHandler(t)
tests := []struct {
name string
body string
want int
}{
{name: "no path", body: `{}`, want: http.StatusBadRequest},
{name: "a blank path", body: `{"path":" "}`, want: http.StatusBadRequest},
{name: "not an untracked worktree", body: `{"path":"/nowhere"}`, want: http.StatusConflict},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := do(t, handler, http.MethodPost, "/api/projects/proj-git/worktree-workstreams", tt.body)
var body struct {
Error string `json:"error"`
}
if recorder.Code != tt.want || json.Unmarshal(recorder.Body.Bytes(), &body) != nil || body.Error == "" {
t.Errorf("status = %d (%s), want %d with an error", recorder.Code, recorder.Body.String(), tt.want)
}
})
}
}
47 changes: 47 additions & 0 deletions daemon/internal/domain/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,28 @@ func (s SessionState) Ended() bool {
return s == SessionDone || s == SessionStopped
}

// AllTerminal reports whether every session is in a terminal state, so none
// is left to stop; true for none.
func AllTerminal(sessions []Session) bool {
for _, session := range sessions {
if !session.State.Terminal() {
return false
}
}
return true
}

// LiveCount is the number of sessions that have not ended (SessionState.Ended).
func LiveCount(sessions []Session) int {
live := 0
for _, session := range sessions {
if !session.State.Ended() {
live++
}
}
return live
}

// statePrecedence is attention-first: error > waiting > unknown > running >
// starting > idle > stopped. "Done" only surfaces once every child is terminal.
// Starting ranks below running because a workstream that already has a live agent
Expand Down Expand Up @@ -309,6 +331,10 @@ type Workstream struct {
// no workstream, so nothing is offered on it but its removal, and its
// StatusMessage says why. Not persisted, as placeholders are not.
CreateFailed bool `json:"createFailed,omitempty"`
// FolderMissing marks a worktree workstream whose folder is gone, kept
// listed while a session in it has not ended. Derived by the reconciler;
// not persisted.
FolderMissing bool `json:"folderMissing,omitempty"`
}

// OpenMode is one way a workstream can be handed to the user for interactive
Expand Down Expand Up @@ -422,6 +448,21 @@ type Project struct {
RuntimeState RuntimeState `json:"runtimeState"`
Effective string `json:"effectiveState"`
Workstreams []Workstream `json:"workstreams"`
// UntrackedWorktrees are the project's linked git worktrees no workstream
// works in, suggested for adding. Derived by the reconciler; not persisted.
UntrackedWorktrees []UntrackedWorktree `json:"untrackedWorktrees"`
}

// UntrackedWorktree is a linked worktree of a project's repository that no
// workstream works in: a folder HomeShell suggests adding as a workstream.
// Derived by the reconciler; not persisted.
type UntrackedWorktree struct {
Name string `json:"name"`
Branch string `json:"branch,omitempty"`
Path string `json:"path"`
SessionCount int `json:"sessionCount"` // Sessions not ended; derived by Recompute
// Sessions are the ones reported in the folder, hidden until it is added.
Sessions []Session `json:"-"`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sessions on a suggestion never reach a client, and notify only walks project.Workstreams (notify.go), so an agent waiting for input in an external worktree now goes silent, where before this PR its adopted workstream showed and notified it. On upgrade an existing adopted workstream in such a folder is dropped too, so a maintainer should confirm that trading visibility for "never add on its own" is intended. If it is, sessionCount should at least flag a waiting session.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks! This is handled in #8.

}

// StrategyLabel returns the human-readable display label for a raw strategy ID.
Expand Down Expand Up @@ -480,6 +521,12 @@ func (p *Project) Recompute() {
workstreamStates[i] = w.State
workstreamRuntimeStates[i] = w.RuntimeState
}
if p.UntrackedWorktrees == nil {
p.UntrackedWorktrees = []UntrackedWorktree{}
}
for i := range p.UntrackedWorktrees {
p.UntrackedWorktrees[i].SessionCount = LiveCount(p.UntrackedWorktrees[i].Sessions)
}
p.State = Aggregate(workstreamStates)
p.RuntimeState = AggregateRuntime(workstreamRuntimeStates)
p.Effective = EffectiveState(p.RuntimeState, p.State)
Expand Down
77 changes: 77 additions & 0 deletions daemon/internal/domain/domain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,30 @@ func TestSessionStateBusy(t *testing.T) {
}
}

func TestAllTerminal(t *testing.T) {
tests := []struct {
name string
states []SessionState
want bool
}{
{"none", nil, true},
{"all terminal", []SessionState{SessionDone, SessionStopped, SessionError}, true},
{"one idle", []SessionState{SessionStopped, SessionIdle}, false},
{"one running", []SessionState{SessionRunning}, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var sessions []Session
for _, state := range test.states {
sessions = append(sessions, Session{ID: "s", State: state})
}
if got := AllTerminal(sessions); got != test.want {
t.Errorf("AllTerminal = %v, want %v", got, test.want)
}
})
}
}

func TestSessionStateTerminal(t *testing.T) {
// Error is terminal: the session never started, so it holds no slot.
terminal := []SessionState{SessionDone, SessionStopped, SessionError}
Expand Down Expand Up @@ -344,3 +368,56 @@ func TestRuntimeStateValid(t *testing.T) {
}
}
}

func TestRecomputeCountsLiveSessionsOnUntrackedWorktrees(t *testing.T) {
tests := []struct {
name string
states []SessionState
want int
}{
{"none", nil, 0},
{"only ended", []SessionState{SessionDone, SessionStopped}, 0},
{"a failed one, which has not ended", []SessionState{SessionError}, 1},
{"live and ended", []SessionState{
SessionRunning, SessionWaiting, SessionDone, SessionStopped,
}, 2},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var sessions []Session
for _, state := range test.states {
sessions = append(sessions, Session{ID: "s", State: state})
}
worktree := UntrackedWorktree{Name: "wt", Path: "/wt", Sessions: sessions}
project := Project{UntrackedWorktrees: []UntrackedWorktree{worktree}}
project.Recompute()
if got := project.UntrackedWorktrees[0].SessionCount; got != test.want {
t.Errorf("SessionCount = %d, want %d", got, test.want)
}
})
}
}

// A suggestion's sessions stay hidden: clients see only how many are live.
func TestUntrackedWorktreeJSONLeavesOutItsSessions(t *testing.T) {
worktree := UntrackedWorktree{Name: "wt", Path: "/wt", Sessions: []Session{{ID: "s", State: SessionRunning}}}
data, err := json.Marshal(worktree)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), `"sessions"`) {
t.Errorf("suggestion JSON lists its sessions: %s", data)
}
}

func TestRecomputeMakesNoUntrackedWorktreesAnEmptyList(t *testing.T) {
project := Project{}
project.Recompute()
data, err := json.Marshal(project)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), `"untrackedWorktrees":[]`) {
t.Errorf("want an empty array, got %s", data)
}
}
Loading
Loading