]> git.giacomolli.uk - onechat/blobdiff - subagent_run_test.go
Check spacing between Go statement blocks
[onechat] / subagent_run_test.go
index a59b499eae015a037baf3daee59dce13cfda8a28..f637dcfcc9938edc983bfc75d9c1aba41d3948b6 100644 (file)
@@ -3,7 +3,6 @@ package main
 import (
        "context"
        "io"
 import (
        "context"
        "io"
-       "log"
        "net/http"
        "os"
        "path/filepath"
        "net/http"
        "os"
        "path/filepath"
@@ -22,7 +21,9 @@ const subagentTestFullContext = `{"error": {"message": "Your input exceeds the c
 
 func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
        server := newModelFake(t)
 
 func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
        server := newModelFake(t)
+
        var test *TurnTestLoop
        var test *TurnTestLoop
+
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                last := subagentTestLastItem(call)
                switch {
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                last := subagentTestLastItem(call)
                switch {
@@ -48,6 +49,7 @@ func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
 
        name := test.events.Last("subagent")
        require.True(t, subagentNameValid(name), name)
 
        name := test.events.Last("subagent")
        require.True(t, subagentNameValid(name), name)
+
        work := filepath.Join(test.loop.runs.subagents.dir, name, "work")
        require.DirExists(t, work)
 
        work := filepath.Join(test.loop.runs.subagents.dir, name, "work")
        require.DirExists(t, work)
 
@@ -67,9 +69,10 @@ func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
                Source: name,
                Status: subagentFinished,
        }, test.events.LastEvent("work"))
                Source: name,
                Status: subagentFinished,
        }, test.events.LastEvent("work"))
-       require.Equal(t, "subagent "+name+" is done, and its report goes to the agent\n", test.logs.String())
+       require.Equal(t, "subagent "+name+" started\nsubagent "+name+" done after 0s\n", test.logs.String())
 
        var first, second *ModelFakeCall
 
        var first, second *ModelFakeCall
+
        for n := range server.Calls() {
                call := server.Call(n)
                if !subagentTestCall(call) {
        for n := range server.Calls() {
                call := server.Call(n)
                if !subagentTestCall(call) {
@@ -98,6 +101,7 @@ func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
        require.Equal(t, instructions, first.body["instructions"])
 
        var tools []string
        require.Equal(t, instructions, first.body["instructions"])
 
        var tools []string
+
        for _, tool := range first.body["tools"].([]any) {
                tools = append(tools, tool.(map[string]any)["name"].(string))
        }
        for _, tool := range first.body["tools"].([]any) {
                tools = append(tools, tool.(map[string]any)["name"].(string))
        }
@@ -113,6 +117,7 @@ func TestSpawnRunsASubagentInTheBackground(t *testing.T) {
        require.Equal(t, "0|note: subagent\n\n1|user: Count the files.\n\n2|tool: shell {\"command\":\"pwd\"}\n\n3|echo: "+work+"\n\n\n4|reply: There are 3 files.", log)
 
        var agents []string
        require.Equal(t, "0|note: subagent\n\n1|user: Count the files.\n\n2|tool: shell {\"command\":\"pwd\"}\n\n3|echo: "+work+"\n\n\n4|reply: There are 3 files.", log)
 
        var agents []string
+
        for _, record := range modelReadUsage(t, test.usagePath) {
                agents = append(agents, record.Agent)
        }
        for _, record := range modelReadUsage(t, test.usagePath) {
                agents = append(agents, record.Agent)
        }
@@ -141,6 +146,7 @@ func TestReportJoinsTheNextRequestOfARunningTurn(t *testing.T) {
        require.NoError(t, err)
 
        <-arrived
        require.NoError(t, err)
 
        <-arrived
+
        report := subagentReport("GreenOtter", []string{"It is done."})
        test.loop.Report("GreenOtter", report, subagentFinished)
        close(release)
        report := subagentReport("GreenOtter", []string{"It is done."})
        test.loop.Report("GreenOtter", report, subagentFinished)
        close(release)
@@ -171,6 +177,7 @@ func TestFullContextGivesAFailedReport(t *testing.T) {
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                if subagentTestCall(call) {
                        w.WriteHeader(http.StatusBadRequest)
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                if subagentTestCall(call) {
                        w.WriteHeader(http.StatusBadRequest)
+
                        _, _ = io.WriteString(w, subagentTestFullContext)
 
                        return
                        _, _ = io.WriteString(w, subagentTestFullContext)
 
                        return
@@ -186,11 +193,11 @@ func TestFullContextGivesAFailedReport(t *testing.T) {
 
        name := test.events.Last("subagent")
        require.Equal(t, []string{
 
        name := test.events.Last("subagent")
        require.Equal(t, []string{
-               "work: [" + name + "]\nfailed: model call: HTTP 400: " + subagentTestFullContext + "\n\nFull chat: zoom(\"" + name + "\")",
+               "work: [" + name + "]\nfailed: create model response: model call: HTTP 400: " + subagentTestFullContext + "\n\nFull chat: zoom(\"" + name + "\")",
                "reply: It failed.",
        }, test.Log(t))
        require.Equal(t, subagentFailed, test.events.LastEvent("work").Status)
                "reply: It failed.",
        }, test.Log(t))
        require.Equal(t, subagentFailed, test.events.LastEvent("work").Status)
-       require.Equal(t, "subagent "+name+" failed, and its report tells the agent: model call: HTTP 400: "+subagentTestFullContext+"\n", test.logs.String())
+       require.Equal(t, "subagent "+name+" started\nsubagent "+name+" failed after 0s: create model response: model call: HTTP 400: "+subagentTestFullContext+"\n", test.logs.String())
 }
 
 func TestSubagentHasItsOwnEffortAndNoSpawn(t *testing.T) {
 }
 
 func TestSubagentHasItsOwnEffortAndNoSpawn(t *testing.T) {
@@ -261,6 +268,7 @@ func TestTellReachesARunningSubagentBetweenItsToolCalls(t *testing.T) {
        require.NoError(t, err)
 
        <-arrived
        require.NoError(t, err)
 
        <-arrived
+
        name := test.events.Last("subagent")
        output, err := runs.Tell(t.Context(), name, "Use the second disk.")
        require.NoError(t, err)
        name := test.events.Last("subagent")
        output, err := runs.Tell(t.Context(), name, "Use the second disk.")
        require.NoError(t, err)
@@ -295,6 +303,7 @@ func TestTellAfterTheFinalAnswerStartsAnotherChain(t *testing.T) {
        require.NoError(t, err)
 
        <-arrived
        require.NoError(t, err)
 
        <-arrived
+
        name := test.events.Last("subagent")
        _, err = runs.Tell(t.Context(), name, "Count again.")
        require.NoError(t, err)
        name := test.events.Last("subagent")
        _, err = runs.Tell(t.Context(), name, "Count again.")
        require.NoError(t, err)
@@ -345,7 +354,7 @@ func TestTellToAFinishedSubagentGoesOnFromItsLog(t *testing.T) {
 
 func TestStopEndsASubagentAndItsCommand(t *testing.T) {
        server := newModelFake(t)
 
 func TestStopEndsASubagentAndItsCommand(t *testing.T) {
        server := newModelFake(t)
-       server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
+       server.reply = func(w http.ResponseWriter, _ ModelFakeCall) {
                modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "shell", `{"command":"touch started && sleep 30"}`)}, 100, 0, 5))
        }
 
                modelWriteEvents(w, modelCompletedEvent([]any{modelFunctionCallItem("fc_1", "call_1", "shell", `{"command":"touch started && sleep 30"}`)}, 100, 0, 5))
        }
 
@@ -375,7 +384,7 @@ func TestStopEndsASubagentAndItsCommand(t *testing.T) {
                "work: " + subagentReport(name, []string{"stopped"}),
        }, test.Log(t))
        require.Equal(t, subagentStopped, test.events.LastEvent("work").Status)
                "work: " + subagentReport(name, []string{"stopped"}),
        }, test.Log(t))
        require.Equal(t, subagentStopped, test.events.LastEvent("work").Status)
-       require.Equal(t, "subagent "+name+" is stopped by the user\n", test.logs.String())
+       require.Equal(t, "subagent "+name+" started\nsubagent "+name+" stopped after 0s\n", test.logs.String())
 
        log, err := subagent.Show()
        require.NoError(t, err)
 
        log, err := subagent.Show()
        require.NoError(t, err)
@@ -397,7 +406,7 @@ func TestCloseEndsTheSubagentsWithNoReport(t *testing.T) {
                close(release)
        })
 
                close(release)
        })
 
-       server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
+       server.reply = func(_ http.ResponseWriter, _ ModelFakeCall) {
                close(arrived)
                <-release
        }
                close(arrived)
                <-release
        }
@@ -429,10 +438,12 @@ func TestRestartResumesTheCutSubagents(t *testing.T) {
        })
 
        var restarted atomic.Bool
        })
 
        var restarted atomic.Bool
+
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                switch {
                case subagentTestCall(call) && !restarted.Load():
                        arrived <- struct{}{}
        server.reply = func(w http.ResponseWriter, call ModelFakeCall) {
                switch {
                case subagentTestCall(call) && !restarted.Load():
                        arrived <- struct{}{}
+
                        <-release
                case subagentTestCall(call):
                        modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Built.")}, 100, 0, 5))
                        <-release
                case subagentTestCall(call):
                        modelWriteEvents(w, modelCompletedEvent([]any{modelMessageItem("Built.")}, 100, 0, 5))
@@ -450,7 +461,9 @@ func TestRestartResumesTheCutSubagents(t *testing.T) {
        require.NoError(t, err)
 
        <-arrived
        require.NoError(t, err)
 
        <-arrived
+
        name := first.Last("subagent")
        name := first.Last("subagent")
+
        stop()
        require.Zero(t, first.Count("work"))
 
        stop()
        require.Zero(t, first.Count("work"))
 
@@ -459,11 +472,13 @@ func TestRestartResumesTheCutSubagents(t *testing.T) {
        require.JSONEq(t, `{"running": ["`+name+`"]}`, string(data))
 
        restarted.Store(true)
        require.JSONEq(t, `{"running": ["`+name+`"]}`, string(data))
 
        restarted.Store(true)
+
        second := &TurnEventRecorder{}
        loop, memory, stop := subagentTestStart(t, agent, server, second)
        defer stop()
 
        second.WaitFor(t, "idle", 1)
        second := &TurnEventRecorder{}
        loop, memory, stop := subagentTestStart(t, agent, server, second)
        defer stop()
 
        second.WaitFor(t, "idle", 1)
+
        note := "The daemon restarted, cutting " + name + "; nothing was lost: go on."
        log := subagentTestChat(t, memory)
        require.Equal(t, []string{
        note := "The daemon restarted, cutting " + name + "; nothing was lost: go on."
        log := subagentTestChat(t, memory)
        require.Equal(t, []string{
@@ -515,13 +530,13 @@ func subagentTestStart(t *testing.T, agent *Agent, server *ModelFake, events *Tu
 
        agent.config.Workdir = t.TempDir()
        clock := newTestClock()
 
        agent.config.Workdir = t.TempDir()
        clock := newTestClock()
-       memory, err := openMemory(t.Context(), agent.dir, clock.Now, newFakeSummarizer())
+       memory, err := openMemory(t.Context(), agent.dir, clock.Now, newFakeSummarizer(), discardLog())
        require.NoError(t, err)
 
        subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), clock.Now, subagentNameRandom)
        client := newModelClient(server.URL, ModelAPIKey(modelTestKey), agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
        whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), clock)
        require.NoError(t, err)
 
        subagents := newSubagents(filepath.Join(agent.dir, subagentDirName), clock.Now, subagentNameRandom)
        client := newModelClient(server.URL, ModelAPIKey(modelTestKey), agent.CacheKey(), filepath.Join(agent.dir, "usage.jsonl"))
        whatsapp, _, _ := whatsappStartTest(t, t.TempDir(), clock)
-       loop, err := newTurnLoop(agent, memory, subagents, whatsapp, newTestSchedules(t, clock.Now), client, clock.Now, log.New(io.Discard, "", 0), events.Add)
+       loop, err := newTurnLoop(agent, memory, subagents, whatsapp, newTestSchedules(t, clock.Now), client, clock.Now, discardLog(), events.Add)
        require.NoError(t, err)
 
        ctx, cancel := context.WithCancel(t.Context())
        require.NoError(t, err)
 
        ctx, cancel := context.WithCancel(t.Context())
@@ -544,6 +559,7 @@ func subagentTestChat(t *testing.T, memory *Memory) []string {
        t.Helper()
 
        var lines []string
        t.Helper()
 
        var lines []string
+
        for id := range memory.Len() {
                message, err := memory.Message(id)
                require.NoError(t, err)
        for id := range memory.Len() {
                message, err := memory.Message(id)
                require.NoError(t, err)
@@ -572,7 +588,9 @@ func subagentTestLastItem(call ModelFakeCall) map[string]any {
 // another item.
 func subagentTestText(item map[string]any) string {
        content, _ := item["content"].([]any)
 // another item.
 func subagentTestText(item map[string]any) string {
        content, _ := item["content"].([]any)
+
        var text strings.Builder
        var text strings.Builder
+
        for _, part := range content {
                value, _ := part.(map[string]any)["text"].(string)
                text.WriteString(value)
        for _, part := range content {
                value, _ := part.(map[string]any)["text"].(string)
                text.WriteString(value)