13 "github.com/stretchr/testify/require"
16 func TestDaemonToolsCreateAndTellAChildDuringATurn(t *testing.T) {
18 server := newModelFake(t)
19 agents, err := openDaemonAgents(t.Context(), dir, server.URL, ModelAPIKey(modelTestKey), defaultConfig().Compactor, newTestClock().Now, discardLog())
20 require.NoError(t, err)
23 require.NoError(t, agents.Close())
28 server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
29 if call.body["prompt_cache_key"] != root.agent.CacheKey() {
30 modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Approve the gate size.")}, 100, 0, 5))
41 items = []any{modelFunctionCallItem("fc_1", "call_1", "agent_create", `{"name":"House","responsibility":"Keep garden decisions."}`)}
43 items = []any{modelFunctionCallItem("fc_2", "call_2", "tell", `{"name":"House","message":"Check the gate size."}`)}
45 items = []any{modelFunctionCallItem("fc_3", "call_3", "zoom", `{"id":0,"n":1,"name":"House"}`)}
47 items = []any{modelMessageItem("I will ask the user.")}
50 modelWriteEvents(w, modelCompletedEvent(items, 100, 0, 5))
52 whatsapp, _, _ := whatsappStartTest(t, dir, newTestClock())
53 listener, err := daemonListenSocket(filepath.Join(dir, socketFileName))
54 require.NoError(t, err)
56 ctx, cancel := context.WithCancel(t.Context())
59 done := make(chan error, 1)
61 done <- daemonServe(ctx, listener, nil, whatsapp, root.schedules, func(notify func(Event)) (*TurnLoop, error) {
62 return root.Loop(whatsapp, notify)
68 require.NoError(t, <-done)
71 client := terminalStartTestClient(t, listener.Addr().String())
72 client.WaitFor(t, "[connected to OneChat]")
73 client.Type("Create a child and ask it about the gate.")
74 client.WaitFor(t, "[House] Approve the gate size.")
75 client.WaitFor(t, "I will ask the user.")
76 require.Contains(t, client.Output(), "Started House.")
77 require.Contains(t, client.Output(), "user: Check the gate size.")
79 child, err := openAgent(filepath.Join(root.agent.dir, "children", "House"))
80 require.NoError(t, err)
81 require.Equal(t, root.agent.config.Model, child.config.Model)
82 require.Equal(t, root.agent.config.Effort, child.config.Effort)
83 require.Equal(t, root.agent.config.Workdir, child.config.Workdir)
84 require.Equal(t, root.agent.config.Name, child.config.Parent)
85 require.NotEqual(t, root.agent.CacheKey(), child.CacheKey())
87 client.Type("Show the garden responsibility.")
88 require.Eventually(t, func() bool {
89 for i := range server.Calls() {
90 call := server.Call(i)
91 texts := turnInputTexts(t, call)
92 if len(texts) > 0 && texts[len(texts)-1] == "Show the garden responsibility." {
93 return strings.Contains(strings.Join(texts, "\n"), "Children:\nHouse: Keep garden decisions.")
98 }, 5*time.Second, time.Millisecond)
101 func TestChildCreationRefusesUsedNames(t *testing.T) {
102 test := newDaemonChildrenTest(t)
103 box := test.root.tools
104 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"OneChat","responsibility":"Other plans."}`), "already used")
106 require.NoDirExists(t, filepath.Join(test.root.agent.dir, "children"))
107 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"House","responsibility":" "}`), "responsibility")
108 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"House","responsibility":"Keep garden plans."}`), "Started House.")
109 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"House","responsibility":"Other plans."}`), "already used")
111 test.root.runs.subagents.draw = func() string {
114 subagent, err := test.root.runs.subagents.Create(t.Context())
115 require.NoError(t, err)
116 require.Equal(t, "BlueFox", subagent.name)
117 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"BlueFox","responsibility":"Other plans."}`), "already used by a subagent")
118 require.NoError(t, test.root.runs.subagents.Reserve("Calendar"))
119 require.Contains(t, box.run(t.Context(), "agent_create", `{"name":"Calendar","responsibility":"Keep dates."}`), "already used")
122 func TestChildCreationAcceptsAreaNames(t *testing.T) {
123 testCases := []struct {
132 name: "calendar area",
140 name: "capital letters after the first",
144 name: "thirty-two letters",
145 child: "A" + strings.Repeat("b", 31),
148 for _, tc := range testCases {
149 t.Run(tc.name, func(t *testing.T) {
150 test := newDaemonChildrenTest(t)
151 arguments, err := json.Marshal(ToolAgentCreateArguments{
153 Responsibility: "Keep area decisions.",
155 require.NoError(t, err)
156 require.Contains(t, test.root.tools.run(t.Context(), "agent_create", string(arguments)), "Started "+tc.child+".")
158 child := test.runtime.messages.Child(test.root.agent.config.Name, tc.child)
159 require.NotNil(t, child)
160 require.Equal(t, tc.child, child.agent.config.Name)
161 require.FileExists(t, filepath.Join(child.agent.dir, "config.json"))
166 func TestChildCreationRefusesInvalidAreaNames(t *testing.T) {
167 testCases := []struct {
180 name: "thirty-three letters",
181 child: "A" + strings.Repeat("b", 32),
184 name: "lowercase initial",
204 name: "non-ASCII initial",
208 name: "non-ASCII remainder",
212 for _, tc := range testCases {
213 t.Run(tc.name, func(t *testing.T) {
214 test := newDaemonChildrenTest(t)
215 arguments, err := json.Marshal(ToolAgentCreateArguments{
217 Responsibility: "Keep area decisions.",
219 require.NoError(t, err)
220 require.Contains(t, test.root.tools.run(t.Context(), "agent_create", string(arguments)), "name must have 2 to 32 ASCII letters and start with a capital letter")
221 require.NoDirExists(t, filepath.Join(test.root.agent.dir, "children"))
226 func TestFailedChildPublicationKeepsStartupAndRetryWorking(t *testing.T) {
227 if os.Geteuid() == 0 {
228 t.Skip("requires directory write permissions")
232 root, err := openAgent(filepath.Join(dir, daemonAgentDirName))
233 require.NoError(t, err)
235 subagents := newSubagents(filepath.Join(root.dir, subagentDirName), time.Now, subagentNameRandom)
237 require.NoError(t, subagents.Close())
240 children := filepath.Join(root.dir, "children")
241 require.NoError(t, os.Mkdir(children, 0o500))
243 require.NoError(t, os.Chmod(children, 0o700))
246 _, err = root.CreateChild("GreenOtter", "Keep garden plans.", subagents)
247 require.ErrorContains(t, err, "publish child directory")
248 require.NoDirExists(t, filepath.Join(children, "GreenOtter"))
250 staged, err := filepath.Glob(filepath.Join(root.dir, ".child-*"))
251 require.NoError(t, err)
252 require.Empty(t, staged)
254 server := newModelFake(t)
255 reopened, err := openDaemonAgents(t.Context(), dir, server.URL, ModelAPIKey(modelTestKey), defaultConfig().Compactor, time.Now, discardLog())
256 require.NoError(t, err)
257 require.Len(t, reopened, 1)
260 require.NoError(t, reopened.Close())
263 require.NoError(t, os.Chmod(children, 0o700))
265 child, err := root.CreateChild("GreenOtter", "Keep garden plans.", subagents)
266 require.NoError(t, err)
267 require.Equal(t, filepath.Join(children, "GreenOtter"), child.dir)
270 func TestInterruptedChildPreparationDoesNotStopStartup(t *testing.T) {
272 root, err := openAgent(filepath.Join(dir, daemonAgentDirName))
273 require.NoError(t, err)
275 staged, err := os.MkdirTemp(root.dir, ".child-*")
276 require.NoError(t, err)
277 require.NoError(t, os.WriteFile(filepath.Join(staged, ".config.json.partial"), []byte("{"), 0o600))
279 server := newModelFake(t)
280 agents, err := openDaemonAgents(t.Context(), dir, server.URL, ModelAPIKey(modelTestKey), defaultConfig().Compactor, time.Now, discardLog())
281 require.NoError(t, err)
284 require.NoError(t, agents.Close())
287 require.Len(t, agents, 1)
289 child, err := root.CreateChild("GreenOtter", "Keep garden plans.", agents[0].subagents)
290 require.NoError(t, err)
292 children, err := root.Children()
293 require.NoError(t, err)
294 require.Len(t, children, 1)
295 require.Equal(t, child.config, children[0].config)
296 require.DirExists(t, staged)
299 func TestChildPublicationDoesNotReplaceAnExistingDirectory(t *testing.T) {
300 test := newDaemonChildrenTest(t)
301 path := filepath.Join(test.root.agent.dir, "children", "GreenOtter")
302 require.NoError(t, os.MkdirAll(path, 0o700))
304 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
305 require.ErrorContains(t, err, "publish child directory")
306 require.NoFileExists(t, filepath.Join(path, "config.json"))
307 require.NoError(t, test.root.runs.subagents.Reserve("GreenOtter"))
308 test.root.runs.subagents.Release("GreenOtter")
311 func TestChildNamesStayOutOfSubagentDraws(t *testing.T) {
312 test := newDaemonChildrenTest(t)
313 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
314 require.NoError(t, err)
316 names := []string{"GreenOtter", "BlueFox"}
317 test.root.runs.subagents.draw = func() string {
323 subagent, err := test.root.runs.subagents.Create(t.Context())
324 require.NoError(t, err)
325 require.Equal(t, "BlueFox", subagent.name)
328 func TestChildToolsExcludeCreationAndWhatsApp(t *testing.T) {
329 test := newDaemonChildrenTest(t)
330 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
331 require.NoError(t, err)
333 child := test.runtime.messages.Child(test.root.agent.config.Name, "GreenOtter")
334 require.NotNil(t, child)
336 names := promptToolNames(child.agent.Tools())
337 require.NotContains(t, names, "agent_create")
338 require.NotContains(t, names, "whatsapp_send")
339 require.NotContains(t, names, "whatsapp_find")
340 require.Contains(t, names, "spawn")
341 require.Contains(t, names, "schedule_set")
342 require.Contains(t, names, "schedule_list")
343 require.Contains(t, names, "schedule_remove")
344 require.Equal(t, `error: unknown tool "agent_create"`, child.tools.run(t.Context(), "agent_create", `{"name":"BlueFox","responsibility":"Other plans."}`))
345 require.Nil(t, child.tools.messages.Child("GreenOtter", "OneChat"))
348 func TestZoomReadsTheChildViewAndKeepsSubagentLogs(t *testing.T) {
349 test := newDaemonChildrenTest(t)
350 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
351 require.NoError(t, err)
353 child := test.runtime.messages.Child(test.root.agent.config.Name, "GreenOtter")
354 _, err = child.memory.Append("note", "The gate is narrow.")
355 require.NoError(t, err)
356 require.NoError(t, child.memory.Settle(t.Context()))
358 output := test.root.tools.run(t.Context(), "zoom", `{"id":0,"n":1,"name":"GreenOtter"}`)
359 require.Equal(t, strings.Join(child.memory.ViewLines(nil), ""), output)
360 require.Contains(t, output, "note: The gate is narrow.")
362 test.root.runs.subagents.draw = func() string {
365 subagent, err := test.root.runs.subagents.Create(t.Context())
366 require.NoError(t, err)
368 _, err = subagent.Append("note", "A short task.")
369 require.NoError(t, err)
370 require.Equal(t, "0|note: A short task.", test.root.tools.run(t.Context(), "zoom", `{"id":0,"n":1,"name":"BlueFox"}`))
373 func TestRuntimeChildJoinsBackupLocksAndStopsWithDaemon(t *testing.T) {
374 test := newDaemonChildrenTest(t)
375 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
376 require.NoError(t, err)
378 child := test.runtime.messages.Child(test.root.agent.config.Name, "GreenOtter")
379 _, err = child.memory.Append("note", "Keep the gate plan.")
380 require.NoError(t, err)
382 appended := make(chan error, 1)
383 require.NoError(t, test.runtime.messages.SnapshotAgents(t.Context(), func() error {
384 require.FileExists(t, filepath.Join(child.agent.dir, "view.json"))
387 _, err := child.memory.Append("note", "A later plan.")
392 case err := <-appended:
393 require.FailNow(t, "child append bypasses snapshot lock", "%v", err)
394 case <-time.After(20 * time.Millisecond):
399 require.NoError(t, <-appended)
401 require.NoError(t, test.runtime.Close())
403 test.runtime.opened = nil
404 reopened, err := test.root.openChild(t.Context(), child.agent)
405 require.NoError(t, err)
406 require.Equal(t, 2, reopened.memory.Len())
407 require.NoError(t, reopened.Close())
410 func TestRootStateListsChildResponsibilitiesOnlyWhenPresent(t *testing.T) {
411 test := newDaemonChildrenTest(t)
412 before := test.root.state()
413 require.NotContains(t, before, "Children:")
415 _, err := test.runtime.Create("GreenOtter", "Keep garden plans.")
416 require.NoError(t, err)
418 _, err = test.runtime.Create("BlueFox", "Keep book notes.")
419 require.NoError(t, err)
420 require.Equal(t, before+"\n\nChildren:\nBlueFox: Keep book notes.\nGreenOtter: Keep garden plans.", test.root.state())
422 child := test.runtime.messages.Child(test.root.agent.config.Name, "GreenOtter")
423 require.NotContains(t, child.state(), "Children:")
426 // DaemonChildrenTest owns one root and runtime children without a root turn.
427 type DaemonChildrenTest struct {
429 runtime *DaemonChildren
431 cancel context.CancelFunc
434 func newDaemonChildrenTest(t *testing.T) *DaemonChildrenTest {
437 test := &DaemonChildrenTest{
438 server: newModelFake(t),
440 agents, err := openDaemonAgents(t.Context(), t.TempDir(), test.server.URL, ModelAPIKey(modelTestKey), defaultConfig().Compactor, time.Now, discardLog())
441 require.NoError(t, err)
443 test.root, err = agents[0].Loop(nil, func(Event) {
445 require.NoError(t, err)
447 messages, err := openDaemonMessages([]*TurnLoop{test.root})
448 require.NoError(t, err)
450 ctx, cancel := context.WithCancel(t.Context())
452 test.runtime = &DaemonChildren{
458 test.root.tools.children = test.runtime
461 require.NoError(t, test.runtime.Close())
462 test.root.runs.Close()
463 require.NoError(t, agents.Close())