From 6dc4817b8f88914d2e46a93ef249a1a9aa7e5845 Mon Sep 17 00:00:00 2001 From: Amit Ghadge Date: Sun, 15 Nov 2026 14:47:06 -0800 Subject: [PATCH] Agent teams: group agents by what they work on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A project with a dozen agents is one long list. Teams group them — Backend, UI, a report — across projects and branches: - [[teams]] in config.toml: a name, a colour, and rules (project names, branch patterns) that put a new agent in a team; Settings → Teams edits them. Go (config.TeamFor) and the app (teamFor) read the rules alike, tested on the same cases. - pane.team (pane.team.v1) puts a pane in a team by hand, "-" for none whatever the rules say, "" back to them; it is on PaneInfo, broadcast, scoped like rename, and survives a reload. - conch agent team ID [TEAM | - | -clear], conch status -team NAME, conch task -team NAME. - Conch.app: a project's Agents split by team (colour, count, then No team; a project nobody sorted keeps its list), Team ▸ on an agent's menu, drag an agent onto a team, a Team picker in New Task, and on a team's row Show Side by Side (its agents in one tab) and Broadcast to This Team…. Co-Authored-By: Claude Opus 5.5 --- cmd/conch/agent.go | 4 +- cmd/conch/main.go | 11 +- cmd/conch/project.go | 22 ++- cmd/conch/status.go | 10 +- cmd/conch/team.go | 109 ++++++++++++ cmd/conch/team_test.go | 122 ++++++++++++++ docs/testing/end-to-end.md | 1 + internal/config/config.go | 3 + internal/config/teams.go | 82 +++++++++ internal/config/teams_test.go | 74 ++++++++ internal/configweb/schema.go | 9 + internal/proto/proto.go | 38 +++-- internal/server/agents.go | 4 + internal/server/reload.go | 5 + internal/server/scope.go | 4 +- internal/server/server.go | 15 ++ internal/server/subagents_test.go | 20 +++ internal/server/team_test.go | 57 +++++++ macos/Sources/ConchApp/Folders+Store.swift | 9 + macos/Sources/ConchApp/Store+Teams.swift | 40 +++++ macos/Sources/ConchApp/Store.swift | 19 ++- macos/Sources/ConchApp/Views.swift | 26 ++- macos/Sources/ConchKit/Actions.swift | 5 +- macos/Sources/ConchKit/Broadcast.swift | 6 +- macos/Sources/ConchKit/Layout.swift | 15 ++ macos/Sources/ConchKit/LucideIcons.swift | 2 + macos/Sources/ConchKit/Model.swift | 37 +++- macos/Sources/ConchKit/Protocol.swift | 5 +- macos/Sources/ConchKit/RowMenu.swift | 41 ++++- macos/Sources/ConchKit/SettingsIcons.swift | 4 +- macos/Sources/ConchKit/SettingsTables.swift | 5 + macos/Sources/ConchKit/SettingsUI.swift | 2 +- macos/Sources/ConchKit/Teams.swift | 121 +++++++++++++ macos/Tests/ConchKitTests/TeamsTests.swift | 178 ++++++++++++++++++++ web/src/app/docs/cli/page.mdx | 5 +- web/src/app/docs/configuration/page.mdx | 31 ++++ web/src/app/docs/mac-app/page.mdx | 4 +- 37 files changed, 1107 insertions(+), 38 deletions(-) create mode 100644 cmd/conch/team.go create mode 100644 cmd/conch/team_test.go create mode 100644 internal/config/teams.go create mode 100644 internal/config/teams_test.go create mode 100644 internal/server/team_test.go create mode 100644 macos/Sources/ConchApp/Store+Teams.swift create mode 100644 macos/Sources/ConchKit/Teams.swift create mode 100644 macos/Tests/ConchKitTests/TeamsTests.swift diff --git a/cmd/conch/agent.go b/cmd/conch/agent.go index 72d1d000..7ca4fbcd 100644 --- a/cmd/conch/agent.go +++ b/cmd/conch/agent.go @@ -40,8 +40,10 @@ func runAgent(args []string) error { return agentQuestion(args[1:]) case len(args) >= 1 && args[0] == "answer": return agentAnswer(args[1:]) + case len(args) >= 1 && args[0] == "team": + return agentTeam(args[1:]) case len(args) != 2 || args[0] != "explain": - return errors.New("usage: conch agent explain ID | status | install NAME | prompt [-wait] ID TEXT | question ID | answer [-question QID] ID CHOICE | skill [-remove] [-apply] | setup [-agent NAME] [-copy] [DIR] | add NAME -command BINARY | " + + return errors.New("usage: conch agent explain ID | status | install NAME | prompt [-wait] ID TEXT | question ID | answer [-question QID] ID CHOICE | team ID [TEAM | - | -clear] | skill [-remove] [-apply] | setup [-agent NAME] [-copy] [DIR] | add NAME -command BINARY | " + "sync [-from NAME] [-to NAMES] [-apply] [-undo [STAMP]] [DIR] | library [list | add | skill | on | off | rm | import | plan | apply | undo]") } c, err := connect(false) diff --git a/cmd/conch/main.go b/cmd/conch/main.go index f6d53f6d..27935ce3 100644 --- a/cmd/conch/main.go +++ b/cmd/conch/main.go @@ -70,9 +70,11 @@ Usage: conch server run the server in the foreground conch server stop stop the server and every pane it owns conch server reload run a new conch build without stopping panes - conch status [-wide] [-json] show server and pane status, with the host a terminal is on with ssh; + conch status [-wide] [-json] [-team NAME] + show server and pane status, with the host a terminal is on with ssh; fitted to the terminal (-wide: every column, as piped); BACKGROUND - is what an idle agent left running (-json: agent.background, agent.jobs) + is what an idle agent left running (-json: agent.background, agent.jobs); + -team: only that team's agents conch new [-cwd DIR] [-name N] -- CMD [ARGS...] start a pane (with -m, default: that machine's home) conch send ID TEXT type TEXT into a pane (-keys to send key names); from an agent's @@ -119,6 +121,9 @@ Usage: conch agent question ID what a waiting agent asks, and its choices, as JSON (null when not waiting) conch agent answer [-question QID] ID CHOICE pick a choice of a waiting agent's menu without opening its pane + conch agent team ID [TEAM | - | -clear] + which team an agent is in, or put it in one: - keeps it out of + every team, -clear leaves it to [[teams]]' rules in config.toml conch agent prompt [-wait] [-until done,idle,waiting] [-timeout 30m] [-at TIME] ID TEXT send an agent its next message, refused (exit 3) while it waits on a question; -wait blocks until that work ends; @@ -172,7 +177,7 @@ Usage: | merge [-order P,P] [-remove] [-stop] NAME BRANCH projects kept together because they change together (an API, its web app, their specs), each still a project of its own - conch task [-cwd DIR] [-branch B] [-base B] [-agent A,B] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] [-account NAME] [-sandbox PROVIDER] PROMPT + conch task [-cwd DIR] [-branch B] [-base B] [-agent A,B] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] [-account NAME] [-team NAME] [-sandbox PROVIDER] PROMPT new branch + worktree + Claude with PROMPT; in a folder that isn't a git repository the agent works there instead (with -m and no -cwd: that machine's home); diff --git a/cmd/conch/project.go b/cmd/conch/project.go index 8a2c9f07..3aa5144d 100644 --- a/cmd/conch/project.go +++ b/cmd/conch/project.go @@ -221,13 +221,19 @@ func runTask(args []string) error { wip := fs.Int("wip", 0, "with -queue, how many agents the project runs before it waits (default 3)") account := fs.String("account", "", "the agents' account (conch account list); default: the folder's pin, else each agent's own") after := fs.String("after", "", "start it once this has finished, on top of its branch: a branch, a pane, or a task on the schedule (its ID or -branch)") + team := fs.String("team", "", "put the agents in this team, as the app's Team menu does ([[teams]] in config.toml)") if err := fs.Parse(args); err != nil { return err } + *team = strings.TrimSpace(*team) + // A team is put on a pane, and these start none now. + if *team != "" && (*at != "" || *every != "" || *queue || *after != "" || *inSandbox != "") { + return errors.New("-team puts agents that start now in a team; -at, -every, -queue, -after and -sandbox start them later or elsewhere") + } prompt := strings.Join(fs.Args(), " ") *ticket = strings.TrimSpace(*ticket) if prompt == "" && *issue <= 0 && *ticket == "" { - return errors.New("usage: conch task [-cwd DIR] [-branch B] [-base B] [-agent NAME[,NAME...]] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] [-account NAME] [-sandbox PROVIDER] PROMPT") + return errors.New("usage: conch task [-cwd DIR] [-branch B] [-base B] [-agent NAME[,NAME...]] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] [-account NAME] [-team NAME] [-sandbox PROVIDER] PROMPT") } if *issue < 0 { return errors.New("-issue takes an issue's number") @@ -308,6 +314,9 @@ func runTask(args []string) error { case onRemoteMachine() && dir == "": // Nothing here says where on that machine: the agent starts in its // home, as a machine-level pane, like conch -m M new -agent. + if *team != "" { + return errors.New("-team works in a project: give -cwd") + } return runPlainTask(nil, "", agents, *n, *branch, *base, *name, *account, prompt) case onRemoteMachine(): if err := remoteDir(dir); err != nil { @@ -347,6 +356,9 @@ func runTask(args []string) error { return errors.New("-at, -every, -queue and -after start a task on a branch of its own, so they need a git repository") } // No repository to branch: the agent works in the folder itself. + if *team != "" { + return errors.New("-team works in a git project: put the agent in a team after with conch agent team") + } return runPlainTask(c, dir, agents, *n, *branch, *base, *name, *account, prompt) } branchFrom := prompt @@ -403,6 +415,9 @@ func runTask(args []string) error { } } } + if *team != "" && len(c.MissingCapabilities([]string{proto.CapPaneTeam})) > 0 { + return fmt.Errorf("the conch server (pid %d) is from an older build without teams; reload it with `conch server reload`", c.Server.PID) + } var failed int for _, at := range attempts { var info proto.PaneInfo @@ -426,6 +441,11 @@ func runTask(args []string) error { return fmt.Errorf("%s started, but naming it failed: %v", info.ID, err) } } + if *team != "" { + if err := call(c, proto.MethodPaneTeam, proto.PaneTeamParams{ID: info.ID, Team: *team}, &info); err != nil { + return fmt.Errorf("%s started, but putting it in %s failed: %v", info.ID, *team, err) + } + } fmt.Printf("%s %s %s\n", info.ID, info.Cwd, info.Branch) } if failed > 0 { diff --git a/cmd/conch/status.go b/cmd/conch/status.go index 8f29172b..3ecb3df0 100644 --- a/cmd/conch/status.go +++ b/cmd/conch/status.go @@ -25,7 +25,7 @@ import ( // running and how it stands first, the folder from ~, the command in // whatever room is left, and a line saying how many agents are working. -const statusUsage = "usage: conch status [-wide] [-json]" +const statusUsage = "usage: conch status [-wide] [-json] [-team NAME]" // terminalWidth is the width of the terminal stdout is, or 0 when it is // not one; tests replace it. @@ -44,6 +44,7 @@ func runStatus(args []string) error { fs := flag.NewFlagSet("status", flag.ContinueOnError) wide := fs.Bool("wide", false, "every column, as it is printed to a pipe") asJSON := fs.Bool("json", false, "the server and its panes as JSON") + team := fs.String("team", "", "only the agents in this team ([[teams]] in config.toml, or put there by hand)") if err := fs.Parse(args); err != nil { return err } @@ -71,6 +72,9 @@ func runStatus(args []string) error { defer c.Close() var list proto.PaneList listErr := call(c, proto.MethodPaneList, nil, &list) + if listErr == nil && *team != "" { + list.Panes = onlyTeam(c, list.Panes, *team) + } if *asJSON { if listErr != nil { return listErr @@ -87,6 +91,10 @@ func runStatus(args []string) error { if listErr != nil { return listErr } + if len(list.Panes) == 0 && *team != "" { + fmt.Printf("no agents in %s\n", *team) + return nil + } if len(list.Panes) == 0 { fmt.Println("no panes") return nil diff --git a/cmd/conch/team.go b/cmd/conch/team.go new file mode 100644 index 00000000..d536e07a --- /dev/null +++ b/cmd/conch/team.go @@ -0,0 +1,109 @@ +package main + +import ( + "errors" + "fmt" + "strings" + + "github.com/Amitgb14/conch/internal/client" + "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/proto" +) + +const agentTeamUsage = "usage: conch agent team ID [TEAM | - | -clear]" + +// agentTeam says which team a pane is in, or puts it in one: a name, "-" +// for no team whatever the rules say, or -clear to leave it to the rules. +func agentTeam(args []string) error { + if len(args) < 1 || len(args) > 2 { + return errors.New(agentTeamUsage) + } + ref, team := args[0], "" + set := len(args) == 2 + if set { + team = strings.TrimSpace(args[1]) + switch team { + case "-clear": + team = "" + case "": + return errors.New(agentTeamUsage) + } + } + c, err := connect(false) + if err != nil { + return err + } + defer c.Close() + if missing := c.MissingCapabilities([]string{proto.CapPaneTeam}); len(missing) > 0 { + return fmt.Errorf("the conch server (pid %d) is from an older build without teams; reload it with `conch server reload`", c.Server.PID) + } + id, err := resolvePane(c, ref) + if err != nil { + return err + } + var info proto.PaneInfo + if set { + if err := call(c, proto.MethodPaneTeam, proto.PaneTeamParams{ID: id, Team: team}, &info); err != nil { + return err + } + } else { + var list proto.PaneList + if err := call(c, proto.MethodPaneList, nil, &list); err != nil { + return err + } + for _, p := range list.Panes { + if p.ID == id { + info = p + } + } + } + teams := paneTeams(c, []proto.PaneInfo{info}) + switch { + case teams[info.ID] != "": + how := "by hand" + if info.Team == "" { + how = "by its rule in config.toml" + } + fmt.Printf("%s is in %s (%s)\n", info.ID, teams[info.ID], how) + case info.Team == config.NoTeam: + fmt.Printf("%s is kept out of every team\n", info.ID) + default: + fmt.Printf("%s is in no team\n", info.ID) + } + return nil +} + +// paneTeams is each pane's team, by hand or by config.toml's rules (an +// agent's project and branch); "" for none. +func paneTeams(c *client.Client, panes []proto.PaneInfo) map[string]string { + var teams []config.Team + if cfg, err := config.Load(); err == nil { + teams = cfg.Teams + } + names := map[string]string{} + if len(teams) > 0 { + var projects proto.ProjectList + if call(c, proto.MethodProjectList, nil, &projects) == nil { + for _, p := range projects.Projects { + names[p.ID] = p.Name + } + } + } + out := map[string]string{} + for _, p := range panes { + out[p.ID] = config.TeamFor(teams, p.Team, names[p.ProjectID], p.Branch) + } + return out +} + +// onlyTeam keeps the panes in team (any case). +func onlyTeam(c *client.Client, panes []proto.PaneInfo, team string) []proto.PaneInfo { + teams := paneTeams(c, panes) + var out []proto.PaneInfo + for _, p := range panes { + if strings.EqualFold(teams[p.ID], team) { + out = append(out, p) + } + } + return out +} diff --git a/cmd/conch/team_test.go b/cmd/conch/team_test.go new file mode 100644 index 00000000..06a9b570 --- /dev/null +++ b/cmd/conch/team_test.go @@ -0,0 +1,122 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Amitgb14/conch/internal/config" + "github.com/Amitgb14/conch/internal/proto" +) + +// teamServer is a fake server with three agents in two projects; pane.team +// is recorded and answered with the pane in that team. +func teamServer(t *testing.T) *a4Var[[]proto.PaneTeamParams] { + t.Helper() + a4Env(t) + os.WriteFile(filepath.Join(config.Dir(), "config.toml"), []byte(` +[[teams]] +name = "Backend" +projects = ["api"] + +[[teams]] +name = "UI" +branches = ["ui/*"] +`), 0o644) + srv := startA4Server(t, config.SocketPath()) + seen := newA4Var([]proto.PaneTeamParams(nil)) + panes := []proto.PaneInfo{ + {ID: "p1", Name: "claude", State: proto.PaneRunning, ProjectID: "r1", Branch: "retry", Agent: &proto.AgentStatus{Name: "claude"}}, + {ID: "p2", Name: "codex", State: proto.PaneRunning, ProjectID: "r2", Branch: "ui/nav", Agent: &proto.AgentStatus{Name: "codex"}}, + {ID: "p3", Name: "gemini", State: proto.PaneRunning, ProjectID: "r2", Branch: "docs", Team: "Report", Agent: &proto.AgentStatus{Name: "gemini"}}, + {ID: "p4", Name: "out", State: proto.PaneRunning, ProjectID: "r1", Branch: "x", Team: config.NoTeam, Agent: &proto.AgentStatus{Name: "claude"}}, + } + srv.setHandle(func(msg proto.Message, _ *proto.Conn) (any, *proto.Error) { + switch msg.Method { + case proto.MethodPaneList: + return proto.PaneList{Panes: panes}, nil + case proto.MethodProjectList: + return proto.ProjectList{Projects: []proto.ProjectInfo{{ID: "r1", Name: "api"}, {ID: "r2", Name: "web"}}}, nil + case proto.MethodPaneTeam: + var p proto.PaneTeamParams + json.Unmarshal(msg.Params, &p) + seen.Set(append(seen.Get(), p)) + for _, q := range panes { + if q.ID == p.ID { + q.Team = p.Team + return q, nil + } + } + return nil, proto.Errorf(proto.ErrNotFound, "no pane %s", p.ID) + } + return nil, nil + }) + return seen +} + +func TestAgentTeam(t *testing.T) { + seen := teamServer(t) + run := func(args ...string) (string, error) { + var err error + out, _ := a4Capture(t, "", func() { err = runAgent(append([]string{"team"}, args...)) }) + return out, err + } + for ref, want := range map[string]string{ + "p1": "p1 is in Backend (by its rule in config.toml)", + "codex": "p2 is in UI (by its rule in config.toml)", + "p3": "p3 is in Report (by hand)", + "p4": "p4 is kept out of every team", + "gemini": "p3 is in Report (by hand)", + } { + if out, err := run(ref); err != nil || !strings.Contains(out, want) { + t.Errorf("%s: %q %v, want %q", ref, out, err, want) + } + } + if out, err := run("p1", "UX"); err != nil || !strings.Contains(out, "p1 is in UX (by hand)") { + t.Fatalf("set: %q %v", out, err) + } + run("p1", "-") + run("p1", "-clear") + got := seen.Get() + if len(got) != 3 || got[0] != (proto.PaneTeamParams{ID: "p1", Team: "UX"}) || got[1].Team != "-" || got[2].Team != "" { + t.Fatalf("sent %+v", got) + } + for _, bad := range [][]string{{}, {"p1", "a", "b"}, {"p1", " "}} { + if _, err := run(bad...); err == nil || !strings.Contains(err.Error(), "usage") { + t.Errorf("%q: %v", bad, err) + } + } + if _, err := run("nope"); err == nil { + t.Fatal("an unknown pane should fail") + } +} + +func TestStatusTeam(t *testing.T) { + teamServer(t) + var err error + out, _ := a4Capture(t, "", func() { err = runStatus([]string{"-wide", "-team", "backend"}) }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "p1") || strings.Contains(out, "p2") || strings.Contains(out, "p4") { + t.Fatalf("backend: %s", out) + } + out, _ = a4Capture(t, "", func() { err = runStatus([]string{"-team", "Nobody"}) }) + if err != nil || !strings.Contains(out, "no agents in Nobody") { + t.Fatalf("empty: %q %v", out, err) + } +} + +// -team is for agents that start now: a task kept for later has no pane +// to put in a team. +func TestTaskTeamOnlyNow(t *testing.T) { + a4Env(t) + for _, extra := range [][]string{{"-at", "+30m"}, {"-every", "1h"}, {"-queue"}, {"-after", "main"}, {"-sandbox", "daytona"}} { + args := append(append([]string{"-team", "UI"}, extra...), "do it") + if err := runTask(args); err == nil || !strings.Contains(err.Error(), "start them later or elsewhere") { + t.Errorf("%v: %v", extra, err) + } + } +} diff --git a/docs/testing/end-to-end.md b/docs/testing/end-to-end.md index 0e443ce7..518f7985 100644 --- a/docs/testing/end-to-end.md +++ b/docs/testing/end-to-end.md @@ -424,6 +424,7 @@ What it carries, and what is left over in each row: | 9.180 🖥 | ▶ Run on a real Xcode project | Conch.app on this Mac with Xcode, a real iOS app project (an `.xcodeproj`, or a workspace with CocoaPods) whose folder holds a package with a scheme of its own: open its Mobile Preview (or the Mobile workbench) on an iPhone simulator, press **▶ Run**; change a screen and press it again; try it with the simulator shut down, and in a folder with two projects | `conch preview run` builds the app's scheme (not the package's) for that simulator with the build shown in the terminal, installs it and opens it in the phone pane with no Simulator window; the second Run shows the change; a shut simulator is started first; two projects are named and nothing is built | ☐ | | 9.181 🖥 | Mobile options only for mobile projects | Conch.app on this Mac with three local projects: an iOS app, a plain Go service, and one whose app exists only on an agent's branch (worktree); then have an agent create an Expo app in the Go project | Right-click: **Mobile Preview** on the iOS project and the branch-only one, not on the Go service; a workbench on the Go service has no phone button and no Mobile layout; once the agent writes the Expo app's package.json, Mobile Preview appears there within seconds; in the branch-only project, ▶ Run builds in the checkout that has the app | ☐ | | 9.182 | Pruning merged branches against GitHub | In a real repository: merge one branch's pull request on GitHub with a squash, another with a merge commit, and merge a third locally; push a fourth unmerged; commit once more on a fifth after its merge. Run `conch branch prune -merged`, then Settings → Git → Old branches → Merged in Conch.app, and delete. | All three merged ones are listed (the squashed one once GitHub says it merged), ticked, and deleted; the pushed one and the one with a later commit are not listed; a branch checked out in a worktree is listed and kept. Against a server from before this, both say to reload it and delete nothing. | ☐ | +| 9.183 🖥 | Agent teams in Conch.app with real agents | With `[[teams]]` Backend (a project) and UI (a branch pattern) and a dozen agents across two projects: watch Agents split; right-click one → Team → UI; drag another onto Backend and onto No team; New Task with a team; Show Side by Side and Broadcast to This Team… on a team's row; `conch server reload`; `conch status -team UI`. | Each project's Agents shows Backend, UI, then No team, with counts; a project with no team keeps its list. A move by menu or drag lands at once, in every window and the TUI's `conch status -team`; a reload keeps it. Side by Side puts the team's agents in one tab; the broadcast reaches only them. | ☐ | Everything else marked 💳 wants a model: the brain's providers (1.x), an agent's own state hooks and usage (2.1-2.5, 9.1, 9.21, 9.22, 9.70), saved diff --git a/internal/config/config.go b/internal/config/config.go index 185ab33f..a4c78d84 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -41,6 +41,9 @@ type Config struct { // that matches deciding (permissions.go). After Actions for the same // reason. Permissions []PermissionRule `toml:"permissions,omitempty"` + // Teams group agents by what they work on — backend, UI, a report — + // across projects and branches (teams.go). After the plain tables too. + Teams []Team `toml:"teams,omitempty"` } // WebCfg is the phone gateway, conch web. URL is the address phones open — diff --git a/internal/config/teams.go b/internal/config/teams.go new file mode 100644 index 00000000..77284f5f --- /dev/null +++ b/internal/config/teams.go @@ -0,0 +1,82 @@ +package config + +import ( + "strings" +) + +// Team is a group of agents: a name and a colour, and rules that put an +// agent in it when nobody has — a project it works in, or a branch +// pattern. An agent can also be put in a team by hand (pane.team), which +// wins over every rule. Conch.app reads the same rules +// (ConchKit/Teams.swift), so both say the same team for an agent. +type Team struct { + Name string `toml:"name"` + // Color is one of TeamColors, or "#rrggbb"; "" takes one by the + // team's place in the list. + Color string `toml:"color,omitempty"` + // Projects are project names whose agents join the team. + Projects []string `toml:"projects,omitempty"` + // Branches are patterns, * matching anything, for the branch an agent + // works on: "ui/*", "*-redesign". + Branches []string `toml:"branches,omitempty"` +} + +// TeamColors are the colour names a team may use. +var TeamColors = []string{"blue", "orange", "purple", "teal", "green", "red", "pink", "yellow", "gray"} + +// NoTeam set on a pane by hand keeps it out of every team, whatever the +// rules say. +const NoTeam = "-" + +// TeamFor is the team an agent is in: the one it was put in by hand +// (set), else the first team whose rule matches its project or branch. +// "" is none. A team set by hand that no longer exists is still its team: +// the name is what was chosen, and the tree shows it. +func TeamFor(teams []Team, set, project, branch string) string { + switch set { + case NoTeam: + return "" + case "": + default: + return set + } + for _, t := range teams { + if t.Name == "" { + continue + } + for _, p := range t.Projects { + if project != "" && strings.EqualFold(p, project) { + return t.Name + } + } + for _, b := range t.Branches { + if branch != "" && globMatch(b, branch) { + return t.Name + } + } + } + return "" +} + +// globMatch is a branch pattern: * matches any run of characters, slashes +// included (a branch's slashes are part of its name, not directories); +// anything else is itself. +func globMatch(pattern, s string) bool { + if !strings.Contains(pattern, "*") { + return pattern == s + } + parts := strings.Split(pattern, "*") + if !strings.HasPrefix(s, parts[0]) { + return false + } + s = s[len(parts[0]):] + last := parts[len(parts)-1] + for _, p := range parts[1 : len(parts)-1] { + i := strings.Index(s, p) + if i < 0 { + return false + } + s = s[i+len(p):] + } + return strings.HasSuffix(s, last) && len(s) >= len(last) +} diff --git a/internal/config/teams_test.go b/internal/config/teams_test.go new file mode 100644 index 00000000..040e30f4 --- /dev/null +++ b/internal/config/teams_test.go @@ -0,0 +1,74 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +func TestTeamFor(t *testing.T) { + teams := []Team{ + {Name: "Backend", Projects: []string{"api", "worker"}, Branches: []string{"conch/cloud-*"}}, + {Name: "UI", Projects: []string{"web"}, Branches: []string{"ui/*", "*-redesign", "*desktop*"}}, + {Name: ""}, // a nameless team never takes anyone + {Name: "Everything", Branches: []string{"*"}}, + } + for _, c := range []struct{ set, project, branch, want string }{ + {"", "api", "main", "Backend"}, + {"", "API", "", "Backend"}, // a project name in any case + {"", "conch", "conch/cloud-agent", "Backend"}, + {"", "conch", "ui/nav/dark", "UI"}, // * takes slashes too + {"", "conch", "checkout-redesign", "UI"}, + {"", "conch", "conch/readme-desktop-shots", "UI"}, + {"", "web", "conch/cloud-x", "Backend"}, // the first team that matches, in order + {"", "conch", "anything", "Everything"}, + {"", "", "", ""}, // nothing to match: no team, not "Everything" + {"UX", "api", "main", "UX"}, // by hand wins over every rule + {"Gone", "api", "main", "Gone"}, // even a team since removed + {NoTeam, "api", "main", ""}, // kept out on purpose + } { + if got := TeamFor(teams, c.set, c.project, c.branch); got != c.want { + t.Errorf("TeamFor(%q, %q, %q) = %q, want %q", c.set, c.project, c.branch, got, c.want) + } + } + if TeamFor(nil, "", "api", "main") != "" { + t.Fatal("no teams, no team") + } +} + +func TestGlobMatch(t *testing.T) { + for _, c := range []struct { + p, s string + ok bool + }{ + {"main", "main", true}, {"main", "mainline", false}, + {"ui/*", "ui/", true}, {"ui/*", "ux/a", false}, + {"*-copy", "a-copy", true}, {"*-copy", "-copy", true}, {"*-copy", "copy", false}, + {"a*b*c", "abc", true}, {"a*b*c", "axxbyyc", true}, {"a*b*c", "acb", false}, + {"a*a", "a", false}, {"*", "", true}, {"**", "x/y", true}, + } { + if globMatch(c.p, c.s) != c.ok { + t.Errorf("globMatch(%q, %q) != %v", c.p, c.s, c.ok) + } + } +} + +func TestTeamsRoundTrip(t *testing.T) { + home := t.TempDir() + t.Setenv("CONCH_HOME", home) + cfg := Default() + cfg.Teams = []Team{{Name: "Backend", Color: "blue", Projects: []string{"api"}}, {Name: "UI", Branches: []string{"ui/*"}}} + if err := Save(cfg); err != nil { + t.Fatal(err) + } + got, err := Load() + if err != nil || !reflect.DeepEqual(got.Teams, cfg.Teams) { + t.Fatalf("%+v %v", got.Teams, err) + } + b, _ := os.ReadFile(filepath.Join(home, "config.toml")) + if !strings.Contains(string(b), "[[teams]]") { + t.Fatalf("saved:\n%s", b) + } +} diff --git a/internal/configweb/schema.go b/internal/configweb/schema.go index 3160447e..81fb951e 100644 --- a/internal/configweb/schema.go +++ b/internal/configweb/schema.go @@ -346,6 +346,15 @@ func Schema(c Choices) []Section { {Key: "keep", Label: "Keep the terminal open after", Kind: KindBool, Default: true}, }}, }}, + {ID: "teams", Key: "", Title: "Teams", Icon: "users", Description: "Group agents by what they work on. A new agent joins the first team whose project or branch matches; one put in a team by hand stays there.", + Fields: []Field{ + {Key: "teams", Label: "Teams", Kind: KindTables, Fields: []Field{ + {Key: "name", Label: "Name", Kind: KindString, Placeholder: "Backend"}, + {Key: "color", Label: "Colour", Kind: KindSelect, Options: append([]Option{{Value: "", Label: "By its place"}}, opts(config.TeamColors...)...)}, + {Key: "projects", Label: "Projects", Kind: KindList, Help: "Project names whose agents join it."}, + {Key: "branches", Label: "Branches", Kind: KindList, Help: "Branch patterns, * for anything: ui/*, *-redesign."}, + }}, + }}, {ID: "permissions", Key: "", Title: "Permission rules", Icon: "lock", Description: "Answer an agent's tool requests by rule; the first that matches decides.", Fields: []Field{ {Key: "permissions", Label: "Rules", Kind: KindTables, Fields: []Field{ diff --git a/internal/proto/proto.go b/internal/proto/proto.go index d2edcbbd..bdaffd4e 100644 --- a/internal/proto/proto.go +++ b/internal/proto/proto.go @@ -35,7 +35,7 @@ const ProtocolVersion = 1 var Capabilities = []string{ "pane.v1", "pane.frame.v1", "events.v1", "agent.v1", "project.v1", "pane.scroll.v1", "project.pr.v1", "pane.default_shell.v1", - "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged, CapWorktreeOperation, + "agent.install.v1", "fs.v1", "shell.omz.v1", "agent.setup.v1", "worktree.files.v1", "session.v1", "agent.limits.v1", "server.reload.v1", "session.delete.v1", "session.search.v1", "session.share.v1", "agent.broadcast.v1", "agent.broadcast.shells.v1", "pane.redraw.v1", "fs.upload.v1", "branch.harvest.v1", "worktree.cleanup.v1", "branch.hunks.v1", "project.resolve.v1", CapSessionHandoff, CapWorktreeWatch, CapPaneSearch, CapPaneMonitor, CapWorktreeMove, CapProjectBundle, CapFSFiles, CapFSRead, CapFSTransfer, CapFSSSH, CapPaneSSH, CapBranchRebase, CapAgentSync, CapAgentSyncUser, CapAgentLibrary, CapLibraryKeychain, CapLibraryPlain, CapCloudAgent, CapAgentPrompt, CapTaskName, CapPaneScope, CapScopeRemote, CapAgentSkill, CapAgentSkillPick, CapLibraryFetch, CapBranchGit, CapAgentTiers, CapWorktreeSetup, CapBranchCILog, CapAgentReply, CapSchedule, CapIssues, CapPermissionRules, CapTaskAfter, CapReviewComments, CapSessionStar, CapView, CapPRMerge, CapAutopilot, CapFrameCursor, CapPaneSizeLatest, CapFSFind, CapProjectLog, CapPaneRaw, CapPaneListening, CapUsageHistory, CapCommitShow, CapPRReview, CapReviewSendTo, CapBranchStage, CapReviewThread, CapFSWrite, CapProjectGroups, CapGroupTask, CapGroupTaskMerge, CapFSSearch, CapFSReplace, CapFSOps, CapFSLines, CapAgentChat, CapProjectGitInit, CapAccounts, CapAgentBackground, CapSystemStats, CapTickets, CapAgentInterrupt, CapAgentAttach, CapAutopilotIntake, CapTicketCheck, CapTicketOverview, CapAutopilotTriage, CapBranchPrune, CapBranchPruneMerged, CapPaneTeam, CapWorktreeOperation, } // The tiers an agent can be in, as agent.list reports them. They are in @@ -272,6 +272,9 @@ const CapBranchPrune = "branch.prune.v1" // answers with its old branches, which is not the same list. const CapBranchPruneMerged = "branch.prune.merged.v1" +// CapPaneTeam is pane.team and PaneInfo.Team: agents grouped by team. +const CapPaneTeam = "pane.team.v1" + // CapAutopilotIntake is AutopilotPolicy.Intake: open GitHub issues with a // project's label taken as queued tasks by the server, each once. const CapAutopilotIntake = "autopilot.intake.v1" @@ -446,16 +449,18 @@ const CapPaneSSH = "pane.ssh.v1" // Methods. const ( - MethodHello = "hello" - MethodPing = "ping" - MethodServerStop = "server.stop" - MethodServerReload = "server.reload" - MethodPaneList = "pane.list" - MethodPaneCreate = "pane.create" - MethodPaneClose = "pane.close" - MethodPaneResize = "pane.resize" - MethodPaneSendText = "pane.send_text" - MethodPaneSendKeys = "pane.send_keys" + MethodHello = "hello" + MethodPing = "ping" + MethodServerStop = "server.stop" + MethodServerReload = "server.reload" + MethodPaneList = "pane.list" + MethodPaneCreate = "pane.create" + MethodPaneClose = "pane.close" + MethodPaneResize = "pane.resize" + MethodPaneSendText = "pane.send_text" + MethodPaneSendKeys = "pane.send_keys" + // MethodPaneTeam puts a pane in a team by hand (CapPaneTeam). + MethodPaneTeam = "pane.team" MethodPaneRead = "pane.read" MethodPaneSubscribe = "pane.subscribe" MethodPaneUnsubscribe = "pane.unsubscribe" @@ -807,6 +812,10 @@ type PaneInfo struct { // Account is the account its agent was started on, "" for the agent's // own (CapAccounts). Account string `json:"account,omitempty"` + // Team is the team the pane was put in by hand (CapPaneTeam), "-" for + // kept out of every team; "" leaves it to config.toml's [[teams]] + // rules (config.TeamFor), which clients apply. + Team string `json:"team,omitempty"` // Title is the terminal title with decoration (spinners, the agent's // default title) stripped; agents set it to a summary of their task. Title string `json:"title,omitempty"` @@ -882,6 +891,13 @@ func IsPaneID(ref string) bool { return true } +// PaneTeamParams puts a pane in a team: a name, "-" for no team whatever +// the rules say, or "" to leave it to the rules again. +type PaneTeamParams struct { + ID string `json:"id"` + Team string `json:"team"` +} + // PaneRenameParams renames a pane; an empty name restores the default. type PaneRenameParams struct { ID string `json:"id"` diff --git a/internal/server/agents.go b/internal/server/agents.go index 4497088a..437f950f 100644 --- a/internal/server/agents.go +++ b/internal/server/agents.go @@ -94,6 +94,9 @@ type entry struct { // conversation lives in its account's folder, so an agent is never // moved to another. account string + // team is the team the pane was put in by hand (pane.team), "" for + // none: its clients apply config.toml's rules to that. + team string } func newEntry(p *pane.Pane, dir string, t *detect.Tracker, proj *project) *entry { @@ -115,6 +118,7 @@ func (e *entry) info() proto.PaneInfo { info.Monitor, info.Alert = e.monitor.info() info.LastActive = e.lastActive info.Account = e.account + info.Team = e.team turns := e.turns subs := append([]proto.Subagent(nil), e.subagents.list...) for i := range subs { diff --git a/internal/server/reload.go b/internal/server/reload.go index a91aec79..f1dfc2cd 100644 --- a/internal/server/reload.go +++ b/internal/server/reload.go @@ -61,6 +61,9 @@ type reloadPane struct { // Account the agent was started on (accounts.go); absent from older // state files, whose agents were all on their own. Account string `json:"account,omitempty"` + // Team the pane was put in by hand (pane.team); absent from older + // state files, from before teams. + Team string `json:"team,omitempty"` } // reloadBinary resolves and checks the program to reload into: it must run @@ -149,6 +152,7 @@ func (s *Server) reload(bin string) { rp.MonitorArmed = e.monitor.armed rp.CreatedBy = e.lineage rp.Account = e.account + rp.Team = e.team rp.Subagents, rp.SubagentSession = e.subagents.list, e.subagents.session e.mu.Unlock() if e.transcript != nil { @@ -223,6 +227,7 @@ func (s *Server) adopt(st *reloadState) { e.monitor.alert, e.monitor.armed, e.monitor.lastOut = rp.Alert, rp.MonitorArmed, time.Now() e.lineage = rp.CreatedBy e.account = rp.Account + e.team = rp.Team e.subagents = subagents{list: rp.Subagents, session: rp.SubagentSession} if rp.Transcript != "" { e.transcript = usage.NewTranscript(rp.Transcript) diff --git a/internal/server/scope.go b/internal/server/scope.go index 7af9c2f4..867127fa 100644 --- a/internal/server/scope.go +++ b/internal/server/scope.go @@ -103,7 +103,7 @@ const ( // read, and what an agent starts is its own. var scoped = map[string]scopeKind{ proto.MethodPaneClose: scopePane, proto.MethodPaneSendText: scopePane, proto.MethodPaneSendKeys: scopePane, - proto.MethodPaneSendMouse: scopePane, proto.MethodPaneResize: scopePane, proto.MethodPaneRename: scopePane, + proto.MethodPaneSendMouse: scopePane, proto.MethodPaneResize: scopePane, proto.MethodPaneRename: scopePane, proto.MethodPaneTeam: scopePane, proto.MethodPaneMarkSeen: scopePane, proto.MethodPaneMonitor: scopePane, proto.MethodAgentReport: scopePane, proto.MethodAgentPrompt: scopePane, proto.MethodAgentInterrupt: scopePane, proto.MethodAgentAttach: scopePane, @@ -416,7 +416,7 @@ var verbs = map[string]string{ proto.MethodFSMkdir: "make folders over the ssh login of", proto.MethodFSUpload: "copy files over the ssh login of", proto.MethodFSDownload: "copy files over the ssh login of", proto.MethodPaneCreate: "run a command over the ssh login of", proto.MethodPaneClose: "close", proto.MethodPaneSendText: "type into", proto.MethodPaneSendKeys: "send keys to", - proto.MethodPaneSendMouse: "click in", proto.MethodPaneResize: "resize", proto.MethodPaneRename: "rename", + proto.MethodPaneSendMouse: "click in", proto.MethodPaneResize: "resize", proto.MethodPaneRename: "rename", proto.MethodPaneTeam: "put in a team", proto.MethodPaneMarkSeen: "mark as seen", proto.MethodPaneMonitor: "set monitoring on", proto.MethodAgentReport: "report the state of", proto.MethodAgentPrompt: "prompt", proto.MethodAgentBackgroundStop: "stop a background job of", proto.MethodAgentInterrupt: "stop", proto.MethodAgentAttach: "attach files to", proto.MethodAgentBroadcast: "send a message to", proto.MethodViewShow: "put on screen", proto.MethodSessionShare: "hand a session to", diff --git a/internal/server/server.go b/internal/server/server.go index 55b43f2f..df745a6c 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -770,6 +770,21 @@ func (s *Server) dispatch(c *client, msg proto.Message) (any, *proto.Error) { s.rename(e, rp.Name) return e.info(), nil + case proto.MethodPaneTeam: + tp, e, perr := withPane(s, msg, func(p proto.PaneTeamParams) string { return p.ID }) + if perr != nil { + return nil, perr + } + team := strings.TrimSpace(gitx.Printable(tp.Team)) + if len(team) > 64 { + return nil, proto.Errorf(proto.ErrBadRequest, "a team's name is 64 characters at most") + } + e.mu.Lock() + e.team = team + e.mu.Unlock() + s.reshown(e) + return e.info(), nil + case proto.MethodPaneScroll: sp, e, perr := withPane(s, msg, func(p proto.PaneScrollParams) string { return p.ID }) if perr != nil { diff --git a/internal/server/subagents_test.go b/internal/server/subagents_test.go index 821461e8..e45a057c 100644 --- a/internal/server/subagents_test.go +++ b/internal/server/subagents_test.go @@ -291,3 +291,23 @@ func TestSubagentsReloadState(t *testing.T) { t.Fatalf("none are written when there are none: %s", b) } } + +// A pane's team survives a reload; an older state file, from before +// teams, loads with none. +func TestTeamReloadState(t *testing.T) { + b, err := json.Marshal(reloadPane{Team: "Backend"}) + if err != nil { + t.Fatal(err) + } + var back reloadPane + if err := json.Unmarshal(b, &back); err != nil || back.Team != "Backend" { + t.Fatalf("round trip: %+v %v", back, err) + } + var old reloadPane + if err := json.Unmarshal([]byte(`{"snapshot":{"id":"p1"},"fd":3,"dir":"/x"}`), &old); err != nil || old.Team != "" { + t.Fatalf("older state: %+v %v", old, err) + } + if b, _ := json.Marshal(reloadPane{}); strings.Contains(string(b), "team") { + t.Fatalf("none is written when there is none: %s", b) + } +} diff --git a/internal/server/team_test.go b/internal/server/team_test.go new file mode 100644 index 00000000..90926bbd --- /dev/null +++ b/internal/server/team_test.go @@ -0,0 +1,57 @@ +package server_test + +import ( + "encoding/json" + "slices" + "strings" + "testing" + + "github.com/Amitgb14/conch/internal/proto" +) + +// TestPaneTeam: pane.team puts a pane in a team by hand, says so in its +// info and to every client, and is undone with "" — "-" keeps it out of +// every team whatever config.toml's rules say. A name is cleaned of +// control characters and kept short; a pane that is not there is not found. +func TestPaneTeam(t *testing.T) { + t.Setenv("CONCH_SOCKET", "") + t.Setenv("CONCH_PANE_ID", "") + c, dir := startServer(t) + info := createCat(t, c, dir) + if info.Team != "" { + t.Fatalf("a new pane is in no team: %q", info.Team) + } + set := func(team string) proto.PaneInfo { + t.Helper() + var got proto.PaneInfo + if err := call(t, c, proto.MethodPaneTeam, proto.PaneTeamParams{ID: info.ID, Team: team}, &got); err != nil { + t.Fatal(err) + } + return got + } + if got := set(" Backend "); got.Team != "Backend" { + t.Fatalf("set: %q", got.Team) + } + waitEvent(t, c, func(m proto.Message) bool { + var p proto.PaneInfo + return m.Event == proto.EventPaneUpdated && json.Unmarshal(m.Data, &p) == nil && p.ID == info.ID && p.Team == "Backend" + }) + var list proto.PaneList + if err := call(t, c, proto.MethodPaneList, nil, &list); err != nil || len(list.Panes) != 1 || list.Panes[0].Team != "Backend" { + t.Fatalf("listed: %+v %v", list, err) + } + if got := set("-"); got.Team != "-" { + t.Fatalf("kept out: %q", got.Team) + } + if got := set("UI\x1b]52;c;aGk=\x07"); got.Team != "UI·]52;c;aGk=·" { + t.Fatalf("control characters are not a team's: %q", got.Team) + } + if got := set(""); got.Team != "" { + t.Fatalf("back to the rules: %q", got.Team) + } + badRequest(t, c.Call(t.Context(), proto.MethodPaneTeam, proto.PaneTeamParams{ID: info.ID, Team: strings.Repeat("x", 65)}, nil), "64 characters") + a5Code(t, c.Call(t.Context(), proto.MethodPaneTeam, proto.PaneTeamParams{ID: "p404", Team: "UI"}, nil), proto.ErrNotFound) + if !slices.Contains(proto.Capabilities, proto.CapPaneTeam) { + t.Fatal("pane.team.v1 is not announced") + } +} diff --git a/macos/Sources/ConchApp/Folders+Store.swift b/macos/Sources/ConchApp/Folders+Store.swift index 03ad9e3e..809c50c9 100644 --- a/macos/Sources/ConchApp/Folders+Store.swift +++ b/macos/Sources/ConchApp/Folders+Store.swift @@ -121,6 +121,15 @@ extension Store { /// A row dropped on a folder (into it) or on its section (out of its /// folder): only within the section it belongs to. func drop(_ dragged: String, on node: TreeNode) -> Bool { + // An agent onto a team of its own project joins it; onto No team, + // it is kept out of every team. + if dragged.hasPrefix("team:") { + let k = String(dragged.dropFirst(5)) + guard case .team(let pk, let name) = node.kind, let p = pane(k), let pr = p.projectID, + pk == key(unkey(k).machine, pr) else { return false } + setTeam(k, name.isEmpty ? AgentTeam.none : name) + return true + } // A project onto another groups the two, asked first; onto a group // it joins that group. Only on its own machine. if dragged.hasPrefix("project:") { diff --git a/macos/Sources/ConchApp/Store+Teams.swift b/macos/Sources/ConchApp/Store+Teams.swift new file mode 100644 index 00000000..f5045f7d --- /dev/null +++ b/macos/Sources/ConchApp/Store+Teams.swift @@ -0,0 +1,40 @@ +import AppKit +import ConchKit + +/// Agent teams in the window: putting an agent in one (pane.team.v1), a +/// new one, and a team's agents side by side (Teams.swift for the rules). +extension Store { + /// Puts a pane in a team by hand: a name, "-" for none whatever the + /// rules say, "" to leave it to the rules again. + func setTeam(_ k: String, _ team: String) { + let (m, id) = unkey(k) + guard let c = conns[m] else { return } + guard c.hello?.capabilities?.contains("pane.team.v1") == true else { + error = "conch on \(label(m)) is from an older build without teams: reload its server (conch server reload)." + return + } + struct Params: Encodable { var id: String; var team: String } + Task { + do { try await c.call("pane.team", Params(id: id, team: team)) } catch { self.error = "\(error)" } + } + } + + /// Asks a new team's name and puts the pane in it. A team made here + /// lives on the pane; Settings → Teams gives it a colour and rules. + func newTeam(_ k: String) { + guard let name = ask("New Team", info: "Put this agent in a team of this name. Settings → Teams gives a team a colour, and rules that put new agents in it.", + value: "", button: "Create")?.trimmingCharacters(in: .whitespaces), !name.isEmpty, name != AgentTeam.none else { return } + setTeam(k, name) + } + + /// A team's agents side by side in one tab, named for it. + func showTogether(_ keys: [String], name: String) { + let alive = keys.filter { pane($0)?.running == true && AppWindows.shared.holder(of: $0, except: self) == nil } + guard !alive.isEmpty else { return } + layout.gather(alive, name: name) + if let first = alive.first { focus(first) } + } + + /// A team's colour in the window. + func teamColor(_ name: String) -> RGB { ConchKit.teamColor(name, in: teams) } +} diff --git a/macos/Sources/ConchApp/Store.swift b/macos/Sources/ConchApp/Store.swift index be552a23..c54e3607 100644 --- a/macos/Sources/ConchApp/Store.swift +++ b/macos/Sources/ConchApp/Store.swift @@ -577,7 +577,7 @@ final class Store: ObservableObject { var tree: [TreeNode] { shownMachines.map { m in var node = (snapshots[m.id] ?? Snapshot()).tree(machine: m.id, label: m.label, in: ws, sessions: sessions, allBranches: allBranches, - savedHosts: savedHosts, folders: folders) + savedHosts: savedHosts, folders: folders, teams: teams) if !m.online { node.badge = m.state } return node } @@ -971,6 +971,8 @@ final class Store: ObservableObject { } let acts = parseActions(toml: toml ?? "") if acts != actions { actions = acts } + let ts = parseTeams(toml: toml ?? "") + if ts != teams { teams = ts } let cost = showsCost(toml: toml ?? "") if cost != showCost { showCost = cost } // Scenes of your own, read again each time as themes are: one @@ -2677,7 +2679,8 @@ final class Store: ObservableObject { var items = s.menu(for: node, machine: m, machineOnline: online, label: refLabel(m), among: catalog, folders: folders, savedHosts: m == "local" ? savedHosts : [], canGroup: canGroup(m), canGroupTask: conns[m]?.hello?.capabilities?.contains("group.task.v1") == true, - offerCloud: offersCloud, mobile: m == "local" ? mobileProjectIDs : []) + offerCloud: offersCloud, mobile: m == "local" ? mobileProjectIDs : [], + teams: teams, canTeam: conns[m]?.hello?.capabilities?.contains("pane.team.v1") == true) // The machines this workspace does not list, to bring one here. if case .machine = node.kind, workspaces.count > 1, !hiddenMachines.isEmpty, let at = items.firstIndex(where: { $0.action == .newSandbox }) { @@ -2701,6 +2704,8 @@ final class Store: ObservableObject { /// config.toml's [[actions]], read with the theme. @Published private(set) var actions: [CustomAction] = [] + /// config.toml's [[teams]] (Teams.swift), read with it. + @Published private(set) var teams: [AgentTeam] = [] /// Panes an action with keep runs in: left open when they exit, so /// what the command printed can be read. private var keptPanes: Set = [] @@ -2759,6 +2764,9 @@ final class Store: ObservableObject { switch a { case .open, .divider: activate(node) case .rename(let k): renamePane(k) + case .setTeam(let k, let t): setTeam(k, t) + case .newTeam(let k): newTeam(k) + case .showTogether(let keys, let name): showTogether(keys, name: name) case .prompt(let k): promptAgent(k) case .workbench(let k): openWorkbench(k) case .close(let k): closePane(k) @@ -3377,7 +3385,7 @@ final class Store: ObservableObject { if (d.issue ?? 0) > 0 || !d.ticket.isEmpty || !taskWhenArgs(d.when).isEmpty { guard let b = binary, let dir = snapshots[m]?.project(pr)?.path else { return } taskDraft = nil - let args = onMachine(m, taskArgs(dir: dir, prompt: d.prompt, agent: d.agent, branch: d.branch, issue: d.issue, ticket: d.ticket, when: d.when)) + let args = onMachine(m, taskArgs(dir: dir, prompt: d.prompt, agent: d.agent, branch: d.branch, issue: d.issue, ticket: d.ticket, when: d.when, team: d.team)) job(d.when.isEmpty ? "Starting the task" : "Scheduling the task") { let out = String(decoding: try await runConch(b, args), as: UTF8.self) let said = out.split(separator: "\n").last.map(String.init) ?? "" @@ -3402,6 +3410,7 @@ final class Store: ObservableObject { joinWorkspace(machine: m, pane: p) layout.open(key(m, p.id)) focusTerminal() + if !d.team.isEmpty { setTeam(key(m, p.id), d.team) } } catch { self.error = "Could not start the task: \(error)" } @@ -3464,7 +3473,7 @@ final class Store: ObservableObject { } /// A line of text from a small dialog, or nil when cancelled. - private func ask(_ title: String, info: String, value: String, button: String) -> String? { + func ask(_ title: String, info: String, value: String, button: String) -> String? { let a = NSAlert() a.messageText = title a.informativeText = info @@ -3636,6 +3645,8 @@ struct TaskDraft: Identifiable { var ticket = "" /// When it starts: "" now, else as `conch task -at` and the rest take it. var when = "" + /// The team it joins: a name, "-" for none, "" for its rules'. + var team = "" } private struct PaneRefParams: Encodable { var id: String } diff --git a/macos/Sources/ConchApp/Views.swift b/macos/Sources/ConchApp/Views.swift index 6bbae6f3..84f56150 100644 --- a/macos/Sources/ConchApp/Views.swift +++ b/macos/Sources/ConchApp/Views.swift @@ -1049,11 +1049,15 @@ struct NodeView: View { } /// What dragging this row carries, for a folder to take: a pane outside - /// every project, or a saved host. nil for a row that goes in none. + /// every project, or a saved host; an agent in a project goes to a + /// team of its project instead. nil for a row that goes in none. var dragID: String? { switch node.kind { case .agent(let k), .terminal(let k): - guard let p = store.pane(k), p.projectID == nil || store.snapshots[unkey(k).machine]?.project(p.projectID!) == nil else { return nil } + guard let p = store.pane(k) else { return nil } + if let pr = p.projectID, store.snapshots[unkey(k).machine]?.project(pr) != nil { + return p.agent != nil ? "team:" + k : nil + } return k case .savedHost(let h): return "host:" + h // A project dropped on another groups them, on a group joins it. @@ -1144,6 +1148,12 @@ struct NodeView: View { TreeIcon(open ? "folder-open" : "folder", look: store.appLook, color: Theme.text2, size: 12) case .group: TreeIcon("layout-grid", look: store.appLook) case .groupTask: TreeIcon("git-branch", look: store.appLook, color: Theme.text2, size: 12) + case .team(_, let name): + // Its colour, as the tabs and the status bar give it. + RoundedRectangle(cornerRadius: 3) + .fill(name.isEmpty ? Color.clear : Theme.color(store.teamColor(name))) + .overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(name.isEmpty ? Theme.muted : Color.clear, style: StrokeStyle(lineWidth: 1, dash: [2, 2]))) + .frame(width: 10, height: 10).frame(width: 14) case .section(let name): // Each group with an icon of its own, as Files and Sessions have. TreeIcon(name == "Agents" ? "bot" : name == "Branches" ? "git-branch" : "square-terminal", look: store.appLook, color: Theme.muted, size: 12) @@ -1382,7 +1392,7 @@ struct FolderDragDrop: ViewModifier { var target: Bool { switch node.kind { - case .folder, .cliSection, .group, .project: return true + case .folder, .cliSection, .group, .project, .team: return true default: return false } } @@ -1557,6 +1567,16 @@ struct TaskSheet: View { if project?.git != false { TextField("Branch (conch names one)", text: $draft.branch).frame(maxWidth: 260) } + // Which team it joins: its rules' by default, said by name. + if !store.teams.isEmpty, taskWhenArgs(draft.when).isEmpty { + let ruled = teamFor(store.teams, set: nil, project: project?.name, branch: draft.branch) + Picker("Team", selection: $draft.team) { + Text(ruled.map { "By rule: \($0)" } ?? "By rule: none").tag("") + ForEach(store.teams.map(\.name), id: \.self) { Text($0).tag($0) } + Text("No team").tag(AgentTeam.none) + } + .frame(maxWidth: 220) + } } HStack(spacing: 12) { if !issues.isEmpty { diff --git a/macos/Sources/ConchKit/Actions.swift b/macos/Sources/ConchKit/Actions.swift index 6406de22..31832125 100644 --- a/macos/Sources/ConchKit/Actions.swift +++ b/macos/Sources/ConchKit/Actions.swift @@ -237,8 +237,11 @@ public func taskWhenArgs(_ when: String) -> [String] { /// `conch task`'s arguments for a sheet that needs the command rather than /// task.create: an issue, a ticket, or a time other than now. -public func taskArgs(dir: String, prompt: String, agent: String, branch: String, issue: Int?, ticket: String = "", when: String) -> [String] { +public func taskArgs(dir: String, prompt: String, agent: String, branch: String, issue: Int?, ticket: String = "", when: String, team: String = "") -> [String] { var a = ["task", "-cwd", dir, "-agent", agent] + // A team is put on an agent that starts now: a later one has no pane. + let tm = team.trimmingCharacters(in: .whitespaces) + if !tm.isEmpty && taskWhenArgs(when).isEmpty { a += ["-team", tm] } let b = branch.trimmingCharacters(in: .whitespaces) if !b.isEmpty { a += ["-branch", b] } let t = ticket.trimmingCharacters(in: .whitespaces) diff --git a/macos/Sources/ConchKit/Broadcast.swift b/macos/Sources/ConchKit/Broadcast.swift index fca31693..8d3ac180 100644 --- a/macos/Sources/ConchKit/Broadcast.swift +++ b/macos/Sources/ConchKit/Broadcast.swift @@ -17,10 +17,12 @@ public enum BroadcastScope: Equatable, Sendable { case section(project: String, agents: Bool) /// A machine's panes in no project. case cli(String) + /// These panes (key(machine, id)) on a machine: a team's agents. + case panes(machine: String, keys: [String]) public var machine: String { switch self { - case .machine(let m), .cli(let m): return m + case .machine(let m), .cli(let m), .panes(let m, _): return m case .project(let pk), .section(let pk, _): return unkey(pk).machine } } @@ -50,6 +52,8 @@ extension Snapshot { case .section(let pk, let agents): panes = panes.filter { $0.projectID == unkey(pk).id && ($0.agent != nil) == agents } terminalsTicked = !agents + case .panes(_, let keys): + panes = panes.filter { keys.contains(key(m, $0.id)) } } let targets = panes.map { p in BroadcastTarget(key: key(m, p.id), name: p.displayName, agent: p.agent?.name, waiting: p.agent?.state == .blocked, diff --git a/macos/Sources/ConchKit/Layout.swift b/macos/Sources/ConchKit/Layout.swift index 8cb81358..f16a94b3 100644 --- a/macos/Sources/ConchKit/Layout.swift +++ b/macos/Sources/ConchKit/Layout.swift @@ -181,6 +181,21 @@ public struct Layout: Equatable, Sendable { active = tabs.count - 1 } + /// Puts panes side by side in a tab of their own, named, taken from + /// wherever they are (a pane is shown in one place): a team's agents. + /// Nothing happens for none. + public mutating func gather(_ panes: [String], name: String?) { + var keys: [String] = [] + for p in panes where !keys.contains(p) { keys.append(p) } + guard let root = SplitNode.arranged(keys) else { return } + for p in keys { close(p) } + var tab = Tab(pane: keys[0]) + tab.root = root + if let name, !name.isEmpty { tab.name = name } + tabs.append(tab) + active = tabs.count - 1 + } + /// Puts a new pane beside the focused one. With no tab yet it is a tab. public mutating func split(_ axis: SplitNode.Axis, with new: String) { guard let t = current else { diff --git a/macos/Sources/ConchKit/LucideIcons.swift b/macos/Sources/ConchKit/LucideIcons.swift index e0731f81..92d36b09 100644 --- a/macos/Sources/ConchKit/LucideIcons.swift +++ b/macos/Sources/ConchKit/LucideIcons.swift @@ -49,6 +49,8 @@ public enum LucideIcons { "box": ["M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z", "m3.3 7 8.7 5 8.7-5", "M12 22V12"], "zap": ["M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"], "lock": [svgRect(3, 11, 18, 11, 2), "M7 11V7a5 5 0 0 1 10 0v4"], + // Settings → Teams, and a team's row in the tree. + "users": ["M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2", svgCircle(9, 7, 4), "M22 21v-2a4 4 0 0 0-3-3.87", "M16 3.13a4 4 0 0 1 0 7.75"], "ticket": ["M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z", "M13 5v2", "M13 17v2", "M13 11v2"], "settings": ["M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z", svgCircle(12, 12, 3)], diff --git a/macos/Sources/ConchKit/Model.swift b/macos/Sources/ConchKit/Model.swift index 29acef33..168d2e3e 100644 --- a/macos/Sources/ConchKit/Model.swift +++ b/macos/Sources/ConchKit/Model.swift @@ -530,6 +530,9 @@ public enum NodeKind: Equatable, Sendable { case group(machine: String, name: String) /// A task across a group's repos: its agents, then its branch in each. case groupTask(machine: String, group: String, branch: String) + /// A team's agents in a project's Agents (Teams.swift); name "" is + /// the agents in no team. + case team(project: String, name: String) } public struct TreeNode: Identifiable, Equatable, Sendable { @@ -592,7 +595,7 @@ extension Snapshot { /// conversations, when they have been read. public func tree(machine: String = "local", label: String? = nil, in ws: Workspace? = nil, sessions: [String: Int] = [:], allBranches: Set = [], savedHosts: [SavedHost] = [], - folders: [String: [Folder]] = [:], now: Date = Date()) -> TreeNode { + folders: [String: [Folder]] = [:], teams: [AgentTeam] = [], now: Date = Date()) -> TreeNode { let shown = self.shown(in: ws, machine: machine) var projectNodes: [TreeNode] = [] for pr in projects where ws?.shows(pr, machine: machine) ?? true { @@ -621,7 +624,9 @@ extension Snapshot { if !agents.isEmpty { // Every agent, helpers nested under theirs included, as the TUI counts. sections.append(TreeNode(id: "s:\(pk):agents", kind: .section("Agents"), title: "Agents", badge: "\(agentPanes.count)", - children: agents, fold: tui + "/agents")) + children: byTeam(agents, panes: agentPanes, machine: machine, project: pk, name: pr.name, + teams: teams, fold: tui + "/agents"), + fold: tui + "/agents")) } if !branches.isEmpty { let count = max(pr.branches?.count ?? 0, listed.count) @@ -834,6 +839,34 @@ extension Snapshot { return [working > 0 ? "⠋\(working)" : "", w > 0 ? "⚑\(w)" : "", d > 0 ? "✓\(d)" : ""].filter { !$0.isEmpty }.joined(separator: " ") } + /// A project's agents under their teams, in config.toml's order, then + /// any team put on a pane by hand, then "No team" — or as they are + /// when none of them is in a team, so a project nobody sorted looks + /// as it always did. Helpers stay under the agent that started them. + func byTeam(_ roots: [TreeNode], panes: [PaneInfo], machine: String, project pk: String, name: String, + teams: [AgentTeam], fold: String) -> [TreeNode] { + let byKey = Dictionary(panes.map { (key(machine, $0.id), $0) }, uniquingKeysWith: { a, _ in a }) + func team(_ n: TreeNode) -> String? { + guard case .agent(let k) = n.kind, let p = byKey[k] else { return nil } + return teamFor(teams, set: p.team, project: name, branch: p.branch) + } + let placed = roots.map { (node: $0, team: team($0)) } + guard placed.contains(where: { $0.team != nil }) else { return roots } + func count(_ n: TreeNode) -> Int { + var c = 0 + if case .agent = n.kind { c = 1 } + return c + (n.children ?? []).reduce(0) { $0 + count($1) } + } + var out: [TreeNode] = [] + for t in teamNames(teams, panes: panes) + [""] { + let mine = placed.filter { ($0.team ?? "") == t }.map(\.node) + guard !mine.isEmpty else { continue } + out.append(TreeNode(id: "t:\(pk):\(t)", kind: .team(project: pk, name: t), title: t.isEmpty ? "No team" : t, + badge: "\(mine.reduce(0) { $0 + count($1) })", children: mine, fold: fold + "/team:" + t)) + } + return out + } + /// Panes as the TUI lists them (tree.go paneRows): each one an agent /// started under that agent, when both are in the same list, and an /// agent's subagents under it. A pane whose creator is listed elsewhere diff --git a/macos/Sources/ConchKit/Protocol.swift b/macos/Sources/ConchKit/Protocol.swift index ae31555c..f0263baa 100644 --- a/macos/Sources/ConchKit/Protocol.swift +++ b/macos/Sources/ConchKit/Protocol.swift @@ -117,6 +117,9 @@ public struct PaneInfo: Decodable, Identifiable, Equatable, Sendable { public var agent: AgentStatus? public var title: String? public var customName: Bool? + /// The team it was put in by hand (pane.team.v1), "-" for none on + /// purpose; nil leaves it to config.toml's [[teams]] rules (Teams.swift). + public var team: String? public var projectID: String? public var branch: String? /// The program's process on its machine. @@ -144,7 +147,7 @@ public struct PaneInfo: Decodable, Identifiable, Equatable, Sendable { public var listening: [Int]? enum CodingKeys: String, CodingKey { - case id, name, cwd, cols, rows, state, agent, title, branch, alert, pid, command, created, monitor, listening + case id, name, cwd, cols, rows, state, agent, title, branch, alert, pid, command, created, monitor, listening, team case exitCode = "exit_code" case customName = "custom_name" case projectID = "project_id" diff --git a/macos/Sources/ConchKit/RowMenu.swift b/macos/Sources/ConchKit/RowMenu.swift index 24a740c7..a5fbc9e4 100644 --- a/macos/Sources/ConchKit/RowMenu.swift +++ b/macos/Sources/ConchKit/RowMenu.swift @@ -41,6 +41,13 @@ public enum CheckOutThen: Equatable, Sendable { case nothing, agent, terminal } public enum RowAction: Equatable, Sendable { case open case rename(pane: String) + /// Puts a pane in a team by hand: a name, "-" for none whatever the + /// rules say, "" to leave it to the rules again (pane.team.v1). + case setTeam(pane: String, team: String) + /// Asks a new team's name, and puts the pane in it. + case newTeam(pane: String) + /// Shows panes side by side in a tab of their own, named. + case showTogether(panes: [String], name: String) case prompt(pane: String) /// The agent's branch in one tab: its files, a terminal, its chat and /// its own terminal, arranged by the workbench layout. @@ -235,13 +242,14 @@ extension Snapshot { public func menu(for node: TreeNode, machine: String, machineOnline: Bool = true, label: String? = nil, among: [MachineEntry] = [], folders: [String: [Folder]] = [:], savedHosts: [SavedHost] = [], canGroup: Bool = true, canGroupTask: Bool = true, offerCloud: Bool = false, - mobile: Set = []) -> [RowMenuItem] { + mobile: Set = [], teams: [AgentTeam] = [], canTeam: Bool = false) -> [RowMenuItem] { var out: [RowMenuItem] = [] switch node.kind { case .agent(let k), .terminal(let k): guard let p = pane(unkey(k).id) else { return [] } let agent = p.agent != nil out = [RowMenuItem("Open", .open), RowMenuItem("Rename…", .rename(pane: k))] + if agent && canTeam { out.append(teamMenu(p, key: k, teams: teams)) } if agent && p.running { out.append(RowMenuItem(p.agent?.state == .blocked ? "Prompt… (It Is Waiting for an Answer)" : "Prompt…", .prompt(pane: k))) out.append(RowMenuItem("Open Workbench", .workbench(pane: k))) @@ -371,6 +379,16 @@ extension Snapshot { out += projects.map { RowMenuItem("New Task in \($0.name)…", .newTask(project: key(machine, $0.id))) } if canGroup && projects.count > 1 { out += [.divider, RowMenuItem("New Project Group…", .newGroup(machine: machine))] } if !projects.isEmpty { out += [.divider, RowMenuItem("Collapse All Projects", .collapseProjects(machine: machine))] } + case .team(let pk, let name): + // A team's agents in a project: a message to them, or all of + // them at once in a tab. + let keys = node.agentKeys + guard !keys.isEmpty else { return [] } + let title = name.isEmpty ? "No team" : name + var items = [RowMenuItem("Show Side by Side", .showTogether(panes: keys, name: "\(title) · \(project(unkey(pk).id)?.name ?? "")"))] + let scope = BroadcastScope.panes(machine: machine, keys: keys) + if machineOnline && hasRunning(scope) { items.append(RowMenuItem("Broadcast to \(name.isEmpty ? "These Agents" : "This Team")…", .broadcast(scope))) } + return items case .section(let name): // A project's Agents or Terminals: a message to those alone. guard machineOnline, name == "Agents" || name == "Terminals", node.id.hasPrefix("s:") else { return [] } @@ -443,6 +461,18 @@ extension Snapshot { extension Snapshot { /// Move to Folder ▸: the section's folders, the one it is in ticked, /// out of them when it is in one, and a new folder for it. + /// An agent's Team ▸: the teams, the one it is in ticked; a new one; + /// none; and, for one put in a team by hand, back to the rules. + func teamMenu(_ p: PaneInfo, key k: String, teams: [AgentTeam]) -> RowMenuItem { + let now = teamFor(teams, set: p.team, project: p.projectID.flatMap { project($0)?.name }, branch: p.branch) + var kids = teamNames(teams, panes: panes).map { RowMenuItem(($0 == now ? "✓ " : "") + $0, .setTeam(pane: k, team: $0)) } + if !kids.isEmpty { kids.append(.divider) } + kids.append(RowMenuItem("New Team…", .newTeam(pane: k))) + if now != nil { kids.append(RowMenuItem("No Team", .setTeam(pane: k, team: AgentTeam.none))) } + if let set = p.team, !set.isEmpty { kids.append(RowMenuItem("By Rule", .setTeam(pane: k, team: ""))) } + return RowMenuItem("Team", .divider, children: kids) + } + func folderMenu(_ item: FolderItem, machine: String, section: FolderSection, folders: [String: [Folder]], panes: [PaneInfo]) -> RowMenuItem { let fs = folders[folderKey(machine: machine, section: section)] ?? [] let now = currentFolder(item, machine: machine, section: section, folders: fs) @@ -583,8 +613,17 @@ extension TreeNode { case .branch(let pk, _, _): return unkey(pk).machine case .section: return unkey(String(id.dropFirst(2).split(separator: ":").first ?? "")).machine case .cliSection(let m, _), .folder(let m, _, _), .group(let m, _), .groupTask(let m, _, _): return m + case .team(let pk, _): return unkey(pk).machine } } + + /// Every agent's pane under this row, helpers included, in order. + public var agentKeys: [String] { + var out: [String] = [] + if case .agent(let k) = kind { out.append(k) } + for c in children ?? [] { out += c.agentKeys } + return out + } } /// The capabilities a server lacks that this app's own conch has: what a diff --git a/macos/Sources/ConchKit/SettingsIcons.swift b/macos/Sources/ConchKit/SettingsIcons.swift index 6c25466f..0276662a 100644 --- a/macos/Sources/ConchKit/SettingsIcons.swift +++ b/macos/Sources/ConchKit/SettingsIcons.swift @@ -79,7 +79,7 @@ let sfSymbols: [String: String] = [ "shield-check": "checkmark.shield", "git-merge": "arrow.triangle.merge", "sparkles": "sparkles", "terminal": "terminal", "square-terminal": "apple.terminal", "server": "server.rack", "refresh-cw": "arrow.clockwise", "smartphone": "iphone", "tablet-smartphone": "ipad.and.iphone", "laptop": "laptopcomputer", - "box": "shippingbox", "zap": "bolt", "lock": "lock", "book-open": "book", "ticket": "ticket", + "box": "shippingbox", "zap": "bolt", "lock": "lock", "users": "person.3", "book-open": "book", "ticket": "ticket", // The window's sidebar: machines, a workspace, projects and what is // in them. "cloud": "cloud", "layers": "square.stack.3d.up", "folder": "folder", "folder-open": "folder", @@ -103,7 +103,7 @@ let tileColors: [String: String] = [ "palette": "#e05aa0", "keyboard": "#8e8e93", "bell": "#ff453a", "bot": "#ff9f0a", "book-open": "#bf5af2", "shield-check": "#30d158", "sparkles": "#5e5ce6", "git-merge": "#f05033", "terminal": "#636366", "square-terminal": "#64748b", "laptop": "#0a84ff", "server": "#0a84ff", - "smartphone": "#32ade6", "tablet-smartphone": "#00a3a3", "box": "#ac8e68", "refresh-cw": "#30b0a6", "zap": "#e6b800", "lock": "#8e8e93", "ticket": "#5e5ce6", + "smartphone": "#32ade6", "tablet-smartphone": "#00a3a3", "box": "#ac8e68", "refresh-cw": "#30b0a6", "zap": "#e6b800", "lock": "#8e8e93", "users": "#ff9500", "ticket": "#5e5ce6", "cloud": "#64d2ff", "layers": "#5e5ce6", "folder": "#3a8ee6", "folder-open": "#3a8ee6", "globe": "#32ade6", "monitor": "#5e8ebf", "git-branch": "#f05033", "history": "#a2845e", ] diff --git a/macos/Sources/ConchKit/SettingsTables.swift b/macos/Sources/ConchKit/SettingsTables.swift index fe628725..8d9bc672 100644 --- a/macos/Sources/ConchKit/SettingsTables.swift +++ b/macos/Sources/ConchKit/SettingsTables.swift @@ -191,6 +191,8 @@ public func settingsRowTitle(_ table: String, _ row: [String: JSONValue]) -> Str if !s("name").isEmpty { return s("name") } if !s("run").isEmpty { return s("run") } return "New action" + case "teams": + return s("name").isEmpty ? "New team" : s("name") case "permissions": let tool = s("tool"), match = s("match"), action = s("action") if tool.isEmpty && match.isEmpty && action.isEmpty { return "New rule" } @@ -210,6 +212,9 @@ public func settingsRowDetail(_ table: String, _ row: [String: JSONValue]) -> St case "actions": let on = (row["on"]?.array ?? []).compactMap(\.string) return on.isEmpty ? "every row" : on.joined(separator: ", ") + case "teams": + let rules = (row["projects"]?.array ?? []).compactMap(\.string) + (row["branches"]?.array ?? []).compactMap(\.string) + return rules.isEmpty ? "by hand" : rules.joined(separator: ", ") case "permissions": let agent = row["agent"]?.string ?? "", project = row["project"]?.string ?? "" return [agent.isEmpty ? "every agent" : agent, project.isEmpty ? "every project" : project].joined(separator: " · ") diff --git a/macos/Sources/ConchKit/SettingsUI.swift b/macos/Sources/ConchKit/SettingsUI.swift index 45955629..8e84e4c5 100644 --- a/macos/Sources/ConchKit/SettingsUI.swift +++ b/macos/Sources/ConchKit/SettingsUI.swift @@ -171,7 +171,7 @@ extension SettingsNav { /// for a schema without Git; with one, it is on Git's page. public static let groups: [(String, [String])] = [ ("General", ["ui", "app", "keys", "notify", "update"]), - ("Agents", ["agents", skills, "permissions", "brain"]), + ("Agents", ["agents", skills, "teams", "permissions", "brain"]), ("Workspace", ["git", "verify", "shell", "preview", "actions"]), ("Machines", ["remote", "sandbox", "web"]), ] diff --git a/macos/Sources/ConchKit/Teams.swift b/macos/Sources/ConchKit/Teams.swift new file mode 100644 index 00000000..38732128 --- /dev/null +++ b/macos/Sources/ConchKit/Teams.swift @@ -0,0 +1,121 @@ +import Foundation + +// Agent teams: agents grouped by what they work on — backend, UI, a +// report — across projects and branches. A team is put on a pane by hand +// (pane.team, PaneInfo.team) or by config.toml's [[teams]] rules; both +// sides read the rules alike (internal/config/teams.go), so the app, the +// TUI's CLI and a phone say the same team for an agent. + +/// One [[teams]] entry. +public struct AgentTeam: Equatable, Sendable { + public var name: String + /// A colour name (AgentTeam.colors), "#rrggbb", or "" for one by place. + public var color: String + public var projects: [String] + public var branches: [String] + + public init(name: String, color: String = "", projects: [String] = [], branches: [String] = []) { + self.name = name + self.color = color + self.projects = projects + self.branches = branches + } + + /// The colours a team may name, as config.TeamColors lists them, in the + /// order a team without one takes them by its place. + public static let colors: [(name: String, rgb: RGB)] = [ + ("blue", RGB("#3E7BD6")), ("orange", RGB("#E07B2A")), ("purple", RGB("#8E5CD9")), + ("teal", RGB("#2E9D9A")), ("green", RGB("#3C9D4E")), ("red", RGB("#D9534F")), + ("pink", RGB("#D6589B")), ("yellow", RGB("#C9A227")), ("gray", RGB("#8A9399")), + ] + + /// Set on a pane by hand: kept out of every team, whatever the rules say. + public static let none = "-" +} + +/// config.toml's [[teams]], in order; a team without a name is left out, +/// as Go leaves it out of matching. +public func parseTeams(toml: String) -> [AgentTeam] { + var out: [AgentTeam] = [] + var cur: AgentTeam? = nil + func flush() { + if let c = cur, !c.name.isEmpty { out.append(c) } + cur = nil + } + for raw in toml.components(separatedBy: "\n") { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.hasPrefix("[") { + flush() + if line.replacingOccurrences(of: " ", with: "").hasPrefix("[[teams]]") { cur = AgentTeam(name: "") } + continue + } + guard cur != nil, !line.hasPrefix("#"), let eq = line.firstIndex(of: "=") else { continue } + let k = line[.. String? { + switch set ?? "" { + case AgentTeam.none: return nil + case "": break + case let s: return s + } + for t in teams where !t.name.isEmpty { + if let p = project, !p.isEmpty, t.projects.contains(where: { $0.caseInsensitiveCompare(p) == .orderedSame }) { return t.name } + if let b = branch, !b.isEmpty, t.branches.contains(where: { globMatch($0, b) }) { return t.name } + } + return nil +} + +/// A branch pattern: * matches any run of characters, slashes included. +public func globMatch(_ pattern: String, _ s: String) -> Bool { + guard pattern.contains("*") else { return pattern == s } + let parts = pattern.components(separatedBy: "*") + guard s.hasPrefix(parts[0]) else { return false } + var rest = Substring(s.dropFirst(parts[0].count)) + let last = parts[parts.count - 1] + for p in parts.dropFirst().dropLast() where !p.isEmpty { + guard let r = rest.range(of: p) else { return false } + rest = rest[r.upperBound...] + } + return rest.count >= last.count && rest.hasSuffix(last) +} + +/// A team's colour: what its entry names, else by its place among the +/// teams; a team put on a pane by hand that config.toml does not list +/// takes one from its name, the same every time. +public func teamColor(_ name: String, in teams: [AgentTeam]) -> RGB { + let palette = AgentTeam.colors + if let i = teams.firstIndex(where: { $0.name == name }) { + let c = teams[i].color + if let named = palette.first(where: { $0.name == c }) { return named.rgb } + if c.range(of: #"^#[0-9a-fA-F]{6}$"#, options: .regularExpression) != nil { return RGB(c) } + return palette[i % palette.count].rgb + } + var h: UInt32 = 2166136261 + for b in name.utf8 { h = (h ^ UInt32(b)) &* 16777619 } + return palette[Int(h % UInt32(palette.count))].rgb +} + +/// The team names to offer for a pane: config.toml's, then any put on a +/// pane by hand that it does not list, in the order first seen. +public func teamNames(_ teams: [AgentTeam], panes: [PaneInfo]) -> [String] { + var out = teams.map(\.name) + for p in panes { + if let t = p.team, !t.isEmpty, t != AgentTeam.none, !out.contains(t) { out.append(t) } + } + return out +} diff --git a/macos/Tests/ConchKitTests/TeamsTests.swift b/macos/Tests/ConchKitTests/TeamsTests.swift new file mode 100644 index 00000000..e84483da --- /dev/null +++ b/macos/Tests/ConchKitTests/TeamsTests.swift @@ -0,0 +1,178 @@ +import Foundation +import Testing +@testable import ConchKit + +@Suite struct TeamsTests { + let teams = [ + AgentTeam(name: "Backend", color: "blue", projects: ["api", "worker"], branches: ["conch/cloud-*"]), + AgentTeam(name: "UI", projects: ["web"], branches: ["ui/*", "*-redesign", "*desktop*"]), + AgentTeam(name: "Everything", branches: ["*"]), + ] + + @Test func readsTheTeamsOfConfigToml() { + let toml = """ + [app] + name = "not a team" + + [[teams]] + name = "Backend" + color = "Blue" + projects = ["api", "worker"] + branches = ["conch/cloud-*"] + + [[teams]] + # no name: left out + projects = ["x"] + + [[teams]] + name = " UI " + + [[actions]] + name = "Run tests" + run = "go test ./..." + """ + let got = parseTeams(toml: toml) + #expect(got == [AgentTeam(name: "Backend", color: "blue", projects: ["api", "worker"], branches: ["conch/cloud-*"]), AgentTeam(name: "UI")]) + #expect(parseTeams(toml: "").isEmpty) + } + + // The same cases as Go's TestTeamFor: the app and the CLI say the same team. + @Test func ruleOrHand() { + let cases: [(String?, String?, String?, String?)] = [ + (nil, "api", "main", "Backend"), + (nil, "API", nil, "Backend"), + (nil, "conch", "conch/cloud-agent", "Backend"), + (nil, "conch", "ui/nav/dark", "UI"), + (nil, "conch", "checkout-redesign", "UI"), + (nil, "conch", "conch/readme-desktop-shots", "UI"), + (nil, "web", "conch/cloud-x", "Backend"), + (nil, "conch", "anything", "Everything"), + (nil, nil, nil, nil), + ("", "", "", nil), + ("UX", "api", "main", "UX"), + ("Gone", "api", "main", "Gone"), + ("-", "api", "main", nil), + ] + for (set, project, branch, want) in cases { + #expect(teamFor(teams, set: set, project: project, branch: branch) == want, "\(String(describing: set)) \(String(describing: project)) \(String(describing: branch))") + } + #expect(teamFor([], set: nil, project: "api", branch: "main") == nil) + } + + @Test func branchPatterns() { + let cases: [(String, String, Bool)] = [ + ("main", "main", true), ("main", "mainline", false), + ("ui/*", "ui/", true), ("ui/*", "ux/a", false), + ("*-copy", "a-copy", true), ("*-copy", "-copy", true), ("*-copy", "copy", false), + ("a*b*c", "abc", true), ("a*b*c", "axxbyyc", true), ("a*b*c", "acb", false), + ("a*a", "a", false), ("*", "", true), ("**", "x/y", true), + ] + for (p, s, ok) in cases { #expect(globMatch(p, s) == ok, "\(p) \(s)") } + } + + @Test func colours() { + #expect(teamColor("Backend", in: teams) == RGB("#3E7BD6")) // named + #expect(teamColor("UI", in: teams) == AgentTeam.colors[1].rgb) // by place + #expect(teamColor("Hex", in: [AgentTeam(name: "Hex", color: "#112233")]) == RGB("#112233")) + // One put on a pane by hand: from its name, the same every time. + #expect(teamColor("Ad hoc", in: teams) == teamColor("Ad hoc", in: [])) + #expect(AgentTeam.colors.map(\.name) == ["blue", "orange", "purple", "teal", "green", "red", "pink", "yellow", "gray"]) + } + + func agent(_ id: String, project: String = "r1", branch: String, team: String? = nil, state: AgentState = .working) -> PaneInfo { + var p = PaneInfo(id: id, name: id, agent: AgentStatus(name: "claude", state: state), projectID: project, branch: branch) + p.team = team + return p + } + + func agentsSection(_ s: Snapshot, teams: [AgentTeam]) -> TreeNode? { + let tree = s.tree(machine: "local", teams: teams) + func find(_ n: TreeNode) -> TreeNode? { + if case .section("Agents") = n.kind { return n } + for c in n.children ?? [] { if let f = find(c) { return f } } + return nil + } + return find(tree) + } + + @Test func aProjectsAgentsUnderTheirTeams() throws { + let s = Snapshot(panes: [ + agent("p1", branch: "conch/cloud-agent"), + agent("p2", branch: "ui/nav"), + agent("p3", branch: "docs", team: "Report"), + agent("p4", branch: "ui/x", team: "-"), + agent("p5", branch: "conch/cloud-y"), + ], projects: [ProjectInfo(id: "r1", name: "conch", path: "/c")]) + let rules = [teams[0], teams[1]] + let agents = try #require(agentsSection(s, teams: rules)) + let kids = agents.children ?? [] + #expect(kids.map(\.title) == ["Backend", "UI", "Report", "No team"]) + #expect(kids.map(\.badge) == ["2", "1", "1", "1"]) + #expect(kids[0].kind == .team(project: "local|r1", name: "Backend") && kids[3].kind == .team(project: "local|r1", name: "")) + #expect(kids[0].agentKeys == ["local|p1", "local|p5"]) + #expect(kids[0].fold?.hasSuffix("/agents/team:Backend") == true) + // Nobody in a team: the list as it always was. + let plain = Snapshot(panes: [agent("p1", branch: "x"), agent("p2", branch: "y")], projects: [ProjectInfo(id: "r1", name: "conch", path: "/c")]) + let flat = try #require(agentsSection(plain, teams: rules)) + #expect((flat.children ?? []).allSatisfy { if case .agent = $0.kind { return true }; return false }) + #expect(try #require(agentsSection(plain, teams: [])).children?.count == 2) + } + + @Test func menus() throws { + var p1 = agent("p1", branch: "conch/cloud-agent") + let p2 = agent("p2", branch: "x", team: "Hand") + p1.team = nil + let s = Snapshot(panes: [p1, p2], projects: [ProjectInfo(id: "r1", name: "conch", path: "/c")]) + let row = TreeNode(id: "pane:local|p1", kind: .agent("local|p1"), title: "p1") + // No team menu from a server without teams. + #expect(!s.menu(for: row, machine: "local", teams: teams).contains { $0.title == "Team" }) + let menu = s.menu(for: row, machine: "local", teams: teams, canTeam: true) + let team = try #require(menu.first { $0.title == "Team" }) + let titles = team.children.map(\.title) + #expect(titles == ["✓ Backend", "UI", "Everything", "Hand", "", "New Team…", "No Team"]) + #expect(team.children[1].action == .setTeam(pane: "local|p1", team: "UI")) + // One put in a team by hand can go back to the rules. + let row2 = TreeNode(id: "pane:local|p2", kind: .agent("local|p2"), title: "p2") + let kids2 = try #require(s.menu(for: row2, machine: "local", teams: teams, canTeam: true).first { $0.title == "Team" }).children + #expect(kids2.contains { $0.action == .setTeam(pane: "local|p2", team: "") && $0.title == "By Rule" }) + #expect(kids2.first { $0.title == "✓ Hand" } != nil) + // A team's row: side by side, and a message to its agents. + let teamRow = TreeNode(id: "t:local|r1:Backend", kind: .team(project: "local|r1", name: "Backend"), title: "Backend", + children: [TreeNode(id: "pane:local|p1", kind: .agent("local|p1"), title: "p1")]) + let items = s.menu(for: teamRow, machine: "local") + #expect(items.map(\.title) == ["Show Side by Side", "Broadcast to This Team…"]) + #expect(items[0].action == .showTogether(panes: ["local|p1"], name: "Backend · conch")) + #expect(s.broadcastTargets(.panes(machine: "local", keys: ["local|p1"])).map(\.key) == ["local|p1"]) + #expect(teamRow.machine == "local") + #expect(s.menu(for: TreeNode(id: "t", kind: .team(project: "local|r1", name: ""), title: "No team"), machine: "local").isEmpty) + } + + @Test func gatherPutsTeamInOneTab() { + var l = Layout() + l.open("a") + l.split(.horizontal, with: "b") + l.open("c") + l.gather(["a", "c", "a"], name: "UI · web") + #expect(l.tabs.count == 2) // b alone, then the team's + #expect(l.tabs.last?.root.panes == ["a", "c"] && l.tabs.last?.name == "UI · web" && l.active == 1) + #expect(l.tabs.first?.root.panes == ["b"]) + var empty = Layout() + empty.gather([], name: "x") + #expect(empty.tabs.isEmpty) + } + + @Test func newTaskTeam() { + let now = taskArgs(dir: "/c", prompt: "do it", agent: "claude", branch: "", issue: 3, when: "", team: " UI ") + #expect(now == ["task", "-cwd", "/c", "-agent", "claude", "-team", "UI", "-issue", "3", "do it"]) + // A task kept for later has no pane to put in a team. + #expect(!taskArgs(dir: "/c", prompt: "x", agent: "claude", branch: "", issue: nil, when: "+30m", team: "UI").contains("-team")) + #expect(!taskArgs(dir: "/c", prompt: "x", agent: "claude", branch: "", issue: nil, when: "", team: "").contains("-team")) + } + + @Test func decodesTheTeamFromAServer() throws { + let p = try JSONDecoder().decode(PaneInfo.self, from: Data(#"{"id":"p1","name":"x","state":"running","team":"UI"}"#.utf8)) + #expect(p.team == "UI") + let old = try JSONDecoder().decode(PaneInfo.self, from: Data(#"{"id":"p1","name":"x","state":"running"}"#.utf8)) + #expect(old.team == nil) + } +} diff --git a/web/src/app/docs/cli/page.mdx b/web/src/app/docs/cli/page.mdx index 5ab6f9c6..245ca29c 100644 --- a/web/src/app/docs/cli/page.mdx +++ b/web/src/app/docs/cli/page.mdx @@ -74,7 +74,7 @@ Inside one of its own panes it refuses, the way tmux refuses a nested session: t | --- | --- | | `conch view` | what the terminal is showing: its tabs, what each holds, and which pane has the keyboard. The server keeps no layout of its own — a TUI publishes this and conch carries it | | `conch show [-name NAME] ID...` | ask the terminal to put those panes in front of the person: one is brought up, several are gathered side by side in one tab. A request, not an order | -| `conch status [-wide] [-json]` (or `conch ls`) | show server and pane status. In a terminal it fits the window: a line saying how many agents are working, waiting, done or idle, then each pane's ID, name, agent and its state, what an idle agent [left running](/docs/agents#left-running-in-the-background) (a BACKGROUND column, when any has; the summary line counts them), ssh host (when any pane has one), folder from `~` (cut from the start when it must be, since the end names it) and command (not an agent's, which is the agent; left out when there is no room to say anything). Piped — or with `-wide` — it is the full table scripts read, unchanged: ID, name, state, agent, ssh host, size, folder and command of each pane; `-json` gives the server and its panes as JSON (`{"server": null, "panes": []}` with no server), an agent's background jobs as `agent.background` (how many) and `agent.jobs` (`[{pid, command, since, ports}]`). The ssh column is the host a terminal is logged in to with plain `ssh` right now — the one `-ssh` on `upload` and `download` reaches — and `-` for the rest. Its first line gives the server's uptime, which counts from the *first* server of a chain of reloads — its panes have been alive that whole time — and then `(reloaded N ago)` for when the running binary was loaded, which is the one that says whether your last build got there | +| `conch status [-wide] [-json] [-team NAME]` (or `conch ls`) | show server and pane status; `-team` only that [team](/docs/configuration#teams)'s agents. In a terminal it fits the window: a line saying how many agents are working, waiting, done or idle, then each pane's ID, name, agent and its state, what an idle agent [left running](/docs/agents#left-running-in-the-background) (a BACKGROUND column, when any has; the summary line counts them), ssh host (when any pane has one), folder from `~` (cut from the start when it must be, since the end names it) and command (not an agent's, which is the agent; left out when there is no room to say anything). Piped — or with `-wide` — it is the full table scripts read, unchanged: ID, name, state, agent, ssh host, size, folder and command of each pane; `-json` gives the server and its panes as JSON (`{"server": null, "panes": []}` with no server), an agent's background jobs as `agent.background` (how many) and `agent.jobs` (`[{pid, command, since, ports}]`). The ssh column is the host a terminal is logged in to with plain `ssh` right now — the one `-ssh` on `upload` and `download` reaches — and `-` for the rest. Its first line gives the server's uptime, which counts from the *first* server of a chain of reloads — its panes have been alive that whole time — and then `(reloaded N ago)` for when the running binary was loaded, which is the one that says whether your last build got there | | `conch new [-cwd DIR] [-name N] -- CMD [ARGS...]` | start a pane (default command: your shell; default folder: the current one, or with `-m` that machine's home) and print its ID | | `conch new -agent claude [-account NAME] [-cwd DIR] [-- CLAUDE ARGS...]` | start Claude Code with state tracking; `-account` starts it on another of its [accounts](/docs/agents#several-accounts) | | `conch account list \| add AGENT NAME [-dir DIR] \| remove AGENT NAME` | an agent's other [accounts](/docs/agents#several-accounts) (Claude Code, Codex), each with its plan usage and agents | @@ -154,6 +154,7 @@ conch tells who is asking from the operating system — the process at the other | `conch agent install NAME` | run an agent's installer in a pane and wait for it | | `conch agent prompt [-wait] [-until done,idle,waiting] [-timeout 30m] [-at TIME] ID TEXT...` | send the pane's agent its next message and submit it. Unlike `conch send` it only types into an agent, and never into one waiting on a question — a permission prompt, a menu — where its Enter could answer something nobody read: it exits 3 and types nothing (a question that comes up in the moment before Enter leaves the message typed but unsent). With `-wait` it blocks until the work the message starts has ended — not on the `done` or `idle` still showing from before it — and prints `ID AGENT STATE`; a question the agent asks ends it too, unless `-until` leaves `waiting` out. An agent already working gets the message when that work ends, so that work is the one waited for. Exits 124 if `-timeout` runs out, and fails if the pane ends or another program takes it over. With `-at` (`14:05`, `+30m`, `2026-10-15 09:00`) the server keeps the message and sends it then, once the agent is free — see [Later, and on a schedule](/docs/tasks#later-and-on-a-schedule) | | `conch agent question ID` | what a waiting agent asks and its choices, read off its screen as the [phone](/docs/phone) reads them, as JSON: `{"id": "q_…", "text": "Allow command?", "choices": [{"choice": "1", "label": "Yes", "default": true}, …]}`. `null` when the agent is not waiting, which is an answer rather than an error. The [Mac app](/docs/mac-app) shows it as buttons | +| `conch agent team ID [TEAM \| - \| -clear]` | which [team](/docs/configuration#teams) an agent is in, by hand or by rule, or put it in one: `-` keeps it out of every team, `-clear` leaves it to the rules | | `conch agent answer [-question QID] ID CHOICE` | pick one of those choices without opening the pane: the agent's cursor is moved to it and Enter pressed, as the phone does. With `-question` it is refused if the question has changed since it was read, so a late answer cannot land on the next question | | `conch agent skill [-skill NAMES] [-agent NAMES] [-remove] [-apply]` | install conch's skills — `conch` (how an agent in a conch pane starts, prompts and reads another), `conch-team`, `conch-review`, `conch-ship`, `conch-factory` and `conch-autopilot` ([agents working together](/docs/agents-together)) — where each agent reads your skills: `~/.claude/skills/conch` and the rest for Claude, `~/.agents/skills/conch` for Codex, Gemini and OpenCode, `~/.config/devin/skills/conch` for Devin. `-skill conch,conch-review` installs only those (a name conch has no skill by is refused before anything is written). Without `-apply` it only says what it would do; `-remove` takes it away again. A `conch` skill there that conch didn't write is left alone. With `-m` it installs on that machine. Not from an agent's pane: it is your setup | | `conch skill [-list \| NAME]` | print conch's skill (or the one named; `-list` names them) to stdout instead of installing it, for an agent whose skills folder conch does not manage, a system prompt you assemble yourself, or a sandbox where it goes inline. The same bytes the installer writes | @@ -197,7 +198,7 @@ Projects kept together because they change together — an API, its web app, the ### task -`conch task [-cwd DIR] [-branch B] [-base B] [-agent NAME] [-account NAME] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] PROMPT` creates a branch and worktree and starts an agent with the prompt (`-account` on that [account](/docs/agents#several-accounts) of the agent's; `-at` later, `-every` again and again, `-queue` when the project has room, `-after` once other work has finished, on top of it: see [Later, and on a schedule](/docs/tasks#later-and-on-a-schedule); `conch schedule` lists and removes what is scheduled); in a folder that isn't a git repository — or, with `-m` and no `-cwd`, the machine's home — the agent works there with no branch. See [Tasks](/docs/tasks). +`conch task [-cwd DIR] [-branch B] [-base B] [-agent NAME] [-account NAME] [-n N] [-name N] [-at TIME] [-every SPAN] [-queue [-wip N]] [-after REF] [-issue N | -ticket KEY] [-team NAME] PROMPT` creates a branch and worktree and starts an agent with the prompt (`-account` on that [account](/docs/agents#several-accounts) of the agent's; `-at` later, `-every` again and again, `-queue` when the project has room, `-after` once other work has finished, on top of it: see [Later, and on a schedule](/docs/tasks#later-and-on-a-schedule); `conch schedule` lists and removes what is scheduled); in a folder that isn't a git repository — or, with `-m` and no `-cwd`, the machine's home — the agent works there with no branch. See [Tasks](/docs/tasks). | Flag | Default | | --- | --- | diff --git a/web/src/app/docs/configuration/page.mdx b/web/src/app/docs/configuration/page.mdx index 6731c93e..51905bcc 100644 --- a/web/src/app/docs/configuration/page.mdx +++ b/web/src/app/docs/configuration/page.mdx @@ -181,6 +181,12 @@ project = "" # the project whose tickets are listed: "PROJ" xcode = "" # Xcode.app for the iOS simulators; "" finds it in /Applications android_sdk = "" # the Android SDK, for conch preview's emulators; "" finds it +[[teams]] # agents grouped by what they work on; none by default +name = "Backend" # what the tree and the Team menu call it +color = "blue" # blue, orange, purple, teal, green, red, pink, yellow, gray or #rrggbb +projects = ["api"] # project names whose agents join it +branches = ["conch/cloud-*"] # branch patterns, * for anything + [[actions]] # your own commands on the row menus; none by default name = "Run tests" # the label on the menu run = "go test ./..." # the command, as a shell reads it @@ -384,6 +390,31 @@ Where the phones of a mobile preview come from — Conch.app's [Mobile Preview]( | `xcode` | `""` | the Xcode whose iPhone and iPad simulators are shown: `Xcode.app`, or its `Contents/Developer` folder. `""` uses the Xcode `xcode-select` chose, or `DEVELOPER_DIR` — and when `xcode-select` points at the Command Line Tools, which have no simulators, the Xcode in `/Applications` (`Xcode.app` before a beta). One that is not an Xcode is said in the preview rather than used | | `android_sdk` | `""` | the Android SDK, for `conch preview`'s emulators and phones; `""` looks in `ANDROID_HOME`, `ANDROID_SDK_ROOT` and where Android Studio installs it | +## `[[teams]]` + +Agents grouped by what they work on — backend, UI, a report — so a project with a dozen agents reads as a few teams. In [Conch.app](/docs/mac-app) a project's **Agents** splits into a row per team, each with its count, then **No team**; a project where nobody is in a team keeps its single list. + +```toml +[[teams]] +name = "Backend" +color = "blue" +projects = ["api", "worker"] +branches = ["conch/cloud-*"] + +[[teams]] +name = "UI" +branches = ["ui/*", "*-redesign"] +``` + +A new agent joins the first team whose rule matches its project's name or its branch (`*` matches anything, slashes too). One put in a team by hand stays there whatever the rules say: right-click an agent → **Team**, drag it onto a team's row, pick one in **New Task** (⌘N), or from a shell `conch agent team p3 UI` (`-` for no team, `-clear` back to the rules) and `conch task -team UI`. A team's row has **Show Side by Side**, its agents in one tab, and **Broadcast to This Team…**; `conch status -team UI` lists its agents. **Settings → Teams** edits these. A team set by hand lives on the pane and survives a server reload; it needs a server with `pane.team.v1`. + +| Key | Default | Meaning | +| --- | --- | --- | +| `name` | — | the team's name | +| `color` | by its place | `blue`, `orange`, `purple`, `teal`, `green`, `red`, `pink`, `yellow`, `gray`, or `#rrggbb` | +| `projects` | none | project names, any case, whose agents join it | +| `branches` | none | branch patterns, `*` for anything: `ui/*`, `*-redesign` | + ## `[[actions]]` Commands of your own on conch's menus. Most of what a plugin system gets asked for is this: run the project's tests on this branch, open a pull request, tail a log, open the worktree in something else. Each is already a shell command somebody runs by hand in that checkout — conch's part is knowing *which* checkout. diff --git a/web/src/app/docs/mac-app/page.mdx b/web/src/app/docs/mac-app/page.mdx index 9e09137c..b63a9dbc 100644 --- a/web/src/app/docs/mac-app/page.mdx +++ b/web/src/app/docs/mac-app/page.mdx @@ -29,10 +29,12 @@ The sidebar is conch's tree; tabs and splits work as in the TUI. **Windows:** `⌥⌘N`, or **Open in New Window** on a workspace or project. -**Background:** a scene behind the window, a board of your agents or [your own](/docs/configuration#scenes-of-your-own): **Settings → Mac app → Background**. +**Background:** a scene, or [your own](/docs/configuration#scenes-of-your-own): **Settings → Mac app → Background**. **How:** click a row to open it, right-click for its menu. ⌘. finds the next waiting agent, ⌃⌘S hides the sidebar. +**Teams:** right-click an agent → **Team**, or drag it to a [team](/docs/configuration#teams). + ## Settings **How:** ⚙ in the status bar, or ⌘,. **View → Theme** and **View → Style** change the look. **Agents** installs agents.