| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/provider" |
| 10 | ) |
| 11 | |
| 12 | func TestCopySessionCopiesFullHistoryAndIsIdempotentPerOperation(t *testing.T) { |
| 13 | service, err := NewService("local", NewFilesystemPersistence(filepath.Join(t.TempDir(), "sessions-v4"))) |
| 14 | if err != nil { |
| 15 | t.Fatal(err) |
| 16 | } |
| 17 | t.Cleanup(func() { _ = service.Shutdown(context.Background()) }) |
| 18 | runtime, err := service.Create(t.Context(), CreateOptions{SessionID: "copy-source", CWD: "/workspace", Origin: SessionOriginNew}) |
| 19 | if err != nil { |
| 20 | t.Fatal(err) |
| 21 | } |
| 22 | payload, _ := json.Marshal(map[string]any{"message": provider.Message{ |
| 23 | ID: "copy-message", Role: provider.RoleUser, Content: "complete copy history", |
| 24 | }}) |
| 25 | if _, err := runtime.Session().AppendBatch(t.Context(), "copy-source-message", []Event{{Kind: "message/complete", Payload: payload}}); err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | if _, err := runtime.Session().Flush(t.Context()); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | request := CopyRequest{Source: runtime.Ref(), OperationID: "copy-operation", CWD: "/workspace"} |
| 32 | first, err := service.CopySession(t.Context(), request) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | second, err := service.CopySession(t.Context(), request) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | if first.Child != second.Child || first.Child.SessionID == runtime.Ref().SessionID { |
| 41 | t.Fatalf("copy identities = first:%+v second:%+v source:%+v", first.Child, second.Child, runtime.Ref()) |
| 42 | } |
| 43 | history, err := service.Query().History(t.Context(), first.Child) |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | if len(history) != 1 || history[0].Content != "complete copy history" { |
| 48 | t.Fatalf("copied history = %+v", history) |
| 49 | } |
| 50 | infos, err := service.Query().List(t.Context(), "", 10) |
| 51 | if err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | var copied SessionInfo |
| 55 | for _, info := range infos.Sessions { |
| 56 | if info.SessionID == first.Child.SessionID { |
| 57 | copied = info |
| 58 | break |
| 59 | } |
| 60 | } |
| 61 | if copied.ParentSessionID != runtime.Ref().SessionID || copied.Origin != SessionOriginCanonicalImport { |
| 62 | t.Fatalf("copy header = %+v", copied) |
| 63 | } |
| 64 | } |
| 65 |