package pipeline import ( "context" "fmt" "path/filepath" "testing" "git.a-wan.net/alan/pipelines/internal/protocol" ) func TestChatShellRunsPersistPruneAndInterrupt(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "shell.db") store, err := Open(path) if err != nil { t.Fatal(err) } running := protocol.ChatShellRunRecord{ID: "run_live", SessionID: "ses_1", Command: "sleep 9", Directory: "/w", Status: protocol.ChatShellRunRunning, StartedAt: 1000} if err := store.SaveChatShellRun(ctx, running, 2); err != nil { t.Fatal(err) } code := 3 for i := 0; i < 3; i++ { run := protocol.ChatShellRunRecord{ID: fmt.Sprintf("run_%d", i), SessionID: "ses_1", Command: "false", Directory: "/w", Status: protocol.ChatShellRunExited, ExitCode: &code, StartedAt: int64(2000 + i), EndedAt: int64(2500 + i), Output: "tail", OutputStart: 10, OutputBytes: 14} if err := store.SaveChatShellRun(ctx, run, 2); err != nil { t.Fatal(err) } } if err := store.SaveChatShellRun(ctx, protocol.ChatShellRunRecord{ID: "other", SessionID: "ses_2", Command: "ls", Directory: "/w", Status: protocol.ChatShellRunExited, StartedAt: 1}, 2); err != nil { t.Fatal(err) } runs, err := store.ChatShellRuns(ctx, "ses_1") if err != nil { t.Fatal(err) } // The running run is never pruned; keep counts the newest runs, so only // the finished ones outside the newest two are dropped. ids := []string{} for _, run := range runs { ids = append(ids, run.ID) } if fmt.Sprint(ids) != "[run_live run_1 run_2]" { t.Fatalf("runs = %v", ids) } if got := runs[2]; got.ExitCode == nil || *got.ExitCode != 3 || !got.Truncated || got.Output != "tail" || got.OutputBytes != 14 { t.Fatalf("finished run = %+v", got) } store.Close() store, err = Open(path) if err != nil { t.Fatal(err) } defer store.Close() n, err := store.InterruptChatShellRuns(ctx, 4000, "server restarted") if err != nil || n != 1 { t.Fatalf("interrupt = %d, %v", n, err) } live, found, err := store.ChatShellRun(ctx, "ses_1", "run_live") if err != nil || !found || live.Status != protocol.ChatShellRunInterrupted || live.EndedAt != 4000 || live.DurationMS != 3000 || live.ExitCode != nil { t.Fatalf("interrupted run = %+v found=%v err=%v", live, found, err) } if _, found, _ := store.ChatShellRun(ctx, "ses_2", "run_live"); found { t.Fatal("a run was readable through another session") } }